• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2010 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 //#define LOG_NDEBUG 0
18 #define LOG_TAG "avc_utils"
19 #include <utils/Log.h>
20 
21 #include "include/avc_utils.h"
22 
23 #include <media/stagefright/foundation/ABitReader.h>
24 #include <media/stagefright/foundation/ADebug.h>
25 #include <media/stagefright/foundation/hexdump.h>
26 #include <media/stagefright/MediaDefs.h>
27 #include <media/stagefright/MediaErrors.h>
28 #include <media/stagefright/MetaData.h>
29 #include <utils/misc.h>
30 
31 namespace android {
32 
parseUE(ABitReader * br)33 unsigned parseUE(ABitReader *br) {
34     unsigned numZeroes = 0;
35     while (br->getBits(1) == 0) {
36         ++numZeroes;
37     }
38 
39     unsigned x = br->getBits(numZeroes);
40 
41     return x + (1u << numZeroes) - 1;
42 }
43 
parseUEWithFallback(ABitReader * br,unsigned fallback)44 unsigned parseUEWithFallback(ABitReader *br, unsigned fallback) {
45     unsigned numZeroes = 0;
46     while (br->getBitsWithFallback(1, 1) == 0) {
47         ++numZeroes;
48     }
49     uint32_t x;
50     if (numZeroes < 32) {
51         if (br->getBitsGraceful(numZeroes, &x)) {
52             return x + (1u << numZeroes) - 1;
53         } else {
54             return fallback;
55         }
56     } else {
57         br->skipBits(numZeroes);
58         return fallback;
59     }
60 }
61 
parseSE(ABitReader * br)62 signed parseSE(ABitReader *br) {
63     unsigned codeNum = parseUE(br);
64 
65     return (codeNum & 1) ? (codeNum + 1) / 2 : -signed(codeNum / 2);
66 }
67 
parseSEWithFallback(ABitReader * br,signed fallback)68 signed parseSEWithFallback(ABitReader *br, signed fallback) {
69     // NOTE: parseUE cannot normally return ~0 as the max supported value is 0xFFFE
70     unsigned codeNum = parseUEWithFallback(br, ~0U);
71     if (codeNum == ~0U) {
72         return fallback;
73     }
74     return (codeNum & 1) ? (codeNum + 1) / 2 : -signed(codeNum / 2);
75 }
76 
skipScalingList(ABitReader * br,size_t sizeOfScalingList)77 static void skipScalingList(ABitReader *br, size_t sizeOfScalingList) {
78     size_t lastScale = 8;
79     size_t nextScale = 8;
80     for (size_t j = 0; j < sizeOfScalingList; ++j) {
81         if (nextScale != 0) {
82             signed delta_scale = parseSE(br);
83             nextScale = (lastScale + delta_scale + 256) % 256;
84         }
85 
86         lastScale = (nextScale == 0) ? lastScale : nextScale;
87     }
88 }
89 
90 // Determine video dimensions from the sequence parameterset.
FindAVCDimensions(const sp<ABuffer> & seqParamSet,int32_t * width,int32_t * height,int32_t * sarWidth,int32_t * sarHeight)91 void FindAVCDimensions(
92         const sp<ABuffer> &seqParamSet,
93         int32_t *width, int32_t *height,
94         int32_t *sarWidth, int32_t *sarHeight) {
95     ABitReader br(seqParamSet->data() + 1, seqParamSet->size() - 1);
96 
97     unsigned profile_idc = br.getBits(8);
98     br.skipBits(16);
99     parseUE(&br);  // seq_parameter_set_id
100 
101     unsigned chroma_format_idc = 1;  // 4:2:0 chroma format
102 
103     if (profile_idc == 100 || profile_idc == 110
104             || profile_idc == 122 || profile_idc == 244
105             || profile_idc == 44 || profile_idc == 83 || profile_idc == 86) {
106         chroma_format_idc = parseUE(&br);
107         if (chroma_format_idc == 3) {
108             br.skipBits(1);  // residual_colour_transform_flag
109         }
110         parseUE(&br);  // bit_depth_luma_minus8
111         parseUE(&br);  // bit_depth_chroma_minus8
112         br.skipBits(1);  // qpprime_y_zero_transform_bypass_flag
113 
114         if (br.getBits(1)) {  // seq_scaling_matrix_present_flag
115             for (size_t i = 0; i < 8; ++i) {
116                 if (br.getBits(1)) {  // seq_scaling_list_present_flag[i]
117 
118                     // WARNING: the code below has not ever been exercised...
119                     // need a real-world example.
120 
121                     if (i < 6) {
122                         // ScalingList4x4[i],16,...
123                         skipScalingList(&br, 16);
124                     } else {
125                         // ScalingList8x8[i-6],64,...
126                         skipScalingList(&br, 64);
127                     }
128                 }
129             }
130         }
131     }
132 
133     parseUE(&br);  // log2_max_frame_num_minus4
134     unsigned pic_order_cnt_type = parseUE(&br);
135 
136     if (pic_order_cnt_type == 0) {
137         parseUE(&br);  // log2_max_pic_order_cnt_lsb_minus4
138     } else if (pic_order_cnt_type == 1) {
139         // offset_for_non_ref_pic, offset_for_top_to_bottom_field and
140         // offset_for_ref_frame are technically se(v), but since we are
141         // just skipping over them the midpoint does not matter.
142 
143         br.getBits(1);  // delta_pic_order_always_zero_flag
144         parseUE(&br);  // offset_for_non_ref_pic
145         parseUE(&br);  // offset_for_top_to_bottom_field
146 
147         unsigned num_ref_frames_in_pic_order_cnt_cycle = parseUE(&br);
148         for (unsigned i = 0; i < num_ref_frames_in_pic_order_cnt_cycle; ++i) {
149             parseUE(&br);  // offset_for_ref_frame
150         }
151     }
152 
153     parseUE(&br);  // num_ref_frames
154     br.getBits(1);  // gaps_in_frame_num_value_allowed_flag
155 
156     unsigned pic_width_in_mbs_minus1 = parseUE(&br);
157     unsigned pic_height_in_map_units_minus1 = parseUE(&br);
158     unsigned frame_mbs_only_flag = br.getBits(1);
159 
160     *width = pic_width_in_mbs_minus1 * 16 + 16;
161 
162     *height = (2 - frame_mbs_only_flag)
163         * (pic_height_in_map_units_minus1 * 16 + 16);
164 
165     if (!frame_mbs_only_flag) {
166         br.getBits(1);  // mb_adaptive_frame_field_flag
167     }
168 
169     br.getBits(1);  // direct_8x8_inference_flag
170 
171     if (br.getBits(1)) {  // frame_cropping_flag
172         unsigned frame_crop_left_offset = parseUE(&br);
173         unsigned frame_crop_right_offset = parseUE(&br);
174         unsigned frame_crop_top_offset = parseUE(&br);
175         unsigned frame_crop_bottom_offset = parseUE(&br);
176 
177         unsigned cropUnitX, cropUnitY;
178         if (chroma_format_idc == 0  /* monochrome */) {
179             cropUnitX = 1;
180             cropUnitY = 2 - frame_mbs_only_flag;
181         } else {
182             unsigned subWidthC = (chroma_format_idc == 3) ? 1 : 2;
183             unsigned subHeightC = (chroma_format_idc == 1) ? 2 : 1;
184 
185             cropUnitX = subWidthC;
186             cropUnitY = subHeightC * (2 - frame_mbs_only_flag);
187         }
188 
189         ALOGV("frame_crop = (%u, %u, %u, %u), cropUnitX = %u, cropUnitY = %u",
190              frame_crop_left_offset, frame_crop_right_offset,
191              frame_crop_top_offset, frame_crop_bottom_offset,
192              cropUnitX, cropUnitY);
193 
194         *width -=
195             (frame_crop_left_offset + frame_crop_right_offset) * cropUnitX;
196         *height -=
197             (frame_crop_top_offset + frame_crop_bottom_offset) * cropUnitY;
198     }
199 
200     if (sarWidth != NULL) {
201         *sarWidth = 0;
202     }
203 
204     if (sarHeight != NULL) {
205         *sarHeight = 0;
206     }
207 
208     if (br.getBits(1)) {  // vui_parameters_present_flag
209         unsigned sar_width = 0, sar_height = 0;
210 
211         if (br.getBits(1)) {  // aspect_ratio_info_present_flag
212             unsigned aspect_ratio_idc = br.getBits(8);
213 
214             if (aspect_ratio_idc == 255 /* extendedSAR */) {
215                 sar_width = br.getBits(16);
216                 sar_height = br.getBits(16);
217             } else {
218                 static const struct { unsigned width, height; } kFixedSARs[] = {
219                         {   0,  0 }, // Invalid
220                         {   1,  1 },
221                         {  12, 11 },
222                         {  10, 11 },
223                         {  16, 11 },
224                         {  40, 33 },
225                         {  24, 11 },
226                         {  20, 11 },
227                         {  32, 11 },
228                         {  80, 33 },
229                         {  18, 11 },
230                         {  15, 11 },
231                         {  64, 33 },
232                         { 160, 99 },
233                         {   4,  3 },
234                         {   3,  2 },
235                         {   2,  1 },
236                 };
237 
238                 if (aspect_ratio_idc > 0 && aspect_ratio_idc < NELEM(kFixedSARs)) {
239                     sar_width = kFixedSARs[aspect_ratio_idc].width;
240                     sar_height = kFixedSARs[aspect_ratio_idc].height;
241                 }
242             }
243         }
244 
245         ALOGV("sample aspect ratio = %u : %u", sar_width, sar_height);
246 
247         if (sarWidth != NULL) {
248             *sarWidth = sar_width;
249         }
250 
251         if (sarHeight != NULL) {
252             *sarHeight = sar_height;
253         }
254     }
255 }
256 
getNextNALUnit(const uint8_t ** _data,size_t * _size,const uint8_t ** nalStart,size_t * nalSize,bool startCodeFollows)257 status_t getNextNALUnit(
258         const uint8_t **_data, size_t *_size,
259         const uint8_t **nalStart, size_t *nalSize,
260         bool startCodeFollows) {
261     const uint8_t *data = *_data;
262     size_t size = *_size;
263 
264     *nalStart = NULL;
265     *nalSize = 0;
266 
267     if (size < 3) {
268         return -EAGAIN;
269     }
270 
271     size_t offset = 0;
272 
273     // A valid startcode consists of at least two 0x00 bytes followed by 0x01.
274     for (; offset + 2 < size; ++offset) {
275         if (data[offset + 2] == 0x01 && data[offset] == 0x00
276                 && data[offset + 1] == 0x00) {
277             break;
278         }
279     }
280     if (offset + 2 >= size) {
281         *_data = &data[offset];
282         *_size = 2;
283         return -EAGAIN;
284     }
285     offset += 3;
286 
287     size_t startOffset = offset;
288 
289     for (;;) {
290         while (offset < size && data[offset] != 0x01) {
291             ++offset;
292         }
293 
294         if (offset == size) {
295             if (startCodeFollows) {
296                 offset = size + 2;
297                 break;
298             }
299 
300             return -EAGAIN;
301         }
302 
303         if (data[offset - 1] == 0x00 && data[offset - 2] == 0x00) {
304             break;
305         }
306 
307         ++offset;
308     }
309 
310     size_t endOffset = offset - 2;
311     while (endOffset > startOffset + 1 && data[endOffset - 1] == 0x00) {
312         --endOffset;
313     }
314 
315     *nalStart = &data[startOffset];
316     *nalSize = endOffset - startOffset;
317 
318     if (offset + 2 < size) {
319         *_data = &data[offset - 2];
320         *_size = size - offset + 2;
321     } else {
322         *_data = NULL;
323         *_size = 0;
324     }
325 
326     return OK;
327 }
328 
FindNAL(const uint8_t * data,size_t size,unsigned nalType)329 static sp<ABuffer> FindNAL(const uint8_t *data, size_t size, unsigned nalType) {
330     const uint8_t *nalStart;
331     size_t nalSize;
332     while (getNextNALUnit(&data, &size, &nalStart, &nalSize, true) == OK) {
333         if ((nalStart[0] & 0x1f) == nalType) {
334             sp<ABuffer> buffer = new ABuffer(nalSize);
335             memcpy(buffer->data(), nalStart, nalSize);
336             return buffer;
337         }
338     }
339 
340     return NULL;
341 }
342 
AVCProfileToString(uint8_t profile)343 const char *AVCProfileToString(uint8_t profile) {
344     switch (profile) {
345         case kAVCProfileBaseline:
346             return "Baseline";
347         case kAVCProfileMain:
348             return "Main";
349         case kAVCProfileExtended:
350             return "Extended";
351         case kAVCProfileHigh:
352             return "High";
353         case kAVCProfileHigh10:
354             return "High 10";
355         case kAVCProfileHigh422:
356             return "High 422";
357         case kAVCProfileHigh444:
358             return "High 444";
359         case kAVCProfileCAVLC444Intra:
360             return "CAVLC 444 Intra";
361         default:   return "Unknown";
362     }
363 }
364 
MakeAVCCodecSpecificData(const sp<ABuffer> & accessUnit)365 sp<MetaData> MakeAVCCodecSpecificData(const sp<ABuffer> &accessUnit) {
366     const uint8_t *data = accessUnit->data();
367     size_t size = accessUnit->size();
368 
369     sp<ABuffer> seqParamSet = FindNAL(data, size, 7);
370     if (seqParamSet == NULL) {
371         return NULL;
372     }
373 
374     int32_t width, height;
375     int32_t sarWidth, sarHeight;
376     FindAVCDimensions(
377             seqParamSet, &width, &height, &sarWidth, &sarHeight);
378 
379     sp<ABuffer> picParamSet = FindNAL(data, size, 8);
380     CHECK(picParamSet != NULL);
381 
382     size_t csdSize =
383         1 + 3 + 1 + 1
384         + 2 * 1 + seqParamSet->size()
385         + 1 + 2 * 1 + picParamSet->size();
386 
387     sp<ABuffer> csd = new ABuffer(csdSize);
388     uint8_t *out = csd->data();
389 
390     *out++ = 0x01;  // configurationVersion
391     memcpy(out, seqParamSet->data() + 1, 3);  // profile/level...
392 
393     uint8_t profile = out[0];
394     uint8_t level = out[2];
395 
396     out += 3;
397     *out++ = (0x3f << 2) | 1;  // lengthSize == 2 bytes
398     *out++ = 0xe0 | 1;
399 
400     *out++ = seqParamSet->size() >> 8;
401     *out++ = seqParamSet->size() & 0xff;
402     memcpy(out, seqParamSet->data(), seqParamSet->size());
403     out += seqParamSet->size();
404 
405     *out++ = 1;
406 
407     *out++ = picParamSet->size() >> 8;
408     *out++ = picParamSet->size() & 0xff;
409     memcpy(out, picParamSet->data(), picParamSet->size());
410 
411 #if 0
412     ALOGI("AVC seq param set");
413     hexdump(seqParamSet->data(), seqParamSet->size());
414 #endif
415 
416     sp<MetaData> meta = new MetaData;
417     meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_AVC);
418 
419     meta->setData(kKeyAVCC, kTypeAVCC, csd->data(), csd->size());
420     meta->setInt32(kKeyWidth, width);
421     meta->setInt32(kKeyHeight, height);
422 
423     if (sarWidth > 1 || sarHeight > 1) {
424         // We treat 0:0 (unspecified) as 1:1.
425 
426         meta->setInt32(kKeySARWidth, sarWidth);
427         meta->setInt32(kKeySARHeight, sarHeight);
428 
429         ALOGI("found AVC codec config (%d x %d, %s-profile level %d.%d) "
430               "SAR %d : %d",
431              width,
432              height,
433              AVCProfileToString(profile),
434              level / 10,
435              level % 10,
436              sarWidth,
437              sarHeight);
438     } else {
439         ALOGI("found AVC codec config (%d x %d, %s-profile level %d.%d)",
440              width,
441              height,
442              AVCProfileToString(profile),
443              level / 10,
444              level % 10);
445     }
446 
447     return meta;
448 }
449 
IsIDR(const sp<ABuffer> & buffer)450 bool IsIDR(const sp<ABuffer> &buffer) {
451     const uint8_t *data = buffer->data();
452     size_t size = buffer->size();
453 
454     bool foundIDR = false;
455 
456     const uint8_t *nalStart;
457     size_t nalSize;
458     while (getNextNALUnit(&data, &size, &nalStart, &nalSize, true) == OK) {
459         CHECK_GT(nalSize, 0u);
460 
461         unsigned nalType = nalStart[0] & 0x1f;
462 
463         if (nalType == 5) {
464             foundIDR = true;
465             break;
466         }
467     }
468 
469     return foundIDR;
470 }
471 
IsAVCReferenceFrame(const sp<ABuffer> & accessUnit)472 bool IsAVCReferenceFrame(const sp<ABuffer> &accessUnit) {
473     const uint8_t *data = accessUnit->data();
474     size_t size = accessUnit->size();
475 
476     const uint8_t *nalStart;
477     size_t nalSize;
478     while (getNextNALUnit(&data, &size, &nalStart, &nalSize, true) == OK) {
479         CHECK_GT(nalSize, 0u);
480 
481         unsigned nalType = nalStart[0] & 0x1f;
482 
483         if (nalType == 5) {
484             return true;
485         } else if (nalType == 1) {
486             unsigned nal_ref_idc = (nalStart[0] >> 5) & 3;
487             return nal_ref_idc != 0;
488         }
489     }
490 
491     return true;
492 }
493 
FindAVCLayerId(const uint8_t * data,size_t size)494 uint32_t FindAVCLayerId(const uint8_t *data, size_t size) {
495     CHECK(data != NULL);
496 
497     const unsigned kSvcNalType = 0xE;
498     const unsigned kSvcNalSearchRange = 32;
499     // SVC NAL
500     // |---0 1110|1--- ----|---- ----|iii- ---|
501     //       ^                        ^
502     //   NAL-type = 0xE               layer-Id
503     //
504     // layer_id 0 is for base layer, while 1, 2, ... are enhancement layers.
505     // Layer n uses reference frames from layer 0, 1, ..., n-1.
506 
507     uint32_t layerId = 0;
508     sp<ABuffer> svcNAL = FindNAL(
509             data, size > kSvcNalSearchRange ? kSvcNalSearchRange : size, kSvcNalType);
510     if (svcNAL != NULL && svcNAL->size() >= 4) {
511         layerId = (*(svcNAL->data() + 3) >> 5) & 0x7;
512     }
513     return layerId;
514 }
515 
MakeAACCodecSpecificData(unsigned profile,unsigned sampling_freq_index,unsigned channel_configuration)516 sp<MetaData> MakeAACCodecSpecificData(
517         unsigned profile, unsigned sampling_freq_index,
518         unsigned channel_configuration) {
519     sp<MetaData> meta = new MetaData;
520     meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AAC);
521 
522     CHECK_LE(sampling_freq_index, 11u);
523     static const int32_t kSamplingFreq[] = {
524         96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050,
525         16000, 12000, 11025, 8000
526     };
527     meta->setInt32(kKeySampleRate, kSamplingFreq[sampling_freq_index]);
528     meta->setInt32(kKeyChannelCount, channel_configuration);
529 
530     static const uint8_t kStaticESDS[] = {
531         0x03, 22,
532         0x00, 0x00,     // ES_ID
533         0x00,           // streamDependenceFlag, URL_Flag, OCRstreamFlag
534 
535         0x04, 17,
536         0x40,                       // Audio ISO/IEC 14496-3
537         0x00, 0x00, 0x00, 0x00,
538         0x00, 0x00, 0x00, 0x00,
539         0x00, 0x00, 0x00, 0x00,
540 
541         0x05, 2,
542         // AudioSpecificInfo follows
543 
544         // oooo offf fccc c000
545         // o - audioObjectType
546         // f - samplingFreqIndex
547         // c - channelConfig
548     };
549     sp<ABuffer> csd = new ABuffer(sizeof(kStaticESDS) + 2);
550     memcpy(csd->data(), kStaticESDS, sizeof(kStaticESDS));
551 
552     csd->data()[sizeof(kStaticESDS)] =
553         ((profile + 1) << 3) | (sampling_freq_index >> 1);
554 
555     csd->data()[sizeof(kStaticESDS) + 1] =
556         ((sampling_freq_index << 7) & 0x80) | (channel_configuration << 3);
557 
558     meta->setData(kKeyESDS, 0, csd->data(), csd->size());
559 
560     return meta;
561 }
562 
ExtractDimensionsFromVOLHeader(const uint8_t * data,size_t size,int32_t * width,int32_t * height)563 bool ExtractDimensionsFromVOLHeader(
564         const uint8_t *data, size_t size, int32_t *width, int32_t *height) {
565     ABitReader br(&data[4], size - 4);
566     br.skipBits(1);  // random_accessible_vol
567     unsigned video_object_type_indication = br.getBits(8);
568 
569     CHECK_NE(video_object_type_indication,
570              0x21u /* Fine Granularity Scalable */);
571 
572     unsigned video_object_layer_verid __unused;
573     unsigned video_object_layer_priority __unused;
574     if (br.getBits(1)) {
575         video_object_layer_verid = br.getBits(4);
576         video_object_layer_priority = br.getBits(3);
577     }
578     unsigned aspect_ratio_info = br.getBits(4);
579     if (aspect_ratio_info == 0x0f /* extended PAR */) {
580         br.skipBits(8);  // par_width
581         br.skipBits(8);  // par_height
582     }
583     if (br.getBits(1)) {  // vol_control_parameters
584         br.skipBits(2);  // chroma_format
585         br.skipBits(1);  // low_delay
586         if (br.getBits(1)) {  // vbv_parameters
587             br.skipBits(15);  // first_half_bit_rate
588             CHECK(br.getBits(1));  // marker_bit
589             br.skipBits(15);  // latter_half_bit_rate
590             CHECK(br.getBits(1));  // marker_bit
591             br.skipBits(15);  // first_half_vbv_buffer_size
592             CHECK(br.getBits(1));  // marker_bit
593             br.skipBits(3);  // latter_half_vbv_buffer_size
594             br.skipBits(11);  // first_half_vbv_occupancy
595             CHECK(br.getBits(1));  // marker_bit
596             br.skipBits(15);  // latter_half_vbv_occupancy
597             CHECK(br.getBits(1));  // marker_bit
598         }
599     }
600     unsigned video_object_layer_shape = br.getBits(2);
601     CHECK_EQ(video_object_layer_shape, 0x00u /* rectangular */);
602 
603     CHECK(br.getBits(1));  // marker_bit
604     unsigned vop_time_increment_resolution = br.getBits(16);
605     CHECK(br.getBits(1));  // marker_bit
606 
607     if (br.getBits(1)) {  // fixed_vop_rate
608         // range [0..vop_time_increment_resolution)
609 
610         // vop_time_increment_resolution
611         // 2 => 0..1, 1 bit
612         // 3 => 0..2, 2 bits
613         // 4 => 0..3, 2 bits
614         // 5 => 0..4, 3 bits
615         // ...
616 
617         CHECK_GT(vop_time_increment_resolution, 0u);
618         --vop_time_increment_resolution;
619 
620         unsigned numBits = 0;
621         while (vop_time_increment_resolution > 0) {
622             ++numBits;
623             vop_time_increment_resolution >>= 1;
624         }
625 
626         br.skipBits(numBits);  // fixed_vop_time_increment
627     }
628 
629     CHECK(br.getBits(1));  // marker_bit
630     unsigned video_object_layer_width = br.getBits(13);
631     CHECK(br.getBits(1));  // marker_bit
632     unsigned video_object_layer_height = br.getBits(13);
633     CHECK(br.getBits(1));  // marker_bit
634 
635     unsigned interlaced __unused = br.getBits(1);
636 
637     *width = video_object_layer_width;
638     *height = video_object_layer_height;
639 
640     return true;
641 }
642 
GetMPEGAudioFrameSize(uint32_t header,size_t * frame_size,int * out_sampling_rate,int * out_channels,int * out_bitrate,int * out_num_samples)643 bool GetMPEGAudioFrameSize(
644         uint32_t header, size_t *frame_size,
645         int *out_sampling_rate, int *out_channels,
646         int *out_bitrate, int *out_num_samples) {
647     *frame_size = 0;
648 
649     if (out_sampling_rate) {
650         *out_sampling_rate = 0;
651     }
652 
653     if (out_channels) {
654         *out_channels = 0;
655     }
656 
657     if (out_bitrate) {
658         *out_bitrate = 0;
659     }
660 
661     if (out_num_samples) {
662         *out_num_samples = 1152;
663     }
664 
665     if ((header & 0xffe00000) != 0xffe00000) {
666         return false;
667     }
668 
669     unsigned version = (header >> 19) & 3;
670 
671     if (version == 0x01) {
672         return false;
673     }
674 
675     unsigned layer = (header >> 17) & 3;
676 
677     if (layer == 0x00) {
678         return false;
679     }
680 
681     unsigned protection __unused = (header >> 16) & 1;
682 
683     unsigned bitrate_index = (header >> 12) & 0x0f;
684 
685     if (bitrate_index == 0 || bitrate_index == 0x0f) {
686         // Disallow "free" bitrate.
687         return false;
688     }
689 
690     unsigned sampling_rate_index = (header >> 10) & 3;
691 
692     if (sampling_rate_index == 3) {
693         return false;
694     }
695 
696     static const int kSamplingRateV1[] = { 44100, 48000, 32000 };
697     int sampling_rate = kSamplingRateV1[sampling_rate_index];
698     if (version == 2 /* V2 */) {
699         sampling_rate /= 2;
700     } else if (version == 0 /* V2.5 */) {
701         sampling_rate /= 4;
702     }
703 
704     unsigned padding = (header >> 9) & 1;
705 
706     if (layer == 3) {
707         // layer I
708 
709         static const int kBitrateV1[] = {
710             32, 64, 96, 128, 160, 192, 224, 256,
711             288, 320, 352, 384, 416, 448
712         };
713 
714         static const int kBitrateV2[] = {
715             32, 48, 56, 64, 80, 96, 112, 128,
716             144, 160, 176, 192, 224, 256
717         };
718 
719         int bitrate =
720             (version == 3 /* V1 */)
721                 ? kBitrateV1[bitrate_index - 1]
722                 : kBitrateV2[bitrate_index - 1];
723 
724         if (out_bitrate) {
725             *out_bitrate = bitrate;
726         }
727 
728         *frame_size = (12000 * bitrate / sampling_rate + padding) * 4;
729 
730         if (out_num_samples) {
731             *out_num_samples = 384;
732         }
733     } else {
734         // layer II or III
735 
736         static const int kBitrateV1L2[] = {
737             32, 48, 56, 64, 80, 96, 112, 128,
738             160, 192, 224, 256, 320, 384
739         };
740 
741         static const int kBitrateV1L3[] = {
742             32, 40, 48, 56, 64, 80, 96, 112,
743             128, 160, 192, 224, 256, 320
744         };
745 
746         static const int kBitrateV2[] = {
747             8, 16, 24, 32, 40, 48, 56, 64,
748             80, 96, 112, 128, 144, 160
749         };
750 
751         int bitrate;
752         if (version == 3 /* V1 */) {
753             bitrate = (layer == 2 /* L2 */)
754                 ? kBitrateV1L2[bitrate_index - 1]
755                 : kBitrateV1L3[bitrate_index - 1];
756 
757             if (out_num_samples) {
758                 *out_num_samples = 1152;
759             }
760         } else {
761             // V2 (or 2.5)
762 
763             bitrate = kBitrateV2[bitrate_index - 1];
764             if (out_num_samples) {
765                 *out_num_samples = (layer == 1 /* L3 */) ? 576 : 1152;
766             }
767         }
768 
769         if (out_bitrate) {
770             *out_bitrate = bitrate;
771         }
772 
773         if (version == 3 /* V1 */) {
774             *frame_size = 144000 * bitrate / sampling_rate + padding;
775         } else {
776             // V2 or V2.5
777             size_t tmp = (layer == 1 /* L3 */) ? 72000 : 144000;
778             *frame_size = tmp * bitrate / sampling_rate + padding;
779         }
780     }
781 
782     if (out_sampling_rate) {
783         *out_sampling_rate = sampling_rate;
784     }
785 
786     if (out_channels) {
787         int channel_mode = (header >> 6) & 3;
788 
789         *out_channels = (channel_mode == 3) ? 1 : 2;
790     }
791 
792     return true;
793 }
794 
795 }  // namespace android
796 
797