oggparsevorbis: support official chapter extension
[libav.git] / libavformat / oggparsevorbis.c
CommitLineData
49fe9c05
VG
1/*
2 * Copyright (C) 2005 Michael Ahlberg, Måns Rullgård
3 *
4 * Permission is hereby granted, free of charge, to any person
5 * obtaining a copy of this software and associated documentation
6 * files (the "Software"), to deal in the Software without
7 * restriction, including without limitation the rights to use, copy,
8 * modify, merge, publish, distribute, sublicense, and/or sell copies
9 * of the Software, and to permit persons to whom the Software is
10 * furnished to do so, subject to the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
19 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
20 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22 * DEALINGS IN THE SOFTWARE.
23 */
9146ca37
MR
24
25#include <stdlib.h>
49fe9c05 26
245976da
DB
27#include "libavutil/avstring.h"
28#include "libavutil/bswap.h"
d2d67e42 29#include "libavutil/dict.h"
245976da 30#include "libavcodec/bytestream.h"
49fe9c05 31#include "libavcodec/get_bits.h"
f63412fc 32#include "libavcodec/vorbis_parser.h"
9146ca37 33#include "avformat.h"
19711af5 34#include "internal.h"
a0ddef24 35#include "oggdec.h"
fb66c31d 36#include "vorbiscomment.h"
9146ca37 37
8730fad5
DC
38static int ogm_chapter(AVFormatContext *as, uint8_t *key, uint8_t *val)
39{
40 int i, cnum, h, m, s, ms, keylen = strlen(key);
41 AVChapter *chapter = NULL;
42
9c15ef35 43 if (keylen < 9 || sscanf(key, "CHAPTER%03d", &cnum) != 1)
8730fad5
DC
44 return 0;
45
9c15ef35 46 if (keylen <= 10) {
8730fad5
DC
47 if (sscanf(val, "%02d:%02d:%02d.%03d", &h, &m, &s, &ms) < 4)
48 return 0;
49
49fe9c05
VG
50 avpriv_new_chapter(as, cnum, (AVRational) { 1, 1000 },
51 ms + 1000 * (s + 60 * (m + 60 * h)),
52 AV_NOPTS_VALUE, NULL);
8730fad5 53 av_free(val);
9c15ef35 54 } else if (!strcmp(key + keylen - 4, "NAME")) {
49fe9c05 55 for (i = 0; i < as->nb_chapters; i++)
8730fad5
DC
56 if (as->chapters[i]->id == cnum) {
57 chapter = as->chapters[i];
58 break;
59 }
60 if (!chapter)
61 return 0;
62
49fe9c05 63 av_dict_set(&chapter->metadata, "title", val, AV_DICT_DONT_STRDUP_VAL);
8730fad5
DC
64 } else
65 return 0;
66
67 av_free(key);
68 return 1;
69}
70
49fe9c05
VG
71int ff_vorbis_comment(AVFormatContext *as, AVDictionary **m,
72 const uint8_t *buf, int size)
9146ca37 73{
49fe9c05 74 const uint8_t *p = buf;
47a0513b 75 const uint8_t *end = buf + size;
98422c44
RD
76 unsigned n, j;
77 int s;
9146ca37 78
49fe9c05
VG
79 /* must have vendor_length and user_comment_list_length */
80 if (size < 8)
90e15e34 81 return AVERROR_INVALIDDATA;
9146ca37 82
0a770ae7 83 s = bytestream_get_le32(&p);
9146ca37 84
98422c44 85 if (end - p - 4 < s || s < 0)
90e15e34 86 return AVERROR_INVALIDDATA;
9146ca37
MR
87
88 p += s;
9146ca37 89
0a770ae7 90 n = bytestream_get_le32(&p);
9146ca37 91
98422c44 92 while (end - p >= 4 && n > 0) {
47a0513b 93 const char *t, *v;
9146ca37
MR
94 int tl, vl;
95
0a770ae7 96 s = bytestream_get_le32(&p);
9146ca37 97
98422c44 98 if (end - p < s || s < 0)
9146ca37
MR
99 break;
100
49fe9c05 101 t = p;
9146ca37 102 p += s;
9146ca37
MR
103 n--;
104
4bd684bc 105 v = memchr(t, '=', s);
9146ca37
MR
106 if (!v)
107 continue;
108
109 tl = v - t;
110 vl = s - tl - 1;
111 v++;
112
4bd684bc 113 if (tl && vl) {
e3b44649
JR
114 char *tt, *ct;
115
116 tt = av_malloc(tl + 1);
117 ct = av_malloc(vl + 1);
118 if (!tt || !ct) {
119 av_freep(&tt);
120 av_freep(&ct);
49fe9c05
VG
121 av_log(as, AV_LOG_WARNING,
122 "out-of-memory error. skipping VorbisComment tag.\n");
e3b44649
JR
123 continue;
124 }
9146ca37
MR
125
126 for (j = 0; j < tl; j++)
efa7f420 127 tt[j] = av_toupper(t[j]);
9146ca37
MR
128 tt[tl] = 0;
129
4bd684bc 130 memcpy(ct, v, vl);
9146ca37
MR
131 ct[vl] = 0;
132
8730fad5 133 if (!ogm_chapter(as, tt, ct))
d2d67e42 134 av_dict_set(m, tt, ct,
49fe9c05
VG
135 AV_DICT_DONT_STRDUP_KEY |
136 AV_DICT_DONT_STRDUP_VAL);
9146ca37
MR
137 }
138 }
139
972c5f9e 140 if (p != end)
49fe9c05
VG
141 av_log(as, AV_LOG_INFO,
142 "%ti bytes of comment header remain\n", end - p);
9146ca37 143 if (n > 0)
4bd684bc
MR
144 av_log(as, AV_LOG_INFO,
145 "truncated comment header, %i comments not found\n", n);
9146ca37 146
ad7768f4 147 ff_metadata_conv(m, NULL, ff_vorbiscomment_metadata_conv);
03700d39 148
9146ca37
MR
149 return 0;
150}
151
49fe9c05
VG
152/*
153 * Parse the vorbis header
154 *
9146ca37
MR
155 * Vorbis Identification header from Vorbis_I_spec.html#vorbis-spec-codec
156 * [vorbis_version] = read 32 bits as unsigned integer | Not used
157 * [audio_channels] = read 8 bit integer as unsigned | Used
115329f1 158 * [audio_sample_rate] = read 32 bits as unsigned integer | Used
9146ca37
MR
159 * [bitrate_maximum] = read 32 bits as signed integer | Not used yet
160 * [bitrate_nominal] = read 32 bits as signed integer | Not used yet
161 * [bitrate_minimum] = read 32 bits as signed integer | Used as bitrate
162 * [blocksize_0] = read 4 bits as unsigned integer | Not Used
163 * [blocksize_1] = read 4 bits as unsigned integer | Not Used
164 * [framing_flag] = read one bit | Not Used
49fe9c05 165 */
9146ca37 166
77be08ee 167struct oggvorbis_private {
ad2b531d
MR
168 unsigned int len[3];
169 unsigned char *packet[3];
f63412fc
JR
170 VorbisParseContext vp;
171 int64_t final_pts;
172 int final_duration;
77be08ee 173};
ad2b531d 174
49fe9c05
VG
175static unsigned int fixup_vorbis_headers(AVFormatContext *as,
176 struct oggvorbis_private *priv,
177 uint8_t **buf)
ad2b531d 178{
5626f994 179 int i, offset, len, err;
ad2b531d
MR
180 unsigned char *ptr;
181
182 len = priv->len[0] + priv->len[1] + priv->len[2];
49fe9c05 183 ptr = *buf = av_mallocz(len + len / 255 + 64);
ad2b531d 184
49fe9c05
VG
185 ptr[0] = 2;
186 offset = 1;
ad2b531d
MR
187 offset += av_xiphlacing(&ptr[offset], priv->len[0]);
188 offset += av_xiphlacing(&ptr[offset], priv->len[1]);
4bd684bc 189 for (i = 0; i < 3; i++) {
ad2b531d
MR
190 memcpy(&ptr[offset], priv->packet[i], priv->len[i]);
191 offset += priv->len[i];
2ac41150 192 av_freep(&priv->packet[i]);
ad2b531d 193 }
5626f994
AK
194 if ((err = av_reallocp(buf, offset + FF_INPUT_BUFFER_PADDING_SIZE)) < 0)
195 return err;
ad2b531d
MR
196 return offset;
197}
198
fba8e5b6 199static void vorbis_cleanup(AVFormatContext *s, int idx)
d894f747
LB
200{
201 struct ogg *ogg = s->priv_data;
202 struct ogg_stream *os = ogg->streams + idx;
203 struct oggvorbis_private *priv = os->private;
204 int i;
205 if (os->private)
206 for (i = 0; i < 3; i++)
207 av_freep(&priv->packet[i]);
208}
ad2b531d 209
49fe9c05 210static int vorbis_header(AVFormatContext *s, int idx)
9146ca37 211{
77be08ee 212 struct ogg *ogg = s->priv_data;
49fe9c05 213 AVStream *st = s->streams[idx];
77be08ee 214 struct ogg_stream *os = ogg->streams + idx;
77be08ee 215 struct oggvorbis_private *priv;
8f8320d7 216 int pkt_type = os->buf[os->pstart];
9146ca37 217
8f8320d7 218 if (!os->private) {
77be08ee 219 os->private = av_mallocz(sizeof(struct oggvorbis_private));
4bd684bc 220 if (!os->private)
90e15e34 221 return AVERROR(ENOMEM);
ad2b531d 222 }
9146ca37 223
3562684d
LB
224 if (!(pkt_type & 1))
225 return 0;
226
8f8320d7 227 if (os->psize < 1 || pkt_type > 5)
90e15e34 228 return AVERROR_INVALIDDATA;
f5475e1b 229
ad2b531d 230 priv = os->private;
73c44cb2 231
49fe9c05 232 if (priv->packet[pkt_type >> 1])
90e15e34 233 return AVERROR_INVALIDDATA;
73c44cb2 234 if (pkt_type > 1 && !priv->packet[0] || pkt_type > 3 && !priv->packet[1])
90e15e34 235 return AVERROR_INVALIDDATA;
73c44cb2 236
49fe9c05 237 priv->len[pkt_type >> 1] = os->psize;
8f8320d7
DC
238 priv->packet[pkt_type >> 1] = av_mallocz(os->psize);
239 memcpy(priv->packet[pkt_type >> 1], os->buf + os->pstart, os->psize);
9146ca37 240 if (os->buf[os->pstart] == 1) {
47a0513b 241 const uint8_t *p = os->buf + os->pstart + 7; /* skip "\001vorbis" tag */
736e63ed 242 unsigned blocksize, bs0, bs1;
ce20edb7 243 int srate;
f5475e1b
MR
244
245 if (os->psize != 30)
90e15e34 246 return AVERROR_INVALIDDATA;
f5475e1b 247
736e63ed 248 if (bytestream_get_le32(&p) != 0) /* vorbis_version */
90e15e34 249 return AVERROR_INVALIDDATA;
736e63ed 250
739587bf 251 st->codec->channels = bytestream_get_byte(&p);
49fe9c05 252 srate = bytestream_get_le32(&p);
739587bf
MR
253 p += 4; // skip maximum bitrate
254 st->codec->bit_rate = bytestream_get_le32(&p); // nominal bitrate
736e63ed
MR
255 p += 4; // skip minimum bitrate
256
257 blocksize = bytestream_get_byte(&p);
49fe9c05
VG
258 bs0 = blocksize & 15;
259 bs1 = blocksize >> 4;
736e63ed
MR
260
261 if (bs0 > bs1)
90e15e34 262 return AVERROR_INVALIDDATA;
736e63ed 263 if (bs0 < 6 || bs1 > 13)
90e15e34 264 return AVERROR_INVALIDDATA;
736e63ed
MR
265
266 if (bytestream_get_byte(&p) != 1) /* framing_flag */
90e15e34 267 return AVERROR_INVALIDDATA;
9146ca37 268
72415b2a 269 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
49fe9c05 270 st->codec->codec_id = AV_CODEC_ID_VORBIS;
9146ca37 271
ce20edb7
RD
272 if (srate > 0) {
273 st->codec->sample_rate = srate;
c3f9ebf7 274 avpriv_set_pts_info(st, 64, 1, srate);
ce20edb7 275 }
9146ca37 276 } else if (os->buf[os->pstart] == 3) {
8cb3c557 277 if (os->psize > 8 &&
49fe9c05
VG
278 ff_vorbis_comment(s, &st->metadata, os->buf + os->pstart + 7,
279 os->psize - 8) >= 0) {
8cb3c557
RD
280 // drop all metadata we parsed and which is not required by libvorbis
281 unsigned new_len = 7 + 4 + AV_RL32(priv->packet[1] + 7) + 4 + 1;
282 if (new_len >= 16 && new_len < os->psize) {
283 AV_WL32(priv->packet[1] + new_len - 5, 0);
284 priv->packet[1][new_len - 1] = 1;
49fe9c05 285 priv->len[1] = new_len;
8cb3c557
RD
286 }
287 }
ad2b531d 288 } else {
d872fb0f
MS
289 int ret = fixup_vorbis_headers(s, priv, &st->codec->extradata);
290 if (ret < 0) {
291 st->codec->extradata_size = 0;
292 return ret;
293 }
294 st->codec->extradata_size = ret;
f63412fc
JR
295 if ((ret = avpriv_vorbis_parse_extradata(st->codec, &priv->vp))) {
296 av_freep(&st->codec->extradata);
297 st->codec->extradata_size = 0;
298 return ret;
299 }
9146ca37
MR
300 }
301
8f8320d7 302 return 1;
9146ca37
MR
303}
304
f63412fc
JR
305static int vorbis_packet(AVFormatContext *s, int idx)
306{
307 struct ogg *ogg = s->priv_data;
308 struct ogg_stream *os = ogg->streams + idx;
309 struct oggvorbis_private *priv = os->private;
310 int duration;
311
312 /* first packet handling
49fe9c05
VG
313 * here we parse the duration of each packet in the first page and compare
314 * the total duration to the page granule to find the encoder delay and
315 * set the first timestamp */
f63412fc
JR
316 if (!os->lastpts) {
317 int seg;
49fe9c05
VG
318 uint8_t *last_pkt = os->buf + os->pstart;
319 uint8_t *next_pkt = last_pkt;
f63412fc
JR
320 int first_duration = 0;
321
322 avpriv_vorbis_parse_reset(&priv->vp);
323 duration = 0;
324 for (seg = 0; seg < os->nsegs; seg++) {
325 if (os->segments[seg] < 255) {
326 int d = avpriv_vorbis_parse_frame(&priv->vp, last_pkt, 1);
327 if (d < 0) {
328 duration = os->granule;
329 break;
330 }
331 if (!duration)
332 first_duration = d;
333 duration += d;
49fe9c05 334 last_pkt = next_pkt + os->segments[seg];
f63412fc
JR
335 }
336 next_pkt += os->segments[seg];
337 }
49fe9c05
VG
338 os->lastpts =
339 os->lastdts = os->granule - duration;
f63412fc
JR
340 s->streams[idx]->start_time = os->lastpts + first_duration;
341 if (s->streams[idx]->duration)
342 s->streams[idx]->duration -= s->streams[idx]->start_time;
49fe9c05
VG
343 s->streams[idx]->cur_dts = AV_NOPTS_VALUE;
344 priv->final_pts = AV_NOPTS_VALUE;
f63412fc
JR
345 avpriv_vorbis_parse_reset(&priv->vp);
346 }
347
348 /* parse packet duration */
349 if (os->psize > 0) {
350 duration = avpriv_vorbis_parse_frame(&priv->vp, os->buf + os->pstart, 1);
351 if (duration <= 0) {
352 os->pflags |= AV_PKT_FLAG_CORRUPT;
353 return 0;
354 }
355 os->pduration = duration;
356 }
357
358 /* final packet handling
49fe9c05
VG
359 * here we save the pts of the first packet in the final page, sum up all
360 * packet durations in the final page except for the last one, and compare
361 * to the page granule to find the duration of the final packet */
f63412fc
JR
362 if (os->flags & OGG_FLAG_EOS) {
363 if (os->lastpts != AV_NOPTS_VALUE) {
49fe9c05 364 priv->final_pts = os->lastpts;
f63412fc
JR
365 priv->final_duration = 0;
366 }
367 if (os->segp == os->nsegs)
368 os->pduration = os->granule - priv->final_pts - priv->final_duration;
369 priv->final_duration += os->pduration;
370 }
371
372 return 0;
373}
374
77be08ee 375const struct ogg_codec ff_vorbis_codec = {
49fe9c05 376 .magic = "\001vorbis",
9146ca37 377 .magicsize = 7,
49fe9c05
VG
378 .header = vorbis_header,
379 .packet = vorbis_packet,
380 .cleanup = vorbis_cleanup,
7751e469 381 .nb_header = 3,
9146ca37 382};