1/*
2 * Copyright (c) 2012 Andrew D'Addesio
3 * Copyright (c) 2013-2014 Mozilla Corporation
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/**
23 * @file
24 * Opus decoder/parser shared code
25 */
26
27#include <stdint.h>
28
29#include "libavutil/error.h"
30
31#include "opus.h"
32#include "vorbis.h"
33
34static const uint16_t opus_frame_duration[32] = {
35    480, 960, 1920, 2880,
36    480, 960, 1920, 2880,
37    480, 960, 1920, 2880,
38    480, 960,
39    480, 960,
40    120, 240,  480,  960,
41    120, 240,  480,  960,
42    120, 240,  480,  960,
43    120, 240,  480,  960,
44};
45
46/**
47 * Read a 1- or 2-byte frame length
48 */
49static inline int xiph_lacing_16bit(const uint8_t **ptr, const uint8_t *end)
50{
51    int val;
52
53    if (*ptr >= end)
54        return AVERROR_INVALIDDATA;
55    val = *(*ptr)++;
56    if (val >= 252) {
57        if (*ptr >= end)
58            return AVERROR_INVALIDDATA;
59        val += 4 * *(*ptr)++;
60    }
61    return val;
62}
63
64/**
65 * Read a multi-byte length (used for code 3 packet padding size)
66 */
67static inline int xiph_lacing_full(const uint8_t **ptr, const uint8_t *end)
68{
69    int val = 0;
70    int next;
71
72    while (1) {
73        if (*ptr >= end || val > INT_MAX - 254)
74            return AVERROR_INVALIDDATA;
75        next = *(*ptr)++;
76        val += next;
77        if (next < 255)
78            break;
79        else
80            val--;
81    }
82    return val;
83}
84
85/**
86 * Parse Opus packet info from raw packet data
87 */
88int ff_opus_parse_packet(OpusPacket *pkt, const uint8_t *buf, int buf_size,
89                         int self_delimiting)
90{
91    const uint8_t *ptr = buf;
92    const uint8_t *end = buf + buf_size;
93    int padding = 0;
94    int frame_bytes, i;
95
96    if (buf_size < 1)
97        goto fail;
98
99    /* TOC byte */
100    i = *ptr++;
101    pkt->code   = (i     ) & 0x3;
102    pkt->stereo = (i >> 2) & 0x1;
103    pkt->config = (i >> 3) & 0x1F;
104
105    /* code 2 and code 3 packets have at least 1 byte after the TOC */
106    if (pkt->code >= 2 && buf_size < 2)
107        goto fail;
108
109    switch (pkt->code) {
110    case 0:
111        /* 1 frame */
112        pkt->frame_count = 1;
113        pkt->vbr         = 0;
114
115        if (self_delimiting) {
116            int len = xiph_lacing_16bit(&ptr, end);
117            if (len < 0 || len > end - ptr)
118                goto fail;
119            end      = ptr + len;
120            buf_size = end - buf;
121        }
122
123        frame_bytes = end - ptr;
124        if (frame_bytes > MAX_FRAME_SIZE)
125            goto fail;
126        pkt->frame_offset[0] = ptr - buf;
127        pkt->frame_size[0]   = frame_bytes;
128        break;
129    case 1:
130        /* 2 frames, equal size */
131        pkt->frame_count = 2;
132        pkt->vbr         = 0;
133
134        if (self_delimiting) {
135            int len = xiph_lacing_16bit(&ptr, end);
136            if (len < 0 || 2 * len > end - ptr)
137                goto fail;
138            end      = ptr + 2 * len;
139            buf_size = end - buf;
140        }
141
142        frame_bytes = end - ptr;
143        if (frame_bytes & 1 || frame_bytes >> 1 > MAX_FRAME_SIZE)
144            goto fail;
145        pkt->frame_offset[0] = ptr - buf;
146        pkt->frame_size[0]   = frame_bytes >> 1;
147        pkt->frame_offset[1] = pkt->frame_offset[0] + pkt->frame_size[0];
148        pkt->frame_size[1]   = frame_bytes >> 1;
149        break;
150    case 2:
151        /* 2 frames, different sizes */
152        pkt->frame_count = 2;
153        pkt->vbr         = 1;
154
155        /* read 1st frame size */
156        frame_bytes = xiph_lacing_16bit(&ptr, end);
157        if (frame_bytes < 0)
158            goto fail;
159
160        if (self_delimiting) {
161            int len = xiph_lacing_16bit(&ptr, end);
162            if (len < 0 || len + frame_bytes > end - ptr)
163                goto fail;
164            end      = ptr + frame_bytes + len;
165            buf_size = end - buf;
166        }
167
168        pkt->frame_offset[0] = ptr - buf;
169        pkt->frame_size[0]   = frame_bytes;
170
171        /* calculate 2nd frame size */
172        frame_bytes = end - ptr - pkt->frame_size[0];
173        if (frame_bytes < 0 || frame_bytes > MAX_FRAME_SIZE)
174            goto fail;
175        pkt->frame_offset[1] = pkt->frame_offset[0] + pkt->frame_size[0];
176        pkt->frame_size[1]   = frame_bytes;
177        break;
178    case 3:
179        /* 1 to 48 frames, can be different sizes */
180        i = *ptr++;
181        pkt->frame_count = (i     ) & 0x3F;
182        padding          = (i >> 6) & 0x01;
183        pkt->vbr         = (i >> 7) & 0x01;
184
185        if (pkt->frame_count == 0 || pkt->frame_count > MAX_FRAMES)
186            goto fail;
187
188        /* read padding size */
189        if (padding) {
190            padding = xiph_lacing_full(&ptr, end);
191            if (padding < 0)
192                goto fail;
193        }
194
195        /* read frame sizes */
196        if (pkt->vbr) {
197            /* for VBR, all frames except the final one have their size coded
198               in the bitstream. the last frame size is implicit. */
199            int total_bytes = 0;
200            for (i = 0; i < pkt->frame_count - 1; i++) {
201                frame_bytes = xiph_lacing_16bit(&ptr, end);
202                if (frame_bytes < 0)
203                    goto fail;
204                pkt->frame_size[i] = frame_bytes;
205                total_bytes += frame_bytes;
206            }
207
208            if (self_delimiting) {
209                int len = xiph_lacing_16bit(&ptr, end);
210                if (len < 0 || len + total_bytes + padding > end - ptr)
211                    goto fail;
212                end      = ptr + total_bytes + len + padding;
213                buf_size = end - buf;
214            }
215
216            frame_bytes = end - ptr - padding;
217            if (total_bytes > frame_bytes)
218                goto fail;
219            pkt->frame_offset[0] = ptr - buf;
220            for (i = 1; i < pkt->frame_count; i++)
221                pkt->frame_offset[i] = pkt->frame_offset[i-1] + pkt->frame_size[i-1];
222            pkt->frame_size[pkt->frame_count-1] = frame_bytes - total_bytes;
223        } else {
224            /* for CBR, the remaining packet bytes are divided evenly between
225               the frames */
226            if (self_delimiting) {
227                frame_bytes = xiph_lacing_16bit(&ptr, end);
228                if (frame_bytes < 0 || pkt->frame_count * frame_bytes + padding > end - ptr)
229                    goto fail;
230                end      = ptr + pkt->frame_count * frame_bytes + padding;
231                buf_size = end - buf;
232            } else {
233                frame_bytes = end - ptr - padding;
234                if (frame_bytes % pkt->frame_count ||
235                    frame_bytes / pkt->frame_count > MAX_FRAME_SIZE)
236                    goto fail;
237                frame_bytes /= pkt->frame_count;
238            }
239
240            pkt->frame_offset[0] = ptr - buf;
241            pkt->frame_size[0]   = frame_bytes;
242            for (i = 1; i < pkt->frame_count; i++) {
243                pkt->frame_offset[i] = pkt->frame_offset[i-1] + pkt->frame_size[i-1];
244                pkt->frame_size[i]   = frame_bytes;
245            }
246        }
247    }
248
249    pkt->packet_size = buf_size;
250    pkt->data_size   = pkt->packet_size - padding;
251
252    /* total packet duration cannot be larger than 120ms */
253    pkt->frame_duration = opus_frame_duration[pkt->config];
254    if (pkt->frame_duration * pkt->frame_count > MAX_PACKET_DUR)
255        goto fail;
256
257    /* set mode and bandwidth */
258    if (pkt->config < 12) {
259        pkt->mode = OPUS_MODE_SILK;
260        pkt->bandwidth = pkt->config >> 2;
261    } else if (pkt->config < 16) {
262        pkt->mode = OPUS_MODE_HYBRID;
263        pkt->bandwidth = OPUS_BANDWIDTH_SUPERWIDEBAND + (pkt->config >= 14);
264    } else {
265        pkt->mode = OPUS_MODE_CELT;
266        pkt->bandwidth = (pkt->config - 16) >> 2;
267        /* skip mediumband */
268        if (pkt->bandwidth)
269            pkt->bandwidth++;
270    }
271
272    return 0;
273
274fail:
275    memset(pkt, 0, sizeof(*pkt));
276    return AVERROR_INVALIDDATA;
277}
278
279static int channel_reorder_vorbis(int nb_channels, int channel_idx)
280{
281    return ff_vorbis_channel_layout_offsets[nb_channels - 1][channel_idx];
282}
283
284static int channel_reorder_unknown(int nb_channels, int channel_idx)
285{
286    return channel_idx;
287}
288
289av_cold int ff_opus_parse_extradata(AVCodecContext *avctx,
290                                    OpusContext *s)
291{
292    static const uint8_t default_channel_map[2] = { 0, 1 };
293    uint8_t default_extradata[19] = {
294        'O', 'p', 'u', 's', 'H', 'e', 'a', 'd',
295        1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
296    };
297
298    int (*channel_reorder)(int, int) = channel_reorder_unknown;
299
300    const uint8_t *extradata, *channel_map;
301    int extradata_size;
302    int version, channels, map_type, streams, stereo_streams, i, j;
303    uint64_t layout;
304
305    if (!avctx->extradata) {
306        if (avctx->channels > 2) {
307            av_log(avctx, AV_LOG_ERROR,
308                   "Multichannel configuration without extradata.\n");
309            return AVERROR(EINVAL);
310        }
311        default_extradata[9] = (avctx->channels == 1) ? 1 : 2;
312        extradata      = default_extradata;
313        extradata_size = sizeof(default_extradata);
314    } else {
315        extradata = avctx->extradata;
316        extradata_size = avctx->extradata_size;
317    }
318
319    if (extradata_size < 19) {
320        av_log(avctx, AV_LOG_ERROR, "Invalid extradata size: %d\n",
321               extradata_size);
322        return AVERROR_INVALIDDATA;
323    }
324
325    version = extradata[8];
326    if (version > 15) {
327        avpriv_request_sample(avctx, "Extradata version %d", version);
328        return AVERROR_PATCHWELCOME;
329    }
330
331    avctx->delay = AV_RL16(extradata + 10);
332
333    channels = extradata[9];
334    if (!channels) {
335        av_log(avctx, AV_LOG_ERROR, "Zero channel count specified in the extadata\n");
336        return AVERROR_INVALIDDATA;
337    }
338
339    s->gain_i = AV_RL16(extradata + 16);
340    if (s->gain_i)
341        s->gain = pow(10, s->gain_i / (20.0 * 256));
342
343    map_type = extradata[18];
344    if (!map_type) {
345        if (channels > 2) {
346            av_log(avctx, AV_LOG_ERROR,
347                   "Channel mapping 0 is only specified for up to 2 channels\n");
348            return AVERROR_INVALIDDATA;
349        }
350        layout         = (channels == 1) ? AV_CH_LAYOUT_MONO : AV_CH_LAYOUT_STEREO;
351        streams        = 1;
352        stereo_streams = channels - 1;
353        channel_map    = default_channel_map;
354    } else if (map_type == 1 || map_type == 255) {
355        if (extradata_size < 21 + channels) {
356            av_log(avctx, AV_LOG_ERROR, "Invalid extradata size: %d\n",
357                   extradata_size);
358            return AVERROR_INVALIDDATA;
359        }
360
361        streams        = extradata[19];
362        stereo_streams = extradata[20];
363        if (!streams || stereo_streams > streams ||
364            streams + stereo_streams > 255) {
365            av_log(avctx, AV_LOG_ERROR,
366                   "Invalid stream/stereo stream count: %d/%d\n", streams, stereo_streams);
367            return AVERROR_INVALIDDATA;
368        }
369
370        if (map_type == 1) {
371            if (channels > 8) {
372                av_log(avctx, AV_LOG_ERROR,
373                       "Channel mapping 1 is only specified for up to 8 channels\n");
374                return AVERROR_INVALIDDATA;
375            }
376            layout = ff_vorbis_channel_layouts[channels - 1];
377            channel_reorder = channel_reorder_vorbis;
378        } else
379            layout = 0;
380
381        channel_map = extradata + 21;
382    } else {
383        avpriv_request_sample(avctx, "Mapping type %d", map_type);
384        return AVERROR_PATCHWELCOME;
385    }
386
387    s->channel_maps = av_mallocz_array(channels, sizeof(*s->channel_maps));
388    if (!s->channel_maps)
389        return AVERROR(ENOMEM);
390
391    for (i = 0; i < channels; i++) {
392        ChannelMap *map = &s->channel_maps[i];
393        uint8_t     idx = channel_map[channel_reorder(channels, i)];
394
395        if (idx == 255) {
396            map->silence = 1;
397            continue;
398        } else if (idx >= streams + stereo_streams) {
399            av_log(avctx, AV_LOG_ERROR,
400                   "Invalid channel map for output channel %d: %d\n", i, idx);
401            return AVERROR_INVALIDDATA;
402        }
403
404        /* check that we din't see this index yet */
405        map->copy = 0;
406        for (j = 0; j < i; j++)
407            if (channel_map[channel_reorder(channels, j)] == idx) {
408                map->copy     = 1;
409                map->copy_idx = j;
410                break;
411            }
412
413        if (idx < 2 * stereo_streams) {
414            map->stream_idx  = idx / 2;
415            map->channel_idx = idx & 1;
416        } else {
417            map->stream_idx  = idx - stereo_streams;
418            map->channel_idx = 0;
419        }
420    }
421
422    avctx->channels       = channels;
423    avctx->channel_layout = layout;
424    s->nb_streams         = streams;
425    s->nb_stereo_streams  = stereo_streams;
426
427    return 0;
428}
429