FFmpeg  4.4.9
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 <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 {
46  uint16_t size;
47 } OGGPage;
48 
49 typedef struct OGGStreamContext {
50  unsigned page_counter;
52  int header_len[3];
53  /** for theora granule */
54  int kfgshift;
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
65 
66 typedef struct OGGPageList {
68  struct OGGPageList *next;
69 } OGGPageList;
70 
71 typedef struct OGGContext {
72  const AVClass *class;
74  int pref_size; ///< preferred page size (0 => fill all segments)
75  int64_t pref_duration; ///< preferred page duration (0 => fill all segments)
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 static void ogg_write_page(AVFormatContext *s, OGGPage *page, int extra_flags)
103 {
104  OGGStreamContext *oggstream = s->streams[page->stream_index]->priv_data;
105  uint8_t buf[4 + 1 + 1 + 8 + 4 + 4 + 4 + 1 + 255], *ptr = buf, *crc_pos;
106  const AVCRC *crc_table = av_crc_get_table(AV_CRC_32_IEEE);
107  uint32_t crc;
108 
109  bytestream_put_le32(&ptr, MKTAG('O', 'g', 'g', 'S'));
110  bytestream_put_byte(&ptr, 0);
111  bytestream_put_byte(&ptr, page->flags | extra_flags);
112  bytestream_put_le64(&ptr, page->granule);
113  bytestream_put_le32(&ptr, oggstream->serial_num);
114  bytestream_put_le32(&ptr, oggstream->page_counter++);
115  crc_pos = ptr;
116  bytestream_put_le32(&ptr, 0);
117  bytestream_put_byte(&ptr, page->segments_count);
118  bytestream_put_buffer(&ptr, page->segments, page->segments_count);
119 
120  crc = av_crc(crc_table, 0, buf, ptr - buf);
121  crc = av_crc(crc_table, crc, page->data, page->size);
122  bytestream_put_be32(&crc_pos, crc);
123 
124  avio_write(s->pb, buf, ptr - buf);
125  avio_write(s->pb, page->data, page->size);
127  oggstream->page_count--;
128 }
129 
130 static int ogg_key_granule(OGGStreamContext *oggstream, int64_t granule)
131 {
132  return (oggstream->kfgshift && !(granule & ((1<<oggstream->kfgshift)-1))) ||
133  (oggstream->isvp8 && !((granule >> 3) & 0x07ffffff));
134 }
135 
137 {
138  if (oggstream->kfgshift)
139  return (granule>>oggstream->kfgshift) +
140  (granule & ((1<<oggstream->kfgshift)-1));
141  else if (oggstream->isvp8)
142  return granule >> 32;
143  else
144  return granule;
145 }
146 
148 {
149  AVStream *st2 = s->streams[next->stream_index];
150  AVStream *st = s->streams[page->stream_index];
151  int64_t next_granule, cur_granule;
152 
153  if (next->granule == -1 || page->granule == -1)
154  return 0;
155 
156  next_granule = av_rescale_q(ogg_granule_to_timestamp(st2->priv_data, next->granule),
157  st2->time_base, AV_TIME_BASE_Q);
158  cur_granule = av_rescale_q(ogg_granule_to_timestamp(st->priv_data, page->granule),
159  st ->time_base, AV_TIME_BASE_Q);
160  return next_granule > cur_granule;
161 }
162 
163 static int ogg_reset_cur_page(OGGStreamContext *oggstream)
164 {
165  oggstream->page.granule = -1;
166  oggstream->page.flags = 0;
167  oggstream->page.segments_count = 0;
168  oggstream->page.size = 0;
169  return 0;
170 }
171 
173 {
174  OGGContext *ogg = s->priv_data;
175  OGGPageList **p = &ogg->page_list;
176  OGGPageList *l = av_mallocz(sizeof(*l));
177 
178  if (!l) {
179  ogg_reset_cur_page(oggstream);
180  return AVERROR(ENOMEM);
181  }
182  l->page = oggstream->page;
183 
184  oggstream->page.start_granule = ogg_granule_to_timestamp(oggstream, oggstream->page.granule);
185  oggstream->page_count++;
186  ogg_reset_cur_page(oggstream);
187 
188  while (*p) {
189  if (ogg_compare_granule(s, &(*p)->page, &l->page))
190  break;
191  p = &(*p)->next;
192  }
193  l->next = *p;
194  *p = l;
195 
196  return 0;
197 }
198 
200  uint8_t *data, unsigned size, int64_t granule,
201  int header)
202 {
203  OGGStreamContext *oggstream = st->priv_data;
204  OGGContext *ogg = s->priv_data;
205  int total_segments = size / 255 + 1;
206  uint8_t *p = data;
207  int i, segments, len, flush = 0;
208 
209  // Handles VFR by flushing page because this frame needs to have a timestamp
210  // For theora and VP8, keyframes also need to have a timestamp to correctly mark
211  // them as such, otherwise seeking will not work correctly at the very
212  // least with old libogg versions.
213  // Do not try to flush header packets though, that will create broken files.
215  (ogg_granule_to_timestamp(oggstream, granule) >
216  ogg_granule_to_timestamp(oggstream, oggstream->last_granule) + 1 ||
217  ogg_key_granule(oggstream, granule))) {
218  if (oggstream->page.granule != -1)
219  ogg_buffer_page(s, oggstream);
220  flush = 1;
221  }
222 
223  // avoid a continued page
224  if (!header && oggstream->page.size > 0 &&
225  MAX_PAGE_SIZE - oggstream->page.size < size) {
226  ogg_buffer_page(s, oggstream);
227  }
228 
229  for (i = 0; i < total_segments; ) {
230  OGGPage *page = &oggstream->page;
231 
232  segments = FFMIN(total_segments - i, 255 - page->segments_count);
233 
234  if (i && !page->segments_count)
235  page->flags |= 1; // continued packet
236 
237  memset(page->segments+page->segments_count, 255, segments - 1);
238  page->segments_count += segments - 1;
239 
240  len = FFMIN(size, segments*255);
241  page->segments[page->segments_count++] = len - (segments-1)*255;
242  memcpy(page->data+page->size, p, len);
243  p += len;
244  size -= len;
245  i += segments;
246  page->size += len;
247 
248  if (i == total_segments)
249  page->granule = granule;
250 
251  {
252  AVStream *st = s->streams[page->stream_index];
253 
254  int64_t start = av_rescale_q(page->start_granule, st->time_base,
256  int64_t next = av_rescale_q(ogg_granule_to_timestamp(oggstream, page->granule),
258 
259  if (page->segments_count == 255) {
260  ogg_buffer_page(s, oggstream);
261  } else if (!header) {
262  if ((ogg->pref_size > 0 && page->size >= ogg->pref_size) ||
263  (ogg->pref_duration > 0 && next - start >= ogg->pref_duration)) {
264  ogg_buffer_page(s, oggstream);
265  }
266  }
267  }
268  }
269 
270  if (flush && oggstream->page.granule != -1)
271  ogg_buffer_page(s, oggstream);
272 
273  return 0;
274 }
275 
277  int *header_len, AVDictionary **m, int framing_bit,
278  AVChapter **chapters, unsigned int nb_chapters)
279 {
280  const char *vendor = bitexact ? "ffmpeg" : LIBAVFORMAT_IDENT;
281  AVIOContext pb;
282  int64_t size;
283  uint8_t *p;
284 
286 
287  size = offset + ff_vorbiscomment_length(*m, vendor, chapters, nb_chapters) + framing_bit;
288  if (size > INT_MAX)
289  return NULL;
290  p = av_mallocz(size);
291  if (!p)
292  return NULL;
293 
294  ffio_init_context(&pb, p + offset, size - offset, 1, NULL, NULL, NULL, NULL);
295  ff_vorbiscomment_write(&pb, *m, vendor, chapters, nb_chapters);
296  if (framing_bit)
297  avio_w8(&pb, 1);
298 
299  *header_len = size;
300  return p;
301 }
302 
304  OGGStreamContext *oggstream, int bitexact,
305  AVDictionary **m)
306 {
307  uint8_t *p;
308 
310  return AVERROR(EINVAL);
311 
312  // first packet: STREAMINFO
313  oggstream->header_len[0] = 51;
314  oggstream->header[0] = av_mallocz(51); // per ogg flac specs
315  p = oggstream->header[0];
316  if (!p)
317  return AVERROR(ENOMEM);
318  bytestream_put_byte(&p, 0x7F);
319  bytestream_put_buffer(&p, "FLAC", 4);
320  bytestream_put_byte(&p, 1); // major version
321  bytestream_put_byte(&p, 0); // minor version
322  bytestream_put_be16(&p, 1); // headers packets without this one
323  bytestream_put_buffer(&p, "fLaC", 4);
324  bytestream_put_byte(&p, 0x00); // streaminfo
325  bytestream_put_be24(&p, 34);
327 
328  // second packet: VorbisComment
329  p = ogg_write_vorbiscomment(4, bitexact, &oggstream->header_len[1], m, 0, NULL, 0);
330  if (!p)
331  return AVERROR(ENOMEM);
332  oggstream->header[1] = p;
333  bytestream_put_byte(&p, 0x84); // last metadata block and vorbis comment
334  bytestream_put_be24(&p, oggstream->header_len[1] - 4);
335 
336  return 0;
337 }
338 
339 #define SPEEX_HEADER_SIZE 80
340 
342  OGGStreamContext *oggstream, int bitexact,
343  AVDictionary **m)
344 {
345  uint8_t *p;
346 
348  return AVERROR_INVALIDDATA;
349 
350  // first packet: Speex header
352  if (!p)
353  return AVERROR(ENOMEM);
354  oggstream->header[0] = p;
355  oggstream->header_len[0] = SPEEX_HEADER_SIZE;
357  AV_WL32(&oggstream->header[0][68], 0); // set extra_headers to 0
358 
359  // second packet: VorbisComment
360  p = ogg_write_vorbiscomment(0, bitexact, &oggstream->header_len[1], m, 0, NULL, 0);
361  if (!p)
362  return AVERROR(ENOMEM);
363  oggstream->header[1] = p;
364 
365  return 0;
366 }
367 
368 #define OPUS_HEADER_SIZE 19
369 
371  OGGStreamContext *oggstream, int bitexact,
372  AVDictionary **m, AVChapter **chapters,
373  unsigned int nb_chapters)
374 {
375  uint8_t *p;
376 
377  if (par->extradata_size < OPUS_HEADER_SIZE)
378  return AVERROR_INVALIDDATA;
379 
380  /* first packet: Opus header */
381  p = av_mallocz(par->extradata_size);
382  if (!p)
383  return AVERROR(ENOMEM);
384  oggstream->header[0] = p;
385  oggstream->header_len[0] = par->extradata_size;
387 
388  /* second packet: VorbisComment */
389  p = ogg_write_vorbiscomment(8, bitexact, &oggstream->header_len[1], m, 0, chapters, nb_chapters);
390  if (!p)
391  return AVERROR(ENOMEM);
392  oggstream->header[1] = p;
393  bytestream_put_buffer(&p, "OpusTags", 8);
394 
395  return 0;
396 }
397 
398 #define VP8_HEADER_SIZE 26
399 
401  OGGStreamContext *oggstream, int bitexact)
402 {
403  AVCodecParameters *par = st->codecpar;
404  uint8_t *p;
405 
406  /* first packet: VP8 header */
408  if (!p)
409  return AVERROR(ENOMEM);
410  oggstream->header[0] = p;
411  oggstream->header_len[0] = VP8_HEADER_SIZE;
412  bytestream_put_byte(&p, 0x4f); // HDRID
413  bytestream_put_buffer(&p, "VP80", 4); // Identifier
414  bytestream_put_byte(&p, 1); // HDRTYP
415  bytestream_put_byte(&p, 1); // VMAJ
416  bytestream_put_byte(&p, 0); // VMIN
417  bytestream_put_be16(&p, par->width);
418  bytestream_put_be16(&p, par->height);
419  bytestream_put_be24(&p, par->sample_aspect_ratio.num);
420  bytestream_put_be24(&p, par->sample_aspect_ratio.den);
421  if (st->r_frame_rate.num > 0 && st->r_frame_rate.den > 0) {
422  // OggVP8 requires pts to increase by 1 per visible frame, so use the least common
423  // multiple framerate if available.
424  av_log(s, AV_LOG_DEBUG, "Changing time base from %d/%d to %d/%d\n",
425  st->time_base.num, st->time_base.den,
426  st->r_frame_rate.den, st->r_frame_rate.num);
428  }
429  bytestream_put_be32(&p, st->time_base.den);
430  bytestream_put_be32(&p, st->time_base.num);
431 
432  /* optional second packet: VorbisComment */
434  p = ogg_write_vorbiscomment(7, bitexact, &oggstream->header_len[1], &st->metadata, 0, NULL, 0);
435  if (!p)
436  return AVERROR(ENOMEM);
437  oggstream->header[1] = p;
438  bytestream_put_byte(&p, 0x4f); // HDRID
439  bytestream_put_buffer(&p, "VP80", 4); // Identifier
440  bytestream_put_byte(&p, 2); // HDRTYP
441  bytestream_put_byte(&p, 0x20);
442  }
443 
444  oggstream->isvp8 = 1;
445 
446  return 0;
447 }
448 
450 {
451  OGGContext *ogg = s->priv_data;
452  OGGPageList *next, *p;
453 
454  if (!ogg->page_list)
455  return;
456 
457  for (p = ogg->page_list; p; ) {
458  OGGStreamContext *oggstream =
459  s->streams[p->page.stream_index]->priv_data;
460  if (oggstream->page_count < 2 && !flush)
461  break;
462  ogg_write_page(s, &p->page,
463  flush == 1 && oggstream->page_count == 1 ? 4 : 0); // eos
464  next = p->next;
465  av_freep(&p);
466  p = next;
467  }
468  ogg->page_list = p;
469 }
470 
472 {
473  OGGContext *ogg = s->priv_data;
474  OGGStreamContext *oggstream = NULL;
475  int i, j;
476 
477  if (ogg->pref_size)
478  av_log(s, AV_LOG_WARNING, "The pagesize option is deprecated\n");
479 
480  for (i = 0; i < s->nb_streams; i++) {
481  AVStream *st = s->streams[i];
482  unsigned serial_num = i + ogg->serial_offset;
483 
484  if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
485  if (st->codecpar->codec_id == AV_CODEC_ID_OPUS)
486  /* Opus requires a fixed 48kHz clock */
487  avpriv_set_pts_info(st, 64, 1, 48000);
488  else
489  avpriv_set_pts_info(st, 64, 1, st->codecpar->sample_rate);
490  }
491 
492  if (st->codecpar->codec_id != AV_CODEC_ID_VORBIS &&
498  av_log(s, AV_LOG_ERROR, "Unsupported codec id in stream %d\n", i);
499  return AVERROR(EINVAL);
500  }
501 
502  if ((!st->codecpar->extradata || !st->codecpar->extradata_size) &&
504  av_log(s, AV_LOG_ERROR, "No extradata present\n");
505  return AVERROR_INVALIDDATA;
506  }
507  oggstream = av_mallocz(sizeof(*oggstream));
508  if (!oggstream)
509  return AVERROR(ENOMEM);
510 
511  oggstream->page.stream_index = i;
512 
513  if (!(s->flags & AVFMT_FLAG_BITEXACT))
514  do {
515  serial_num = av_get_random_seed();
516  for (j = 0; j < i; j++) {
517  OGGStreamContext *sc = s->streams[j]->priv_data;
518  if (serial_num == sc->serial_num)
519  break;
520  }
521  } while (j < i);
522  oggstream->serial_num = serial_num;
523 
524  av_dict_copy(&st->metadata, s->metadata, AV_DICT_DONT_OVERWRITE);
525 
526  st->priv_data = oggstream;
527  if (st->codecpar->codec_id == AV_CODEC_ID_FLAC) {
528  int err = ogg_build_flac_headers(st->codecpar, oggstream,
529  s->flags & AVFMT_FLAG_BITEXACT,
530  &st->metadata);
531  if (err) {
532  av_log(s, AV_LOG_ERROR, "Error writing FLAC headers\n");
533  return err;
534  }
535  } else if (st->codecpar->codec_id == AV_CODEC_ID_SPEEX) {
536  int err = ogg_build_speex_headers(st->codecpar, oggstream,
537  s->flags & AVFMT_FLAG_BITEXACT,
538  &st->metadata);
539  if (err) {
540  av_log(s, AV_LOG_ERROR, "Error writing Speex headers\n");
541  return err;
542  }
543  } else if (st->codecpar->codec_id == AV_CODEC_ID_OPUS) {
544  int err = ogg_build_opus_headers(st->codecpar, oggstream,
545  s->flags & AVFMT_FLAG_BITEXACT,
546  &st->metadata, s->chapters, s->nb_chapters);
547  if (err) {
548  av_log(s, AV_LOG_ERROR, "Error writing Opus headers\n");
549  return err;
550  }
551  } else if (st->codecpar->codec_id == AV_CODEC_ID_VP8) {
552  int err = ogg_build_vp8_headers(s, st, oggstream,
553  s->flags & AVFMT_FLAG_BITEXACT);
554  if (err) {
555  av_log(s, AV_LOG_ERROR, "Error writing VP8 headers\n");
556  return err;
557  }
558  } else {
559  uint8_t *p;
560  const char *cstr = st->codecpar->codec_id == AV_CODEC_ID_VORBIS ? "vorbis" : "theora";
561  int header_type = st->codecpar->codec_id == AV_CODEC_ID_VORBIS ? 3 : 0x81;
562  int framing_bit = st->codecpar->codec_id == AV_CODEC_ID_VORBIS ? 1 : 0;
563 
565  st->codecpar->codec_id == AV_CODEC_ID_VORBIS ? 30 : 42,
566  (const uint8_t**)oggstream->header, oggstream->header_len) < 0) {
567  av_log(s, AV_LOG_ERROR, "Extradata corrupted\n");
568  oggstream->header[1] = NULL;
569  return AVERROR_INVALIDDATA;
570  }
571 
573  &oggstream->header_len[1], &st->metadata,
574  framing_bit, NULL, 0);
575  oggstream->header[1] = p;
576  if (!p)
577  return AVERROR(ENOMEM);
578 
579  bytestream_put_byte(&p, header_type);
580  bytestream_put_buffer(&p, cstr, 6);
581 
582  if (st->codecpar->codec_id == AV_CODEC_ID_THEORA) {
583  int den = AV_RB32(oggstream->header[0] + 22), num = AV_RB32(oggstream->header[0] + 26);
584  /* Make sure to use time base stored in the Theora stream header to write
585  correct timestamps */
586  if (st->time_base.num != num || st->time_base.den != den) {
587  av_log(s, AV_LOG_DEBUG, "Changing time base from %d/%d to %d/%d\n",
588  st->time_base.num, st->time_base.den, num, den);
589  avpriv_set_pts_info(st, 64, num, den);
590  }
591  /** KFGSHIFT is the width of the less significant section of the granule position
592  The less significant section is the frame count since the last keyframe */
593  oggstream->kfgshift = ((oggstream->header[0][40]&3)<<3)|(oggstream->header[0][41]>>5);
594  oggstream->vrev = oggstream->header[0][9];
595  av_log(s, AV_LOG_DEBUG, "theora kfgshift %d, vrev %d\n",
596  oggstream->kfgshift, oggstream->vrev);
597  }
598  }
599  }
600 
601  return 0;
602 }
603 
605 {
606  OGGStreamContext *oggstream = NULL;
607  int i, j;
608 
609  for (j = 0; j < s->nb_streams; j++) {
610  oggstream = s->streams[j]->priv_data;
611  ogg_buffer_data(s, s->streams[j], oggstream->header[0],
612  oggstream->header_len[0], 0, 1);
613  oggstream->page.flags |= 2; // bos
614  ogg_buffer_page(s, oggstream);
615  }
616  for (j = 0; j < s->nb_streams; j++) {
617  AVStream *st = s->streams[j];
618  oggstream = st->priv_data;
619  for (i = 1; i < 3; i++) {
620  if (oggstream->header_len[i])
621  ogg_buffer_data(s, st, oggstream->header[i],
622  oggstream->header_len[i], 0, 1);
623  }
624  ogg_buffer_page(s, oggstream);
625  }
626 
627  oggstream->page.start_granule = AV_NOPTS_VALUE;
628 
629  ogg_write_pages(s, 2);
630 
631  return 0;
632 }
633 
635 {
636  AVStream *st = s->streams[pkt->stream_index];
637  OGGStreamContext *oggstream = st->priv_data;
638  int ret;
639  int64_t granule;
640 
641  if (st->codecpar->codec_id == AV_CODEC_ID_THEORA) {
642  int64_t pts = oggstream->vrev < 1 ? pkt->pts : pkt->pts + pkt->duration;
643  int pframe_count;
644  if (pkt->flags & AV_PKT_FLAG_KEY)
645  oggstream->last_kf_pts = pts;
646  pframe_count = pts - oggstream->last_kf_pts;
647  // prevent frame count from overflow if key frame flag is not set
648  if (pframe_count >= (1<<oggstream->kfgshift)) {
649  oggstream->last_kf_pts += pframe_count;
650  pframe_count = 0;
651  }
652  granule = (oggstream->last_kf_pts<<oggstream->kfgshift) | pframe_count;
653  } else if (st->codecpar->codec_id == AV_CODEC_ID_OPUS)
654  granule = pkt->pts + pkt->duration +
656  (AVRational){ 1, st->codecpar->sample_rate },
657  st->time_base);
658  else if (st->codecpar->codec_id == AV_CODEC_ID_VP8) {
659  int64_t pts, invcnt, dist;
660  int visible;
661 
662  visible = (pkt->data[0] >> 4) & 1;
663  pts = pkt->pts + pkt->duration;
664  invcnt = (oggstream->last_granule >> 30) & 3;
665  invcnt = visible ? 3 : (invcnt == 3 ? 0 : invcnt + 1);
666  dist = (pkt->flags & AV_PKT_FLAG_KEY) ? 0 : ((oggstream->last_granule >> 3) & 0x07ffffff) + 1;
667 
668  granule = (pts << 32) | (invcnt << 30) | (dist << 3);
669  } else
670  granule = pkt->pts + pkt->duration;
671 
672  if (oggstream->page.start_granule == AV_NOPTS_VALUE)
673  oggstream->page.start_granule = pkt->pts;
674 
675  ret = ogg_buffer_data(s, st, pkt->data, pkt->size, granule, 0);
676  if (ret < 0)
677  return ret;
678 
679  ogg_write_pages(s, 0);
680 
681  oggstream->last_granule = granule;
682 
683  return 0;
684 }
685 
687 {
688  int i;
689 
690  if (pkt)
692 
693  for (i = 0; i < s->nb_streams; i++) {
694  OGGStreamContext *oggstream = s->streams[i]->priv_data;
695  if (oggstream->page.segments_count)
696  ogg_buffer_page(s, oggstream);
697  }
698 
699  ogg_write_pages(s, 2);
700  return 1;
701 }
702 
704 {
705  int i;
706 
707  /* flush current page if needed */
708  for (i = 0; i < s->nb_streams; i++) {
709  OGGStreamContext *oggstream = s->streams[i]->priv_data;
710 
711  if (oggstream->page.size > 0)
712  ogg_buffer_page(s, oggstream);
713  }
714 
715  ogg_write_pages(s, 1);
716 
717  return 0;
718 }
719 
721 {
722  OGGContext *ogg = s->priv_data;
723  OGGPageList *p = ogg->page_list;
724  int i;
725 
726  for (i = 0; i < s->nb_streams; i++) {
727  AVStream *st = s->streams[i];
728  OGGStreamContext *oggstream = st->priv_data;
729  if (!oggstream)
730  continue;
731  if (st->codecpar->codec_id == AV_CODEC_ID_FLAC ||
735  av_freep(&oggstream->header[0]);
736  }
737  av_freep(&oggstream->header[1]);
738  }
739 
740  while (p) {
741  OGGPageList *next = p->next;
742  av_free(p);
743  p = next;
744  }
745  ogg->page_list = NULL;
746 }
747 
748 #if CONFIG_OGG_MUXER
749 OGG_CLASS(ogg, Ogg)
751  .name = "ogg",
752  .long_name = NULL_IF_CONFIG_SMALL("Ogg"),
753  .mime_type = "application/ogg",
754  .extensions = "ogg"
755 #if !CONFIG_OGV_MUXER
756  ",ogv"
757 #endif
758 #if !CONFIG_SPX_MUXER
759  ",spx"
760 #endif
761 #if !CONFIG_OPUS_MUXER
762  ",opus"
763 #endif
764  ,
765  .priv_data_size = sizeof(OGGContext),
766  .audio_codec = CONFIG_LIBVORBIS_ENCODER ?
768  .video_codec = AV_CODEC_ID_THEORA,
769  .init = ogg_init,
773  .deinit = ogg_free,
775  .priv_class = &ogg_muxer_class,
776 };
777 #endif
778 
779 #if CONFIG_OGA_MUXER
780 OGG_CLASS(oga, Ogg audio)
782  .name = "oga",
783  .long_name = NULL_IF_CONFIG_SMALL("Ogg Audio"),
784  .mime_type = "audio/ogg",
785  .extensions = "oga",
786  .priv_data_size = sizeof(OGGContext),
787  .audio_codec = AV_CODEC_ID_FLAC,
788  .init = ogg_init,
792  .deinit = ogg_free,
794  .priv_class = &oga_muxer_class,
795 };
796 #endif
797 
798 #if CONFIG_OGV_MUXER
799 OGG_CLASS(ogv, Ogg video)
801  .name = "ogv",
802  .long_name = NULL_IF_CONFIG_SMALL("Ogg Video"),
803  .mime_type = "video/ogg",
804  .extensions = "ogv",
805  .priv_data_size = sizeof(OGGContext),
806  .audio_codec = CONFIG_LIBVORBIS_ENCODER ?
808  .video_codec = CONFIG_LIBTHEORA_ENCODER ?
810  .init = ogg_init,
814  .deinit = ogg_free,
816  .priv_class = &ogv_muxer_class,
817 };
818 #endif
819 
820 #if CONFIG_SPX_MUXER
821 OGG_CLASS(spx, Ogg Speex)
823  .name = "spx",
824  .long_name = NULL_IF_CONFIG_SMALL("Ogg Speex"),
825  .mime_type = "audio/ogg",
826  .extensions = "spx",
827  .priv_data_size = sizeof(OGGContext),
828  .audio_codec = AV_CODEC_ID_SPEEX,
829  .init = ogg_init,
833  .deinit = ogg_free,
835  .priv_class = &spx_muxer_class,
836 };
837 #endif
838 
839 #if CONFIG_OPUS_MUXER
840 OGG_CLASS(opus, Ogg Opus)
842  .name = "opus",
843  .long_name = NULL_IF_CONFIG_SMALL("Ogg Opus"),
844  .mime_type = "audio/ogg",
845  .extensions = "opus",
846  .priv_data_size = sizeof(OGGContext),
847  .audio_codec = AV_CODEC_ID_OPUS,
848  .init = ogg_init,
852  .deinit = ogg_free,
854  .priv_class = &opus_muxer_class,
855 };
856 #endif
static void flush(AVCodecContext *avctx)
AVOutputFormat ff_ogg_muxer
AVOutputFormat ff_opus_muxer
AVOutputFormat ff_oga_muxer
AVOutputFormat ff_spx_muxer
AVOutputFormat ff_ogv_muxer
uint8_t
Main libavformat public API header.
#define AVFMT_FLAG_BITEXACT
When muxing, try to avoid writing any random/volatile data to the output.
Definition: avformat.h:1380
#define AVFMT_ALLOW_FLUSH
Format allows flushing.
Definition: avformat.h:471
#define AVFMT_TS_NEGATIVE
Format allows muxing negative timestamps.
Definition: avformat.h:475
#define AVFMT_TS_NONSTRICT
Format does not require strictly increasing timestamps, but they must still be monotonic.
Definition: avformat.h:472
void avio_write_marker(AVIOContext *s, int64_t time, enum AVIODataMarkerType type)
Mark the written bytestream as a specific type.
Definition: aviobuf.c:486
void avio_w8(AVIOContext *s, int b)
Definition: aviobuf.c:208
@ AVIO_DATA_MARKER_FLUSH_POINT
A point in the output bytestream where the underlying AVIOContext might flush the buffer depending on...
Definition: avio.h:146
void avio_write(AVIOContext *s, const unsigned char *buf, int size)
Definition: aviobuf.c:230
int ffio_init_context(AVIOContext *s, unsigned char *buffer, int buffer_size, int write_flag, void *opaque, int(*read_packet)(void *opaque, uint8_t *buf, int buf_size), int(*write_packet)(void *opaque, uint8_t *buf, int buf_size), int64_t(*seek)(void *opaque, int64_t offset, int whence))
Definition: aviobuf.c:88
#define AV_RB32
Definition: intreadwrite.h:130
static av_cold int init(AVCodecContext *avctx)
Definition: avrndec.c:31
static av_always_inline void bytestream_put_buffer(uint8_t **b, const uint8_t *src, unsigned int size)
Definition: bytestream.h:372
#define flags(name, subs,...)
Definition: cbs_av1.c:572
#define s(width, name)
Definition: cbs_vp9.c:257
static void deinit(AVFormatContext *s)
Definition: chromaprint.c:50
#define FFMIN(a, b)
Definition: common.h:105
#define MKTAG(a, b, c, d)
Definition: common.h:478
#define CONFIG_LIBTHEORA_ENCODER
Definition: config.h:1482
#define CONFIG_LIBVORBIS_ENCODER
Definition: config.h:1485
#define NULL
Definition: coverity.c:32
long long int64_t
Definition: coverity.c:34
Public header for CRC hash function implementation.
static void write_packet(OutputFile *of, AVPacket *pkt, OutputStream *ost, int unqueue)
Definition: ffmpeg.c:740
static void write_header(FFV1Context *f)
Definition: ffv1enc.c:348
FLAC (Free Lossless Audio Codec) decoder/demuxer common functions.
#define FLAC_STREAMINFO_SIZE
Definition: flac.h:34
@ AV_OPT_TYPE_INT64
Definition: opt.h:226
@ AV_OPT_TYPE_INT
Definition: opt.h:225
@ AV_CODEC_ID_VORBIS
Definition: codec_id.h:429
@ AV_CODEC_ID_VP8
Definition: codec_id.h:189
@ AV_CODEC_ID_THEORA
Definition: codec_id.h:79
@ AV_CODEC_ID_FLAC
Definition: codec_id.h:436
@ AV_CODEC_ID_SPEEX
Definition: codec_id.h:459
@ AV_CODEC_ID_OPUS
Definition: codec_id.h:484
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition: packet.h:410
const AVCRC * av_crc_get_table(AVCRCId crc_id)
Get an initialized standard CRC table.
Definition: crc.c:374
uint32_t AVCRC
Definition: crc.h:47
uint32_t av_crc(const AVCRC *ctx, uint32_t crc, const uint8_t *buffer, size_t length)
Calculate the CRC of a block.
Definition: crc.c:394
@ AV_CRC_32_IEEE
Definition: crc.h:53
uint32_t av_get_random_seed(void)
Get a seed to use in conjunction with random functions.
Definition: random_seed.c:120
#define AV_DICT_IGNORE_SUFFIX
Return first entry in a dictionary whose first part corresponds to the search key,...
Definition: dict.h:70
int av_dict_copy(AVDictionary **dst, const AVDictionary *src, int flags)
Copy entries from one AVDictionary struct into another.
Definition: dict.c:213
#define AV_DICT_DONT_OVERWRITE
Don't overwrite existing entries.
Definition: dict.h:76
AVDictionaryEntry * av_dict_get(const AVDictionary *m, const char *key, const AVDictionaryEntry *prev, int flags)
Get a dictionary entry with matching key.
Definition: dict.c:40
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition: error.h:59
#define AVERROR(e)
Definition: error.h:43
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition: log.h:215
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:200
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:194
int64_t av_rescale_q(int64_t a, AVRational bq, AVRational cq)
Rescale a 64-bit integer by 2 rational numbers.
Definition: mathematics.c:142
void * av_mallocz(size_t size)
Allocate a memory block with alignment suitable for all memory accesses (including vectors if availab...
Definition: mem.c:237
@ AVMEDIA_TYPE_AUDIO
Definition: avutil.h:202
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition: avutil.h:248
#define AV_TIME_BASE_Q
Internal time base represented as fractional value.
Definition: avutil.h:260
int i
Definition: input.c:407
#define AV_WL32(p, v)
Definition: intreadwrite.h:426
void avpriv_set_pts_info(AVStream *s, int pts_wrap_bits, unsigned int pts_num, unsigned int pts_den)
Set the time base and wrapping info for a given stream.
Definition: utils.c:4944
void ff_metadata_conv(AVDictionary **pm, const AVMetadataConv *d_conv, const AVMetadataConv *s_conv)
Definition: metadata.c:26
#define LIBAVFORMAT_IDENT
Definition: version.h:46
common internal API header
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification.
Definition: internal.h:117
const char data[16]
Definition: mxf.c:142
#define OPUS_HEADER_SIZE
Definition: oggenc.c:368
static int ogg_write_header(AVFormatContext *s)
Definition: oggenc.c:604
static int ogg_build_opus_headers(AVCodecParameters *par, OGGStreamContext *oggstream, int bitexact, AVDictionary **m, AVChapter **chapters, unsigned int nb_chapters)
Definition: oggenc.c:370
static int ogg_compare_granule(AVFormatContext *s, OGGPage *next, OGGPage *page)
Definition: oggenc.c:147
static int ogg_build_vp8_headers(AVFormatContext *s, AVStream *st, OGGStreamContext *oggstream, int bitexact)
Definition: oggenc.c:400
static int ogg_write_packet_internal(AVFormatContext *s, AVPacket *pkt)
Definition: oggenc.c:634
static const AVOption options[]
Definition: oggenc.c:82
static int ogg_buffer_page(AVFormatContext *s, OGGStreamContext *oggstream)
Definition: oggenc.c:172
static void ogg_write_page(AVFormatContext *s, OGGPage *page, int extra_flags)
Definition: oggenc.c:102
static int ogg_reset_cur_page(OGGStreamContext *oggstream)
Definition: oggenc.c:163
#define OGG_CLASS(flavor, name)
Definition: oggenc.c:94
static int ogg_build_flac_headers(AVCodecParameters *par, OGGStreamContext *oggstream, int bitexact, AVDictionary **m)
Definition: oggenc.c:303
static int ogg_buffer_data(AVFormatContext *s, AVStream *st, uint8_t *data, unsigned size, int64_t granule, int header)
Definition: oggenc.c:199
#define SPEEX_HEADER_SIZE
Definition: oggenc.c:339
#define VP8_HEADER_SIZE
Definition: oggenc.c:398
#define MAX_PAGE_SIZE
Definition: oggenc.c:36
static int ogg_write_packet(AVFormatContext *s, AVPacket *pkt)
Definition: oggenc.c:686
static int64_t ogg_granule_to_timestamp(OGGStreamContext *oggstream, int64_t granule)
Definition: oggenc.c:136
static int ogg_key_granule(OGGStreamContext *oggstream, int64_t granule)
Definition: oggenc.c:130
static int ogg_build_speex_headers(AVCodecParameters *par, OGGStreamContext *oggstream, int bitexact, AVDictionary **m)
Definition: oggenc.c:341
static void ogg_free(AVFormatContext *s)
Definition: oggenc.c:720
static void ogg_write_pages(AVFormatContext *s, int flush)
Definition: oggenc.c:449
static int ogg_init(AVFormatContext *s)
Definition: oggenc.c:471
static int ogg_write_trailer(AVFormatContext *s)
Definition: oggenc.c:703
#define OFFSET(x)
Definition: oggenc.c:79
static uint8_t * ogg_write_vorbiscomment(int64_t offset, int bitexact, int *header_len, AVDictionary **m, int framing_bit, AVChapter **chapters, unsigned int nb_chapters)
Definition: oggenc.c:276
#define PARAM
Definition: oggenc.c:80
AVOptions.
static const uint8_t header[24]
Definition: sdr2.c:67
Describe the class of an AVClass context structure.
Definition: log.h:67
This struct describes the properties of an encoded stream.
Definition: codec_par.h:52
int extradata_size
Size of the extradata content in bytes.
Definition: codec_par.h:78
int width
Video only.
Definition: codec_par.h:126
enum AVMediaType codec_type
General type of the encoded data.
Definition: codec_par.h:56
AVRational sample_aspect_ratio
Video only.
Definition: codec_par.h:136
uint8_t * extradata
Extra binary data needed for initializing the decoder, codec-dependent.
Definition: codec_par.h:74
enum AVCodecID codec_id
Specific type of the encoded data (the codec used).
Definition: codec_par.h:60
int sample_rate
Audio only.
Definition: codec_par.h:170
int initial_padding
Audio only.
Definition: codec_par.h:189
Format I/O context.
Definition: avformat.h:1232
Bytestream IO Context.
Definition: avio.h:161
AVOption.
Definition: opt.h:248
const char * name
Definition: avformat.h:491
This structure stores compressed data.
Definition: packet.h:346
int stream_index
Definition: packet.h:371
int flags
A combination of AV_PKT_FLAG values.
Definition: packet.h:375
int size
Definition: packet.h:370
int64_t duration
Duration of this packet in AVStream->time_base units, 0 if unknown.
Definition: packet.h:387
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
Definition: packet.h:362
uint8_t * data
Definition: packet.h:369
Rational number (pair of numerator and denominator).
Definition: rational.h:58
int num
Numerator.
Definition: rational.h:59
int den
Denominator.
Definition: rational.h:60
Stream structure.
Definition: avformat.h:873
AVCodecParameters * codecpar
Codec parameters associated with this stream.
Definition: avformat.h:1038
AVDictionary * metadata
Definition: avformat.h:937
void * priv_data
Definition: avformat.h:888
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented.
Definition: avformat.h:902
AVRational r_frame_rate
Real base framerate of the stream.
Definition: avformat.h:1015
int64_t pref_duration
preferred page duration (0 => fill all segments)
Definition: oggenc.c:75
int serial_offset
Definition: oggenc.c:76
OGGPageList * page_list
Definition: oggenc.c:73
int pref_size
preferred page size (0 => fill all segments)
Definition: oggenc.c:74
OGGPage page
Definition: oggenc.c:67
struct OGGPageList * next
Definition: oggenc.c:68
Definition: oggenc.c:38
uint8_t data[MAX_PAGE_SIZE]
Definition: oggenc.c:45
uint16_t size
Definition: oggenc.c:46
int stream_index
Definition: oggenc.c:41
uint8_t segments_count
Definition: oggenc.c:43
uint8_t segments[255]
Definition: oggenc.c:44
uint8_t flags
Definition: oggenc.c:42
int64_t start_granule
Definition: oggenc.c:39
int64_t granule
Definition: oggenc.c:40
int kfgshift
for theora granule
Definition: oggenc.c:54
unsigned serial_num
serial number
Definition: oggenc.c:62
unsigned page_count
number of page buffered
Definition: oggenc.c:60
int64_t last_kf_pts
Definition: oggenc.c:55
uint8_t * header[3]
Definition: oggenc.c:51
unsigned page_counter
Definition: oggenc.c:50
OGGPage page
current page
Definition: oggenc.c:61
int64_t last_granule
last packet granule
Definition: oggenc.c:63
int header_len[3]
Definition: oggenc.c:52
Definition: oggdec.h:102
#define av_free(p)
#define av_freep(p)
#define av_log(a,...)
AVPacket * pkt
Definition: movenc.c:59
static int64_t pts
int size
static int write_trailer(AVFormatContext *s1)
Definition: v4l2enc.c:98
static const uint8_t offset[127][2]
Definition: vf_spp.c:107
int len
int ff_vorbiscomment_write(AVIOContext *pb, const AVDictionary *m, const char *vendor_string, AVChapter **chapters, unsigned int nb_chapters)
Write a VorbisComment into an AVIOContext.
Definition: vorbiscomment.c:65
const AVMetadataConv ff_vorbiscomment_metadata_conv[]
VorbisComment metadata conversion mapping.
Definition: vorbiscomment.c:33
int64_t ff_vorbiscomment_length(const AVDictionary *m, const char *vendor_string, AVChapter **chapters, unsigned int nb_chapters)
Calculate the length in bytes of a VorbisComment.
Definition: vorbiscomment.c:41
int avpriv_split_xiph_headers(const uint8_t *extradata, int extradata_size, int first_header_size, const uint8_t *header_start[3], int header_len[3])
Split a single extradata buffer into the three headers that most Xiph codecs use.
Definition: xiph.c:24