FFmpeg
 All Data Structures Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
oggenc.c
Go to the documentation of this file.
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 "libavutil/crc.h"
23 #include "libavutil/opt.h"
24 #include "libavutil/mathematics.h"
25 #include "libavutil/opt.h"
26 #include "libavutil/random_seed.h"
27 #include "libavcodec/xiph.h"
28 #include "libavcodec/bytestream.h"
29 #include "libavcodec/flac.h"
30 #include "avformat.h"
31 #include "avio_internal.h"
32 #include "internal.h"
33 #include "vorbiscomment.h"
34 
35 #define MAX_PAGE_SIZE 65025
36 
37 typedef struct {
38  int64_t granule;
44  uint16_t size;
45 } OGGPage;
46 
47 typedef struct {
48  unsigned page_counter;
49  uint8_t *header[3];
50  int header_len[3];
51  /** for theora granule */
52  int kfgshift;
53  int64_t last_kf_pts;
54  int vrev;
55  int eos;
56  unsigned page_count; ///< number of page buffered
57  OGGPage page; ///< current page
58  unsigned serial_num; ///< serial number
59  int64_t last_granule; ///< last packet granule
61 
62 typedef struct OGGPageList {
64  struct OGGPageList *next;
65 } OGGPageList;
66 
67 typedef struct {
68  const AVClass *class;
70  int pref_size; ///< preferred page size (0 => fill all segments)
71 } OGGContext;
72 
73 #define OFFSET(x) offsetof(OGGContext, x)
74 #define PARAM AV_OPT_FLAG_ENCODING_PARAM
75 
76 static const AVOption options[] = {
77  { "oggpagesize", "Set preferred Ogg page size.",
78  offsetof(OGGContext, pref_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, MAX_PAGE_SIZE, AV_OPT_FLAG_ENCODING_PARAM},
79  { "pagesize", "preferred page size in bytes",
80  OFFSET(pref_size), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, MAX_PAGE_SIZE, PARAM },
81  { NULL },
82 };
83 
84 static const AVClass ogg_muxer_class = {
85  .class_name = "Ogg muxer",
86  .item_name = av_default_item_name,
87  .option = options,
88  .version = LIBAVUTIL_VERSION_INT,
89 };
90 
91 
92 static void ogg_update_checksum(AVFormatContext *s, AVIOContext *pb, int64_t crc_offset)
93 {
94  int64_t pos = avio_tell(pb);
95  uint32_t checksum = ffio_get_checksum(pb);
96  avio_seek(pb, crc_offset, SEEK_SET);
97  avio_wb32(pb, checksum);
98  avio_seek(pb, pos, SEEK_SET);
99 }
100 
101 static int ogg_write_page(AVFormatContext *s, OGGPage *page, int extra_flags)
102 {
103  OGGStreamContext *oggstream = s->streams[page->stream_index]->priv_data;
104  AVIOContext *pb;
105  int64_t crc_offset;
106  int ret, size;
107  uint8_t *buf;
108 
109  ret = avio_open_dyn_buf(&pb);
110  if (ret < 0)
111  return ret;
113  ffio_wfourcc(pb, "OggS");
114  avio_w8(pb, 0);
115  avio_w8(pb, page->flags | extra_flags);
116  avio_wl64(pb, page->granule);
117  avio_wl32(pb, oggstream->serial_num);
118  avio_wl32(pb, oggstream->page_counter++);
119  crc_offset = avio_tell(pb);
120  avio_wl32(pb, 0); // crc
121  avio_w8(pb, page->segments_count);
122  avio_write(pb, page->segments, page->segments_count);
123  avio_write(pb, page->data, page->size);
124 
125  ogg_update_checksum(s, pb, crc_offset);
126  avio_flush(pb);
127 
128  size = avio_close_dyn_buf(pb, &buf);
129  if (size < 0)
130  return size;
131 
132  avio_write(s->pb, buf, size);
133  avio_flush(s->pb);
134  av_free(buf);
135  oggstream->page_count--;
136  return 0;
137 }
138 
139 static int ogg_key_granule(OGGStreamContext *oggstream, int64_t granule)
140 {
141  return oggstream->kfgshift && !(granule & ((1<<oggstream->kfgshift)-1));
142 }
143 
144 static int64_t ogg_granule_to_timestamp(OGGStreamContext *oggstream, int64_t granule)
145 {
146  if (oggstream->kfgshift)
147  return (granule>>oggstream->kfgshift) +
148  (granule & ((1<<oggstream->kfgshift)-1));
149  else
150  return granule;
151 }
152 
154 {
155  AVStream *st2 = s->streams[next->stream_index];
156  AVStream *st = s->streams[page->stream_index];
157  int64_t next_granule, cur_granule;
158 
159  if (next->granule == -1 || page->granule == -1)
160  return 0;
161 
162  next_granule = av_rescale_q(ogg_granule_to_timestamp(st2->priv_data, next->granule),
163  st2->time_base, AV_TIME_BASE_Q);
164  cur_granule = av_rescale_q(ogg_granule_to_timestamp(st->priv_data, page->granule),
165  st ->time_base, AV_TIME_BASE_Q);
166  return next_granule > cur_granule;
167 }
168 
169 static int ogg_reset_cur_page(OGGStreamContext *oggstream)
170 {
171  oggstream->page.granule = -1;
172  oggstream->page.flags = 0;
173  oggstream->page.segments_count = 0;
174  oggstream->page.size = 0;
175  return 0;
176 }
177 
179 {
180  OGGContext *ogg = s->priv_data;
181  OGGPageList **p = &ogg->page_list;
182  OGGPageList *l = av_mallocz(sizeof(*l));
183 
184  if (!l)
185  return AVERROR(ENOMEM);
186  l->page = oggstream->page;
187 
188  oggstream->page_count++;
189  ogg_reset_cur_page(oggstream);
190 
191  while (*p) {
192  if (ogg_compare_granule(s, &(*p)->page, &l->page))
193  break;
194  p = &(*p)->next;
195  }
196  l->next = *p;
197  *p = l;
198 
199  return 0;
200 }
201 
203  uint8_t *data, unsigned size, int64_t granule,
204  int header)
205 {
206  OGGStreamContext *oggstream = st->priv_data;
207  OGGContext *ogg = s->priv_data;
208  int total_segments = size / 255 + 1;
209  uint8_t *p = data;
210  int i, segments, len, flush = 0;
211 
212  // Handles VFR by flushing page because this frame needs to have a timestamp
213  // For theora, keyframes also need to have a timestamp to correctly mark
214  // them as such, otherwise seeking will not work correctly at the very
215  // least with old libogg versions.
216  // Do not try to flush header packets though, that will create broken files.
217  if (st->codec->codec_id == AV_CODEC_ID_THEORA && !header &&
218  (ogg_granule_to_timestamp(oggstream, granule) >
219  ogg_granule_to_timestamp(oggstream, oggstream->last_granule) + 1 ||
220  ogg_key_granule(oggstream, granule))) {
221  if (oggstream->page.granule != -1)
222  ogg_buffer_page(s, oggstream);
223  flush = 1;
224  }
225 
226  for (i = 0; i < total_segments; ) {
227  OGGPage *page = &oggstream->page;
228 
229  segments = FFMIN(total_segments - i, 255 - page->segments_count);
230 
231  if (i && !page->segments_count)
232  page->flags |= 1; // continued packet
233 
234  memset(page->segments+page->segments_count, 255, segments - 1);
235  page->segments_count += segments - 1;
236 
237  len = FFMIN(size, segments*255);
238  page->segments[page->segments_count++] = len - (segments-1)*255;
239  memcpy(page->data+page->size, p, len);
240  p += len;
241  size -= len;
242  i += segments;
243  page->size += len;
244 
245  if (i == total_segments)
246  page->granule = granule;
247 
248  if (!header && (page->segments_count == 255 ||
249  (ogg->pref_size > 0 && page->size >= ogg->pref_size))) {
250  ogg_buffer_page(s, oggstream);
251  }
252  }
253 
254  if (flush && oggstream->page.granule != -1)
255  ogg_buffer_page(s, oggstream);
256 
257  return 0;
258 }
259 
260 static uint8_t *ogg_write_vorbiscomment(int offset, int bitexact,
261  int *header_len, AVDictionary **m, int framing_bit)
262 {
263  const char *vendor = bitexact ? "ffmpeg" : LIBAVFORMAT_IDENT;
264  int size;
265  uint8_t *p, *p0;
266  unsigned int count;
267 
269 
270  size = offset + ff_vorbiscomment_length(*m, vendor, &count) + framing_bit;
271  p = av_mallocz(size);
272  if (!p)
273  return NULL;
274  p0 = p;
275 
276  p += offset;
277  ff_vorbiscomment_write(&p, m, vendor, count);
278  if (framing_bit)
279  bytestream_put_byte(&p, 1);
280 
281  *header_len = size;
282  return p0;
283 }
284 
286  OGGStreamContext *oggstream, int bitexact,
287  AVDictionary **m)
288 {
289  enum FLACExtradataFormat format;
290  uint8_t *streaminfo;
291  uint8_t *p;
292 
293  if (!avpriv_flac_is_extradata_valid(avctx, &format, &streaminfo))
294  return -1;
295 
296  // first packet: STREAMINFO
297  oggstream->header_len[0] = 51;
298  oggstream->header[0] = av_mallocz(51); // per ogg flac specs
299  p = oggstream->header[0];
300  if (!p)
301  return AVERROR(ENOMEM);
302  bytestream_put_byte(&p, 0x7F);
303  bytestream_put_buffer(&p, "FLAC", 4);
304  bytestream_put_byte(&p, 1); // major version
305  bytestream_put_byte(&p, 0); // minor version
306  bytestream_put_be16(&p, 1); // headers packets without this one
307  bytestream_put_buffer(&p, "fLaC", 4);
308  bytestream_put_byte(&p, 0x00); // streaminfo
309  bytestream_put_be24(&p, 34);
311 
312  // second packet: VorbisComment
313  p = ogg_write_vorbiscomment(4, bitexact, &oggstream->header_len[1], m, 0);
314  if (!p)
315  return AVERROR(ENOMEM);
316  oggstream->header[1] = p;
317  bytestream_put_byte(&p, 0x84); // last metadata block and vorbis comment
318  bytestream_put_be24(&p, oggstream->header_len[1] - 4);
319 
320  return 0;
321 }
322 
323 #define SPEEX_HEADER_SIZE 80
324 
326  OGGStreamContext *oggstream, int bitexact,
327  AVDictionary **m)
328 {
329  uint8_t *p;
330 
331  if (avctx->extradata_size < SPEEX_HEADER_SIZE)
332  return -1;
333 
334  // first packet: Speex header
336  if (!p)
337  return AVERROR(ENOMEM);
338  oggstream->header[0] = p;
339  oggstream->header_len[0] = SPEEX_HEADER_SIZE;
341  AV_WL32(&oggstream->header[0][68], 0); // set extra_headers to 0
342 
343  // second packet: VorbisComment
344  p = ogg_write_vorbiscomment(0, bitexact, &oggstream->header_len[1], m, 0);
345  if (!p)
346  return AVERROR(ENOMEM);
347  oggstream->header[1] = p;
348 
349  return 0;
350 }
351 
352 #define OPUS_HEADER_SIZE 19
353 
355  OGGStreamContext *oggstream, int bitexact,
356  AVDictionary **m)
357 {
358  uint8_t *p;
359 
360  if (avctx->extradata_size < OPUS_HEADER_SIZE)
361  return -1;
362 
363  /* first packet: Opus header */
364  p = av_mallocz(avctx->extradata_size);
365  if (!p)
366  return AVERROR(ENOMEM);
367  oggstream->header[0] = p;
368  oggstream->header_len[0] = avctx->extradata_size;
369  bytestream_put_buffer(&p, avctx->extradata, avctx->extradata_size);
370 
371  /* second packet: VorbisComment */
372  p = ogg_write_vorbiscomment(8, bitexact, &oggstream->header_len[1], m, 0);
373  if (!p)
374  return AVERROR(ENOMEM);
375  oggstream->header[1] = p;
376  bytestream_put_buffer(&p, "OpusTags", 8);
377 
378  return 0;
379 }
380 
382 {
383  OGGStreamContext *oggstream;
384  int i, j;
385 
386  for (i = 0; i < s->nb_streams; i++) {
387  AVStream *st = s->streams[i];
388  unsigned serial_num = i;
389 
390  if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
391  if (st->codec->codec_id == AV_CODEC_ID_OPUS)
392  /* Opus requires a fixed 48kHz clock */
393  avpriv_set_pts_info(st, 64, 1, 48000);
394  else
395  avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);
396  } else if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
398  if (st->codec->codec_id != AV_CODEC_ID_VORBIS &&
400  st->codec->codec_id != AV_CODEC_ID_SPEEX &&
401  st->codec->codec_id != AV_CODEC_ID_FLAC &&
402  st->codec->codec_id != AV_CODEC_ID_OPUS) {
403  av_log(s, AV_LOG_ERROR, "Unsupported codec id in stream %d\n", i);
404  return -1;
405  }
406 
407  if (!st->codec->extradata || !st->codec->extradata_size) {
408  av_log(s, AV_LOG_ERROR, "No extradata present\n");
409  return -1;
410  }
411  oggstream = av_mallocz(sizeof(*oggstream));
412  oggstream->page.stream_index = i;
413 
414  if (!(st->codec->flags & CODEC_FLAG_BITEXACT))
415  do {
416  serial_num = av_get_random_seed();
417  for (j = 0; j < i; j++) {
418  OGGStreamContext *sc = s->streams[j]->priv_data;
419  if (serial_num == sc->serial_num)
420  break;
421  }
422  } while (j < i);
423  oggstream->serial_num = serial_num;
424 
425  st->priv_data = oggstream;
426  if (st->codec->codec_id == AV_CODEC_ID_FLAC) {
427  int err = ogg_build_flac_headers(st->codec, oggstream,
429  &s->metadata);
430  if (err) {
431  av_log(s, AV_LOG_ERROR, "Error writing FLAC headers\n");
432  av_freep(&st->priv_data);
433  return err;
434  }
435  } else if (st->codec->codec_id == AV_CODEC_ID_SPEEX) {
436  int err = ogg_build_speex_headers(st->codec, oggstream,
438  &s->metadata);
439  if (err) {
440  av_log(s, AV_LOG_ERROR, "Error writing Speex headers\n");
441  av_freep(&st->priv_data);
442  return err;
443  }
444  } else if (st->codec->codec_id == AV_CODEC_ID_OPUS) {
445  int err = ogg_build_opus_headers(st->codec, oggstream,
447  &s->metadata);
448  if (err) {
449  av_log(s, AV_LOG_ERROR, "Error writing Opus headers\n");
450  av_freep(&st->priv_data);
451  return err;
452  }
453  } else {
454  uint8_t *p;
455  const char *cstr = st->codec->codec_id == AV_CODEC_ID_VORBIS ? "vorbis" : "theora";
456  int header_type = st->codec->codec_id == AV_CODEC_ID_VORBIS ? 3 : 0x81;
457  int framing_bit = st->codec->codec_id == AV_CODEC_ID_VORBIS ? 1 : 0;
458 
460  st->codec->codec_id == AV_CODEC_ID_VORBIS ? 30 : 42,
461  oggstream->header, oggstream->header_len) < 0) {
462  av_log(s, AV_LOG_ERROR, "Extradata corrupted\n");
463  av_freep(&st->priv_data);
464  return -1;
465  }
466 
468  &oggstream->header_len[1], &s->metadata,
469  framing_bit);
470  oggstream->header[1] = p;
471  if (!p)
472  return AVERROR(ENOMEM);
473 
474  bytestream_put_byte(&p, header_type);
475  bytestream_put_buffer(&p, cstr, 6);
476 
477  if (st->codec->codec_id == AV_CODEC_ID_THEORA) {
478  /** KFGSHIFT is the width of the less significant section of the granule position
479  The less significant section is the frame count since the last keyframe */
480  oggstream->kfgshift = ((oggstream->header[0][40]&3)<<3)|(oggstream->header[0][41]>>5);
481  oggstream->vrev = oggstream->header[0][9];
482  av_log(s, AV_LOG_DEBUG, "theora kfgshift %d, vrev %d\n",
483  oggstream->kfgshift, oggstream->vrev);
484  }
485  }
486  }
487 
488  for (j = 0; j < s->nb_streams; j++) {
489  OGGStreamContext *oggstream = s->streams[j]->priv_data;
490  ogg_buffer_data(s, s->streams[j], oggstream->header[0],
491  oggstream->header_len[0], 0, 1);
492  oggstream->page.flags |= 2; // bos
493  ogg_buffer_page(s, oggstream);
494  }
495  for (j = 0; j < s->nb_streams; j++) {
496  AVStream *st = s->streams[j];
497  OGGStreamContext *oggstream = st->priv_data;
498  for (i = 1; i < 3; i++) {
499  if (oggstream->header_len[i])
500  ogg_buffer_data(s, st, oggstream->header[i],
501  oggstream->header_len[i], 0, 1);
502  }
503  ogg_buffer_page(s, oggstream);
504  }
505  return 0;
506 }
507 
509 {
510  OGGContext *ogg = s->priv_data;
511  OGGPageList *next, *p;
512 
513  if (!ogg->page_list)
514  return;
515 
516  for (p = ogg->page_list; p; ) {
517  OGGStreamContext *oggstream =
519  if (oggstream->page_count < 2 && !flush)
520  break;
521  ogg_write_page(s, &p->page,
522  flush && oggstream->page_count == 1 ? 4 : 0); // eos
523  next = p->next;
524  av_freep(&p);
525  p = next;
526  }
527  ogg->page_list = p;
528 }
529 
531 {
532  AVStream *st = s->streams[pkt->stream_index];
533  OGGStreamContext *oggstream = st->priv_data;
534  int ret;
535  int64_t granule;
536 
537  if (st->codec->codec_id == AV_CODEC_ID_THEORA) {
538  int64_t pts = oggstream->vrev < 1 ? pkt->pts : pkt->pts + pkt->duration;
539  int pframe_count;
540  if (pkt->flags & AV_PKT_FLAG_KEY)
541  oggstream->last_kf_pts = pts;
542  pframe_count = pts - oggstream->last_kf_pts;
543  // prevent frame count from overflow if key frame flag is not set
544  if (pframe_count >= (1<<oggstream->kfgshift)) {
545  oggstream->last_kf_pts += pframe_count;
546  pframe_count = 0;
547  }
548  granule = (oggstream->last_kf_pts<<oggstream->kfgshift) | pframe_count;
549  } else if (st->codec->codec_id == AV_CODEC_ID_OPUS)
550  granule = pkt->pts + pkt->duration + av_rescale_q(st->codec->delay, (AVRational){ 1, st->codec->sample_rate }, st->time_base);
551  else
552  granule = pkt->pts + pkt->duration;
553 
554  ret = ogg_buffer_data(s, st, pkt->data, pkt->size, granule, 0);
555  if (ret < 0)
556  return ret;
557 
558  ogg_write_pages(s, 0);
559 
560  oggstream->last_granule = granule;
561 
562  return 0;
563 }
564 
566 {
567  int i;
568 
569  /* flush current page */
570  for (i = 0; i < s->nb_streams; i++)
571  ogg_buffer_page(s, s->streams[i]->priv_data);
572 
573  ogg_write_pages(s, 1);
574 
575  for (i = 0; i < s->nb_streams; i++) {
576  AVStream *st = s->streams[i];
577  OGGStreamContext *oggstream = st->priv_data;
578  if (st->codec->codec_id == AV_CODEC_ID_FLAC ||
579  st->codec->codec_id == AV_CODEC_ID_SPEEX ||
580  st->codec->codec_id == AV_CODEC_ID_OPUS) {
581  av_freep(&oggstream->header[0]);
582  }
583  av_freep(&oggstream->header[1]);
584  av_freep(&st->priv_data);
585  }
586  return 0;
587 }
588 
590  .name = "ogg",
591  .long_name = NULL_IF_CONFIG_SMALL("Ogg"),
592  .mime_type = "application/ogg",
593  .extensions = "ogg,ogv,spx,opus",
594  .priv_data_size = sizeof(OGGContext),
595  .audio_codec = AV_CODEC_ID_FLAC,
596  .video_codec = AV_CODEC_ID_THEORA,
600  .priv_class = &ogg_muxer_class,
601 };