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