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
31namespace android {
32
33unsigned 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
44unsigned 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
62signed parseSE(ABitReader *br) {
63    unsigned codeNum = parseUE(br);
64
65    return (codeNum & 1) ? (codeNum + 1) / 2 : -signed(codeNum / 2);
66}
67
68signed 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
77static 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.
91void 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
257status_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
329static 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
343const 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
365sp<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 > 0 && sarHeight > 0) && (sarWidth != 1 || sarHeight != 1)) {
424        // We treat *:0 and 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
450template <typename T>
451bool IsIDRInternal(const sp<T> &buffer) {
452    const uint8_t *data = buffer->data();
453    size_t size = buffer->size();
454
455    bool foundIDR = false;
456
457    const uint8_t *nalStart;
458    size_t nalSize;
459    while (getNextNALUnit(&data, &size, &nalStart, &nalSize, true) == OK) {
460        if (nalSize == 0u) {
461            ALOGW("skipping empty nal unit from potentially malformed bitstream");
462            continue;
463        }
464
465        unsigned nalType = nalStart[0] & 0x1f;
466
467        if (nalType == 5) {
468            foundIDR = true;
469            break;
470        }
471    }
472
473    return foundIDR;
474}
475
476bool IsIDR(const sp<ABuffer> &buffer) {
477    return IsIDRInternal(buffer);
478}
479
480bool IsIDR(const sp<MediaCodecBuffer> &buffer) {
481    return IsIDRInternal(buffer);
482}
483
484bool IsAVCReferenceFrame(const sp<ABuffer> &accessUnit) {
485    const uint8_t *data = accessUnit->data();
486    size_t size = accessUnit->size();
487    if (data == NULL) {
488        ALOGE("IsAVCReferenceFrame: called on NULL data (%p, %zu)", accessUnit.get(), size);
489        return false;
490    }
491
492    const uint8_t *nalStart;
493    size_t nalSize;
494    while (getNextNALUnit(&data, &size, &nalStart, &nalSize, true) == OK) {
495        if (nalSize == 0) {
496            ALOGE("IsAVCReferenceFrame: invalid nalSize: 0 (%p, %zu)", accessUnit.get(), size);
497            return false;
498        }
499
500        unsigned nalType = nalStart[0] & 0x1f;
501
502        if (nalType == 5) {
503            return true;
504        } else if (nalType == 1) {
505            unsigned nal_ref_idc = (nalStart[0] >> 5) & 3;
506            return nal_ref_idc != 0;
507        }
508    }
509
510    return true;
511}
512
513uint32_t FindAVCLayerId(const uint8_t *data, size_t size) {
514    CHECK(data != NULL);
515
516    const unsigned kSvcNalType = 0xE;
517    const unsigned kSvcNalSearchRange = 32;
518    // SVC NAL
519    // |---0 1110|1--- ----|---- ----|iii- ---|
520    //       ^                        ^
521    //   NAL-type = 0xE               layer-Id
522    //
523    // layer_id 0 is for base layer, while 1, 2, ... are enhancement layers.
524    // Layer n uses reference frames from layer 0, 1, ..., n-1.
525
526    uint32_t layerId = 0;
527    sp<ABuffer> svcNAL = FindNAL(
528            data, size > kSvcNalSearchRange ? kSvcNalSearchRange : size, kSvcNalType);
529    if (svcNAL != NULL && svcNAL->size() >= 4) {
530        layerId = (*(svcNAL->data() + 3) >> 5) & 0x7;
531    }
532    return layerId;
533}
534
535sp<MetaData> MakeAACCodecSpecificData(
536        unsigned profile, unsigned sampling_freq_index,
537        unsigned channel_configuration) {
538    sp<MetaData> meta = new MetaData;
539    meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AAC);
540
541    CHECK_LE(sampling_freq_index, 11u);
542    static const int32_t kSamplingFreq[] = {
543        96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050,
544        16000, 12000, 11025, 8000
545    };
546    meta->setInt32(kKeySampleRate, kSamplingFreq[sampling_freq_index]);
547    meta->setInt32(kKeyChannelCount, channel_configuration);
548
549    static const uint8_t kStaticESDS[] = {
550        0x03, 22,
551        0x00, 0x00,     // ES_ID
552        0x00,           // streamDependenceFlag, URL_Flag, OCRstreamFlag
553
554        0x04, 17,
555        0x40,                       // Audio ISO/IEC 14496-3
556        0x00, 0x00, 0x00, 0x00,
557        0x00, 0x00, 0x00, 0x00,
558        0x00, 0x00, 0x00, 0x00,
559
560        0x05, 2,
561        // AudioSpecificInfo follows
562
563        // oooo offf fccc c000
564        // o - audioObjectType
565        // f - samplingFreqIndex
566        // c - channelConfig
567    };
568    sp<ABuffer> csd = new ABuffer(sizeof(kStaticESDS) + 2);
569    memcpy(csd->data(), kStaticESDS, sizeof(kStaticESDS));
570
571    csd->data()[sizeof(kStaticESDS)] =
572        ((profile + 1) << 3) | (sampling_freq_index >> 1);
573
574    csd->data()[sizeof(kStaticESDS) + 1] =
575        ((sampling_freq_index << 7) & 0x80) | (channel_configuration << 3);
576
577    meta->setData(kKeyESDS, 0, csd->data(), csd->size());
578
579    return meta;
580}
581
582bool ExtractDimensionsFromVOLHeader(
583        const uint8_t *data, size_t size, int32_t *width, int32_t *height) {
584    ABitReader br(&data[4], size - 4);
585    br.skipBits(1);  // random_accessible_vol
586    unsigned video_object_type_indication = br.getBits(8);
587
588    CHECK_NE(video_object_type_indication,
589             0x21u /* Fine Granularity Scalable */);
590
591    unsigned video_object_layer_verid __unused;
592    unsigned video_object_layer_priority __unused;
593    if (br.getBits(1)) {
594        video_object_layer_verid = br.getBits(4);
595        video_object_layer_priority = br.getBits(3);
596    }
597    unsigned aspect_ratio_info = br.getBits(4);
598    if (aspect_ratio_info == 0x0f /* extended PAR */) {
599        br.skipBits(8);  // par_width
600        br.skipBits(8);  // par_height
601    }
602    if (br.getBits(1)) {  // vol_control_parameters
603        br.skipBits(2);  // chroma_format
604        br.skipBits(1);  // low_delay
605        if (br.getBits(1)) {  // vbv_parameters
606            br.skipBits(15);  // first_half_bit_rate
607            CHECK(br.getBits(1));  // marker_bit
608            br.skipBits(15);  // latter_half_bit_rate
609            CHECK(br.getBits(1));  // marker_bit
610            br.skipBits(15);  // first_half_vbv_buffer_size
611            CHECK(br.getBits(1));  // marker_bit
612            br.skipBits(3);  // latter_half_vbv_buffer_size
613            br.skipBits(11);  // first_half_vbv_occupancy
614            CHECK(br.getBits(1));  // marker_bit
615            br.skipBits(15);  // latter_half_vbv_occupancy
616            CHECK(br.getBits(1));  // marker_bit
617        }
618    }
619    unsigned video_object_layer_shape = br.getBits(2);
620    CHECK_EQ(video_object_layer_shape, 0x00u /* rectangular */);
621
622    CHECK(br.getBits(1));  // marker_bit
623    unsigned vop_time_increment_resolution = br.getBits(16);
624    CHECK(br.getBits(1));  // marker_bit
625
626    if (br.getBits(1)) {  // fixed_vop_rate
627        // range [0..vop_time_increment_resolution)
628
629        // vop_time_increment_resolution
630        // 2 => 0..1, 1 bit
631        // 3 => 0..2, 2 bits
632        // 4 => 0..3, 2 bits
633        // 5 => 0..4, 3 bits
634        // ...
635
636        CHECK_GT(vop_time_increment_resolution, 0u);
637        --vop_time_increment_resolution;
638
639        unsigned numBits = 0;
640        while (vop_time_increment_resolution > 0) {
641            ++numBits;
642            vop_time_increment_resolution >>= 1;
643        }
644
645        br.skipBits(numBits);  // fixed_vop_time_increment
646    }
647
648    CHECK(br.getBits(1));  // marker_bit
649    unsigned video_object_layer_width = br.getBits(13);
650    CHECK(br.getBits(1));  // marker_bit
651    unsigned video_object_layer_height = br.getBits(13);
652    CHECK(br.getBits(1));  // marker_bit
653
654    unsigned interlaced __unused = br.getBits(1);
655
656    *width = video_object_layer_width;
657    *height = video_object_layer_height;
658
659    return true;
660}
661
662bool GetMPEGAudioFrameSize(
663        uint32_t header, size_t *frame_size,
664        int *out_sampling_rate, int *out_channels,
665        int *out_bitrate, int *out_num_samples) {
666    *frame_size = 0;
667
668    if (out_sampling_rate) {
669        *out_sampling_rate = 0;
670    }
671
672    if (out_channels) {
673        *out_channels = 0;
674    }
675
676    if (out_bitrate) {
677        *out_bitrate = 0;
678    }
679
680    if (out_num_samples) {
681        *out_num_samples = 1152;
682    }
683
684    if ((header & 0xffe00000) != 0xffe00000) {
685        return false;
686    }
687
688    unsigned version = (header >> 19) & 3;
689
690    if (version == 0x01) {
691        return false;
692    }
693
694    unsigned layer = (header >> 17) & 3;
695
696    if (layer == 0x00) {
697        return false;
698    }
699
700    unsigned protection __unused = (header >> 16) & 1;
701
702    unsigned bitrate_index = (header >> 12) & 0x0f;
703
704    if (bitrate_index == 0 || bitrate_index == 0x0f) {
705        // Disallow "free" bitrate.
706        return false;
707    }
708
709    unsigned sampling_rate_index = (header >> 10) & 3;
710
711    if (sampling_rate_index == 3) {
712        return false;
713    }
714
715    static const int kSamplingRateV1[] = { 44100, 48000, 32000 };
716    int sampling_rate = kSamplingRateV1[sampling_rate_index];
717    if (version == 2 /* V2 */) {
718        sampling_rate /= 2;
719    } else if (version == 0 /* V2.5 */) {
720        sampling_rate /= 4;
721    }
722
723    unsigned padding = (header >> 9) & 1;
724
725    if (layer == 3) {
726        // layer I
727
728        static const int kBitrateV1[] = {
729            32, 64, 96, 128, 160, 192, 224, 256,
730            288, 320, 352, 384, 416, 448
731        };
732
733        static const int kBitrateV2[] = {
734            32, 48, 56, 64, 80, 96, 112, 128,
735            144, 160, 176, 192, 224, 256
736        };
737
738        int bitrate =
739            (version == 3 /* V1 */)
740                ? kBitrateV1[bitrate_index - 1]
741                : kBitrateV2[bitrate_index - 1];
742
743        if (out_bitrate) {
744            *out_bitrate = bitrate;
745        }
746
747        *frame_size = (12000 * bitrate / sampling_rate + padding) * 4;
748
749        if (out_num_samples) {
750            *out_num_samples = 384;
751        }
752    } else {
753        // layer II or III
754
755        static const int kBitrateV1L2[] = {
756            32, 48, 56, 64, 80, 96, 112, 128,
757            160, 192, 224, 256, 320, 384
758        };
759
760        static const int kBitrateV1L3[] = {
761            32, 40, 48, 56, 64, 80, 96, 112,
762            128, 160, 192, 224, 256, 320
763        };
764
765        static const int kBitrateV2[] = {
766            8, 16, 24, 32, 40, 48, 56, 64,
767            80, 96, 112, 128, 144, 160
768        };
769
770        int bitrate;
771        if (version == 3 /* V1 */) {
772            bitrate = (layer == 2 /* L2 */)
773                ? kBitrateV1L2[bitrate_index - 1]
774                : kBitrateV1L3[bitrate_index - 1];
775
776            if (out_num_samples) {
777                *out_num_samples = 1152;
778            }
779        } else {
780            // V2 (or 2.5)
781
782            bitrate = kBitrateV2[bitrate_index - 1];
783            if (out_num_samples) {
784                *out_num_samples = (layer == 1 /* L3 */) ? 576 : 1152;
785            }
786        }
787
788        if (out_bitrate) {
789            *out_bitrate = bitrate;
790        }
791
792        if (version == 3 /* V1 */) {
793            *frame_size = 144000 * bitrate / sampling_rate + padding;
794        } else {
795            // V2 or V2.5
796            size_t tmp = (layer == 1 /* L3 */) ? 72000 : 144000;
797            *frame_size = tmp * bitrate / sampling_rate + padding;
798        }
799    }
800
801    if (out_sampling_rate) {
802        *out_sampling_rate = sampling_rate;
803    }
804
805    if (out_channels) {
806        int channel_mode = (header >> 6) & 3;
807
808        *out_channels = (channel_mode == 3) ? 1 : 2;
809    }
810
811    return true;
812}
813
814}  // namespace android
815
816