Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(260)

Side by Side Diff: media/webm/chromeos/webm_encoder.cc

Issue 10809068: Revert 148024 - [cros] Implement WebM encoder/muxer for animated avatar capture. (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src/
Patch Set: Created 8 years, 5 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
« no previous file with comments | « media/webm/chromeos/webm_encoder.h ('k') | no next file » | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "media/webm/chromeos/webm_encoder.h"
6
7 #include "base/bind.h"
8 #include "base/file_util.h"
9 #include "base/logging.h"
10 #include "base/memory/scoped_generic_obj.h"
11 #include "libyuv/convert.h"
12 #include "libyuv/video_common.h"
13 #include "third_party/skia/include/core/SkBitmap.h"
14
15 extern "C" {
16 // Getting the right degree of C compatibility has been a constant struggle.
17 // - Stroustrup, C++ Report, 12(7), July/August 2000.
18 #define private priv
19 #include "third_party/libvpx/source/libvpx/libmkv/EbmlIDs.h"
20 #include "third_party/libvpx/source/libvpx/libmkv/EbmlWriter.h"
21 #undef private
22 }
23
24 // Number of encoder threads to use.
25 static const int kNumEncoderThreads = 2;
26
27 // Need a fixed size serializer for the track ID. libmkv provides a 64 bit
28 // one, but not a 32 bit one.
29 static void Ebml_SerializeUnsigned32(EbmlGlobal* ebml,
30 unsigned long class_id,
31 uint64_t value) {
32 uint8 size_serialized = 4 | 0x80;
33 Ebml_WriteID(ebml, class_id);
34 Ebml_Serialize(ebml, &size_serialized, sizeof(size_serialized), 1);
35 Ebml_Serialize(ebml, &value, sizeof(value), 4);
36 }
37
38 // Wrapper functor for vpx_codec_destroy().
39 class VpxCodecDestroyHelper {
40 public:
41 void operator()(vpx_codec_ctx_t* codec) {
42 vpx_codec_destroy(codec);
43 }
44 };
45
46 // Wrapper functor for vpx_img_free().
47 class VpxImgFreeHelper {
48 public:
49 void operator()(vpx_image_t* image) {
50 vpx_img_free(image);
51 }
52 };
53
54 namespace media {
55
56 namespace chromeos {
57
58 WebmEncoder::WebmEncoder(const FilePath& output_path,
59 int bitrate,
60 bool realtime)
61 : bitrate_(bitrate),
62 deadline_(realtime ? VPX_DL_REALTIME : VPX_DL_GOOD_QUALITY),
63 output_path_(output_path),
64 has_errors_(false) {
65 ebml_writer_.write_cb = base::Bind(
66 &WebmEncoder::EbmlWrite, base::Unretained(this));
67 ebml_writer_.serialize_cb = base::Bind(
68 &WebmEncoder::EbmlSerialize, base::Unretained(this));
69 }
70
71 bool WebmEncoder::EncodeFromSprite(const SkBitmap& sprite,
72 int fps_n,
73 int fps_d) {
74 DCHECK(!sprite.isNull());
75 DCHECK(!sprite.empty());
76
77 has_errors_ = false;
78 width_ = sprite.width();
79 height_ = sprite.width();
80 fps_.num = fps_n;
81 fps_.den = fps_d;
82
83 // Sprite is tiled vertically.
84 size_t frame_count = sprite.height() / width_;
85
86 vpx_image_t image;
87 vpx_img_alloc(&image, VPX_IMG_FMT_I420, width_, height_, 16);
88 // Ensure that image is freed after return.
89 ScopedGenericObj<vpx_image_t*, VpxImgFreeHelper> image_ptr(&image);
90
91 const vpx_codec_iface_t* codec_iface = vpx_codec_vp8_cx();
92 DCHECK(codec_iface);
93 vpx_codec_err_t ret = vpx_codec_enc_config_default(codec_iface, &config_, 0);
94 DCHECK_EQ(VPX_CODEC_OK, ret);
95
96 config_.rc_target_bitrate = bitrate_;
97 config_.g_w = width_;
98 config_.g_h = height_;
99 config_.g_pass = VPX_RC_ONE_PASS;
100 config_.g_profile = 0; // Default profile.
101 config_.g_threads = kNumEncoderThreads;
102 config_.rc_min_quantizer = 0;
103 config_.rc_max_quantizer = 63; // Maximum possible range.
104 config_.g_timebase.num = fps_.den;
105 config_.g_timebase.den = fps_.num;
106 config_.kf_mode = VPX_KF_AUTO; // Auto key frames.
107
108 vpx_codec_ctx_t codec;
109 ret = vpx_codec_enc_init(&codec, codec_iface, &config_, 0);
110 if (ret != VPX_CODEC_OK)
111 return false;
112 // Ensure that codec context is freed after return.
113 ScopedGenericObj<vpx_codec_ctx_t*, VpxCodecDestroyHelper> codec_ptr(&codec);
114
115 SkAutoLockPixels lock_sprite(sprite);
116
117 const uint8* src = reinterpret_cast<const uint8*>(sprite.getAddr32(0, 0));
118 size_t src_frame_size = sprite.getSize();
119 int crop_y = 0;
120
121 if (!WriteWebmHeader())
122 return false;
123
124 for (size_t frame = 0; frame < frame_count && !has_errors_; ++frame) {
125 int res = libyuv::ConvertToI420(
126 src, src_frame_size,
127 image.planes[VPX_PLANE_Y], image.stride[VPX_PLANE_Y],
128 image.planes[VPX_PLANE_U], image.stride[VPX_PLANE_U],
129 image.planes[VPX_PLANE_V], image.stride[VPX_PLANE_V],
130 0, crop_y, // src origin
131 width_, sprite.height(), // src size
132 width_, height_, // dest size
133 libyuv::kRotate0,
134 libyuv::FOURCC_ARGB);
135 if (res) {
136 has_errors_ = true;
137 break;
138 }
139 crop_y += height_;
140
141 ret = vpx_codec_encode(&codec, &image, frame, 1, 0, deadline_);
142 if (ret != VPX_CODEC_OK) {
143 has_errors_ = true;
144 break;
145 }
146
147 vpx_codec_iter_t iter = NULL;
148 const vpx_codec_cx_pkt_t* packet;
149 while (!has_errors_ && (packet = vpx_codec_get_cx_data(&codec, &iter))) {
150 if (packet->kind == VPX_CODEC_CX_FRAME_PKT)
151 WriteWebmBlock(packet);
152 }
153 }
154
155 return WriteWebmFooter();
156 }
157
158 bool WebmEncoder::WriteWebmHeader() {
159 output_ = file_util::OpenFile(output_path_, "wb");
160 if (!output_)
161 return false;
162
163 // Global header.
164 StartSubElement(EBML);
165 {
166 Ebml_SerializeUnsigned(&ebml_writer_, EBMLVersion, 1);
167 Ebml_SerializeUnsigned(&ebml_writer_, EBMLReadVersion, 1);
168 Ebml_SerializeUnsigned(&ebml_writer_, EBMLMaxIDLength, 4);
169 Ebml_SerializeUnsigned(&ebml_writer_, EBMLMaxSizeLength, 8);
170 Ebml_SerializeString(&ebml_writer_, DocType, "webm");
171 Ebml_SerializeUnsigned(&ebml_writer_, DocTypeVersion, 2);
172 Ebml_SerializeUnsigned(&ebml_writer_, DocTypeReadVersion, 2);
173 }
174 EndSubElement(); // EBML
175
176 // Single segment with a video track.
177 StartSubElement(Segment);
178 {
179 StartSubElement(Info);
180 {
181 // All timecodes in the segment will be expressed in milliseconds.
182 Ebml_SerializeUnsigned(&ebml_writer_, TimecodeScale, 1000000);
183 }
184 EndSubElement(); // Info
185
186 StartSubElement(Tracks);
187 {
188 StartSubElement(TrackEntry);
189 {
190 Ebml_SerializeUnsigned(&ebml_writer_, TrackNumber, 1);
191 Ebml_SerializeUnsigned32(&ebml_writer_, TrackUID, 1);
192 Ebml_SerializeUnsigned(&ebml_writer_, TrackType, 1); // Video
193 Ebml_SerializeString(&ebml_writer_, CodecID, "V_VP8");
194
195 StartSubElement(Video);
196 {
197 Ebml_SerializeUnsigned(&ebml_writer_, PixelWidth, width_);
198 Ebml_SerializeUnsigned(&ebml_writer_, PixelHeight, height_);
199 Ebml_SerializeUnsigned(&ebml_writer_, StereoMode, 0); // Mono
200 float fps = static_cast<float>(fps_.num) / fps_.den;
201 Ebml_SerializeFloat(&ebml_writer_, FrameRate, fps);
202 }
203 EndSubElement(); // Video
204 }
205 EndSubElement(); // TrackEntry
206 }
207 EndSubElement(); // Tracks
208
209 StartSubElement(Cluster); {
210 Ebml_SerializeUnsigned(&ebml_writer_, Timecode, 0);
211 } // Cluster left open.
212 } // Segment left open.
213
214 // No check for |has_errors_| here because |false| is only returned when
215 // opening file fails.
216 return true;
217 }
218
219 void WebmEncoder::WriteWebmBlock(const vpx_codec_cx_pkt_t* packet) {
220 bool is_keyframe = packet->data.frame.flags & VPX_FRAME_IS_KEY;
221 int64_t pts_ms = 1000 * packet->data.frame.pts * fps_.den / fps_.num;
222
223 DVLOG(1) << "Video packet @" << pts_ms << " ms "
224 << packet->data.frame.sz << " bytes "
225 << (is_keyframe ? "K" : "");
226
227 Ebml_WriteID(&ebml_writer_, SimpleBlock);
228
229 uint32 block_length = (packet->data.frame.sz + 4) | 0x10000000;
230 EbmlSerializeHelper(&block_length, 4);
231
232 uint8 track_number = 1 | 0x80;
233 EbmlSerializeHelper(&track_number, 1);
234
235 EbmlSerializeHelper(&pts_ms, 2);
236
237 uint8 flags = 0;
238 if (is_keyframe)
239 flags |= 0x80;
240 if (packet->data.frame.flags & VPX_FRAME_IS_INVISIBLE)
241 flags |= 0x08;
242 EbmlSerializeHelper(&flags, 1);
243
244 EbmlWrite(packet->data.frame.buf, packet->data.frame.sz);
245 }
246
247 bool WebmEncoder::WriteWebmFooter() {
248 EndSubElement(); // Cluster
249 EndSubElement(); // Segment
250 DCHECK(ebml_sub_elements_.empty());
251 return file_util::CloseFile(output_) && !has_errors_;
252 }
253
254 void WebmEncoder::StartSubElement(unsigned long class_id) {
255 Ebml_WriteID(&ebml_writer_, class_id);
256 ebml_sub_elements_.push(ftell(output_));
257 static const uint64_t kUnknownLen = 0x01FFFFFFFFFFFFFFLLU;
258 EbmlSerializeHelper(&kUnknownLen, 8);
259 }
260
261 void WebmEncoder::EndSubElement() {
262 DCHECK(!ebml_sub_elements_.empty());
263
264 long int end_pos = ftell(output_);
265 long int start_pos = ebml_sub_elements_.top();
266 ebml_sub_elements_.pop();
267
268 uint64_t size = (end_pos - start_pos - 8) | 0x0100000000000000ULL;
269 // Seek to the beginning of the sub-element and patch in the calculated size.
270 if (fseek(output_, start_pos, SEEK_SET)) {
271 has_errors_ = true;
272 LOG(ERROR) << "Error writing to " << output_path_.value();
273 }
274 EbmlSerializeHelper(&size, 8);
275
276 // Restore write position.
277 if (fseek(output_, end_pos, SEEK_SET)) {
278 has_errors_ = true;
279 LOG(ERROR) << "Error writing to " << output_path_.value();
280 }
281 }
282
283 void WebmEncoder::EbmlWrite(const void* buffer,
284 unsigned long len) {
285 if (fwrite(buffer, 1, len, output_) != len) {
286 has_errors_ = true;
287 LOG(ERROR) << "Error writing to " << output_path_.value();
288 }
289 }
290
291 template <class T>
292 void WebmEncoder::EbmlSerializeHelper(const T* buffer, unsigned long len) {
293 for (int i = len - 1; i >= 0; i--) {
294 uint8 c = *buffer >> (i * CHAR_BIT);
295 EbmlWrite(&c, 1);
296 }
297 }
298
299 void WebmEncoder::EbmlSerialize(const void* buffer,
300 int buffer_size,
301 unsigned long len) {
302 switch (buffer_size) {
303 case 1:
304 return EbmlSerializeHelper(static_cast<const int8_t*>(buffer), len);
305 case 2:
306 return EbmlSerializeHelper(static_cast<const int16_t*>(buffer), len);
307 case 4:
308 return EbmlSerializeHelper(static_cast<const int32_t*>(buffer), len);
309 case 8:
310 return EbmlSerializeHelper(static_cast<const int64_t*>(buffer), len);
311 default:
312 NOTREACHED() << "Invalid EbmlSerialize length: " << len;
313 }
314 }
315
316 } // namespace chromeos
317
318 } // namespace media
OLDNEW
« no previous file with comments | « media/webm/chromeos/webm_encoder.h ('k') | no next file » | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698