• Main Page
  • Related Pages
  • Modules
  • Data Structures
  • Files
  • Examples
  • File List
  • Globals

libavformat/oggenc.c

Go to the documentation of this file.
00001 /*
00002  * Ogg muxer
00003  * Copyright (c) 2007 Baptiste Coudurier <baptiste dot coudurier at free dot fr>
00004  *
00005  * This file is part of Libav.
00006  *
00007  * Libav is free software; you can redistribute it and/or
00008  * modify it under the terms of the GNU Lesser General Public
00009  * License as published by the Free Software Foundation; either
00010  * version 2.1 of the License, or (at your option) any later version.
00011  *
00012  * Libav is distributed in the hope that it will be useful,
00013  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00014  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00015  * Lesser General Public License for more details.
00016  *
00017  * You should have received a copy of the GNU Lesser General Public
00018  * License along with Libav; if not, write to the Free Software
00019  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
00020  */
00021 
00022 #include "libavutil/crc.h"
00023 #include "libavutil/mathematics.h"
00024 #include "libavutil/random_seed.h"
00025 #include "libavcodec/xiph.h"
00026 #include "libavcodec/bytestream.h"
00027 #include "libavcodec/flac.h"
00028 #include "avformat.h"
00029 #include "avio_internal.h"
00030 #include "internal.h"
00031 #include "vorbiscomment.h"
00032 
00033 #define MAX_PAGE_SIZE 65025
00034 
00035 typedef struct {
00036     int64_t granule;
00037     int stream_index;
00038     uint8_t flags;
00039     uint8_t segments_count;
00040     uint8_t segments[255];
00041     uint8_t data[MAX_PAGE_SIZE];
00042     uint16_t size;
00043 } OGGPage;
00044 
00045 typedef struct {
00046     unsigned page_counter;
00047     uint8_t *header[3];
00048     int header_len[3];
00050     int kfgshift;
00051     int64_t last_kf_pts;
00052     int vrev;
00053     int eos;
00054     unsigned page_count; 
00055     OGGPage page; 
00056     unsigned serial_num; 
00057     int64_t last_granule; 
00058 } OGGStreamContext;
00059 
00060 typedef struct OGGPageList {
00061     OGGPage page;
00062     struct OGGPageList *next;
00063 } OGGPageList;
00064 
00065 typedef struct {
00066     OGGPageList *page_list;
00067 } OGGContext;
00068 
00069 static void ogg_update_checksum(AVFormatContext *s, AVIOContext *pb, int64_t crc_offset)
00070 {
00071     int64_t pos = avio_tell(pb);
00072     uint32_t checksum = ffio_get_checksum(pb);
00073     avio_seek(pb, crc_offset, SEEK_SET);
00074     avio_wb32(pb, checksum);
00075     avio_seek(pb, pos, SEEK_SET);
00076 }
00077 
00078 static int ogg_write_page(AVFormatContext *s, OGGPage *page, int extra_flags)
00079 {
00080     OGGStreamContext *oggstream = s->streams[page->stream_index]->priv_data;
00081     AVIOContext *pb;
00082     int64_t crc_offset;
00083     int ret, size;
00084     uint8_t *buf;
00085 
00086     ret = avio_open_dyn_buf(&pb);
00087     if (ret < 0)
00088         return ret;
00089     ffio_init_checksum(pb, ff_crc04C11DB7_update, 0);
00090     ffio_wfourcc(pb, "OggS");
00091     avio_w8(pb, 0);
00092     avio_w8(pb, page->flags | extra_flags);
00093     avio_wl64(pb, page->granule);
00094     avio_wl32(pb, oggstream->serial_num);
00095     avio_wl32(pb, oggstream->page_counter++);
00096     crc_offset = avio_tell(pb);
00097     avio_wl32(pb, 0); // crc
00098     avio_w8(pb, page->segments_count);
00099     avio_write(pb, page->segments, page->segments_count);
00100     avio_write(pb, page->data, page->size);
00101 
00102     ogg_update_checksum(s, pb, crc_offset);
00103     avio_flush(pb);
00104 
00105     size = avio_close_dyn_buf(pb, &buf);
00106     if (size < 0)
00107         return size;
00108 
00109     avio_write(s->pb, buf, size);
00110     avio_flush(s->pb);
00111     av_free(buf);
00112     oggstream->page_count--;
00113     return 0;
00114 }
00115 
00116 static int64_t ogg_granule_to_timestamp(OGGStreamContext *oggstream, int64_t granule)
00117 {
00118     if (oggstream->kfgshift)
00119         return (granule>>oggstream->kfgshift) +
00120             (granule & ((1<<oggstream->kfgshift)-1));
00121     else
00122         return granule;
00123 }
00124 
00125 static int ogg_compare_granule(AVFormatContext *s, OGGPage *next, OGGPage *page)
00126 {
00127     AVStream *st2 = s->streams[next->stream_index];
00128     AVStream *st  = s->streams[page->stream_index];
00129     int64_t next_granule, cur_granule;
00130 
00131     if (next->granule == -1 || page->granule == -1)
00132         return 0;
00133 
00134     next_granule = av_rescale_q(ogg_granule_to_timestamp(st2->priv_data, next->granule),
00135                                 st2->time_base, AV_TIME_BASE_Q);
00136     cur_granule  = av_rescale_q(ogg_granule_to_timestamp(st->priv_data, page->granule),
00137                                 st ->time_base, AV_TIME_BASE_Q);
00138     return next_granule > cur_granule;
00139 }
00140 
00141 static int ogg_reset_cur_page(OGGStreamContext *oggstream)
00142 {
00143     oggstream->page.granule = -1;
00144     oggstream->page.flags = 0;
00145     oggstream->page.segments_count = 0;
00146     oggstream->page.size = 0;
00147     return 0;
00148 }
00149 
00150 static int ogg_buffer_page(AVFormatContext *s, OGGStreamContext *oggstream)
00151 {
00152     OGGContext *ogg = s->priv_data;
00153     OGGPageList **p = &ogg->page_list;
00154     OGGPageList *l = av_mallocz(sizeof(*l));
00155 
00156     if (!l)
00157         return AVERROR(ENOMEM);
00158     l->page = oggstream->page;
00159 
00160     oggstream->page_count++;
00161     ogg_reset_cur_page(oggstream);
00162 
00163     while (*p) {
00164         if (ogg_compare_granule(s, &(*p)->page, &l->page))
00165             break;
00166         p = &(*p)->next;
00167     }
00168     l->next = *p;
00169     *p = l;
00170 
00171     return 0;
00172 }
00173 
00174 static int ogg_buffer_data(AVFormatContext *s, AVStream *st,
00175                            uint8_t *data, unsigned size, int64_t granule)
00176 {
00177     OGGStreamContext *oggstream = st->priv_data;
00178     int total_segments = size / 255 + 1;
00179     uint8_t *p = data;
00180     int i, segments, len, flush = 0;
00181 
00182     // Handles VFR by flushing page because this frame needs to have a timestamp
00183     if (st->codec->codec_id == CODEC_ID_THEORA &&
00184         ogg_granule_to_timestamp(oggstream, granule) >
00185         ogg_granule_to_timestamp(oggstream, oggstream->last_granule) + 1) {
00186         if (oggstream->page.granule != -1)
00187             ogg_buffer_page(s, oggstream);
00188         flush = 1;
00189     }
00190 
00191     for (i = 0; i < total_segments; ) {
00192         OGGPage *page = &oggstream->page;
00193 
00194         segments = FFMIN(total_segments - i, 255 - page->segments_count);
00195 
00196         if (i && !page->segments_count)
00197             page->flags |= 1; // continued packet
00198 
00199         memset(page->segments+page->segments_count, 255, segments - 1);
00200         page->segments_count += segments - 1;
00201 
00202         len = FFMIN(size, segments*255);
00203         page->segments[page->segments_count++] = len - (segments-1)*255;
00204         memcpy(page->data+page->size, p, len);
00205         p += len;
00206         size -= len;
00207         i += segments;
00208         page->size += len;
00209 
00210         if (i == total_segments)
00211             page->granule = granule;
00212 
00213         if (page->segments_count == 255) {
00214             ogg_buffer_page(s, oggstream);
00215         }
00216     }
00217 
00218     if (flush && oggstream->page.granule != -1)
00219         ogg_buffer_page(s, oggstream);
00220 
00221     return 0;
00222 }
00223 
00224 static uint8_t *ogg_write_vorbiscomment(int offset, int bitexact,
00225                                         int *header_len, AVDictionary **m, int framing_bit)
00226 {
00227     const char *vendor = bitexact ? "Libav" : LIBAVFORMAT_IDENT;
00228     int size;
00229     uint8_t *p, *p0;
00230     unsigned int count;
00231 
00232     ff_metadata_conv(m, ff_vorbiscomment_metadata_conv, NULL);
00233 
00234     size = offset + ff_vorbiscomment_length(*m, vendor, &count) + framing_bit;
00235     p = av_mallocz(size);
00236     if (!p)
00237         return NULL;
00238     p0 = p;
00239 
00240     p += offset;
00241     ff_vorbiscomment_write(&p, m, vendor, count);
00242     if (framing_bit)
00243         bytestream_put_byte(&p, 1);
00244 
00245     *header_len = size;
00246     return p0;
00247 }
00248 
00249 static int ogg_build_flac_headers(AVCodecContext *avctx,
00250                                   OGGStreamContext *oggstream, int bitexact,
00251                                   AVDictionary **m)
00252 {
00253     enum FLACExtradataFormat format;
00254     uint8_t *streaminfo;
00255     uint8_t *p;
00256 
00257     if (!avpriv_flac_is_extradata_valid(avctx, &format, &streaminfo))
00258         return -1;
00259 
00260     // first packet: STREAMINFO
00261     oggstream->header_len[0] = 51;
00262     oggstream->header[0] = av_mallocz(51); // per ogg flac specs
00263     p = oggstream->header[0];
00264     if (!p)
00265         return AVERROR(ENOMEM);
00266     bytestream_put_byte(&p, 0x7F);
00267     bytestream_put_buffer(&p, "FLAC", 4);
00268     bytestream_put_byte(&p, 1); // major version
00269     bytestream_put_byte(&p, 0); // minor version
00270     bytestream_put_be16(&p, 1); // headers packets without this one
00271     bytestream_put_buffer(&p, "fLaC", 4);
00272     bytestream_put_byte(&p, 0x00); // streaminfo
00273     bytestream_put_be24(&p, 34);
00274     bytestream_put_buffer(&p, streaminfo, FLAC_STREAMINFO_SIZE);
00275 
00276     // second packet: VorbisComment
00277     p = ogg_write_vorbiscomment(4, bitexact, &oggstream->header_len[1], m, 0);
00278     if (!p)
00279         return AVERROR(ENOMEM);
00280     oggstream->header[1] = p;
00281     bytestream_put_byte(&p, 0x84); // last metadata block and vorbis comment
00282     bytestream_put_be24(&p, oggstream->header_len[1] - 4);
00283 
00284     return 0;
00285 }
00286 
00287 #define SPEEX_HEADER_SIZE 80
00288 
00289 static int ogg_build_speex_headers(AVCodecContext *avctx,
00290                                    OGGStreamContext *oggstream, int bitexact,
00291                                    AVDictionary **m)
00292 {
00293     uint8_t *p;
00294 
00295     if (avctx->extradata_size < SPEEX_HEADER_SIZE)
00296         return -1;
00297 
00298     // first packet: Speex header
00299     p = av_mallocz(SPEEX_HEADER_SIZE);
00300     if (!p)
00301         return AVERROR(ENOMEM);
00302     oggstream->header[0] = p;
00303     oggstream->header_len[0] = SPEEX_HEADER_SIZE;
00304     bytestream_put_buffer(&p, avctx->extradata, SPEEX_HEADER_SIZE);
00305     AV_WL32(&oggstream->header[0][68], 0);  // set extra_headers to 0
00306 
00307     // second packet: VorbisComment
00308     p = ogg_write_vorbiscomment(0, bitexact, &oggstream->header_len[1], m, 0);
00309     if (!p)
00310         return AVERROR(ENOMEM);
00311     oggstream->header[1] = p;
00312 
00313     return 0;
00314 }
00315 
00316 static int ogg_write_header(AVFormatContext *s)
00317 {
00318     OGGStreamContext *oggstream;
00319     int i, j;
00320 
00321     for (i = 0; i < s->nb_streams; i++) {
00322         AVStream *st = s->streams[i];
00323         unsigned serial_num = i;
00324 
00325         if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
00326             avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);
00327         else if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
00328             avpriv_set_pts_info(st, 64, st->codec->time_base.num, st->codec->time_base.den);
00329         if (st->codec->codec_id != CODEC_ID_VORBIS &&
00330             st->codec->codec_id != CODEC_ID_THEORA &&
00331             st->codec->codec_id != CODEC_ID_SPEEX  &&
00332             st->codec->codec_id != CODEC_ID_FLAC) {
00333             av_log(s, AV_LOG_ERROR, "Unsupported codec id in stream %d\n", i);
00334             return -1;
00335         }
00336 
00337         if (!st->codec->extradata || !st->codec->extradata_size) {
00338             av_log(s, AV_LOG_ERROR, "No extradata present\n");
00339             return -1;
00340         }
00341         oggstream = av_mallocz(sizeof(*oggstream));
00342         oggstream->page.stream_index = i;
00343 
00344         if (!(st->codec->flags & CODEC_FLAG_BITEXACT))
00345             do {
00346                 serial_num = av_get_random_seed();
00347                 for (j = 0; j < i; j++) {
00348                     OGGStreamContext *sc = s->streams[j]->priv_data;
00349                     if (serial_num == sc->serial_num)
00350                         break;
00351                 }
00352             } while (j < i);
00353         oggstream->serial_num = serial_num;
00354 
00355         st->priv_data = oggstream;
00356         if (st->codec->codec_id == CODEC_ID_FLAC) {
00357             int err = ogg_build_flac_headers(st->codec, oggstream,
00358                                              st->codec->flags & CODEC_FLAG_BITEXACT,
00359                                              &s->metadata);
00360             if (err) {
00361                 av_log(s, AV_LOG_ERROR, "Error writing FLAC headers\n");
00362                 av_freep(&st->priv_data);
00363                 return err;
00364             }
00365         } else if (st->codec->codec_id == CODEC_ID_SPEEX) {
00366             int err = ogg_build_speex_headers(st->codec, oggstream,
00367                                               st->codec->flags & CODEC_FLAG_BITEXACT,
00368                                               &s->metadata);
00369             if (err) {
00370                 av_log(s, AV_LOG_ERROR, "Error writing Speex headers\n");
00371                 av_freep(&st->priv_data);
00372                 return err;
00373             }
00374         } else {
00375             uint8_t *p;
00376             const char *cstr = st->codec->codec_id == CODEC_ID_VORBIS ? "vorbis" : "theora";
00377             int header_type = st->codec->codec_id == CODEC_ID_VORBIS ? 3 : 0x81;
00378             int framing_bit = st->codec->codec_id == CODEC_ID_VORBIS ? 1 : 0;
00379 
00380             if (avpriv_split_xiph_headers(st->codec->extradata, st->codec->extradata_size,
00381                                       st->codec->codec_id == CODEC_ID_VORBIS ? 30 : 42,
00382                                       oggstream->header, oggstream->header_len) < 0) {
00383                 av_log(s, AV_LOG_ERROR, "Extradata corrupted\n");
00384                 av_freep(&st->priv_data);
00385                 return -1;
00386             }
00387 
00388             p = ogg_write_vorbiscomment(7, st->codec->flags & CODEC_FLAG_BITEXACT,
00389                                         &oggstream->header_len[1], &s->metadata,
00390                                         framing_bit);
00391             if (!p)
00392                 return AVERROR(ENOMEM);
00393 
00394             oggstream->header[1] = p;
00395             bytestream_put_byte(&p, header_type);
00396             bytestream_put_buffer(&p, cstr, 6);
00397 
00398             if (st->codec->codec_id == CODEC_ID_THEORA) {
00401                 oggstream->kfgshift = ((oggstream->header[0][40]&3)<<3)|(oggstream->header[0][41]>>5);
00402                 oggstream->vrev = oggstream->header[0][9];
00403                 av_log(s, AV_LOG_DEBUG, "theora kfgshift %d, vrev %d\n",
00404                        oggstream->kfgshift, oggstream->vrev);
00405             }
00406         }
00407     }
00408 
00409     for (j = 0; j < s->nb_streams; j++) {
00410         OGGStreamContext *oggstream = s->streams[j]->priv_data;
00411         ogg_buffer_data(s, s->streams[j], oggstream->header[0],
00412                         oggstream->header_len[0], 0);
00413         oggstream->page.flags |= 2; // bos
00414         ogg_buffer_page(s, oggstream);
00415     }
00416     for (j = 0; j < s->nb_streams; j++) {
00417         AVStream *st = s->streams[j];
00418         OGGStreamContext *oggstream = st->priv_data;
00419         for (i = 1; i < 3; i++) {
00420             if (oggstream && oggstream->header_len[i])
00421                 ogg_buffer_data(s, st, oggstream->header[i],
00422                                 oggstream->header_len[i], 0);
00423         }
00424         ogg_buffer_page(s, oggstream);
00425     }
00426     return 0;
00427 }
00428 
00429 static void ogg_write_pages(AVFormatContext *s, int flush)
00430 {
00431     OGGContext *ogg = s->priv_data;
00432     OGGPageList *next, *p;
00433 
00434     if (!ogg->page_list)
00435         return;
00436 
00437     for (p = ogg->page_list; p; ) {
00438         OGGStreamContext *oggstream =
00439             s->streams[p->page.stream_index]->priv_data;
00440         if (oggstream->page_count < 2 && !flush)
00441             break;
00442         ogg_write_page(s, &p->page,
00443                        flush && oggstream->page_count == 1 ? 4 : 0); // eos
00444         next = p->next;
00445         av_freep(&p);
00446         p = next;
00447     }
00448     ogg->page_list = p;
00449 }
00450 
00451 static int ogg_write_packet(AVFormatContext *s, AVPacket *pkt)
00452 {
00453     AVStream *st = s->streams[pkt->stream_index];
00454     OGGStreamContext *oggstream = st->priv_data;
00455     int ret;
00456     int64_t granule;
00457 
00458     if (st->codec->codec_id == CODEC_ID_THEORA) {
00459         int64_t pts = oggstream->vrev < 1 ? pkt->pts : pkt->pts + pkt->duration;
00460         int pframe_count;
00461         if (pkt->flags & AV_PKT_FLAG_KEY)
00462             oggstream->last_kf_pts = pts;
00463         pframe_count = pts - oggstream->last_kf_pts;
00464         // prevent frame count from overflow if key frame flag is not set
00465         if (pframe_count >= (1<<oggstream->kfgshift)) {
00466             oggstream->last_kf_pts += pframe_count;
00467             pframe_count = 0;
00468         }
00469         granule = (oggstream->last_kf_pts<<oggstream->kfgshift) | pframe_count;
00470     } else
00471         granule = pkt->pts + pkt->duration;
00472 
00473     ret = ogg_buffer_data(s, st, pkt->data, pkt->size, granule);
00474     if (ret < 0)
00475         return ret;
00476 
00477     ogg_write_pages(s, 0);
00478 
00479     oggstream->last_granule = granule;
00480 
00481     return 0;
00482 }
00483 
00484 static int ogg_write_trailer(AVFormatContext *s)
00485 {
00486     int i;
00487 
00488     /* flush current page */
00489     for (i = 0; i < s->nb_streams; i++)
00490         ogg_buffer_page(s, s->streams[i]->priv_data);
00491 
00492     ogg_write_pages(s, 1);
00493 
00494     for (i = 0; i < s->nb_streams; i++) {
00495         AVStream *st = s->streams[i];
00496         OGGStreamContext *oggstream = st->priv_data;
00497         if (st->codec->codec_id == CODEC_ID_FLAC ||
00498             st->codec->codec_id == CODEC_ID_SPEEX) {
00499             av_free(oggstream->header[0]);
00500             av_free(oggstream->header[1]);
00501         }
00502         av_freep(&st->priv_data);
00503     }
00504     return 0;
00505 }
00506 
00507 AVOutputFormat ff_ogg_muxer = {
00508     .name              = "ogg",
00509     .long_name         = NULL_IF_CONFIG_SMALL("Ogg"),
00510     .mime_type         = "application/ogg",
00511     .extensions        = "ogg,ogv,spx",
00512     .priv_data_size    = sizeof(OGGContext),
00513     .audio_codec       = CODEC_ID_FLAC,
00514     .video_codec       = CODEC_ID_THEORA,
00515     .write_header      = ogg_write_header,
00516     .write_packet      = ogg_write_packet,
00517     .write_trailer     = ogg_write_trailer,
00518 };
Generated on Thu Jan 24 2013 17:08:55 for Libav by doxygen 1.7.1