1/*
2 * Musepack SV8 demuxer
3 * Copyright (c) 2007 Konstantin Shishkov
4 *
5 * This file is part of Libav.
6 *
7 * Libav 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 * Libav 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 Libav; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22#include "libavcodec/get_bits.h"
23#include "libavcodec/unary.h"
24#include "avformat.h"
25#include "internal.h"
26#include "avio_internal.h"
27
28/// Two-byte MPC tag
29#define MKMPCTAG(a, b) (a | (b << 8))
30
31#define TAG_MPCK MKTAG('M','P','C','K')
32
33/// Reserved MPC tags
34enum MPCPacketTags{
35    TAG_STREAMHDR   = MKMPCTAG('S','H'),
36    TAG_STREAMEND   = MKMPCTAG('S','E'),
37
38    TAG_AUDIOPACKET = MKMPCTAG('A','P'),
39
40    TAG_SEEKTBLOFF  = MKMPCTAG('S','O'),
41    TAG_SEEKTABLE   = MKMPCTAG('S','T'),
42
43    TAG_REPLAYGAIN  = MKMPCTAG('R','G'),
44    TAG_ENCINFO     = MKMPCTAG('E','I'),
45};
46
47static const int mpc8_rate[8] = { 44100, 48000, 37800, 32000, -1, -1, -1, -1 };
48
49typedef struct {
50    int ver;
51    int frame;
52    int64_t header_pos;
53    int64_t samples;
54} MPCContext;
55
56static inline int64_t bs_get_v(uint8_t **bs)
57{
58    int64_t v = 0;
59    int br = 0;
60    int c;
61
62    do {
63        c = **bs; (*bs)++;
64        v <<= 7;
65        v |= c & 0x7F;
66        br++;
67        if (br > 10)
68            return -1;
69    } while (c & 0x80);
70
71    return v - br;
72}
73
74static int mpc8_probe(AVProbeData *p)
75{
76    uint8_t *bs = p->buf + 4;
77    uint8_t *bs_end = bs + p->buf_size;
78    int64_t size;
79
80    if (p->buf_size < 16)
81        return 0;
82    if (AV_RL32(p->buf) != TAG_MPCK)
83        return 0;
84    while (bs < bs_end + 3) {
85        int header_found = (bs[0] == 'S' && bs[1] == 'H');
86        if (bs[0] < 'A' || bs[0] > 'Z' || bs[1] < 'A' || bs[1] > 'Z')
87            return 0;
88        bs += 2;
89        size = bs_get_v(&bs);
90        if (size < 2)
91            return 0;
92        if (bs + size - 2 >= bs_end)
93            return AVPROBE_SCORE_MAX / 4 - 1; //seems to be valid MPC but no header yet
94        if (header_found) {
95            if (size < 11 || size > 28)
96                return 0;
97            if (!AV_RL32(bs)) //zero CRC is invalid
98                return 0;
99            return AVPROBE_SCORE_MAX;
100        } else {
101            bs += size - 2;
102        }
103    }
104    return 0;
105}
106
107static inline int64_t gb_get_v(GetBitContext *gb)
108{
109    int64_t v = 0;
110    int bits = 0;
111    while(get_bits1(gb) && bits < 64-7){
112        v <<= 7;
113        v |= get_bits(gb, 7);
114        bits += 7;
115    }
116    v <<= 7;
117    v |= get_bits(gb, 7);
118
119    return v;
120}
121
122static void mpc8_get_chunk_header(AVIOContext *pb, int *tag, int64_t *size)
123{
124    int64_t pos;
125    pos = avio_tell(pb);
126    *tag = avio_rl16(pb);
127    *size = ffio_read_varlen(pb);
128    *size -= avio_tell(pb) - pos;
129}
130
131static void mpc8_parse_seektable(AVFormatContext *s, int64_t off)
132{
133    MPCContext *c = s->priv_data;
134    int tag;
135    int64_t size, pos, ppos[2];
136    uint8_t *buf;
137    int i, t, seekd;
138    GetBitContext gb;
139
140    avio_seek(s->pb, off, SEEK_SET);
141    mpc8_get_chunk_header(s->pb, &tag, &size);
142    if(tag != TAG_SEEKTABLE){
143        av_log(s, AV_LOG_ERROR, "No seek table at given position\n");
144        return;
145    }
146    if(!(buf = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE)))
147        return;
148    avio_read(s->pb, buf, size);
149    init_get_bits(&gb, buf, size * 8);
150    size = gb_get_v(&gb);
151    if(size > UINT_MAX/4 || size > c->samples/1152){
152        av_log(s, AV_LOG_ERROR, "Seek table is too big\n");
153        return;
154    }
155    seekd = get_bits(&gb, 4);
156    for(i = 0; i < 2; i++){
157        pos = gb_get_v(&gb) + c->header_pos;
158        ppos[1 - i] = pos;
159        av_add_index_entry(s->streams[0], pos, i, 0, 0, AVINDEX_KEYFRAME);
160    }
161    for(; i < size; i++){
162        t = get_unary(&gb, 1, 33) << 12;
163        t += get_bits(&gb, 12);
164        if(t & 1)
165            t = -(t & ~1);
166        pos = (t >> 1) + ppos[0]*2 - ppos[1];
167        av_add_index_entry(s->streams[0], pos, i << seekd, 0, 0, AVINDEX_KEYFRAME);
168        ppos[1] = ppos[0];
169        ppos[0] = pos;
170    }
171    av_free(buf);
172}
173
174static void mpc8_handle_chunk(AVFormatContext *s, int tag, int64_t chunk_pos, int64_t size)
175{
176    AVIOContext *pb = s->pb;
177    int64_t pos, off;
178
179    switch(tag){
180    case TAG_SEEKTBLOFF:
181        pos = avio_tell(pb) + size;
182        off = ffio_read_varlen(pb);
183        mpc8_parse_seektable(s, chunk_pos + off);
184        avio_seek(pb, pos, SEEK_SET);
185        break;
186    default:
187        avio_skip(pb, size);
188    }
189}
190
191static int mpc8_read_header(AVFormatContext *s, AVFormatParameters *ap)
192{
193    MPCContext *c = s->priv_data;
194    AVIOContext *pb = s->pb;
195    AVStream *st;
196    int tag = 0;
197    int64_t size, pos;
198
199    c->header_pos = avio_tell(pb);
200    if(avio_rl32(pb) != TAG_MPCK){
201        av_log(s, AV_LOG_ERROR, "Not a Musepack8 file\n");
202        return -1;
203    }
204
205    while(!pb->eof_reached){
206        pos = avio_tell(pb);
207        mpc8_get_chunk_header(pb, &tag, &size);
208        if(tag == TAG_STREAMHDR)
209            break;
210        mpc8_handle_chunk(s, tag, pos, size);
211    }
212    if(tag != TAG_STREAMHDR){
213        av_log(s, AV_LOG_ERROR, "Stream header not found\n");
214        return -1;
215    }
216    pos = avio_tell(pb);
217    avio_skip(pb, 4); //CRC
218    c->ver = avio_r8(pb);
219    if(c->ver != 8){
220        av_log(s, AV_LOG_ERROR, "Unknown stream version %d\n", c->ver);
221        return -1;
222    }
223    c->samples = ffio_read_varlen(pb);
224    ffio_read_varlen(pb); //silence samples at the beginning
225
226    st = avformat_new_stream(s, NULL);
227    if (!st)
228        return AVERROR(ENOMEM);
229    st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
230    st->codec->codec_id = CODEC_ID_MUSEPACK8;
231    st->codec->bits_per_coded_sample = 16;
232
233    st->codec->extradata_size = 2;
234    st->codec->extradata = av_mallocz(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
235    avio_read(pb, st->codec->extradata, st->codec->extradata_size);
236
237    st->codec->channels = (st->codec->extradata[1] >> 4) + 1;
238    st->codec->sample_rate = mpc8_rate[st->codec->extradata[0] >> 5];
239    avpriv_set_pts_info(st, 32, 1152  << (st->codec->extradata[1]&3)*2, st->codec->sample_rate);
240    st->duration = c->samples / (1152 << (st->codec->extradata[1]&3)*2);
241    size -= avio_tell(pb) - pos;
242
243    return 0;
244}
245
246static int mpc8_read_packet(AVFormatContext *s, AVPacket *pkt)
247{
248    MPCContext *c = s->priv_data;
249    int tag;
250    int64_t pos, size;
251
252    while(!s->pb->eof_reached){
253        pos = avio_tell(s->pb);
254        mpc8_get_chunk_header(s->pb, &tag, &size);
255        if (size < 0)
256            return -1;
257        if(tag == TAG_AUDIOPACKET){
258            if(av_get_packet(s->pb, pkt, size) < 0)
259                return AVERROR(ENOMEM);
260            pkt->stream_index = 0;
261            pkt->pts = c->frame;
262            return 0;
263        }
264        if(tag == TAG_STREAMEND)
265            return AVERROR(EIO);
266        mpc8_handle_chunk(s, tag, pos, size);
267    }
268    return AVERROR_EOF;
269}
270
271static int mpc8_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
272{
273    AVStream *st = s->streams[stream_index];
274    MPCContext *c = s->priv_data;
275    int index = av_index_search_timestamp(st, timestamp, flags);
276
277    if(index < 0) return -1;
278    avio_seek(s->pb, st->index_entries[index].pos, SEEK_SET);
279    c->frame = st->index_entries[index].timestamp;
280    return 0;
281}
282
283
284AVInputFormat ff_mpc8_demuxer = {
285    .name           = "mpc8",
286    .long_name      = NULL_IF_CONFIG_SMALL("Musepack SV8"),
287    .priv_data_size = sizeof(MPCContext),
288    .read_probe     = mpc8_probe,
289    .read_header    = mpc8_read_header,
290    .read_packet    = mpc8_read_packet,
291    .read_seek      = mpc8_read_seek,
292};
293