libavformat/oggparsevorbis.c
49fe9c05
 /*
  * Copyright (C) 2005  Michael Ahlberg, Måns Rullgård
  *
  * Permission is hereby granted, free of charge, to any person
  * obtaining a copy of this software and associated documentation
  * files (the "Software"), to deal in the Software without
  * restriction, including without limitation the rights to use, copy,
  * modify, merge, publish, distribute, sublicense, and/or sell copies
  * of the Software, and to permit persons to whom the Software is
  * furnished to do so, subject to the following conditions:
  *
  *  The above copyright notice and this permission notice shall be
  *  included in all copies or substantial portions of the Software.
  *
  *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  *  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  *  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  *  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  *  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  *  WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  *  DEALINGS IN THE SOFTWARE.
  */
9146ca37
 
 #include <stdlib.h>
49fe9c05
 
245976da
 #include "libavutil/avstring.h"
19378221
 #include "libavutil/base64.h"
245976da
 #include "libavutil/bswap.h"
d2d67e42
 #include "libavutil/dict.h"
245976da
 #include "libavcodec/bytestream.h"
49fe9c05
 #include "libavcodec/get_bits.h"
2f3fadfb
 #include "libavcodec/vorbis_parser.h"
9146ca37
 #include "avformat.h"
92b03cf9
 #include "flac_picture.h"
19711af5
 #include "internal.h"
a0ddef24
 #include "oggdec.h"
fb66c31d
 #include "vorbiscomment.h"
0048deb8
 #include "replaygain.h"
9146ca37
 
8730fad5
 static int ogm_chapter(AVFormatContext *as, uint8_t *key, uint8_t *val)
 {
     int i, cnum, h, m, s, ms, keylen = strlen(key);
     AVChapter *chapter = NULL;
 
04b98362
     if (keylen < 9 || sscanf(key, "CHAPTER%03d", &cnum) != 1)
8730fad5
         return 0;
 
04b98362
     if (keylen <= 10) {
8730fad5
         if (sscanf(val, "%02d:%02d:%02d.%03d", &h, &m, &s, &ms) < 4)
             return 0;
 
49fe9c05
         avpriv_new_chapter(as, cnum, (AVRational) { 1, 1000 },
                            ms + 1000 * (s + 60 * (m + 60 * h)),
                            AV_NOPTS_VALUE, NULL);
8730fad5
         av_free(val);
9c15ef35
     } else if (!strcmp(key + keylen - 4, "NAME")) {
49fe9c05
         for (i = 0; i < as->nb_chapters; i++)
8730fad5
             if (as->chapters[i]->id == cnum) {
                 chapter = as->chapters[i];
                 break;
             }
         if (!chapter)
             return 0;
 
49fe9c05
         av_dict_set(&chapter->metadata, "title", val, AV_DICT_DONT_STRDUP_VAL);
8730fad5
     } else
         return 0;
 
     av_free(key);
     return 1;
 }
 
db68ef89
 int ff_vorbis_stream_comment(AVFormatContext *as, AVStream *st,
                              const uint8_t *buf, int size)
 {
     int updates = ff_vorbis_comment(as, &st->metadata, buf, size, 1);
 
     if (updates > 0) {
         st->event_flags |= AVSTREAM_EVENT_FLAG_METADATA_UPDATED;
     }
 
     return updates;
 }
 
49fe9c05
 int ff_vorbis_comment(AVFormatContext *as, AVDictionary **m,
23f741f7
                       const uint8_t *buf, int size,
                       int parse_picture)
9146ca37
 {
49fe9c05
     const uint8_t *p   = buf;
47a0513b
     const uint8_t *end = buf + size;
db68ef89
     int updates        = 0;
98422c44
     unsigned n, j;
     int s;
9146ca37
 
49fe9c05
     /* must have vendor_length and user_comment_list_length */
     if (size < 8)
90e15e34
         return AVERROR_INVALIDDATA;
9146ca37
 
0a770ae7
     s = bytestream_get_le32(&p);
9146ca37
 
98422c44
     if (end - p - 4 < s || s < 0)
90e15e34
         return AVERROR_INVALIDDATA;
9146ca37
 
     p += s;
 
0a770ae7
     n = bytestream_get_le32(&p);
9146ca37
 
98422c44
     while (end - p >= 4 && n > 0) {
47a0513b
         const char *t, *v;
9146ca37
         int tl, vl;
 
0a770ae7
         s = bytestream_get_le32(&p);
9146ca37
 
98422c44
         if (end - p < s || s < 0)
9146ca37
             break;
 
49fe9c05
         t  = p;
9146ca37
         p += s;
         n--;
 
4bd684bc
         v = memchr(t, '=', s);
9146ca37
         if (!v)
             continue;
 
         tl = v - t;
         vl = s - tl - 1;
         v++;
 
4bd684bc
         if (tl && vl) {
e3b44649
             char *tt, *ct;
 
             tt = av_malloc(tl + 1);
             ct = av_malloc(vl + 1);
             if (!tt || !ct) {
                 av_freep(&tt);
                 av_freep(&ct);
fd2384f0
                 return AVERROR(ENOMEM);
e3b44649
             }
9146ca37
 
             for (j = 0; j < tl; j++)
88d55b82
                 tt[j] = av_toupper(t[j]);
9146ca37
             tt[tl] = 0;
 
4bd684bc
             memcpy(ct, v, vl);
9146ca37
             ct[vl] = 0;
 
c18375ec
             /* The format in which the pictures are stored is the FLAC format.
              * Xiph says: "The binary FLAC picture structure is base64 encoded
              * and placed within a VorbisComment with the tag name
              * 'METADATA_BLOCK_PICTURE'. This is the preferred and
              * recommended way of embedding cover art within VorbisComments."
              */
23f741f7
             if (!strcmp(tt, "METADATA_BLOCK_PICTURE") && parse_picture) {
19378221
                 int ret;
                 char *pict = av_malloc(vl);
 
                 if (!pict) {
                     av_log(as, AV_LOG_WARNING, "out-of-memory error. Skipping cover art block.\n");
f3b7f470
                     av_freep(&tt);
d0a882ab
                     av_freep(&ct);
19378221
                     continue;
                 }
                 if ((ret = av_base64_decode(pict, ct, vl)) > 0)
                     ret = ff_flac_parse_picture(as, pict, ret);
f3b7f470
                 av_freep(&tt);
d0a882ab
                 av_freep(&ct);
c18375ec
                 av_freep(&pict);
19378221
                 if (ret < 0) {
                     av_log(as, AV_LOG_WARNING, "Failed to parse cover art block.\n");
                     continue;
                 }
0dc66553
             } else if (!ogm_chapter(as, tt, ct)) {
db68ef89
                 updates++;
b978391e
                 if (av_dict_get(*m, tt, NULL, 0)) {
0dc66553
                     av_dict_set(m, tt, ";", AV_DICT_APPEND);
                 }
d2d67e42
                 av_dict_set(m, tt, ct,
49fe9c05
                             AV_DICT_DONT_STRDUP_KEY |
0dc66553
                             AV_DICT_APPEND);
                 av_freep(&ct);
             }
9146ca37
         }
     }
 
972c5f9e
     if (p != end)
49fe9c05
         av_log(as, AV_LOG_INFO,
ced0d6c1
                "%"PTRDIFF_SPECIFIER" bytes of comment header remain\n", end - p);
9146ca37
     if (n > 0)
4bd684bc
         av_log(as, AV_LOG_INFO,
                "truncated comment header, %i comments not found\n", n);
9146ca37
 
ad7768f4
     ff_metadata_conv(m, NULL, ff_vorbiscomment_metadata_conv);
03700d39
 
db68ef89
     return updates;
9146ca37
 }
 
49fe9c05
 /*
  * Parse the vorbis header
  *
9146ca37
  * Vorbis Identification header from Vorbis_I_spec.html#vorbis-spec-codec
  * [vorbis_version] = read 32 bits as unsigned integer | Not used
  * [audio_channels] = read 8 bit integer as unsigned | Used
115329f1
  * [audio_sample_rate] = read 32 bits as unsigned integer | Used
9146ca37
  * [bitrate_maximum] = read 32 bits as signed integer | Not used yet
  * [bitrate_nominal] = read 32 bits as signed integer | Not used yet
  * [bitrate_minimum] = read 32 bits as signed integer | Used as bitrate
  * [blocksize_0] = read 4 bits as unsigned integer | Not Used
  * [blocksize_1] = read 4 bits as unsigned integer | Not Used
  * [framing_flag] = read one bit | Not Used
49fe9c05
  */
9146ca37
 
77be08ee
 struct oggvorbis_private {
ad2b531d
     unsigned int len[3];
     unsigned char *packet[3];
2f3fadfb
     AVVorbisParseContext *vp;
f63412fc
     int64_t final_pts;
     int final_duration;
77be08ee
 };
ad2b531d
 
ed9245db
 static int fixup_vorbis_headers(AVFormatContext *as,
                                 struct oggvorbis_private *priv,
                                 uint8_t **buf)
ad2b531d
 {
5626f994
     int i, offset, len, err;
20dfab33
     int buf_len;
ad2b531d
     unsigned char *ptr;
 
     len = priv->len[0] + priv->len[1] + priv->len[2];
f3968ab4
     buf_len = len + len / 255 + 64;
0451ff29
     ptr = *buf = av_realloc(NULL, buf_len);
ed9245db
     if (!ptr)
         return AVERROR(ENOMEM);
0451ff29
     memset(*buf, '\0', buf_len);
ad2b531d
 
49fe9c05
     ptr[0]  = 2;
     offset  = 1;
ad2b531d
     offset += av_xiphlacing(&ptr[offset], priv->len[0]);
     offset += av_xiphlacing(&ptr[offset], priv->len[1]);
4bd684bc
     for (i = 0; i < 3; i++) {
ad2b531d
         memcpy(&ptr[offset], priv->packet[i], priv->len[i]);
         offset += priv->len[i];
2ac41150
         av_freep(&priv->packet[i]);
ad2b531d
     }
5626f994
     if ((err = av_reallocp(buf, offset + FF_INPUT_BUFFER_PADDING_SIZE)) < 0)
         return err;
ad2b531d
     return offset;
 }
 
7a6beedd
 static void vorbis_cleanup(AVFormatContext *s, int idx)
d894f747
 {
     struct ogg *ogg = s->priv_data;
     struct ogg_stream *os = ogg->streams + idx;
     struct oggvorbis_private *priv = os->private;
     int i;
2f3fadfb
     if (os->private) {
         av_vorbis_parse_free(&priv->vp);
d894f747
         for (i = 0; i < 3; i++)
             av_freep(&priv->packet[i]);
2f3fadfb
     }
d894f747
 }
ad2b531d
 
5a633ec2
 static int vorbis_update_metadata(AVFormatContext *s, int idx)
 {
     struct ogg *ogg = s->priv_data;
     struct ogg_stream *os = ogg->streams + idx;
     AVStream *st = s->streams[idx];
     int ret;
 
     if (os->psize <= 8)
         return 0;
 
     /* New metadata packet; release old data. */
     av_dict_free(&st->metadata);
a8db7879
     ret = ff_vorbis_stream_comment(s, st, os->buf + os->pstart + 7,
                                    os->psize - 8);
5a633ec2
     if (ret < 0)
         return ret;
 
     /* Update the metadata if possible. */
     av_freep(&os->new_metadata);
     if (st->metadata) {
         os->new_metadata = av_packet_pack_dictionary(st->metadata, &os->new_metadata_size);
     /* Send an empty dictionary to indicate that metadata has been cleared. */
     } else {
         os->new_metadata = av_malloc(1);
         os->new_metadata_size = 0;
     }
 
     return ret;
 }
 
49fe9c05
 static int vorbis_header(AVFormatContext *s, int idx)
9146ca37
 {
77be08ee
     struct ogg *ogg = s->priv_data;
49fe9c05
     AVStream *st    = s->streams[idx];
77be08ee
     struct ogg_stream *os = ogg->streams + idx;
     struct oggvorbis_private *priv;
8f8320d7
     int pkt_type = os->buf[os->pstart];
9146ca37
 
8f8320d7
     if (!os->private) {
77be08ee
         os->private = av_mallocz(sizeof(struct oggvorbis_private));
4bd684bc
         if (!os->private)
90e15e34
             return AVERROR(ENOMEM);
ad2b531d
     }
9146ca37
 
c04c43b3
     priv = os->private;
 
3562684d
     if (!(pkt_type & 1))
c04c43b3
         return priv->vp ? 0 : AVERROR_INVALIDDATA;
3562684d
 
8f8320d7
     if (os->psize < 1 || pkt_type > 5)
90e15e34
         return AVERROR_INVALIDDATA;
f5475e1b
 
49fe9c05
     if (priv->packet[pkt_type >> 1])
90e15e34
         return AVERROR_INVALIDDATA;
73c44cb2
     if (pkt_type > 1 && !priv->packet[0] || pkt_type > 3 && !priv->packet[1])
90e15e34
         return AVERROR_INVALIDDATA;
73c44cb2
 
49fe9c05
     priv->len[pkt_type >> 1]    = os->psize;
8f8320d7
     priv->packet[pkt_type >> 1] = av_mallocz(os->psize);
84aea80f
     if (!priv->packet[pkt_type >> 1])
         return AVERROR(ENOMEM);
8f8320d7
     memcpy(priv->packet[pkt_type >> 1], os->buf + os->pstart, os->psize);
9146ca37
     if (os->buf[os->pstart] == 1) {
47a0513b
         const uint8_t *p = os->buf + os->pstart + 7; /* skip "\001vorbis" tag */
736e63ed
         unsigned blocksize, bs0, bs1;
ce20edb7
         int srate;
1d29624c
         int channels;
f5475e1b
 
         if (os->psize != 30)
90e15e34
             return AVERROR_INVALIDDATA;
f5475e1b
 
736e63ed
         if (bytestream_get_le32(&p) != 0) /* vorbis_version */
90e15e34
             return AVERROR_INVALIDDATA;
736e63ed
 
f3968ab4
         channels = bytestream_get_byte(&p);
1d29624c
         if (st->codec->channels && channels != st->codec->channels) {
             av_log(s, AV_LOG_ERROR, "Channel change is not supported\n");
             return AVERROR_PATCHWELCOME;
         }
         st->codec->channels = channels;
49fe9c05
         srate               = bytestream_get_le32(&p);
739587bf
         p += 4; // skip maximum bitrate
         st->codec->bit_rate = bytestream_get_le32(&p); // nominal bitrate
736e63ed
         p += 4; // skip minimum bitrate
 
         blocksize = bytestream_get_byte(&p);
49fe9c05
         bs0       = blocksize & 15;
         bs1       = blocksize >> 4;
736e63ed
 
         if (bs0 > bs1)
90e15e34
             return AVERROR_INVALIDDATA;
736e63ed
         if (bs0 < 6 || bs1 > 13)
90e15e34
             return AVERROR_INVALIDDATA;
736e63ed
 
         if (bytestream_get_byte(&p) != 1) /* framing_flag */
90e15e34
             return AVERROR_INVALIDDATA;
9146ca37
 
72415b2a
         st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
49fe9c05
         st->codec->codec_id   = AV_CODEC_ID_VORBIS;
9146ca37
 
ce20edb7
         if (srate > 0) {
             st->codec->sample_rate = srate;
c3f9ebf7
             avpriv_set_pts_info(st, 64, 1, srate);
ce20edb7
         }
9146ca37
     } else if (os->buf[os->pstart] == 3) {
f5d1d1e4
         if (vorbis_update_metadata(s, idx) >= 0 && priv->len[1] > 10) {
0048deb8
             unsigned new_len;
 
             int ret = ff_replaygain_export(st, st->metadata);
             if (ret < 0)
                 return ret;
 
8cb3c557
             // drop all metadata we parsed and which is not required by libvorbis
0048deb8
             new_len = 7 + 4 + AV_RL32(priv->packet[1] + 7) + 4 + 1;
8cb3c557
             if (new_len >= 16 && new_len < os->psize) {
                 AV_WL32(priv->packet[1] + new_len - 5, 0);
                 priv->packet[1][new_len - 1] = 1;
49fe9c05
                 priv->len[1]                 = new_len;
8cb3c557
             }
         }
ad2b531d
     } else {
d872fb0f
         int ret = fixup_vorbis_headers(s, priv, &st->codec->extradata);
         if (ret < 0) {
             st->codec->extradata_size = 0;
             return ret;
         }
         st->codec->extradata_size = ret;
2f3fadfb
 
         priv->vp = av_vorbis_parse_init(st->codec->extradata, st->codec->extradata_size);
         if (!priv->vp) {
f63412fc
             av_freep(&st->codec->extradata);
             st->codec->extradata_size = 0;
4b2763cd
             return AVERROR_UNKNOWN;
f63412fc
         }
9146ca37
     }
 
8f8320d7
     return 1;
9146ca37
 }
 
f63412fc
 static int vorbis_packet(AVFormatContext *s, int idx)
 {
     struct ogg *ogg = s->priv_data;
     struct ogg_stream *os = ogg->streams + idx;
     struct oggvorbis_private *priv = os->private;
5a633ec2
     int duration, flags = 0;
f63412fc
 
     /* first packet handling
49fe9c05
      * here we parse the duration of each packet in the first page and compare
      * the total duration to the page granule to find the encoder delay and
      * set the first timestamp */
12b97dd3
     if ((!os->lastpts || os->lastpts == AV_NOPTS_VALUE) && !(os->flags & OGG_FLAG_EOS) && (int64_t)os->granule>=0) {
1f95ad48
         int seg, d;
49fe9c05
         uint8_t *last_pkt  = os->buf + os->pstart;
         uint8_t *next_pkt  = last_pkt;
f63412fc
 
2f3fadfb
         av_vorbis_parse_reset(priv->vp);
f63412fc
         duration = 0;
1f95ad48
         seg = os->segp;
f74be366
         d = av_vorbis_parse_frame_flags(priv->vp, last_pkt, 1, &flags);
1f95ad48
         if (d < 0) {
             os->pflags |= AV_PKT_FLAG_CORRUPT;
             return 0;
5a633ec2
         } else if (flags & VORBIS_FLAG_COMMENT) {
             vorbis_update_metadata(s, idx);
             flags = 0;
1f95ad48
         }
         duration += d;
         last_pkt = next_pkt =  next_pkt + os->psize;
         for (; seg < os->nsegs; seg++) {
f63412fc
             if (os->segments[seg] < 255) {
f74be366
                 int d = av_vorbis_parse_frame_flags(priv->vp, last_pkt, 1, &flags);
f63412fc
                 if (d < 0) {
                     duration = os->granule;
                     break;
5a633ec2
                 } else if (flags & VORBIS_FLAG_COMMENT) {
                     vorbis_update_metadata(s, idx);
                     flags = 0;
f63412fc
                 }
                 duration += d;
49fe9c05
                 last_pkt  = next_pkt + os->segments[seg];
f63412fc
             }
             next_pkt += os->segments[seg];
         }
49fe9c05
         os->lastpts                 =
         os->lastdts                 = os->granule - duration;
27b8ef5b
 
         if (!os->granule && duration) //hack to deal with broken files (Ticket3710)
             os->lastpts = os->lastdts = AV_NOPTS_VALUE;
 
f3968ab4
         if (s->streams[idx]->start_time == AV_NOPTS_VALUE) {
45a7b067
             s->streams[idx]->start_time = FFMAX(os->lastpts, 0);
45581ed1
             if (s->streams[idx]->duration != AV_NOPTS_VALUE)
fe5c5bcc
                 s->streams[idx]->duration -= s->streams[idx]->start_time;
         }
49fe9c05
         priv->final_pts          = AV_NOPTS_VALUE;
2f3fadfb
         av_vorbis_parse_reset(priv->vp);
f63412fc
     }
 
     /* parse packet duration */
     if (os->psize > 0) {
f74be366
         duration = av_vorbis_parse_frame_flags(priv->vp, os->buf + os->pstart, 1, &flags);
1f95ad48
         if (duration < 0) {
f63412fc
             os->pflags |= AV_PKT_FLAG_CORRUPT;
             return 0;
5a633ec2
         } else if (flags & VORBIS_FLAG_COMMENT) {
             vorbis_update_metadata(s, idx);
             flags = 0;
f63412fc
         }
         os->pduration = duration;
     }
 
     /* final packet handling
49fe9c05
      * here we save the pts of the first packet in the final page, sum up all
      * packet durations in the final page except for the last one, and compare
      * to the page granule to find the duration of the final packet */
f63412fc
     if (os->flags & OGG_FLAG_EOS) {
         if (os->lastpts != AV_NOPTS_VALUE) {
49fe9c05
             priv->final_pts      = os->lastpts;
f63412fc
             priv->final_duration = 0;
         }
         if (os->segp == os->nsegs)
             os->pduration = os->granule - priv->final_pts - priv->final_duration;
         priv->final_duration += os->pduration;
     }
 
     return 0;
 }
 
77be08ee
 const struct ogg_codec ff_vorbis_codec = {
49fe9c05
     .magic     = "\001vorbis",
9146ca37
     .magicsize = 7,
49fe9c05
     .header    = vorbis_header,
     .packet    = vorbis_packet,
     .cleanup   = vorbis_cleanup,
7751e469
     .nb_header = 3,
9146ca37
 };