1/*
2 * MPEG-4 Audio common code
3 * Copyright (c) 2008 Baptiste Coudurier <baptiste.coudurier@free.fr>
4 *
5 * This file is part of FFmpeg.
6 *
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22#include "bitstream.h"
23#include "mpeg4audio.h"
24
25const int ff_mpeg4audio_sample_rates[16] = {
26    96000, 88200, 64000, 48000, 44100, 32000,
27    24000, 22050, 16000, 12000, 11025, 8000, 7350
28};
29
30const uint8_t ff_mpeg4audio_channels[8] = {
31    0, 1, 2, 3, 4, 5, 6, 8
32};
33
34static inline int get_object_type(GetBitContext *gb)
35{
36    int object_type = get_bits(gb, 5);
37    if (object_type == 31)
38        object_type = 32 + get_bits(gb, 6);
39    return object_type;
40}
41
42static inline int get_sample_rate(GetBitContext *gb, int *index)
43{
44    *index = get_bits(gb, 4);
45    return *index == 0x0f ? get_bits(gb, 24) :
46        ff_mpeg4audio_sample_rates[*index];
47}
48
49int ff_mpeg4audio_get_config(MPEG4AudioConfig *c, const uint8_t *buf, int buf_size)
50{
51    GetBitContext gb;
52    int specific_config_bitindex;
53
54    init_get_bits(&gb, buf, buf_size*8);
55    c->object_type = get_object_type(&gb);
56    c->sample_rate = get_sample_rate(&gb, &c->sampling_index);
57    c->chan_config = get_bits(&gb, 4);
58    c->sbr = -1;
59    if (c->object_type == 5) {
60        c->ext_object_type = c->object_type;
61        c->sbr = 1;
62        c->ext_sample_rate = get_sample_rate(&gb, &c->ext_sampling_index);
63        c->object_type = get_object_type(&gb);
64    } else
65        c->ext_object_type = 0;
66
67    specific_config_bitindex = get_bits_count(&gb);
68
69    if (c->ext_object_type != 5) {
70        int bits_left = buf_size*8 - specific_config_bitindex;
71        for (; bits_left > 15; bits_left--) {
72            if (show_bits(&gb, 11) == 0x2b7) { // sync extension
73                get_bits(&gb, 11);
74                c->ext_object_type = get_object_type(&gb);
75                if (c->ext_object_type == 5 && (c->sbr = get_bits1(&gb)) == 1)
76                    c->ext_sample_rate = get_sample_rate(&gb, &c->ext_sampling_index);
77                break;
78            } else
79                get_bits1(&gb); // skip 1 bit
80        }
81    }
82    return specific_config_bitindex;
83}
84