LCOV - code coverage report
Current view: top level - libavformat - oggenc.c (source / functions) Hit Total Coverage
Test: coverage.info Lines: 324 411 78.8 %
Date: 2017-12-13 18:07:29 Functions: 18 20 90.0 %

          Line data    Source code
       1             : /*
       2             :  * Ogg muxer
       3             :  * Copyright (c) 2007 Baptiste Coudurier <baptiste dot coudurier at free dot 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 <stdint.h>
      23             : 
      24             : #include "libavutil/crc.h"
      25             : #include "libavutil/mathematics.h"
      26             : #include "libavutil/opt.h"
      27             : #include "libavutil/random_seed.h"
      28             : #include "libavcodec/xiph.h"
      29             : #include "libavcodec/bytestream.h"
      30             : #include "libavcodec/flac.h"
      31             : #include "avformat.h"
      32             : #include "avio_internal.h"
      33             : #include "internal.h"
      34             : #include "vorbiscomment.h"
      35             : 
      36             : #define MAX_PAGE_SIZE 65025
      37             : 
      38             : typedef struct OGGPage {
      39             :     int64_t start_granule;
      40             :     int64_t granule;
      41             :     int stream_index;
      42             :     uint8_t flags;
      43             :     uint8_t segments_count;
      44             :     uint8_t segments[255];
      45             :     uint8_t data[MAX_PAGE_SIZE];
      46             :     uint16_t size;
      47             : } OGGPage;
      48             : 
      49             : typedef struct OGGStreamContext {
      50             :     unsigned page_counter;
      51             :     uint8_t *header[3];
      52             :     int header_len[3];
      53             :     /** for theora granule */
      54             :     int kfgshift;
      55             :     int64_t last_kf_pts;
      56             :     int vrev;
      57             :     /* for VP8 granule */
      58             :     int isvp8;
      59             :     int eos;
      60             :     unsigned page_count; ///< number of page buffered
      61             :     OGGPage page; ///< current page
      62             :     unsigned serial_num; ///< serial number
      63             :     int64_t last_granule; ///< last packet granule
      64             : } OGGStreamContext;
      65             : 
      66             : typedef struct OGGPageList {
      67             :     OGGPage page;
      68             :     struct OGGPageList *next;
      69             : } OGGPageList;
      70             : 
      71             : typedef struct OGGContext {
      72             :     const AVClass *class;
      73             :     OGGPageList *page_list;
      74             :     int pref_size; ///< preferred page size (0 => fill all segments)
      75             :     int64_t pref_duration;      ///< preferred page duration (0 => fill all segments)
      76             :     int serial_offset;
      77             : } OGGContext;
      78             : 
      79             : #define OFFSET(x) offsetof(OGGContext, x)
      80             : #define PARAM AV_OPT_FLAG_ENCODING_PARAM
      81             : 
      82             : static const AVOption options[] = {
      83             :     { "serial_offset", "serial number offset",
      84             :         OFFSET(serial_offset), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, PARAM },
      85             :     { "oggpagesize", "Set preferred Ogg page size.",
      86             :       OFFSET(pref_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, MAX_PAGE_SIZE, PARAM},
      87             :     { "pagesize", "preferred page size in bytes (deprecated)",
      88             :         OFFSET(pref_size), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, MAX_PAGE_SIZE, PARAM },
      89             :     { "page_duration", "preferred page duration, in microseconds",
      90             :         OFFSET(pref_duration), AV_OPT_TYPE_INT64, { .i64 = 1000000 }, 0, INT64_MAX, PARAM },
      91             :     { NULL },
      92             : };
      93             : 
      94             : #define OGG_CLASS(flavor, name)\
      95             : static const AVClass flavor ## _muxer_class = {\
      96             :     .class_name = #name " muxer",\
      97             :     .item_name  = av_default_item_name,\
      98             :     .option     = options,\
      99             :     .version    = LIBAVUTIL_VERSION_INT,\
     100             : };
     101             : 
     102          47 : static void ogg_update_checksum(AVFormatContext *s, AVIOContext *pb, int64_t crc_offset)
     103             : {
     104          47 :     int64_t pos = avio_tell(pb);
     105          47 :     uint32_t checksum = ffio_get_checksum(pb);
     106          47 :     avio_seek(pb, crc_offset, SEEK_SET);
     107          47 :     avio_wb32(pb, checksum);
     108          47 :     avio_seek(pb, pos, SEEK_SET);
     109          47 : }
     110             : 
     111          47 : static int ogg_write_page(AVFormatContext *s, OGGPage *page, int extra_flags)
     112             : {
     113          47 :     OGGStreamContext *oggstream = s->streams[page->stream_index]->priv_data;
     114             :     AVIOContext *pb;
     115             :     int64_t crc_offset;
     116             :     int ret, size;
     117             :     uint8_t *buf;
     118             : 
     119          47 :     ret = avio_open_dyn_buf(&pb);
     120          47 :     if (ret < 0)
     121           0 :         return ret;
     122          47 :     ffio_init_checksum(pb, ff_crc04C11DB7_update, 0);
     123          47 :     ffio_wfourcc(pb, "OggS");
     124          47 :     avio_w8(pb, 0);
     125          47 :     avio_w8(pb, page->flags | extra_flags);
     126          47 :     avio_wl64(pb, page->granule);
     127          47 :     avio_wl32(pb, oggstream->serial_num);
     128          47 :     avio_wl32(pb, oggstream->page_counter++);
     129          47 :     crc_offset = avio_tell(pb);
     130          47 :     avio_wl32(pb, 0); // crc
     131          47 :     avio_w8(pb, page->segments_count);
     132          47 :     avio_write(pb, page->segments, page->segments_count);
     133          47 :     avio_write(pb, page->data, page->size);
     134             : 
     135          47 :     ogg_update_checksum(s, pb, crc_offset);
     136          47 :     avio_flush(pb);
     137             : 
     138          47 :     size = avio_close_dyn_buf(pb, &buf);
     139          47 :     if (size < 0)
     140           0 :         return size;
     141             : 
     142          47 :     avio_write(s->pb, buf, size);
     143          47 :     avio_flush(s->pb);
     144          47 :     av_free(buf);
     145          47 :     oggstream->page_count--;
     146          47 :     return 0;
     147             : }
     148             : 
     149         119 : static int ogg_key_granule(OGGStreamContext *oggstream, int64_t granule)
     150             : {
     151         239 :     return (oggstream->kfgshift && !(granule & ((1<<oggstream->kfgshift)-1))) ||
     152         229 :            (oggstream->isvp8    && !((granule >> 3) & 0x07ffffff));
     153             : }
     154             : 
     155        1445 : static int64_t ogg_granule_to_timestamp(OGGStreamContext *oggstream, int64_t granule)
     156             : {
     157        1445 :     if (oggstream->kfgshift)
     158          90 :         return (granule>>oggstream->kfgshift) +
     159          45 :             (granule & ((1<<oggstream->kfgshift)-1));
     160        1400 :     else if (oggstream->isvp8)
     161         371 :         return granule >> 32;
     162             :     else
     163        1029 :         return granule;
     164             : }
     165             : 
     166          59 : static int ogg_compare_granule(AVFormatContext *s, OGGPage *next, OGGPage *page)
     167             : {
     168          59 :     AVStream *st2 = s->streams[next->stream_index];
     169          59 :     AVStream *st  = s->streams[page->stream_index];
     170             :     int64_t next_granule, cur_granule;
     171             : 
     172          59 :     if (next->granule == -1 || page->granule == -1)
     173          15 :         return 0;
     174             : 
     175          44 :     next_granule = av_rescale_q(ogg_granule_to_timestamp(st2->priv_data, next->granule),
     176          44 :                                 st2->time_base, AV_TIME_BASE_Q);
     177          44 :     cur_granule  = av_rescale_q(ogg_granule_to_timestamp(st->priv_data, page->granule),
     178          44 :                                 st ->time_base, AV_TIME_BASE_Q);
     179          44 :     return next_granule > cur_granule;
     180             : }
     181             : 
     182          47 : static int ogg_reset_cur_page(OGGStreamContext *oggstream)
     183             : {
     184          47 :     oggstream->page.granule = -1;
     185          47 :     oggstream->page.flags = 0;
     186          47 :     oggstream->page.segments_count = 0;
     187          47 :     oggstream->page.size = 0;
     188          47 :     return 0;
     189             : }
     190             : 
     191          47 : static int ogg_buffer_page(AVFormatContext *s, OGGStreamContext *oggstream)
     192             : {
     193          47 :     OGGContext *ogg = s->priv_data;
     194          47 :     OGGPageList **p = &ogg->page_list;
     195          47 :     OGGPageList *l = av_mallocz(sizeof(*l));
     196             : 
     197          47 :     if (!l)
     198           0 :         return AVERROR(ENOMEM);
     199          47 :     l->page = oggstream->page;
     200             : 
     201          47 :     oggstream->page.start_granule = ogg_granule_to_timestamp(oggstream, oggstream->page.granule);
     202          47 :     oggstream->page_count++;
     203          47 :     ogg_reset_cur_page(oggstream);
     204             : 
     205         152 :     while (*p) {
     206          59 :         if (ogg_compare_granule(s, &(*p)->page, &l->page))
     207           1 :             break;
     208          58 :         p = &(*p)->next;
     209             :     }
     210          47 :     l->next = *p;
     211          47 :     *p = l;
     212             : 
     213          47 :     return 0;
     214             : }
     215             : 
     216        1067 : static int ogg_buffer_data(AVFormatContext *s, AVStream *st,
     217             :                            uint8_t *data, unsigned size, int64_t granule,
     218             :                            int header)
     219             : {
     220        1067 :     OGGStreamContext *oggstream = st->priv_data;
     221        1067 :     OGGContext *ogg = s->priv_data;
     222        1067 :     int total_segments = size / 255 + 1;
     223        1067 :     uint8_t *p = data;
     224        1067 :     int i, segments, len, flush = 0;
     225             : 
     226             :     // Handles VFR by flushing page because this frame needs to have a timestamp
     227             :     // For theora and VP8, keyframes also need to have a timestamp to correctly mark
     228             :     // them as such, otherwise seeking will not work correctly at the very
     229             :     // least with old libogg versions.
     230             :     // Do not try to flush header packets though, that will create broken files.
     231        1186 :     if ((st->codecpar->codec_id == AV_CODEC_ID_THEORA || st->codecpar->codec_id == AV_CODEC_ID_VP8) && !header &&
     232         119 :         (ogg_granule_to_timestamp(oggstream, granule) >
     233         238 :          ogg_granule_to_timestamp(oggstream, oggstream->last_granule) + 1 ||
     234         119 :          ogg_key_granule(oggstream, granule))) {
     235           2 :         if (oggstream->page.granule != -1)
     236           0 :             ogg_buffer_page(s, oggstream);
     237           2 :         flush = 1;
     238             :     }
     239             : 
     240             :     // avoid a continued page
     241        2086 :     if (!header && oggstream->page.size > 0 &&
     242        1019 :         MAX_PAGE_SIZE - oggstream->page.size < size) {
     243           0 :         ogg_buffer_page(s, oggstream);
     244             :     }
     245             : 
     246        3206 :     for (i = 0; i < total_segments; ) {
     247        1072 :         OGGPage *page = &oggstream->page;
     248             : 
     249        1072 :         segments = FFMIN(total_segments - i, 255 - page->segments_count);
     250             : 
     251        1072 :         if (i && !page->segments_count)
     252           5 :             page->flags |= 1; // continued packet
     253             : 
     254        1072 :         memset(page->segments+page->segments_count, 255, segments - 1);
     255        1072 :         page->segments_count += segments - 1;
     256             : 
     257        1072 :         len = FFMIN(size, segments*255);
     258        1072 :         page->segments[page->segments_count++] = len - (segments-1)*255;
     259        1072 :         memcpy(page->data+page->size, p, len);
     260        1072 :         p += len;
     261        1072 :         size -= len;
     262        1072 :         i += segments;
     263        1072 :         page->size += len;
     264             : 
     265        1072 :         if (i == total_segments)
     266        1067 :             page->granule = granule;
     267             : 
     268             :         {
     269        1072 :             AVStream *st = s->streams[page->stream_index];
     270             : 
     271        1072 :             int64_t start = av_rescale_q(page->start_granule, st->time_base,
     272        1072 :                                          AV_TIME_BASE_Q);
     273        1072 :             int64_t next  = av_rescale_q(ogg_granule_to_timestamp(oggstream, page->granule),
     274        1072 :                                          st->time_base, AV_TIME_BASE_Q);
     275             : 
     276        1072 :             if (page->segments_count == 255) {
     277           5 :                 ogg_buffer_page(s, oggstream);
     278        1067 :             } else if (!header) {
     279        2096 :                 if ((ogg->pref_size     > 0 && page->size   >= ogg->pref_size) ||
     280        2096 :                     (ogg->pref_duration > 0 && next - start >= ogg->pref_duration)) {
     281          20 :                     ogg_buffer_page(s, oggstream);
     282             :                 }
     283             :             }
     284             :         }
     285             :     }
     286             : 
     287        1067 :     if (flush && oggstream->page.granule != -1)
     288           2 :         ogg_buffer_page(s, oggstream);
     289             : 
     290        1067 :     return 0;
     291             : }
     292             : 
     293           7 : static uint8_t *ogg_write_vorbiscomment(int64_t offset, int bitexact,
     294             :                                         int *header_len, AVDictionary **m, int framing_bit)
     295             : {
     296           7 :     const char *vendor = bitexact ? "ffmpeg" : LIBAVFORMAT_IDENT;
     297             :     int64_t size;
     298             :     uint8_t *p, *p0;
     299             : 
     300           7 :     ff_metadata_conv(m, ff_vorbiscomment_metadata_conv, NULL);
     301             : 
     302           7 :     size = offset + ff_vorbiscomment_length(*m, vendor) + framing_bit;
     303           7 :     if (size > INT_MAX)
     304           0 :         return NULL;
     305           7 :     p = av_mallocz(size);
     306           7 :     if (!p)
     307           0 :         return NULL;
     308           7 :     p0 = p;
     309             : 
     310           7 :     p += offset;
     311           7 :     ff_vorbiscomment_write(&p, m, vendor);
     312           7 :     if (framing_bit)
     313           4 :         bytestream_put_byte(&p, 1);
     314             : 
     315           7 :     *header_len = size;
     316           7 :     return p0;
     317             : }
     318             : 
     319           1 : static int ogg_build_flac_headers(AVCodecParameters *par,
     320             :                                   OGGStreamContext *oggstream, int bitexact,
     321             :                                   AVDictionary **m)
     322             : {
     323             :     uint8_t *p;
     324             : 
     325           1 :     if (par->extradata_size < FLAC_STREAMINFO_SIZE)
     326           0 :         return AVERROR(EINVAL);
     327             : 
     328             :     // first packet: STREAMINFO
     329           1 :     oggstream->header_len[0] = 51;
     330           1 :     oggstream->header[0] = av_mallocz(51); // per ogg flac specs
     331           1 :     p = oggstream->header[0];
     332           1 :     if (!p)
     333           0 :         return AVERROR(ENOMEM);
     334           1 :     bytestream_put_byte(&p, 0x7F);
     335           1 :     bytestream_put_buffer(&p, "FLAC", 4);
     336           1 :     bytestream_put_byte(&p, 1); // major version
     337           1 :     bytestream_put_byte(&p, 0); // minor version
     338           1 :     bytestream_put_be16(&p, 1); // headers packets without this one
     339           1 :     bytestream_put_buffer(&p, "fLaC", 4);
     340           1 :     bytestream_put_byte(&p, 0x00); // streaminfo
     341           1 :     bytestream_put_be24(&p, 34);
     342           1 :     bytestream_put_buffer(&p, par->extradata, FLAC_STREAMINFO_SIZE);
     343             : 
     344             :     // second packet: VorbisComment
     345           1 :     p = ogg_write_vorbiscomment(4, bitexact, &oggstream->header_len[1], m, 0);
     346           1 :     if (!p)
     347           0 :         return AVERROR(ENOMEM);
     348           1 :     oggstream->header[1] = p;
     349           1 :     bytestream_put_byte(&p, 0x84); // last metadata block and vorbis comment
     350           1 :     bytestream_put_be24(&p, oggstream->header_len[1] - 4);
     351             : 
     352           1 :     return 0;
     353             : }
     354             : 
     355             : #define SPEEX_HEADER_SIZE 80
     356             : 
     357           0 : static int ogg_build_speex_headers(AVCodecParameters *par,
     358             :                                    OGGStreamContext *oggstream, int bitexact,
     359             :                                    AVDictionary **m)
     360             : {
     361             :     uint8_t *p;
     362             : 
     363           0 :     if (par->extradata_size < SPEEX_HEADER_SIZE)
     364           0 :         return AVERROR_INVALIDDATA;
     365             : 
     366             :     // first packet: Speex header
     367           0 :     p = av_mallocz(SPEEX_HEADER_SIZE);
     368           0 :     if (!p)
     369           0 :         return AVERROR(ENOMEM);
     370           0 :     oggstream->header[0] = p;
     371           0 :     oggstream->header_len[0] = SPEEX_HEADER_SIZE;
     372           0 :     bytestream_put_buffer(&p, par->extradata, SPEEX_HEADER_SIZE);
     373           0 :     AV_WL32(&oggstream->header[0][68], 0);  // set extra_headers to 0
     374             : 
     375             :     // second packet: VorbisComment
     376           0 :     p = ogg_write_vorbiscomment(0, bitexact, &oggstream->header_len[1], m, 0);
     377           0 :     if (!p)
     378           0 :         return AVERROR(ENOMEM);
     379           0 :     oggstream->header[1] = p;
     380             : 
     381           0 :     return 0;
     382             : }
     383             : 
     384             : #define OPUS_HEADER_SIZE 19
     385             : 
     386           0 : static int ogg_build_opus_headers(AVCodecParameters *par,
     387             :                                   OGGStreamContext *oggstream, int bitexact,
     388             :                                   AVDictionary **m)
     389             : {
     390             :     uint8_t *p;
     391             : 
     392           0 :     if (par->extradata_size < OPUS_HEADER_SIZE)
     393           0 :         return AVERROR_INVALIDDATA;
     394             : 
     395             :     /* first packet: Opus header */
     396           0 :     p = av_mallocz(par->extradata_size);
     397           0 :     if (!p)
     398           0 :         return AVERROR(ENOMEM);
     399           0 :     oggstream->header[0] = p;
     400           0 :     oggstream->header_len[0] = par->extradata_size;
     401           0 :     bytestream_put_buffer(&p, par->extradata, par->extradata_size);
     402             : 
     403             :     /* second packet: VorbisComment */
     404           0 :     p = ogg_write_vorbiscomment(8, bitexact, &oggstream->header_len[1], m, 0);
     405           0 :     if (!p)
     406           0 :         return AVERROR(ENOMEM);
     407           0 :     oggstream->header[1] = p;
     408           0 :     bytestream_put_buffer(&p, "OpusTags", 8);
     409             : 
     410           0 :     return 0;
     411             : }
     412             : 
     413             : #define VP8_HEADER_SIZE 26
     414             : 
     415           1 : static int ogg_build_vp8_headers(AVFormatContext *s, AVStream *st,
     416             :                                  OGGStreamContext *oggstream, int bitexact)
     417             : {
     418           1 :     AVCodecParameters *par = st->codecpar;
     419             :     uint8_t *p;
     420             : 
     421             :     /* first packet: VP8 header */
     422           1 :     p = av_mallocz(VP8_HEADER_SIZE);
     423           1 :     if (!p)
     424           0 :         return AVERROR(ENOMEM);
     425           1 :     oggstream->header[0] = p;
     426           1 :     oggstream->header_len[0] = VP8_HEADER_SIZE;
     427           1 :     bytestream_put_byte(&p, 0x4f); // HDRID
     428           1 :     bytestream_put_buffer(&p, "VP80", 4); // Identifier
     429           1 :     bytestream_put_byte(&p, 1); // HDRTYP
     430           1 :     bytestream_put_byte(&p, 1); // VMAJ
     431           1 :     bytestream_put_byte(&p, 0); // VMIN
     432           1 :     bytestream_put_be16(&p, par->width);
     433           1 :     bytestream_put_be16(&p, par->height);
     434           1 :     bytestream_put_be24(&p, par->sample_aspect_ratio.num);
     435           1 :     bytestream_put_be24(&p, par->sample_aspect_ratio.den);
     436           1 :     if (st->r_frame_rate.num > 0 && st->r_frame_rate.den > 0) {
     437             :         // OggVP8 requires pts to increase by 1 per visible frame, so use the least common
     438             :         // multiple framerate if available.
     439           1 :         av_log(s, AV_LOG_DEBUG, "Changing time base from %d/%d to %d/%d\n",
     440             :                st->time_base.num, st->time_base.den,
     441             :                st->r_frame_rate.den, st->r_frame_rate.num);
     442           1 :         avpriv_set_pts_info(st, 64, st->r_frame_rate.den, st->r_frame_rate.num);
     443             :     }
     444           1 :     bytestream_put_be32(&p, st->time_base.den);
     445           1 :     bytestream_put_be32(&p, st->time_base.num);
     446             : 
     447             :     /* optional second packet: VorbisComment */
     448           1 :     if (av_dict_get(st->metadata, "", NULL, AV_DICT_IGNORE_SUFFIX)) {
     449           1 :         p = ogg_write_vorbiscomment(7, bitexact, &oggstream->header_len[1], &st->metadata, 0);
     450           1 :         if (!p)
     451           0 :             return AVERROR(ENOMEM);
     452           1 :         oggstream->header[1] = p;
     453           1 :         bytestream_put_byte(&p, 0x4f); // HDRID
     454           1 :         bytestream_put_buffer(&p, "VP80", 4); // Identifier
     455           1 :         bytestream_put_byte(&p, 2); // HDRTYP
     456           1 :         bytestream_put_byte(&p, 0x20);
     457             :     }
     458             : 
     459           1 :     oggstream->isvp8 = 1;
     460             : 
     461           1 :     return 0;
     462             : }
     463             : 
     464        1060 : static void ogg_write_pages(AVFormatContext *s, int flush)
     465             : {
     466        1060 :     OGGContext *ogg = s->priv_data;
     467             :     OGGPageList *next, *p;
     468             : 
     469        1060 :     if (!ogg->page_list)
     470         154 :         return;
     471             : 
     472        1859 :     for (p = ogg->page_list; p; ) {
     473         941 :         OGGStreamContext *oggstream =
     474         941 :             s->streams[p->page.stream_index]->priv_data;
     475         941 :         if (oggstream->page_count < 2 && !flush)
     476         894 :             break;
     477          54 :         ogg_write_page(s, &p->page,
     478          13 :                        flush == 1 && oggstream->page_count == 1 ? 4 : 0); // eos
     479          47 :         next = p->next;
     480          47 :         av_freep(&p);
     481          47 :         p = next;
     482             :     }
     483         906 :     ogg->page_list = p;
     484             : }
     485             : 
     486           6 : static int ogg_init(AVFormatContext *s)
     487             : {
     488           6 :     OGGContext *ogg = s->priv_data;
     489           6 :     OGGStreamContext *oggstream = NULL;
     490             :     int i, j;
     491             : 
     492           6 :     if (ogg->pref_size)
     493           0 :         av_log(s, AV_LOG_WARNING, "The pagesize option is deprecated\n");
     494             : 
     495          13 :     for (i = 0; i < s->nb_streams; i++) {
     496           7 :         AVStream *st = s->streams[i];
     497           7 :         unsigned serial_num = i + ogg->serial_offset;
     498             : 
     499           7 :         if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
     500           5 :             if (st->codecpar->codec_id == AV_CODEC_ID_OPUS)
     501             :                 /* Opus requires a fixed 48kHz clock */
     502           0 :                 avpriv_set_pts_info(st, 64, 1, 48000);
     503             :             else
     504           5 :                 avpriv_set_pts_info(st, 64, 1, st->codecpar->sample_rate);
     505             :         }
     506             : 
     507          10 :         if (st->codecpar->codec_id != AV_CODEC_ID_VORBIS &&
     508           5 :             st->codecpar->codec_id != AV_CODEC_ID_THEORA &&
     509           4 :             st->codecpar->codec_id != AV_CODEC_ID_SPEEX  &&
     510           3 :             st->codecpar->codec_id != AV_CODEC_ID_FLAC   &&
     511           2 :             st->codecpar->codec_id != AV_CODEC_ID_OPUS   &&
     512           1 :             st->codecpar->codec_id != AV_CODEC_ID_VP8) {
     513           0 :             av_log(s, AV_LOG_ERROR, "Unsupported codec id in stream %d\n", i);
     514           0 :             return AVERROR(EINVAL);
     515             :         }
     516             : 
     517           8 :         if ((!st->codecpar->extradata || !st->codecpar->extradata_size) &&
     518           1 :             st->codecpar->codec_id != AV_CODEC_ID_VP8) {
     519           0 :             av_log(s, AV_LOG_ERROR, "No extradata present\n");
     520           0 :             return AVERROR_INVALIDDATA;
     521             :         }
     522           7 :         oggstream = av_mallocz(sizeof(*oggstream));
     523           7 :         if (!oggstream)
     524           0 :             return AVERROR(ENOMEM);
     525             : 
     526           7 :         oggstream->page.stream_index = i;
     527             : 
     528           7 :         if (!(s->flags & AVFMT_FLAG_BITEXACT))
     529             :             do {
     530           1 :                 serial_num = av_get_random_seed();
     531           1 :                 for (j = 0; j < i; j++) {
     532           0 :                     OGGStreamContext *sc = s->streams[j]->priv_data;
     533           0 :                     if (serial_num == sc->serial_num)
     534           0 :                         break;
     535             :                 }
     536           1 :             } while (j < i);
     537           7 :         oggstream->serial_num = serial_num;
     538             : 
     539           7 :         av_dict_copy(&st->metadata, s->metadata, AV_DICT_DONT_OVERWRITE);
     540             : 
     541           7 :         st->priv_data = oggstream;
     542           7 :         if (st->codecpar->codec_id == AV_CODEC_ID_FLAC) {
     543           2 :             int err = ogg_build_flac_headers(st->codecpar, oggstream,
     544           1 :                                              s->flags & AVFMT_FLAG_BITEXACT,
     545             :                                              &st->metadata);
     546           1 :             if (err) {
     547           0 :                 av_log(s, AV_LOG_ERROR, "Error writing FLAC headers\n");
     548           0 :                 av_freep(&st->priv_data);
     549           0 :                 return err;
     550             :             }
     551           6 :         } else if (st->codecpar->codec_id == AV_CODEC_ID_SPEEX) {
     552           0 :             int err = ogg_build_speex_headers(st->codecpar, oggstream,
     553           0 :                                               s->flags & AVFMT_FLAG_BITEXACT,
     554             :                                               &st->metadata);
     555           0 :             if (err) {
     556           0 :                 av_log(s, AV_LOG_ERROR, "Error writing Speex headers\n");
     557           0 :                 av_freep(&st->priv_data);
     558           0 :                 return err;
     559             :             }
     560           6 :         } else if (st->codecpar->codec_id == AV_CODEC_ID_OPUS) {
     561           0 :             int err = ogg_build_opus_headers(st->codecpar, oggstream,
     562           0 :                                              s->flags & AVFMT_FLAG_BITEXACT,
     563             :                                              &st->metadata);
     564           0 :             if (err) {
     565           0 :                 av_log(s, AV_LOG_ERROR, "Error writing Opus headers\n");
     566           0 :                 av_freep(&st->priv_data);
     567           0 :                 return err;
     568             :             }
     569           6 :         } else if (st->codecpar->codec_id == AV_CODEC_ID_VP8) {
     570           1 :             int err = ogg_build_vp8_headers(s, st, oggstream,
     571           1 :                                             s->flags & AVFMT_FLAG_BITEXACT);
     572           1 :             if (err) {
     573           0 :                 av_log(s, AV_LOG_ERROR, "Error writing VP8 headers\n");
     574           0 :                 av_freep(&st->priv_data);
     575           0 :                 return err;
     576             :             }
     577             :         } else {
     578             :             uint8_t *p;
     579           5 :             const char *cstr = st->codecpar->codec_id == AV_CODEC_ID_VORBIS ? "vorbis" : "theora";
     580           5 :             int header_type = st->codecpar->codec_id == AV_CODEC_ID_VORBIS ? 3 : 0x81;
     581           5 :             int framing_bit = st->codecpar->codec_id == AV_CODEC_ID_VORBIS ? 1 : 0;
     582             : 
     583           5 :             if (avpriv_split_xiph_headers(st->codecpar->extradata, st->codecpar->extradata_size,
     584           5 :                                       st->codecpar->codec_id == AV_CODEC_ID_VORBIS ? 30 : 42,
     585           5 :                                       (const uint8_t**)oggstream->header, oggstream->header_len) < 0) {
     586           0 :                 av_log(s, AV_LOG_ERROR, "Extradata corrupted\n");
     587           0 :                 av_freep(&st->priv_data);
     588           0 :                 return AVERROR_INVALIDDATA;
     589             :             }
     590             : 
     591           5 :             p = ogg_write_vorbiscomment(7, s->flags & AVFMT_FLAG_BITEXACT,
     592             :                                         &oggstream->header_len[1], &st->metadata,
     593             :                                         framing_bit);
     594           5 :             oggstream->header[1] = p;
     595           5 :             if (!p)
     596           0 :                 return AVERROR(ENOMEM);
     597             : 
     598           5 :             bytestream_put_byte(&p, header_type);
     599           5 :             bytestream_put_buffer(&p, cstr, 6);
     600             : 
     601           5 :             if (st->codecpar->codec_id == AV_CODEC_ID_THEORA) {
     602           1 :                 int den = AV_RB32(oggstream->header[0] + 22), num = AV_RB32(oggstream->header[0] + 26);
     603             :                 /* Make sure to use time base stored in the Theora stream header to write
     604             :                    correct timestamps */
     605           1 :                 if (st->time_base.num != num || st->time_base.den != den) {
     606           1 :                     av_log(s, AV_LOG_DEBUG, "Changing time base from %d/%d to %d/%d\n",
     607             :                            st->time_base.num, st->time_base.den, num, den);
     608           1 :                     avpriv_set_pts_info(st, 64, num, den);
     609             :                 }
     610             :                 /** KFGSHIFT is the width of the less significant section of the granule position
     611             :                     The less significant section is the frame count since the last keyframe */
     612           1 :                 oggstream->kfgshift = ((oggstream->header[0][40]&3)<<3)|(oggstream->header[0][41]>>5);
     613           1 :                 oggstream->vrev = oggstream->header[0][9];
     614           1 :                 av_log(s, AV_LOG_DEBUG, "theora kfgshift %d, vrev %d\n",
     615             :                        oggstream->kfgshift, oggstream->vrev);
     616             :             }
     617             :         }
     618             :     }
     619             : 
     620           6 :     return 0;
     621             : }
     622             : 
     623           6 : static int ogg_write_header(AVFormatContext *s)
     624             : {
     625           6 :     OGGStreamContext *oggstream = NULL;
     626             :     int i, j;
     627             : 
     628          13 :     for (j = 0; j < s->nb_streams; j++) {
     629           7 :         oggstream = s->streams[j]->priv_data;
     630           7 :         ogg_buffer_data(s, s->streams[j], oggstream->header[0],
     631           7 :                         oggstream->header_len[0], 0, 1);
     632           7 :         oggstream->page.flags |= 2; // bos
     633           7 :         ogg_buffer_page(s, oggstream);
     634             :     }
     635          13 :     for (j = 0; j < s->nb_streams; j++) {
     636           7 :         AVStream *st = s->streams[j];
     637           7 :         oggstream = st->priv_data;
     638          21 :         for (i = 1; i < 3; i++) {
     639          14 :             if (oggstream->header_len[i])
     640          12 :                 ogg_buffer_data(s, st, oggstream->header[i],
     641          12 :                                 oggstream->header_len[i], 0, 1);
     642             :         }
     643           7 :         ogg_buffer_page(s, oggstream);
     644             :     }
     645             : 
     646           6 :     oggstream->page.start_granule = AV_NOPTS_VALUE;
     647             : 
     648           6 :     ogg_write_pages(s, 2);
     649             : 
     650           6 :     return 0;
     651             : }
     652             : 
     653        1048 : static int ogg_write_packet_internal(AVFormatContext *s, AVPacket *pkt)
     654             : {
     655        1048 :     AVStream *st = s->streams[pkt->stream_index];
     656        1048 :     OGGStreamContext *oggstream = st->priv_data;
     657             :     int ret;
     658             :     int64_t granule;
     659             : 
     660        1048 :     if (st->codecpar->codec_id == AV_CODEC_ID_THEORA) {
     661           8 :         int64_t pts = oggstream->vrev < 1 ? pkt->pts : pkt->pts + pkt->duration;
     662             :         int pframe_count;
     663           8 :         if (pkt->flags & AV_PKT_FLAG_KEY)
     664           1 :             oggstream->last_kf_pts = pts;
     665           8 :         pframe_count = pts - oggstream->last_kf_pts;
     666             :         // prevent frame count from overflow if key frame flag is not set
     667           8 :         if (pframe_count >= (1<<oggstream->kfgshift)) {
     668           0 :             oggstream->last_kf_pts += pframe_count;
     669           0 :             pframe_count = 0;
     670             :         }
     671           8 :         granule = (oggstream->last_kf_pts<<oggstream->kfgshift) | pframe_count;
     672        1040 :     } else if (st->codecpar->codec_id == AV_CODEC_ID_OPUS)
     673           0 :         granule = pkt->pts + pkt->duration +
     674           0 :                   av_rescale_q(st->codecpar->initial_padding,
     675           0 :                                (AVRational){ 1, st->codecpar->sample_rate },
     676             :                                st->time_base);
     677        1040 :     else if (st->codecpar->codec_id == AV_CODEC_ID_VP8) {
     678             :         int64_t pts, invcnt, dist;
     679             :         int visible;
     680             : 
     681         111 :         visible = (pkt->data[0] >> 4) & 1;
     682         111 :         pts     = pkt->pts + pkt->duration;
     683         111 :         invcnt  = (oggstream->last_granule >> 30) & 3;
     684         111 :         invcnt  = visible ? 3 : (invcnt == 3 ? 0 : invcnt + 1);
     685         111 :         dist    = (pkt->flags & AV_PKT_FLAG_KEY) ? 0 : ((oggstream->last_granule >> 3) & 0x07ffffff) + 1;
     686             : 
     687         111 :         granule = (pts << 32) | (invcnt << 30) | (dist << 3);
     688             :     } else
     689         929 :         granule = pkt->pts + pkt->duration;
     690             : 
     691        1048 :     if (oggstream->page.start_granule == AV_NOPTS_VALUE)
     692           6 :         oggstream->page.start_granule = pkt->pts;
     693             : 
     694        1048 :     ret = ogg_buffer_data(s, st, pkt->data, pkt->size, granule, 0);
     695        1048 :     if (ret < 0)
     696           0 :         return ret;
     697             : 
     698        1048 :     ogg_write_pages(s, 0);
     699             : 
     700        1048 :     oggstream->last_granule = granule;
     701             : 
     702        1048 :     return 0;
     703             : }
     704             : 
     705        1048 : static int ogg_write_packet(AVFormatContext *s, AVPacket *pkt)
     706             : {
     707             :     int i;
     708             : 
     709        1048 :     if (pkt)
     710        1048 :         return ogg_write_packet_internal(s, pkt);
     711             : 
     712           0 :     for (i = 0; i < s->nb_streams; i++) {
     713           0 :         OGGStreamContext *oggstream = s->streams[i]->priv_data;
     714           0 :         if (oggstream->page.segments_count)
     715           0 :             ogg_buffer_page(s, oggstream);
     716             :     }
     717             : 
     718           0 :     ogg_write_pages(s, 2);
     719           0 :     return 1;
     720             : }
     721             : 
     722           6 : static int ogg_write_trailer(AVFormatContext *s)
     723             : {
     724             :     int i;
     725             : 
     726             :     /* flush current page if needed */
     727          13 :     for (i = 0; i < s->nb_streams; i++) {
     728           7 :         OGGStreamContext *oggstream = s->streams[i]->priv_data;
     729             : 
     730           7 :         if (oggstream->page.size > 0)
     731           6 :             ogg_buffer_page(s, oggstream);
     732             :     }
     733             : 
     734           6 :     ogg_write_pages(s, 1);
     735             : 
     736           6 :     return 0;
     737             : }
     738             : 
     739           6 : static void ogg_free(AVFormatContext *s)
     740             : {
     741             :     int i;
     742             : 
     743          13 :     for (i = 0; i < s->nb_streams; i++) {
     744           7 :         AVStream *st = s->streams[i];
     745           7 :         OGGStreamContext *oggstream = st->priv_data;
     746           7 :         if (!oggstream)
     747           0 :             continue;
     748          13 :         if (st->codecpar->codec_id == AV_CODEC_ID_FLAC ||
     749          12 :             st->codecpar->codec_id == AV_CODEC_ID_SPEEX ||
     750          12 :             st->codecpar->codec_id == AV_CODEC_ID_OPUS ||
     751           6 :             st->codecpar->codec_id == AV_CODEC_ID_VP8) {
     752           2 :             av_freep(&oggstream->header[0]);
     753             :         }
     754           7 :         av_freep(&oggstream->header[1]);
     755           7 :         av_freep(&st->priv_data);
     756             :     }
     757           6 : }
     758             : 
     759             : #if CONFIG_OGG_MUXER
     760             : OGG_CLASS(ogg, Ogg)
     761             : AVOutputFormat ff_ogg_muxer = {
     762             :     .name              = "ogg",
     763             :     .long_name         = NULL_IF_CONFIG_SMALL("Ogg"),
     764             :     .mime_type         = "application/ogg",
     765             :     .extensions        = "ogg"
     766             : #if !CONFIG_OGV_MUXER
     767             :                          ",ogv"
     768             : #endif
     769             : #if !CONFIG_SPX_MUXER
     770             :                          ",spx"
     771             : #endif
     772             : #if !CONFIG_OPUS_MUXER
     773             :                          ",opus"
     774             : #endif
     775             :                          ,
     776             :     .priv_data_size    = sizeof(OGGContext),
     777             :     .audio_codec       = CONFIG_LIBVORBIS_ENCODER ?
     778             :                          AV_CODEC_ID_VORBIS : AV_CODEC_ID_FLAC,
     779             :     .video_codec       = AV_CODEC_ID_THEORA,
     780             :     .init              = ogg_init,
     781             :     .write_header      = ogg_write_header,
     782             :     .write_packet      = ogg_write_packet,
     783             :     .write_trailer     = ogg_write_trailer,
     784             :     .deinit            = ogg_free,
     785             :     .flags             = AVFMT_TS_NEGATIVE | AVFMT_TS_NONSTRICT | AVFMT_ALLOW_FLUSH,
     786             :     .priv_class        = &ogg_muxer_class,
     787             : };
     788             : #endif
     789             : 
     790             : #if CONFIG_OGA_MUXER
     791             : OGG_CLASS(oga, Ogg audio)
     792             : AVOutputFormat ff_oga_muxer = {
     793             :     .name              = "oga",
     794             :     .long_name         = NULL_IF_CONFIG_SMALL("Ogg Audio"),
     795             :     .mime_type         = "audio/ogg",
     796             :     .extensions        = "oga",
     797             :     .priv_data_size    = sizeof(OGGContext),
     798             :     .audio_codec       = AV_CODEC_ID_FLAC,
     799             :     .init              = ogg_init,
     800             :     .write_header      = ogg_write_header,
     801             :     .write_packet      = ogg_write_packet,
     802             :     .write_trailer     = ogg_write_trailer,
     803             :     .deinit            = ogg_free,
     804             :     .flags             = AVFMT_TS_NEGATIVE | AVFMT_ALLOW_FLUSH,
     805             :     .priv_class        = &oga_muxer_class,
     806             : };
     807             : #endif
     808             : 
     809             : #if CONFIG_OGV_MUXER
     810             : OGG_CLASS(ogv, Ogg video)
     811             : AVOutputFormat ff_ogv_muxer = {
     812             :     .name              = "ogv",
     813             :     .long_name         = NULL_IF_CONFIG_SMALL("Ogg Video"),
     814             :     .mime_type         = "video/ogg",
     815             :     .extensions        = "ogv",
     816             :     .priv_data_size    = sizeof(OGGContext),
     817             :     .audio_codec       = CONFIG_LIBVORBIS_ENCODER ?
     818             :                          AV_CODEC_ID_VORBIS : AV_CODEC_ID_FLAC,
     819             :     .video_codec       = CONFIG_LIBTHEORA_ENCODER ?
     820             :                          AV_CODEC_ID_THEORA : AV_CODEC_ID_VP8,
     821             :     .init              = ogg_init,
     822             :     .write_header      = ogg_write_header,
     823             :     .write_packet      = ogg_write_packet,
     824             :     .write_trailer     = ogg_write_trailer,
     825             :     .deinit            = ogg_free,
     826             :     .flags             = AVFMT_TS_NEGATIVE | AVFMT_TS_NONSTRICT | AVFMT_ALLOW_FLUSH,
     827             :     .priv_class        = &ogv_muxer_class,
     828             : };
     829             : #endif
     830             : 
     831             : #if CONFIG_SPX_MUXER
     832             : OGG_CLASS(spx, Ogg Speex)
     833             : AVOutputFormat ff_spx_muxer = {
     834             :     .name              = "spx",
     835             :     .long_name         = NULL_IF_CONFIG_SMALL("Ogg Speex"),
     836             :     .mime_type         = "audio/ogg",
     837             :     .extensions        = "spx",
     838             :     .priv_data_size    = sizeof(OGGContext),
     839             :     .audio_codec       = AV_CODEC_ID_SPEEX,
     840             :     .init              = ogg_init,
     841             :     .write_header      = ogg_write_header,
     842             :     .write_packet      = ogg_write_packet,
     843             :     .write_trailer     = ogg_write_trailer,
     844             :     .deinit            = ogg_free,
     845             :     .flags             = AVFMT_TS_NEGATIVE | AVFMT_ALLOW_FLUSH,
     846             :     .priv_class        = &spx_muxer_class,
     847             : };
     848             : #endif
     849             : 
     850             : #if CONFIG_OPUS_MUXER
     851             : OGG_CLASS(opus, Ogg Opus)
     852             : AVOutputFormat ff_opus_muxer = {
     853             :     .name              = "opus",
     854             :     .long_name         = NULL_IF_CONFIG_SMALL("Ogg Opus"),
     855             :     .mime_type         = "audio/ogg",
     856             :     .extensions        = "opus",
     857             :     .priv_data_size    = sizeof(OGGContext),
     858             :     .audio_codec       = AV_CODEC_ID_OPUS,
     859             :     .init              = ogg_init,
     860             :     .write_header      = ogg_write_header,
     861             :     .write_packet      = ogg_write_packet,
     862             :     .write_trailer     = ogg_write_trailer,
     863             :     .deinit            = ogg_free,
     864             :     .flags             = AVFMT_TS_NEGATIVE | AVFMT_ALLOW_FLUSH,
     865             :     .priv_class        = &opus_muxer_class,
     866             : };
     867             : #endif

Generated by: LCOV version 1.13