[BackgroundSync] Clean up some tests
[chromium-blink-merge.git] / media / base / android / media_codec_bridge.cc
blob14f33002ea83305cd3033322c276545447edf0f0
1 // Copyright (c) 2013 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.
5 #include "media/base/android/media_codec_bridge.h"
8 #include "base/android/build_info.h"
9 #include "base/android/jni_android.h"
10 #include "base/android/jni_array.h"
11 #include "base/android/jni_string.h"
12 #include "base/basictypes.h"
13 #include "base/lazy_instance.h"
14 #include "base/logging.h"
15 #include "base/numerics/safe_conversions.h"
16 #include "base/strings/string_util.h"
17 #include "base/strings/stringprintf.h"
18 #include "jni/MediaCodecBridge_jni.h"
19 #include "media/base/bit_reader.h"
20 #include "media/base/decrypt_config.h"
22 using base::android::AttachCurrentThread;
23 using base::android::ConvertJavaStringToUTF8;
24 using base::android::ConvertUTF8ToJavaString;
25 using base::android::JavaIntArrayToIntVector;
26 using base::android::ScopedJavaLocalRef;
28 namespace media {
30 enum {
31 kBufferFlagSyncFrame = 1, // BUFFER_FLAG_SYNC_FRAME
32 kBufferFlagEndOfStream = 4, // BUFFER_FLAG_END_OF_STREAM
33 kConfigureFlagEncode = 1, // CONFIGURE_FLAG_ENCODE
36 static const std::string AudioCodecToAndroidMimeType(const AudioCodec& codec) {
37 switch (codec) {
38 case kCodecMP3:
39 return "audio/mpeg";
40 case kCodecVorbis:
41 return "audio/vorbis";
42 case kCodecOpus:
43 return "audio/opus";
44 case kCodecAAC:
45 return "audio/mp4a-latm";
46 default:
47 return std::string();
51 static const std::string VideoCodecToAndroidMimeType(const VideoCodec& codec) {
52 switch (codec) {
53 case kCodecH264:
54 return "video/avc";
55 case kCodecVP8:
56 return "video/x-vnd.on2.vp8";
57 case kCodecVP9:
58 return "video/x-vnd.on2.vp9";
59 default:
60 return std::string();
64 static const std::string CodecTypeToAndroidMimeType(const std::string& codec) {
65 // TODO(xhwang): Shall we handle more detailed strings like "mp4a.40.2"?
66 if (codec == "avc1")
67 return "video/avc";
68 if (codec == "mp4a")
69 return "audio/mp4a-latm";
70 if (codec == "vp8" || codec == "vp8.0")
71 return "video/x-vnd.on2.vp8";
72 if (codec == "vp9" || codec == "vp9.0")
73 return "video/x-vnd.on2.vp9";
74 if (codec == "vorbis")
75 return "audio/vorbis";
76 if (codec == "opus")
77 return "audio/opus";
78 return std::string();
81 // TODO(qinmin): using a map to help all the conversions in this class.
82 static const std::string AndroidMimeTypeToCodecType(const std::string& mime) {
83 if (mime == "video/mp4v-es")
84 return "mp4v";
85 if (mime == "video/avc")
86 return "avc1";
87 if (mime == "video/x-vnd.on2.vp8")
88 return "vp8";
89 if (mime == "video/x-vnd.on2.vp9")
90 return "vp9";
91 if (mime == "audio/mp4a-latm")
92 return "mp4a";
93 if (mime == "audio/mpeg")
94 return "mp3";
95 if (mime == "audio/vorbis")
96 return "vorbis";
97 if (mime == "audio/opus")
98 return "opus";
99 return std::string();
102 static ScopedJavaLocalRef<jintArray>
103 ToJavaIntArray(JNIEnv* env, scoped_ptr<jint[]> native_array, int size) {
104 ScopedJavaLocalRef<jintArray> j_array(env, env->NewIntArray(size));
105 env->SetIntArrayRegion(j_array.obj(), 0, size, native_array.get());
106 return j_array;
109 // static
110 bool MediaCodecBridge::IsAvailable() {
111 // MediaCodec is only available on JB and greater.
112 if (base::android::BuildInfo::GetInstance()->sdk_int() < 16)
113 return false;
114 // Blacklist some devices on Jellybean as for MediaCodec support is buggy.
115 // http://crbug.com/365494.
116 if (base::android::BuildInfo::GetInstance()->sdk_int() == 16) {
117 std::string model(base::android::BuildInfo::GetInstance()->model());
118 return model != "GT-I9100" && model != "GT-I9300" && model != "GT-N7000";
120 return true;
123 // static
124 bool MediaCodecBridge::SupportsSetParameters() {
125 // MediaCodec.setParameters() is only available starting with K.
126 return base::android::BuildInfo::GetInstance()->sdk_int() >= 19;
129 // static
130 bool MediaCodecBridge::SupportsGetName() {
131 // MediaCodec.getName() is only available on JB MR2 and greater.
132 return base::android::BuildInfo::GetInstance()->sdk_int() >= 18;
135 // static
136 std::vector<MediaCodecBridge::CodecsInfo> MediaCodecBridge::GetCodecsInfo() {
137 std::vector<CodecsInfo> codecs_info;
138 if (!IsAvailable())
139 return codecs_info;
141 JNIEnv* env = AttachCurrentThread();
142 std::string mime_type;
143 ScopedJavaLocalRef<jobjectArray> j_codec_info_array =
144 Java_MediaCodecBridge_getCodecsInfo(env);
145 jsize len = env->GetArrayLength(j_codec_info_array.obj());
146 for (jsize i = 0; i < len; ++i) {
147 ScopedJavaLocalRef<jobject> j_info(
148 env, env->GetObjectArrayElement(j_codec_info_array.obj(), i));
149 ScopedJavaLocalRef<jstring> j_codec_type =
150 Java_CodecInfo_codecType(env, j_info.obj());
151 ConvertJavaStringToUTF8(env, j_codec_type.obj(), &mime_type);
152 ScopedJavaLocalRef<jstring> j_codec_name =
153 Java_CodecInfo_codecName(env, j_info.obj());
154 CodecsInfo info;
155 info.codecs = AndroidMimeTypeToCodecType(mime_type);
156 ConvertJavaStringToUTF8(env, j_codec_name.obj(), &info.name);
157 info.direction = static_cast<MediaCodecDirection>(
158 Java_CodecInfo_direction(env, j_info.obj()));
159 codecs_info.push_back(info);
161 return codecs_info;
164 // static
165 std::string MediaCodecBridge::GetDefaultCodecName(
166 const std::string& mime_type,
167 MediaCodecDirection direction) {
168 if (!IsAvailable())
169 return std::string();
171 JNIEnv* env = AttachCurrentThread();
172 ScopedJavaLocalRef<jstring> j_mime = ConvertUTF8ToJavaString(env, mime_type);
173 ScopedJavaLocalRef<jstring> j_codec_name =
174 Java_MediaCodecBridge_getDefaultCodecName(env, j_mime.obj(), direction);
175 return ConvertJavaStringToUTF8(env, j_codec_name.obj());
178 // static
179 std::set<int> MediaCodecBridge::GetEncoderColorFormats(
180 const std::string& mime_type) {
181 std::set<int> color_formats;
182 if (!IsAvailable())
183 return color_formats;
185 JNIEnv* env = AttachCurrentThread();
186 ScopedJavaLocalRef<jstring> j_mime = ConvertUTF8ToJavaString(env, mime_type);
187 ScopedJavaLocalRef<jintArray> j_color_format_array =
188 Java_MediaCodecBridge_getEncoderColorFormatsForMime(env, j_mime.obj());
190 if (j_color_format_array.obj()) {
191 std::vector<int> formats;
192 JavaIntArrayToIntVector(env, j_color_format_array.obj(), &formats);
193 color_formats = std::set<int>(formats.begin(), formats.end());
196 return color_formats;
199 // static
200 bool MediaCodecBridge::CanDecode(const std::string& codec, bool is_secure) {
201 if (!IsAvailable())
202 return false;
204 JNIEnv* env = AttachCurrentThread();
205 std::string mime = CodecTypeToAndroidMimeType(codec);
206 if (mime.empty())
207 return false;
208 ScopedJavaLocalRef<jstring> j_mime = ConvertUTF8ToJavaString(env, mime);
209 ScopedJavaLocalRef<jobject> j_media_codec_bridge =
210 Java_MediaCodecBridge_create(env, j_mime.obj(), is_secure, false);
211 if (!j_media_codec_bridge.is_null()) {
212 Java_MediaCodecBridge_release(env, j_media_codec_bridge.obj());
213 return true;
215 return false;
218 // static
219 bool MediaCodecBridge::IsKnownUnaccelerated(const std::string& mime_type,
220 MediaCodecDirection direction) {
221 if (!IsAvailable())
222 return true;
224 std::string codec_name;
225 if (SupportsGetName()) {
226 codec_name = GetDefaultCodecName(mime_type, direction);
227 } else {
228 std::string codec_type = AndroidMimeTypeToCodecType(mime_type);
229 std::vector<media::MediaCodecBridge::CodecsInfo> codecs_info =
230 MediaCodecBridge::GetCodecsInfo();
231 for (size_t i = 0; i < codecs_info.size(); ++i) {
232 if (codecs_info[i].codecs == codec_type &&
233 codecs_info[i].direction == direction) {
234 codec_name = codecs_info[i].name;
235 break;
239 DVLOG(1) << __PRETTY_FUNCTION__ << "Default codec for " << mime_type <<
240 " : " << codec_name;
241 // It would be nice if MediaCodecInfo externalized some notion of
242 // HW-acceleration but it doesn't. Android Media guidance is that the
243 // "OMX.google" prefix is always used for SW decoders, so that's what we
244 // use. "OMX.SEC.*" codec is Samsung software implementation - report it
245 // as unaccelerated as well. Also temporary blacklist Exynos and MediaTek
246 // devices while HW decoder video freezes and distortions are
247 // investigated - http://crbug.com/446974.
248 if (codec_name.length() > 0) {
249 return (StartsWithASCII(codec_name, "OMX.google.", true) ||
250 StartsWithASCII(codec_name, "OMX.SEC.", true) ||
251 StartsWithASCII(codec_name, "OMX.MTK.", true) ||
252 StartsWithASCII(codec_name, "OMX.Exynos.", true));
254 return true;
257 MediaCodecBridge::MediaCodecBridge(const std::string& mime,
258 bool is_secure,
259 MediaCodecDirection direction) {
260 JNIEnv* env = AttachCurrentThread();
261 CHECK(env);
262 DCHECK(!mime.empty());
263 ScopedJavaLocalRef<jstring> j_mime = ConvertUTF8ToJavaString(env, mime);
264 j_media_codec_.Reset(
265 Java_MediaCodecBridge_create(env, j_mime.obj(), is_secure, direction));
268 MediaCodecBridge::~MediaCodecBridge() {
269 JNIEnv* env = AttachCurrentThread();
270 CHECK(env);
271 if (j_media_codec_.obj())
272 Java_MediaCodecBridge_release(env, j_media_codec_.obj());
275 bool MediaCodecBridge::StartInternal() {
276 JNIEnv* env = AttachCurrentThread();
277 return Java_MediaCodecBridge_start(env, j_media_codec_.obj());
280 MediaCodecStatus MediaCodecBridge::Reset() {
281 JNIEnv* env = AttachCurrentThread();
282 return static_cast<MediaCodecStatus>(
283 Java_MediaCodecBridge_flush(env, j_media_codec_.obj()));
286 void MediaCodecBridge::Stop() {
287 JNIEnv* env = AttachCurrentThread();
288 Java_MediaCodecBridge_stop(env, j_media_codec_.obj());
291 void MediaCodecBridge::GetOutputFormat(int* width, int* height) {
292 JNIEnv* env = AttachCurrentThread();
294 *width = Java_MediaCodecBridge_getOutputWidth(env, j_media_codec_.obj());
295 *height = Java_MediaCodecBridge_getOutputHeight(env, j_media_codec_.obj());
298 int MediaCodecBridge::GetOutputSamplingRate() {
299 JNIEnv* env = AttachCurrentThread();
301 return Java_MediaCodecBridge_getOutputSamplingRate(env, j_media_codec_.obj());
304 MediaCodecStatus MediaCodecBridge::QueueInputBuffer(
305 int index,
306 const uint8* data,
307 size_t data_size,
308 const base::TimeDelta& presentation_time) {
309 DVLOG(3) << __PRETTY_FUNCTION__ << index << ": " << data_size;
310 if (data_size > base::checked_cast<size_t>(kint32max))
311 return MEDIA_CODEC_ERROR;
312 if (data && !FillInputBuffer(index, data, data_size))
313 return MEDIA_CODEC_ERROR;
314 JNIEnv* env = AttachCurrentThread();
315 return static_cast<MediaCodecStatus>(
316 Java_MediaCodecBridge_queueInputBuffer(env,
317 j_media_codec_.obj(),
318 index,
320 data_size,
321 presentation_time.InMicroseconds(),
322 0));
325 MediaCodecStatus MediaCodecBridge::QueueSecureInputBuffer(
326 int index,
327 const uint8* data,
328 size_t data_size,
329 const uint8* key_id,
330 int key_id_size,
331 const uint8* iv,
332 int iv_size,
333 const SubsampleEntry* subsamples,
334 int subsamples_size,
335 const base::TimeDelta& presentation_time) {
336 DVLOG(3) << __PRETTY_FUNCTION__ << index << ": " << data_size;
337 if (data_size > base::checked_cast<size_t>(kint32max))
338 return MEDIA_CODEC_ERROR;
339 if (data && !FillInputBuffer(index, data, data_size))
340 return MEDIA_CODEC_ERROR;
342 JNIEnv* env = AttachCurrentThread();
343 ScopedJavaLocalRef<jbyteArray> j_key_id =
344 base::android::ToJavaByteArray(env, key_id, key_id_size);
345 ScopedJavaLocalRef<jbyteArray> j_iv =
346 base::android::ToJavaByteArray(env, iv, iv_size);
348 // MediaCodec.CryptoInfo documentations says passing NULL for |clear_array|
349 // to indicate that all data is encrypted. But it doesn't specify what
350 // |cypher_array| and |subsamples_size| should be in that case. Passing
351 // one subsample here just to be on the safe side.
352 int new_subsamples_size = subsamples_size == 0 ? 1 : subsamples_size;
354 scoped_ptr<jint[]> native_clear_array(new jint[new_subsamples_size]);
355 scoped_ptr<jint[]> native_cypher_array(new jint[new_subsamples_size]);
357 if (subsamples_size == 0) {
358 DCHECK(!subsamples);
359 native_clear_array[0] = 0;
360 native_cypher_array[0] = data_size;
361 } else {
362 DCHECK_GT(subsamples_size, 0);
363 DCHECK(subsamples);
364 for (int i = 0; i < subsamples_size; ++i) {
365 DCHECK(subsamples[i].clear_bytes <= std::numeric_limits<uint16>::max());
366 if (subsamples[i].cypher_bytes >
367 static_cast<uint32>(std::numeric_limits<jint>::max())) {
368 return MEDIA_CODEC_ERROR;
371 native_clear_array[i] = subsamples[i].clear_bytes;
372 native_cypher_array[i] = subsamples[i].cypher_bytes;
376 ScopedJavaLocalRef<jintArray> clear_array =
377 ToJavaIntArray(env, native_clear_array.Pass(), new_subsamples_size);
378 ScopedJavaLocalRef<jintArray> cypher_array =
379 ToJavaIntArray(env, native_cypher_array.Pass(), new_subsamples_size);
381 return static_cast<MediaCodecStatus>(
382 Java_MediaCodecBridge_queueSecureInputBuffer(
383 env,
384 j_media_codec_.obj(),
385 index,
387 j_iv.obj(),
388 j_key_id.obj(),
389 clear_array.obj(),
390 cypher_array.obj(),
391 new_subsamples_size,
392 presentation_time.InMicroseconds()));
395 void MediaCodecBridge::QueueEOS(int input_buffer_index) {
396 DVLOG(3) << __PRETTY_FUNCTION__ << ": " << input_buffer_index;
397 JNIEnv* env = AttachCurrentThread();
398 Java_MediaCodecBridge_queueInputBuffer(env,
399 j_media_codec_.obj(),
400 input_buffer_index,
404 kBufferFlagEndOfStream);
407 MediaCodecStatus MediaCodecBridge::DequeueInputBuffer(
408 const base::TimeDelta& timeout,
409 int* index) {
410 JNIEnv* env = AttachCurrentThread();
411 ScopedJavaLocalRef<jobject> result = Java_MediaCodecBridge_dequeueInputBuffer(
412 env, j_media_codec_.obj(), timeout.InMicroseconds());
413 *index = Java_DequeueInputResult_index(env, result.obj());
414 MediaCodecStatus status = static_cast<MediaCodecStatus>(
415 Java_DequeueInputResult_status(env, result.obj()));
416 DVLOG(3) << __PRETTY_FUNCTION__ << ": status: " << status
417 << ", index: " << *index;
418 return status;
421 MediaCodecStatus MediaCodecBridge::DequeueOutputBuffer(
422 const base::TimeDelta& timeout,
423 int* index,
424 size_t* offset,
425 size_t* size,
426 base::TimeDelta* presentation_time,
427 bool* end_of_stream,
428 bool* key_frame) {
429 JNIEnv* env = AttachCurrentThread();
430 ScopedJavaLocalRef<jobject> result =
431 Java_MediaCodecBridge_dequeueOutputBuffer(
432 env, j_media_codec_.obj(), timeout.InMicroseconds());
433 *index = Java_DequeueOutputResult_index(env, result.obj());
434 *offset = base::checked_cast<size_t>(
435 Java_DequeueOutputResult_offset(env, result.obj()));
436 *size = base::checked_cast<size_t>(
437 Java_DequeueOutputResult_numBytes(env, result.obj()));
438 if (presentation_time) {
439 *presentation_time = base::TimeDelta::FromMicroseconds(
440 Java_DequeueOutputResult_presentationTimeMicroseconds(env,
441 result.obj()));
443 int flags = Java_DequeueOutputResult_flags(env, result.obj());
444 if (end_of_stream)
445 *end_of_stream = flags & kBufferFlagEndOfStream;
446 if (key_frame)
447 *key_frame = flags & kBufferFlagSyncFrame;
448 MediaCodecStatus status = static_cast<MediaCodecStatus>(
449 Java_DequeueOutputResult_status(env, result.obj()));
450 DVLOG(3) << __PRETTY_FUNCTION__ << ": status: " << status
451 << ", index: " << *index << ", offset: " << *offset
452 << ", size: " << *size << ", flags: " << flags;
453 return status;
456 void MediaCodecBridge::ReleaseOutputBuffer(int index, bool render) {
457 DVLOG(3) << __PRETTY_FUNCTION__ << ": " << index;
458 JNIEnv* env = AttachCurrentThread();
459 CHECK(env);
461 Java_MediaCodecBridge_releaseOutputBuffer(
462 env, j_media_codec_.obj(), index, render);
465 int MediaCodecBridge::GetOutputBuffersCount() {
466 JNIEnv* env = AttachCurrentThread();
467 return Java_MediaCodecBridge_getOutputBuffersCount(env, j_media_codec_.obj());
470 size_t MediaCodecBridge::GetOutputBuffersCapacity() {
471 JNIEnv* env = AttachCurrentThread();
472 return Java_MediaCodecBridge_getOutputBuffersCapacity(env,
473 j_media_codec_.obj());
476 void MediaCodecBridge::GetInputBuffer(int input_buffer_index,
477 uint8** data,
478 size_t* capacity) {
479 JNIEnv* env = AttachCurrentThread();
480 ScopedJavaLocalRef<jobject> j_buffer(Java_MediaCodecBridge_getInputBuffer(
481 env, j_media_codec_.obj(), input_buffer_index));
482 *data = static_cast<uint8*>(env->GetDirectBufferAddress(j_buffer.obj()));
483 *capacity = base::checked_cast<size_t>(
484 env->GetDirectBufferCapacity(j_buffer.obj()));
487 bool MediaCodecBridge::CopyFromOutputBuffer(int index,
488 size_t offset,
489 void* dst,
490 int dst_size) {
491 JNIEnv* env = AttachCurrentThread();
492 ScopedJavaLocalRef<jobject> j_buffer(
493 Java_MediaCodecBridge_getOutputBuffer(env, j_media_codec_.obj(), index));
494 void* src_data =
495 reinterpret_cast<uint8*>(env->GetDirectBufferAddress(j_buffer.obj())) +
496 offset;
497 int src_capacity = env->GetDirectBufferCapacity(j_buffer.obj()) - offset;
498 if (src_capacity < dst_size)
499 return false;
500 memcpy(dst, src_data, dst_size);
501 return true;
504 bool MediaCodecBridge::FillInputBuffer(int index,
505 const uint8* data,
506 size_t size) {
507 uint8* dst = NULL;
508 size_t capacity = 0;
509 GetInputBuffer(index, &dst, &capacity);
510 CHECK(dst);
512 if (size > capacity) {
513 LOG(ERROR) << "Input buffer size " << size
514 << " exceeds MediaCodec input buffer capacity: " << capacity;
515 return false;
518 memcpy(dst, data, size);
519 return true;
522 AudioCodecBridge::AudioCodecBridge(const std::string& mime)
523 // Audio codec doesn't care about security level and there is no need for
524 // audio encoding yet.
525 : MediaCodecBridge(mime, false, MEDIA_CODEC_DECODER) {}
527 bool AudioCodecBridge::Start(const AudioCodec& codec,
528 int sample_rate,
529 int channel_count,
530 const uint8* extra_data,
531 size_t extra_data_size,
532 int64 codec_delay_ns,
533 int64 seek_preroll_ns,
534 bool play_audio,
535 jobject media_crypto) {
536 JNIEnv* env = AttachCurrentThread();
538 if (!media_codec())
539 return false;
541 std::string codec_string = AudioCodecToAndroidMimeType(codec);
542 if (codec_string.empty())
543 return false;
545 ScopedJavaLocalRef<jstring> j_mime =
546 ConvertUTF8ToJavaString(env, codec_string);
547 ScopedJavaLocalRef<jobject> j_format(Java_MediaCodecBridge_createAudioFormat(
548 env, j_mime.obj(), sample_rate, channel_count));
549 DCHECK(!j_format.is_null());
551 if (!ConfigureMediaFormat(j_format.obj(), codec, extra_data, extra_data_size,
552 codec_delay_ns, seek_preroll_ns)) {
553 return false;
556 if (!Java_MediaCodecBridge_configureAudio(
557 env, media_codec(), j_format.obj(), media_crypto, 0, play_audio)) {
558 return false;
561 return StartInternal();
564 bool AudioCodecBridge::ConfigureMediaFormat(jobject j_format,
565 const AudioCodec& codec,
566 const uint8* extra_data,
567 size_t extra_data_size,
568 int64 codec_delay_ns,
569 int64 seek_preroll_ns) {
570 if (extra_data_size == 0 && codec != kCodecOpus)
571 return true;
573 JNIEnv* env = AttachCurrentThread();
574 switch (codec) {
575 case kCodecVorbis: {
576 if (extra_data[0] != 2) {
577 LOG(ERROR) << "Invalid number of vorbis headers before the codec "
578 << "header: " << extra_data[0];
579 return false;
582 size_t header_length[2];
583 // |total_length| keeps track of the total number of bytes before the last
584 // header.
585 size_t total_length = 1;
586 const uint8* current_pos = extra_data;
587 // Calculate the length of the first 2 headers.
588 for (int i = 0; i < 2; ++i) {
589 header_length[i] = 0;
590 while (total_length < extra_data_size) {
591 size_t size = *(++current_pos);
592 total_length += 1 + size;
593 if (total_length > 0x80000000) {
594 LOG(ERROR) << "Vorbis header size too large";
595 return false;
597 header_length[i] += size;
598 if (size < 0xFF)
599 break;
601 if (total_length >= extra_data_size) {
602 LOG(ERROR) << "Invalid vorbis header size in the extra data";
603 return false;
606 current_pos++;
607 // The first header is identification header.
608 ScopedJavaLocalRef<jbyteArray> first_header =
609 base::android::ToJavaByteArray(env, current_pos, header_length[0]);
610 Java_MediaCodecBridge_setCodecSpecificData(
611 env, j_format, 0, first_header.obj());
612 // The last header is codec header.
613 ScopedJavaLocalRef<jbyteArray> last_header =
614 base::android::ToJavaByteArray(
615 env, extra_data + total_length, extra_data_size - total_length);
616 Java_MediaCodecBridge_setCodecSpecificData(
617 env, j_format, 1, last_header.obj());
618 break;
620 case kCodecAAC: {
621 media::BitReader reader(extra_data, extra_data_size);
623 // The following code is copied from aac.cc
624 // TODO(qinmin): refactor the code in aac.cc to make it more reusable.
625 uint8 profile = 0;
626 uint8 frequency_index = 0;
627 uint8 channel_config = 0;
628 if (!reader.ReadBits(5, &profile) ||
629 !reader.ReadBits(4, &frequency_index)) {
630 LOG(ERROR) << "Unable to parse AAC header";
631 return false;
633 if (0xf == frequency_index && !reader.SkipBits(24)) {
634 LOG(ERROR) << "Unable to parse AAC header";
635 return false;
637 if (!reader.ReadBits(4, &channel_config)) {
638 LOG(ERROR) << "Unable to parse AAC header";
639 return false;
642 if (profile < 1 || profile > 4 || frequency_index == 0xf ||
643 channel_config > 7) {
644 LOG(ERROR) << "Invalid AAC header";
645 return false;
647 const size_t kCsdLength = 2;
648 uint8 csd[kCsdLength];
649 csd[0] = profile << 3 | frequency_index >> 1;
650 csd[1] = (frequency_index & 0x01) << 7 | channel_config << 3;
651 ScopedJavaLocalRef<jbyteArray> byte_array =
652 base::android::ToJavaByteArray(env, csd, kCsdLength);
653 Java_MediaCodecBridge_setCodecSpecificData(
654 env, j_format, 0, byte_array.obj());
656 // TODO(qinmin): pass an extra variable to this function to determine
657 // whether we need to call this.
658 Java_MediaCodecBridge_setFrameHasADTSHeader(env, j_format);
659 break;
661 case kCodecOpus: {
662 if (!extra_data || extra_data_size == 0 ||
663 codec_delay_ns < 0 || seek_preroll_ns < 0) {
664 LOG(ERROR) << "Invalid Opus Header";
665 return false;
668 // csd0 - Opus Header
669 ScopedJavaLocalRef<jbyteArray> csd0 =
670 base::android::ToJavaByteArray(env, extra_data, extra_data_size);
671 Java_MediaCodecBridge_setCodecSpecificData(env, j_format, 0, csd0.obj());
673 // csd1 - Codec Delay
674 ScopedJavaLocalRef<jbyteArray> csd1 =
675 base::android::ToJavaByteArray(
676 env, reinterpret_cast<const uint8*>(&codec_delay_ns),
677 sizeof(int64_t));
678 Java_MediaCodecBridge_setCodecSpecificData(env, j_format, 1, csd1.obj());
680 // csd2 - Seek Preroll
681 ScopedJavaLocalRef<jbyteArray> csd2 =
682 base::android::ToJavaByteArray(
683 env, reinterpret_cast<const uint8*>(&seek_preroll_ns),
684 sizeof(int64_t));
685 Java_MediaCodecBridge_setCodecSpecificData(env, j_format, 2, csd2.obj());
686 break;
688 default:
689 LOG(ERROR) << "Invalid header encountered for codec: "
690 << AudioCodecToAndroidMimeType(codec);
691 return false;
693 return true;
696 int64 AudioCodecBridge::PlayOutputBuffer(int index, size_t size) {
697 DCHECK_LE(0, index);
698 int numBytes = base::checked_cast<int>(size);
699 JNIEnv* env = AttachCurrentThread();
700 ScopedJavaLocalRef<jobject> buf =
701 Java_MediaCodecBridge_getOutputBuffer(env, media_codec(), index);
702 uint8* buffer = static_cast<uint8*>(env->GetDirectBufferAddress(buf.obj()));
704 ScopedJavaLocalRef<jbyteArray> byte_array =
705 base::android::ToJavaByteArray(env, buffer, numBytes);
706 return Java_MediaCodecBridge_playOutputBuffer(
707 env, media_codec(), byte_array.obj());
710 void AudioCodecBridge::SetVolume(double volume) {
711 JNIEnv* env = AttachCurrentThread();
712 Java_MediaCodecBridge_setVolume(env, media_codec(), volume);
715 // static
716 AudioCodecBridge* AudioCodecBridge::Create(const AudioCodec& codec) {
717 if (!MediaCodecBridge::IsAvailable())
718 return NULL;
720 const std::string mime = AudioCodecToAndroidMimeType(codec);
721 return mime.empty() ? NULL : new AudioCodecBridge(mime);
724 // static
725 bool AudioCodecBridge::IsKnownUnaccelerated(const AudioCodec& codec) {
726 return MediaCodecBridge::IsKnownUnaccelerated(
727 AudioCodecToAndroidMimeType(codec), MEDIA_CODEC_DECODER);
730 // static
731 bool VideoCodecBridge::IsKnownUnaccelerated(const VideoCodec& codec,
732 MediaCodecDirection direction) {
733 return MediaCodecBridge::IsKnownUnaccelerated(
734 VideoCodecToAndroidMimeType(codec), direction);
737 // static
738 VideoCodecBridge* VideoCodecBridge::CreateDecoder(const VideoCodec& codec,
739 bool is_secure,
740 const gfx::Size& size,
741 jobject surface,
742 jobject media_crypto) {
743 if (!MediaCodecBridge::IsAvailable())
744 return NULL;
746 const std::string mime = VideoCodecToAndroidMimeType(codec);
747 if (mime.empty())
748 return NULL;
750 scoped_ptr<VideoCodecBridge> bridge(
751 new VideoCodecBridge(mime, is_secure, MEDIA_CODEC_DECODER));
752 if (!bridge->media_codec())
753 return NULL;
755 JNIEnv* env = AttachCurrentThread();
756 ScopedJavaLocalRef<jstring> j_mime = ConvertUTF8ToJavaString(env, mime);
757 ScopedJavaLocalRef<jobject> j_format(
758 Java_MediaCodecBridge_createVideoDecoderFormat(
759 env, j_mime.obj(), size.width(), size.height()));
760 DCHECK(!j_format.is_null());
761 if (!Java_MediaCodecBridge_configureVideo(env,
762 bridge->media_codec(),
763 j_format.obj(),
764 surface,
765 media_crypto,
766 0)) {
767 return NULL;
770 return bridge->StartInternal() ? bridge.release() : NULL;
773 // static
774 VideoCodecBridge* VideoCodecBridge::CreateEncoder(const VideoCodec& codec,
775 const gfx::Size& size,
776 int bit_rate,
777 int frame_rate,
778 int i_frame_interval,
779 int color_format) {
780 if (!MediaCodecBridge::IsAvailable())
781 return NULL;
783 const std::string mime = VideoCodecToAndroidMimeType(codec);
784 if (mime.empty())
785 return NULL;
787 scoped_ptr<VideoCodecBridge> bridge(
788 new VideoCodecBridge(mime, false, MEDIA_CODEC_ENCODER));
789 if (!bridge->media_codec())
790 return NULL;
792 JNIEnv* env = AttachCurrentThread();
793 ScopedJavaLocalRef<jstring> j_mime = ConvertUTF8ToJavaString(env, mime);
794 ScopedJavaLocalRef<jobject> j_format(
795 Java_MediaCodecBridge_createVideoEncoderFormat(env,
796 j_mime.obj(),
797 size.width(),
798 size.height(),
799 bit_rate,
800 frame_rate,
801 i_frame_interval,
802 color_format));
803 DCHECK(!j_format.is_null());
804 if (!Java_MediaCodecBridge_configureVideo(env,
805 bridge->media_codec(),
806 j_format.obj(),
807 NULL,
808 NULL,
809 kConfigureFlagEncode)) {
810 return NULL;
813 return bridge->StartInternal() ? bridge.release() : NULL;
816 VideoCodecBridge::VideoCodecBridge(const std::string& mime,
817 bool is_secure,
818 MediaCodecDirection direction)
819 : MediaCodecBridge(mime, is_secure, direction),
820 adaptive_playback_supported_for_testing_(-1) {}
822 void VideoCodecBridge::SetVideoBitrate(int bps) {
823 JNIEnv* env = AttachCurrentThread();
824 Java_MediaCodecBridge_setVideoBitrate(env, media_codec(), bps);
827 void VideoCodecBridge::RequestKeyFrameSoon() {
828 JNIEnv* env = AttachCurrentThread();
829 Java_MediaCodecBridge_requestKeyFrameSoon(env, media_codec());
832 bool VideoCodecBridge::IsAdaptivePlaybackSupported(int width, int height) {
833 if (adaptive_playback_supported_for_testing_ == 0)
834 return false;
835 else if (adaptive_playback_supported_for_testing_ > 0)
836 return true;
837 JNIEnv* env = AttachCurrentThread();
838 return Java_MediaCodecBridge_isAdaptivePlaybackSupported(
839 env, media_codec(), width, height);
842 bool MediaCodecBridge::RegisterMediaCodecBridge(JNIEnv* env) {
843 return RegisterNativesImpl(env);
846 } // namespace media