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

Side by Side Diff: ppapi/examples/video_encode/video_encode.cc

Issue 937643006: Pepper: add video_encoder example (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@bbudge-ppb-video-encoder-impl
Patch Set: Created 5 years, 10 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
« no previous file with comments | « no previous file | ppapi/examples/video_encode/video_encode.html » ('j') | 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) 2014 The Chromium Authors. All rights reserved.
bbudge 2015/02/18 23:43:22 nit: remove (c) and 2015
llandwerlin-old 2015/02/19 16:04:13 Done.
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 <math.h>
6 #include <stdio.h>
7 #include <string.h>
8
9 #include <iostream>
10 #include <sstream>
11 #include <vector>
12
13 #include "ppapi/c/pp_errors.h"
14 #include "ppapi/c/ppb_console.h"
15 #include "ppapi/cpp/input_event.h"
16 #include "ppapi/cpp/instance.h"
17 #include "ppapi/cpp/media_stream_video_track.h"
18 #include "ppapi/cpp/module.h"
19 #include "ppapi/cpp/rect.h"
20 #include "ppapi/cpp/var.h"
21 #include "ppapi/cpp/var_array_buffer.h"
22 #include "ppapi/cpp/var_dictionary.h"
23 #include "ppapi/cpp/video_encoder.h"
24 #include "ppapi/cpp/video_frame.h"
25 #include "ppapi/utility/completion_callback_factory.h"
26
27 // TODO(llandwerlin): turn on by default when we have software encode.
28 // #define USE_VP8_INSTEAD_OF_H264
29
30 // Use assert as a poor-man's CHECK, even in non-debug mode.
31 // Since <assert.h> redefines assert on every inclusion (it doesn't use
32 // include-guards), make sure this is the last file #include'd in this file.
33 #undef NDEBUG
34 #include <assert.h>
35
36 namespace {
37
38 std::string VideoProfileToString(PP_VideoProfile profile) {
39 switch (profile) {
40 case PP_VIDEOPROFILE_H264BASELINE:
41 return "h264baseline";
42 case PP_VIDEOPROFILE_H264MAIN:
43 return "h264main";
44 case PP_VIDEOPROFILE_H264EXTENDED:
45 return "h264extended";
46 case PP_VIDEOPROFILE_H264HIGH:
47 return "h264high";
48 case PP_VIDEOPROFILE_H264HIGH10PROFILE:
49 return "h264high10";
50 case PP_VIDEOPROFILE_H264HIGH422PROFILE:
51 return "h264high422";
52 case PP_VIDEOPROFILE_H264HIGH444PREDICTIVEPROFILE:
53 return "h264high444predictive";
54 case PP_VIDEOPROFILE_H264SCALABLEBASELINE:
55 return "h264scalablebaseline";
56 case PP_VIDEOPROFILE_H264SCALABLEHIGH:
57 return "h264scalablehigh";
58 case PP_VIDEOPROFILE_H264STEREOHIGH:
59 return "h264stereohigh";
60 case PP_VIDEOPROFILE_H264MULTIVIEWHIGH:
61 return "h264multiviewhigh";
62 case PP_VIDEOPROFILE_VP8_ANY:
63 return "vp8";
64 case PP_VIDEOPROFILE_VP9_ANY:
65 return "vp9";
66 // No default to catch unhandled profiles.
bbudge 2015/02/18 23:43:24 nit: indent
llandwerlin-old 2015/02/19 16:04:13 Done.
67 }
68 return "unknown";
69 }
70
71 std::string HardwareAccelerationToString(PP_HardwareAcceleration acceleration) {
72 switch (acceleration) {
73 case PP_HARDWAREACCELERATION_ONLY:
74 return "hardware";
75 case PP_HARDWAREACCELERATION_WITHFALLBACK:
76 return "hardware/software";
77 case PP_HARDWAREACCELERATION_NONE:
78 return "software";
79 // No default to catch unhandled accelerations.
bbudge 2015/02/18 23:43:24 nit: indent
llandwerlin-old 2015/02/19 16:04:13 Done.
80 }
81 return "unknown";
82 }
83
84 // This object is the global object representing this plugin library as long
85 // as it is loaded.
86 class MediaStreamVideoEncoderModule : public pp::Module {
87 public:
88 MediaStreamVideoEncoderModule() : pp::Module() {}
89 virtual ~MediaStreamVideoEncoderModule() {}
90
91 virtual pp::Instance* CreateInstance(PP_Instance instance);
92 };
93
94 class MediaStreamVideoEncoderInstance : public pp::Instance {
95 public:
96 MediaStreamVideoEncoderInstance(PP_Instance instance, pp::Module* module);
97 virtual ~MediaStreamVideoEncoderInstance();
98
99 // pp::Instance implementation.
100 virtual void DidChangeView(const pp::Rect& position,
101 const pp::Rect& clip_ignored);
102 virtual void HandleMessage(const pp::Var& var_message);
103
104 private:
105 void ConfigureTrack();
106 void OnConfiguredTrack(int32_t result);
107 void ProbeEncoder();
108 void OnEncoderProbed(int32_t result,
109 const std::vector<PP_VideoProfileDescription> profiles);
110 void InitializeEncoder();
111 void OnInitializedEncoder(int32_t result);
112 void ScheduleNextGetEncoderFrame();
113 void GetEncoderFrameTick(int32_t result);
114 void GetEncoderFrame();
115 void GetTrackFrame(const pp::VideoFrame& encoder_frame);
116 void OnGetTrackFrame(int32_t result,
117 pp::VideoFrame track_frame,
118 pp::VideoFrame encoder_frame);
119 void OnGetEncoderFrame(int32_t result, const pp::VideoFrame& frame);
120 int32_t CopyTrackFrameToEncoderFrame(pp::VideoFrame dest, pp::VideoFrame src);
121 void EncodeFrame(const pp::VideoFrame& frame);
122 void OnEncodeDone(int32_t result);
123 void OnGetBitstreamBuffer(int32_t result, PP_BitstreamBuffer buffer);
124 void StopEncode();
125
126 void LogError(int32_t error, const std::string& message);
127 void LogWarning(const std::string& message);
128 void Log(const std::string& message);
129
130 void PostDataMessage(const void* buffer, uint32_t size);
131 void PostSignalMessage(const char* name);
132
133 bool is_encoding_;
134
135 pp::VideoEncoder video_encoder_;
136 pp::MediaStreamVideoTrack video_track_;
137 pp::CompletionCallbackFactory<MediaStreamVideoEncoderInstance>
138 callback_factory_;
139
140 PP_VideoProfile video_profile_;
141 PP_VideoFrame_Format frame_format_;
142
143 pp::Size frame_size_;
144 pp::Size plugin_size_;
145 pp::Size encoder_size_;
146 uint32_t encoded_frames_;
147
148 pp::VideoFrame encoder_frame_;
149 };
150
151 MediaStreamVideoEncoderInstance::MediaStreamVideoEncoderInstance(
152 PP_Instance instance,
153 pp::Module* module)
154 : pp::Instance(instance),
155 is_encoding_(false),
156 callback_factory_(this),
157 #if defined(USE_VP8_INSTEAD_OF_H264)
158 video_profile_(PP_VIDEOPROFILE_VP8_ANY),
159 #else
160 video_profile_(PP_VIDEOPROFILE_H264MAIN),
161 #endif
162 frame_format_(PP_VIDEOFRAME_FORMAT_I420),
163 encoded_frames_(0) {
164 }
165
166 MediaStreamVideoEncoderInstance::~MediaStreamVideoEncoderInstance() {
167 }
168
169 //
bbudge 2015/02/18 23:43:24 nit: remove
llandwerlin-old 2015/02/19 16:04:13 Done.
170 //
171 //
172
173 void MediaStreamVideoEncoderInstance::DidChangeView(
174 const pp::Rect& position,
175 const pp::Rect& clip_ignored) {
176 plugin_size_ = position.size();
177 }
178
179 void MediaStreamVideoEncoderInstance::ConfigureTrack() {
180 if (encoder_size_.IsEmpty())
181 frame_size_ = plugin_size_;
182 else
183 frame_size_ = encoder_size_;
184
185 int32_t attrib_list[] = {PP_MEDIASTREAMVIDEOTRACK_ATTRIB_FORMAT,
186 frame_format_,
187 PP_MEDIASTREAMVIDEOTRACK_ATTRIB_WIDTH,
188 frame_size_.width(),
189 PP_MEDIASTREAMVIDEOTRACK_ATTRIB_HEIGHT,
190 frame_size_.height(),
191 PP_MEDIASTREAMVIDEOTRACK_ATTRIB_NONE};
192
193 pp::VarDictionary dict;
194 dict.Set(pp::Var("status"), pp::Var("configuring video track"));
195 dict.Set(pp::Var("width"), pp::Var(frame_size_.width()));
196 dict.Set(pp::Var("height"), pp::Var(frame_size_.height()));
197 PostMessage(dict);
198
199 video_track_.Configure(
200 attrib_list, callback_factory_.NewCallback(
201 &MediaStreamVideoEncoderInstance::OnConfiguredTrack));
202 }
203
204 void MediaStreamVideoEncoderInstance::OnConfiguredTrack(int32_t result) {
205 if (result != PP_OK) {
206 LogError(result, "Cannot configure track");
207 return;
208 }
209
210 if (is_encoding_)
211 GetEncoderFrame();
212 else
213 ProbeEncoder();
214 }
215
216 void MediaStreamVideoEncoderInstance::ProbeEncoder() {
217 video_encoder_ = pp::VideoEncoder(this);
218 video_encoder_.GetSupportedProfiles(callback_factory_.NewCallbackWithOutput(
219 &MediaStreamVideoEncoderInstance::OnEncoderProbed));
220 }
221
222 void MediaStreamVideoEncoderInstance::OnEncoderProbed(
223 int32_t result,
224 const std::vector<PP_VideoProfileDescription> profiles) {
225 bool has_required_profile = false;
226
227 Log("Available profiles:");
228 for (const PP_VideoProfileDescription& profile : profiles) {
229 std::ostringstream oss;
230 oss << " profile=" << VideoProfileToString(profile.profile)
231 << " max_resolution=" << profile.max_resolution.width << "x"
232 << profile.max_resolution.height
233 << " max_framerate=" << profile.max_framerate_numerator << "/"
234 << profile.max_framerate_denominator << " acceleration="
235 << HardwareAccelerationToString(profile.acceleration);
236 Log(oss.str());
237
238 has_required_profile |= profile.profile == video_profile_;
239 }
240
241 if (!has_required_profile) {
242 std::ostringstream oss;
243 oss << "Cannot find required video profile: ";
244 oss << VideoProfileToString(video_profile_);
245 LogError(PP_ERROR_FAILED, oss.str());
246 return;
247 }
248
249 InitializeEncoder();
250 }
251
252 void MediaStreamVideoEncoderInstance::InitializeEncoder() {
253 video_encoder_ = pp::VideoEncoder(this);
254
255 pp::VarDictionary dict;
256 dict.Set(pp::Var("status"), pp::Var("initializing encoder"));
257 dict.Set(pp::Var("width"), pp::Var(encoder_size_.width()));
258 dict.Set(pp::Var("height"), pp::Var(encoder_size_.height()));
259 PostMessage(dict);
260
261 int32_t error = video_encoder_.Initialize(
262 frame_format_, frame_size_, video_profile_, 2000000,
263 PP_HARDWAREACCELERATION_WITHFALLBACK,
264 callback_factory_.NewCallback(
265 &MediaStreamVideoEncoderInstance::OnInitializedEncoder));
266 if (error != PP_OK_COMPLETIONPENDING) {
267 LogError(error, "Cannot initialize encoder");
268 return;
269 }
270 }
271
272 void MediaStreamVideoEncoderInstance::OnInitializedEncoder(int32_t result) {
273 if (result != PP_OK) {
274 LogError(result, "Encoder initialization failed");
275 return;
276 }
277
278 is_encoding_ = true;
279
280 if (video_encoder_.GetFrameCodedSize(&encoder_size_) != PP_OK) {
281 LogError(result, "Cannot get encoder coded frame size");
282 return;
283 }
284
285 pp::VarDictionary dict;
286 dict.Set(pp::Var("status"), pp::Var("encoder initialized"));
287 dict.Set(pp::Var("width"), pp::Var(encoder_size_.width()));
288 dict.Set(pp::Var("height"), pp::Var(encoder_size_.height()));
289 PostMessage(dict);
290
291 video_encoder_.GetBitstreamBuffer(callback_factory_.NewCallbackWithOutput(
292 &MediaStreamVideoEncoderInstance::OnGetBitstreamBuffer));
293
294 if (encoder_size_ != frame_size_)
295 ConfigureTrack();
296 else
297 GetEncoderFrame();
298 }
299
300 void MediaStreamVideoEncoderInstance::ScheduleNextGetEncoderFrame() {
301 pp::Module::Get()->core()->CallOnMainThread(
302 1000 / 30, callback_factory_.NewCallback(
303 &MediaStreamVideoEncoderInstance::GetEncoderFrameTick),
304 0);
305 }
bbudge 2015/02/18 23:43:24 I don't understand why you need to schedule gettin
llandwerlin-old 2015/02/19 00:22:25 There isn't much point to encode as fast at possib
bbudge 2015/02/19 21:54:38 How does it work if the video track is running fas
llandwerlin-old 2015/02/27 14:19:44 In the case of MediaStreamVideoTrack, it will actu
306
307 void MediaStreamVideoEncoderInstance::GetEncoderFrameTick(int32_t result) {
308 if (is_encoding_)
309 GetEncoderFrame();
310 }
311
312 void MediaStreamVideoEncoderInstance::GetEncoderFrame() {
313 video_encoder_.GetVideoFrame(callback_factory_.NewCallbackWithOutput(
314 &MediaStreamVideoEncoderInstance::OnGetEncoderFrame));
315 }
316
317 void MediaStreamVideoEncoderInstance::OnGetEncoderFrame(
318 int32_t result,
319 const pp::VideoFrame& frame) {
320 if (result == PP_ERROR_ABORTED)
321 return;
322 if (result != PP_OK) {
323 LogError(result, "Cannot get video frame from video encoder");
324 return;
325 }
326
327 GetTrackFrame(frame);
328 }
329
330 void MediaStreamVideoEncoderInstance::GetTrackFrame(
331 const pp::VideoFrame& encoder_frame) {
332 video_track_.GetFrame(callback_factory_.NewCallbackWithOutput(
333 &MediaStreamVideoEncoderInstance::OnGetTrackFrame, encoder_frame));
334 }
335
336 void MediaStreamVideoEncoderInstance::OnGetTrackFrame(
337 int32_t result,
338 pp::VideoFrame track_frame,
339 pp::VideoFrame encoder_frame) {
340 if (result == PP_ERROR_ABORTED)
341 return;
342 if (result != PP_OK) {
343 LogError(result, "Cannot get video frame from video track");
344 return;
345 }
346
347 track_frame.GetSize(&frame_size_);
348
349 if (frame_size_ != encoder_size_) {
350 video_track_.RecycleFrame(track_frame);
351 LogError(PP_ERROR_FAILED, "MediaStreamVideoTrack frame size incorrect");
352 return;
353 }
354
355 if (CopyTrackFrameToEncoderFrame(encoder_frame, track_frame) == PP_OK) {
356 EncodeFrame(encoder_frame);
357 ScheduleNextGetEncoderFrame();
358 }
359 video_track_.RecycleFrame(track_frame);
360 }
361
362 int32_t MediaStreamVideoEncoderInstance::CopyTrackFrameToEncoderFrame(
363 pp::VideoFrame dest,
364 pp::VideoFrame src) {
365 if (dest.GetDataBufferSize() < src.GetDataBufferSize()) {
366 std::ostringstream oss;
367 oss << "Incorrect destination video frame buffer size : "
368 << dest.GetDataBufferSize() << " < " << src.GetDataBufferSize();
369 LogError(PP_ERROR_FAILED, oss.str());
370 return PP_ERROR_FAILED;
371 }
372
373 memcpy(dest.GetDataBuffer(), src.GetDataBuffer(), src.GetDataBufferSize());
374 return PP_OK;
375 }
376
377 void MediaStreamVideoEncoderInstance::EncodeFrame(const pp::VideoFrame& frame) {
378 video_encoder_.Encode(frame, PP_FALSE,
379 callback_factory_.NewCallback(
380 &MediaStreamVideoEncoderInstance::OnEncodeDone));
381 }
382
383 void MediaStreamVideoEncoderInstance::OnEncodeDone(int32_t result) {
384 if (result != PP_OK)
385 LogError(result, "Encode failed");
386 }
387
388 void MediaStreamVideoEncoderInstance::OnGetBitstreamBuffer(
389 int32_t result,
390 PP_BitstreamBuffer buffer) {
391 if (result == PP_ERROR_ABORTED)
392 return;
393 if (result != PP_OK) {
394 LogError(result, "Cannot get bitstream buffer");
395 return;
396 }
397
398 encoded_frames_++;
399 PostDataMessage(buffer.buffer, buffer.size);
400 video_encoder_.RecycleBitstreamBuffer(buffer);
401
402 video_encoder_.GetBitstreamBuffer(callback_factory_.NewCallbackWithOutput(
403 &MediaStreamVideoEncoderInstance::OnGetBitstreamBuffer));
404 }
405
406 void MediaStreamVideoEncoderInstance::StopEncode() {
407 video_encoder_.Close();
408 video_track_.Close();
409 is_encoding_ = false;
410 encoded_frames_ = 0;
411 }
412
413 //
414
415 void MediaStreamVideoEncoderInstance::HandleMessage(
416 const pp::Var& var_message) {
417 if (!var_message.is_dictionary()) {
418 LogToConsole(PP_LOGLEVEL_ERROR, pp::Var("Invalid message!"));
419 return;
420 }
421
422 pp::VarDictionary var_dictionary_message(var_message);
423 std::string command = var_dictionary_message.Get("command").AsString();
424
425 if (command == "start") {
426 pp::Var var_track = var_dictionary_message.Get("track");
427 if (!var_track.is_resource()) {
428 LogToConsole(PP_LOGLEVEL_ERROR, pp::Var("Given track is not a resource"));
429 return;
430 }
431 pp::Resource resource_track = var_track.AsResource();
432 video_track_ = pp::MediaStreamVideoTrack(resource_track);
433 video_encoder_ = pp::VideoEncoder();
434 ConfigureTrack();
435 } else if (command == "stop") {
436 StopEncode();
437 PostSignalMessage("stopped");
438 } else {
439 LogToConsole(PP_LOGLEVEL_ERROR, pp::Var("Invalid command!"));
440 }
441 }
442
443 void MediaStreamVideoEncoderInstance::PostDataMessage(const void* buffer,
444 uint32_t size) {
445 pp::VarDictionary dictionary;
446
447 dictionary.Set(pp::Var("name"), pp::Var("data"));
448
449 pp::VarArrayBuffer array_buffer(size);
450 void* data_ptr = array_buffer.Map();
451 memcpy(data_ptr, buffer, size);
452 array_buffer.Unmap();
453 dictionary.Set(pp::Var("data"), array_buffer);
454
455 PostMessage(dictionary);
456 }
457
458 void MediaStreamVideoEncoderInstance::PostSignalMessage(const char* name) {
459 pp::VarDictionary dictionary;
460 dictionary.Set(pp::Var("name"), pp::Var(name));
461
462 PostMessage(dictionary);
463 }
464
465 void MediaStreamVideoEncoderInstance::LogError(int32_t error,
466 const std::string& message) {
467 std::string msg("Error: ");
468 msg.append(pp::Var(error).DebugString());
469 msg.append(" : ");
470 msg.append(message);
471 LogToConsole(PP_LOGLEVEL_ERROR, pp::Var(msg));
472 }
473
474 void MediaStreamVideoEncoderInstance::LogWarning(const std::string& message) {
475 std::string msg("Warning: ");
476 msg.append(message);
477 LogToConsole(PP_LOGLEVEL_WARNING, pp::Var(msg));
478 }
479
480 void MediaStreamVideoEncoderInstance::Log(const std::string& message) {
481 LogToConsole(PP_LOGLEVEL_LOG, pp::Var(message));
482 }
483
484 pp::Instance* MediaStreamVideoEncoderModule::CreateInstance(
485 PP_Instance instance) {
486 return new MediaStreamVideoEncoderInstance(instance, this);
487 }
488
489 } // anonymous namespace
490
491 namespace pp {
492 // Factory function for your specialization of the Module object.
493 Module* CreateModule() {
494 return new MediaStreamVideoEncoderModule();
495 }
496 } // namespace pp
OLDNEW
« no previous file with comments | « no previous file | ppapi/examples/video_encode/video_encode.html » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698