FFmpeg
Loading...
Searching...
No Matches
muxer.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 "config_components.h"
23
24#include <stdint.h>
25
26#include "libavutil/crc.h"
28#include "libavutil/mem.h"
29#include "libavutil/opt.h"
31#include "libavcodec/xiph.h"
33#include "libavcodec/flac.h"
37#include "libavformat/mux.h"
38#include "libavformat/version.h"
40
41#define MAX_PAGE_SIZE 65025
42
43typedef struct OGGPage {
47 uint8_t flags;
49 uint8_t segments[255];
51 uint16_t size;
52} OGGPage;
53
54typedef struct OGGStreamContext {
55 unsigned page_counter;
56 uint8_t *header[3];
57 int header_len[3];
58 /** for theora granule */
61 int vrev;
62 /* for VP8 granule */
63 int isvp8;
64 int eos;
65 unsigned page_count; ///< number of page buffered
66 OGGPage page; ///< current page
67 unsigned serial_num; ///< serial number
68 int64_t last_granule; ///< last packet granule
69 int packet_seen; ///< true when packets have been submitted
71
72typedef struct OGGPageList {
76
77typedef struct OGGContext {
78 const AVClass *class;
80 int64_t pref_duration; ///< preferred page duration (0 => fill all segments)
82 int failed; // if true all packet submission will fail.
83 int ended; ///< a new link could not be started, the packets that follow are dropped
85
86#define OFFSET(x) offsetof(OGGContext, x)
87#define PARAM AV_OPT_FLAG_ENCODING_PARAM
88
90
91static const AVOption options[] = {
92 { "serial_offset", "serial number offset, -1 to derive it from the stream headers",
93 OFFSET(serial_offset), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, INT_MAX, PARAM },
94 { "page_duration", "preferred page duration, in microseconds",
95 OFFSET(pref_duration), AV_OPT_TYPE_INT64, { .i64 = 1000000 }, 0, INT64_MAX, PARAM },
96 { NULL },
97};
98
99static const AVClass ogg_muxer_class = {
100 .class_name = "Ogg (audio/video/Speex/Opus) muxer",
101 .item_name = av_default_item_name,
102 .option = options,
103 .version = LIBAVUTIL_VERSION_INT,
104};
105
107{
108 OGGStreamContext *oggstream = st->priv_data;
109
110 if (st->codecpar->codec_id == AV_CODEC_ID_FLAC ||
114 av_freep(&oggstream->header[0]);
115 }
116
117 av_freep(&oggstream->header[1]);
118}
119
120static void ogg_write_page(AVFormatContext *s, OGGPage *page, int extra_flags)
121{
122 OGGStreamContext *oggstream = s->streams[page->stream_index]->priv_data;
123 uint8_t buf[4 + 1 + 1 + 8 + 4 + 4 + 4 + 1 + 255], *ptr = buf, *crc_pos;
124 const AVCRC *crc_table = av_crc_get_table(AV_CRC_32_IEEE);
125 uint32_t crc;
126
127 bytestream_put_le32(&ptr, MKTAG('O', 'g', 'g', 'S'));
128 bytestream_put_byte(&ptr, 0);
129 bytestream_put_byte(&ptr, page->flags | extra_flags);
130 bytestream_put_le64(&ptr, page->granule);
131 bytestream_put_le32(&ptr, oggstream->serial_num);
132 bytestream_put_le32(&ptr, oggstream->page_counter++);
133 crc_pos = ptr;
134 bytestream_put_le32(&ptr, 0);
135 bytestream_put_byte(&ptr, page->segments_count);
136 bytestream_put_buffer(&ptr, page->segments, page->segments_count);
137
138 crc = av_crc(crc_table, 0, buf, ptr - buf);
139 crc = av_crc(crc_table, crc, page->data, page->size);
140 bytestream_put_be32(&crc_pos, crc);
141
142 avio_write(s->pb, buf, ptr - buf);
143 avio_write(s->pb, page->data, page->size);
145 oggstream->page_count--;
146}
147
148static int ogg_key_granule(OGGStreamContext *oggstream, int64_t granule)
149{
150 return (oggstream->kfgshift && !(granule & ((1<<oggstream->kfgshift)-1))) ||
151 (oggstream->isvp8 && !((granule >> 3) & 0x07ffffff));
152}
153
155{
156 if (oggstream->kfgshift)
157 return (granule>>oggstream->kfgshift) +
158 (granule & ((1<<oggstream->kfgshift)-1));
159 else if (oggstream->isvp8)
160 return granule >> 32;
161 else
162 return granule;
163}
164
166{
167 AVStream *st2 = s->streams[next->stream_index];
168 AVStream *st = s->streams[page->stream_index];
169 int64_t next_granule, cur_granule;
170
171 if (next->granule == -1 || page->granule == -1)
172 return 0;
173
174 next_granule = av_rescale_q(ogg_granule_to_timestamp(st2->priv_data, next->granule),
176 cur_granule = av_rescale_q(ogg_granule_to_timestamp(st->priv_data, page->granule),
178 return next_granule > cur_granule;
179}
180
182{
183 oggstream->page.granule = -1;
184 oggstream->page.flags = 0;
185 oggstream->page.segments_count = 0;
186 oggstream->page.size = 0;
187 return 0;
188}
189
191{
192 OGGContext *ogg = s->priv_data;
193 OGGPageList **p = &ogg->page_list;
194 OGGPageList *l = av_mallocz(sizeof(*l));
195
196 if (!l) {
197 ogg_reset_cur_page(oggstream);
198 return AVERROR(ENOMEM);
199 }
200 l->page = oggstream->page;
201
202 oggstream->page.start_granule = ogg_granule_to_timestamp(oggstream, oggstream->page.granule);
203 oggstream->page_count++;
204 ogg_reset_cur_page(oggstream);
205
206 while (*p) {
207 if (ogg_compare_granule(s, &(*p)->page, &l->page))
208 break;
209 p = &(*p)->next;
210 }
211 l->next = *p;
212 *p = l;
213
214 return 0;
215}
216
218 const uint8_t *data, unsigned size, int64_t granule,
219 int header)
220{
221 OGGStreamContext *oggstream = st->priv_data;
222 OGGContext *ogg = s->priv_data;
223 int total_segments = size / 255 + 1;
224 const uint8_t *p = data;
225 int i, segments, len, ret, flush = 0;
226
227 // Handles VFR by flushing page because this frame needs to have a timestamp
228 // For theora and VP8, keyframes also need to have a timestamp to correctly mark
229 // them as such, otherwise seeking will not work correctly at the very
230 // least with old libogg versions.
231 // Do not try to flush header packets though, that will create broken files.
233 (ogg_granule_to_timestamp(oggstream, granule) >
234 ogg_granule_to_timestamp(oggstream, oggstream->last_granule) + 1 ||
235 ogg_key_granule(oggstream, granule))) {
236 if (oggstream->page.granule != -1 &&
237 (ret = ogg_buffer_page(s, oggstream)) < 0)
238 return ret;
239 flush = 1;
240 }
241
242 // avoid a continued page
243 if (!header && oggstream->page.size > 0 &&
244 MAX_PAGE_SIZE - oggstream->page.size < size) {
245 if ((ret = ogg_buffer_page(s, oggstream)) < 0)
246 return ret;
247 }
248
249 for (i = 0; i < total_segments; ) {
250 OGGPage *page = &oggstream->page;
251
252 segments = FFMIN(total_segments - i, 255 - page->segments_count);
253
254 if (i && !page->segments_count)
255 page->flags |= 1; // continued packet
256
257 memset(page->segments+page->segments_count, 255, segments - 1);
258 page->segments_count += segments - 1;
259
260 len = FFMIN(size, segments*255);
261 page->segments[page->segments_count++] = len - (segments-1)*255;
262 if (len)
263 memcpy(page->data+page->size, p, len);
264 p += len;
265 size -= len;
266 i += segments;
267 page->size += len;
268
269 if (i == total_segments)
270 page->granule = granule;
271
272 {
273 AVRational time_base = s->streams[page->stream_index]->time_base;
274
275 int64_t start = av_rescale_q(page->start_granule, time_base,
277 int64_t next = av_rescale_q(ogg_granule_to_timestamp(oggstream, page->granule),
278 time_base, AV_TIME_BASE_Q);
279
280 if (page->segments_count == 255) {
281 if ((ret = ogg_buffer_page(s, oggstream)) < 0)
282 return ret;
283 } else if (!header) {
284 if (ogg->pref_duration > 0 && next - start >= ogg->pref_duration) {
285 if ((ret = ogg_buffer_page(s, oggstream)) < 0)
286 return ret;
287 }
288 }
289 }
290 }
291
292 if (flush && oggstream->page.granule != -1 &&
293 (ret = ogg_buffer_page(s, oggstream)) < 0)
294 return ret;
295
296 return 0;
297}
298
299static uint8_t *ogg_write_vorbiscomment(int64_t offset, int bitexact,
300 int *header_len, AVDictionary **m, int framing_bit,
301 AVChapter **chapters, unsigned int nb_chapters)
302{
303 const char *vendor = bitexact ? "ffmpeg" : LIBAVFORMAT_IDENT;
304 FFIOContext pb;
306 uint8_t *p;
307
309
310 size = ff_vorbis_comment_length(*m, vendor, chapters, nb_chapters);
311 if (size < 0)
312 return NULL;
313 size += offset + framing_bit;
314 if (size > INT_MAX)
315 return NULL;
316 p = av_mallocz(size);
317 if (!p)
318 return NULL;
319
321 ff_vorbis_comment_write(&pb.pub, *m, vendor, chapters, nb_chapters);
322 if (framing_bit)
323 avio_w8(&pb.pub, 1);
324
325 *header_len = size;
326 return p;
327}
328
330 OGGStreamContext *oggstream, int bitexact,
331 AVDictionary **m)
332{
333 uint8_t *p;
334
336 return AVERROR(EINVAL);
337
338 // first packet: STREAMINFO
339 oggstream->header_len[0] = 51;
340 oggstream->header[0] = av_mallocz(51); // per ogg flac specs
341 p = oggstream->header[0];
342 if (!p)
343 return AVERROR(ENOMEM);
344 bytestream_put_byte(&p, 0x7F);
345 bytestream_put_buffer(&p, "FLAC", 4);
346 bytestream_put_byte(&p, 1); // major version
347 bytestream_put_byte(&p, 0); // minor version
348 bytestream_put_be16(&p, 1); // headers packets without this one
349 bytestream_put_buffer(&p, "fLaC", 4);
350 bytestream_put_byte(&p, 0x00); // streaminfo
351 bytestream_put_be24(&p, 34);
353
354 // second packet: VorbisComment
355 p = ogg_write_vorbiscomment(4, bitexact, &oggstream->header_len[1], m, 0, NULL, 0);
356 if (!p)
357 return AVERROR(ENOMEM);
358 oggstream->header[1] = p;
359 bytestream_put_byte(&p, 0x84); // last metadata block and vorbis comment
360 bytestream_put_be24(&p, oggstream->header_len[1] - 4);
361
362 return 0;
363}
364
365#define SPEEX_HEADER_SIZE 80
366
368 OGGStreamContext *oggstream, int bitexact,
369 AVDictionary **m)
370{
371 uint8_t *p;
372
374 return AVERROR_INVALIDDATA;
375
376 // first packet: Speex header
378 if (!p)
379 return AVERROR(ENOMEM);
380 oggstream->header[0] = p;
381 oggstream->header_len[0] = SPEEX_HEADER_SIZE;
383 AV_WL32(&oggstream->header[0][68], 0); // set extra_headers to 0
384
385 // second packet: VorbisComment
386 p = ogg_write_vorbiscomment(0, bitexact, &oggstream->header_len[1], m, 0, NULL, 0);
387 if (!p)
388 return AVERROR(ENOMEM);
389 oggstream->header[1] = p;
390
391 return 0;
392}
393
394#define OPUS_HEADER_SIZE 19
395
397 OGGStreamContext *oggstream, int bitexact,
398 AVDictionary **m, AVChapter **chapters,
399 unsigned int nb_chapters)
400{
401 uint8_t *p;
402
404 return AVERROR_INVALIDDATA;
405
406 /* first packet: Opus header */
407 p = av_mallocz(par->extradata_size);
408 if (!p)
409 return AVERROR(ENOMEM);
410 oggstream->header[0] = p;
411 oggstream->header_len[0] = par->extradata_size;
413
414 /* second packet: VorbisComment */
415 p = ogg_write_vorbiscomment(8, bitexact, &oggstream->header_len[1], m, 0, chapters, nb_chapters);
416 if (!p)
417 return AVERROR(ENOMEM);
418 oggstream->header[1] = p;
419 bytestream_put_buffer(&p, "OpusTags", 8);
420
421 return 0;
422}
423
424#define VP8_HEADER_SIZE 26
425
427 OGGStreamContext *oggstream, int bitexact)
428{
429 AVCodecParameters *par = st->codecpar;
430 uint8_t *p;
431
432 /* first packet: VP8 header */
434 if (!p)
435 return AVERROR(ENOMEM);
436 oggstream->header[0] = p;
437 oggstream->header_len[0] = VP8_HEADER_SIZE;
438 bytestream_put_byte(&p, 0x4f); // HDRID
439 bytestream_put_buffer(&p, "VP80", 4); // Identifier
440 bytestream_put_byte(&p, 1); // HDRTYP
441 bytestream_put_byte(&p, 1); // VMAJ
442 bytestream_put_byte(&p, 0); // VMIN
443 bytestream_put_be16(&p, par->width);
444 bytestream_put_be16(&p, par->height);
445 bytestream_put_be24(&p, par->sample_aspect_ratio.num);
446 bytestream_put_be24(&p, par->sample_aspect_ratio.den);
447 if (st->r_frame_rate.num > 0 && st->r_frame_rate.den > 0) {
448 // OggVP8 requires pts to increase by 1 per visible frame, so use the least common
449 // multiple framerate if available.
450 av_log(s, AV_LOG_DEBUG, "Changing time base from %d/%d to %d/%d\n",
451 st->time_base.num, st->time_base.den,
454 }
455 bytestream_put_be32(&p, st->time_base.den);
456 bytestream_put_be32(&p, st->time_base.num);
457
458 /* optional second packet: VorbisComment */
459 if (av_dict_count(st->metadata)) {
460 p = ogg_write_vorbiscomment(7, bitexact, &oggstream->header_len[1], &st->metadata, 0, NULL, 0);
461 if (!p)
462 return AVERROR(ENOMEM);
463 oggstream->header[1] = p;
464 bytestream_put_byte(&p, 0x4f); // HDRID
465 bytestream_put_buffer(&p, "VP80", 4); // Identifier
466 bytestream_put_byte(&p, 2); // HDRTYP
467 bytestream_put_byte(&p, 0x20);
468 }
469
470 oggstream->isvp8 = 1;
471
472 return 0;
473}
474
476{
477 OGGContext *ogg = s->priv_data;
478 OGGPageList *next, *p;
479
480 if (!ogg->page_list)
481 return;
482
483 for (p = ogg->page_list; p; ) {
484 OGGStreamContext *oggstream =
485 s->streams[p->page.stream_index]->priv_data;
486 if (oggstream->page_count < 2 && !flush)
487 break;
488 ogg_write_page(s, &p->page,
489 flush == 1 && oggstream->page_count == 1 ? 4 : 0); // eos
490 next = p->next;
491 av_freep(&p);
492 p = next;
493 }
494 ogg->page_list = p;
495}
496
497/**
498 * Derive a bitexact serial number from the stream's header packets, which
499 * makes links muxed apart unlikely to share one, though not certain not to.
500 */
501static unsigned ogg_bitexact_serial(const OGGStreamContext *oggstream, unsigned seed)
502{
504 uint32_t crc = seed;
505
506 for (int i = 0; i < 3; i++)
507 if (oggstream->header_len[i])
508 crc = av_crc(table, crc, oggstream->header[i], oggstream->header_len[i]);
509
510 return crc;
511}
512
513static int ogg_serial_in_use(AVFormatContext *s, int nb_streams, unsigned serial_num)
514{
515 for (int i = 0; i < nb_streams; i++) {
516 const OGGStreamContext *oggstream = s->streams[i]->priv_data;
517 if (oggstream->serial_num == serial_num)
518 return 1;
519 }
520 return 0;
521}
522
523// This function can be used on an initialized context to reinitialize the
524// streams.
526{
527 OGGContext *ogg = s->priv_data;
528 OGGStreamContext *oggstream = NULL;
529 int i;
530
531 for (i = 0; i < s->nb_streams; i++) {
532 AVStream *st = s->streams[i];
533 unsigned serial_num;
534
537 /* Opus requires a fixed 48kHz clock */
538 avpriv_set_pts_info(st, 64, 1, 48000);
539 else
541 }
542
549 av_log(s, AV_LOG_ERROR, "Unsupported codec id in stream %d\n", i);
550 return AVERROR(EINVAL);
551 }
552
553 if ((!st->codecpar->extradata || !st->codecpar->extradata_size) &&
555 av_log(s, AV_LOG_ERROR, "No extradata present\n");
556 return AVERROR_INVALIDDATA;
557 }
558 oggstream = st->priv_data;
559
560 if (!oggstream) {
561 oggstream = av_mallocz(sizeof(*oggstream));
562 if (!oggstream)
563 return AVERROR(ENOMEM);
564 st->priv_data = oggstream;
565 } else {
567 memset(oggstream, 0, sizeof(*oggstream));
568 }
569
570 oggstream->page.stream_index = i;
571
573
574 if (st->codecpar->codec_id == AV_CODEC_ID_FLAC) {
575 int err = ogg_build_flac_headers(st->codecpar, oggstream,
576 s->flags & AVFMT_FLAG_BITEXACT,
577 &st->metadata);
578 if (err) {
579 av_log(s, AV_LOG_ERROR, "Error writing FLAC headers\n");
580 return err;
581 }
582 } else if (st->codecpar->codec_id == AV_CODEC_ID_SPEEX) {
583 int err = ogg_build_speex_headers(st->codecpar, oggstream,
584 s->flags & AVFMT_FLAG_BITEXACT,
585 &st->metadata);
586 if (err) {
587 av_log(s, AV_LOG_ERROR, "Error writing Speex headers\n");
588 return err;
589 }
590 } else if (st->codecpar->codec_id == AV_CODEC_ID_OPUS) {
591 int err = ogg_build_opus_headers(st->codecpar, oggstream,
592 s->flags & AVFMT_FLAG_BITEXACT,
593 &st->metadata, s->chapters, s->nb_chapters);
594 if (err) {
595 av_log(s, AV_LOG_ERROR, "Error writing Opus headers\n");
596 return err;
597 }
598 } else if (st->codecpar->codec_id == AV_CODEC_ID_VP8) {
599 int err = ogg_build_vp8_headers(s, st, oggstream,
600 s->flags & AVFMT_FLAG_BITEXACT);
601 if (err) {
602 av_log(s, AV_LOG_ERROR, "Error writing VP8 headers\n");
603 return err;
604 }
605 } else {
606 uint8_t *p;
607 const char *cstr = st->codecpar->codec_id == AV_CODEC_ID_VORBIS ? "vorbis" : "theora";
608 int header_type = st->codecpar->codec_id == AV_CODEC_ID_VORBIS ? 3 : 0x81;
609 int framing_bit = st->codecpar->codec_id == AV_CODEC_ID_VORBIS ? 1 : 0;
610
612 st->codecpar->codec_id == AV_CODEC_ID_VORBIS ? 30 : 42,
613 (const uint8_t**)oggstream->header, oggstream->header_len) < 0) {
614 av_log(s, AV_LOG_ERROR, "Extradata corrupted\n");
615 oggstream->header[1] = NULL;
616 return AVERROR_INVALIDDATA;
617 }
618
620 &oggstream->header_len[1], &st->metadata,
621 framing_bit, NULL, 0);
622 oggstream->header[1] = p;
623 if (!p)
624 return AVERROR(ENOMEM);
625
626 bytestream_put_byte(&p, header_type);
627 bytestream_put_buffer(&p, cstr, 6);
628
630 int den = AV_RB32(oggstream->header[0] + 22), num = AV_RB32(oggstream->header[0] + 26);
631 /* Make sure to use time base stored in the Theora stream header to write
632 correct timestamps */
633 if (st->time_base.num != num || st->time_base.den != den) {
634 av_log(s, AV_LOG_DEBUG, "Changing time base from %d/%d to %d/%d\n",
635 st->time_base.num, st->time_base.den, num, den);
636 avpriv_set_pts_info(st, 64, num, den);
637 }
638 /** KFGSHIFT is the width of the less significant section of the granule position
639 The less significant section is the frame count since the last keyframe */
640 oggstream->kfgshift = ((oggstream->header[0][40]&3)<<3)|(oggstream->header[0][41]>>5);
641 oggstream->vrev = oggstream->header[0][9];
642 av_log(s, AV_LOG_DEBUG, "theora kfgshift %d, vrev %d\n",
643 oggstream->kfgshift, oggstream->vrev);
644 }
645 }
646
647 if (s->flags & AVFMT_FLAG_BITEXACT && ogg->serial_offset >= 0)
648 serial_num = i + ogg->serial_offset;
649 else if (s->flags & AVFMT_FLAG_BITEXACT)
650 serial_num = ogg_bitexact_serial(oggstream, i);
651 else
652 serial_num = av_get_random_seed();
653 while (ogg_serial_in_use(s, i, serial_num))
654 serial_num = s->flags & AVFMT_FLAG_BITEXACT ? serial_num + 1
656 oggstream->serial_num = serial_num;
657 }
658
659 return 0;
660}
661
663{
664 OGGStreamContext *oggstream = NULL;
665 int i, j, ret;
666
667 for (j = 0; j < s->nb_streams; j++) {
668 oggstream = s->streams[j]->priv_data;
669 ret = ogg_buffer_data(s, s->streams[j], oggstream->header[0],
670 oggstream->header_len[0], 0, 1);
671 if (ret < 0)
672 return ret;
673 oggstream->page.flags |= 2; // bos
674 ret = ogg_buffer_page(s, oggstream);
675 if (ret < 0)
676 return ret;
677 }
678 for (j = 0; j < s->nb_streams; j++) {
679 AVStream *st = s->streams[j];
680 oggstream = st->priv_data;
681 for (i = 1; i < 3; i++) {
682 if (oggstream->header_len[i]) {
683 ret = ogg_buffer_data(s, st, oggstream->header[i],
684 oggstream->header_len[i], 0, 1);
685 if (ret < 0)
686 return ret;
687 }
688 }
689 ret = ogg_buffer_page(s, oggstream);
690 if (ret < 0)
691 return ret;
692 }
693
694 oggstream->page.start_granule = AV_NOPTS_VALUE;
695
696 ogg_write_pages(s, 2);
697
698 return 0;
699}
700
701/**
702 * Keep the current link when a new one cannot be started. New metadata is
703 * then dropped, while new extradata ends the output, as the packets that
704 * follow need its headers.
705 */
706static int ogg_skip_new_link(AVFormatContext *s, const uint8_t *new_extradata,
707 const char *reason)
708{
709 OGGContext *ogg = s->priv_data;
710
711 if (!new_extradata) {
712 av_log(s, AV_LOG_WARNING, "%s: new metadata ignored\n", reason);
713 return 0;
714 }
715
716 av_log(s, AV_LOG_WARNING, "%s: ending the output at the current link\n", reason);
717 ogg->ended = 1;
718 return 0;
719}
720
722{
723 int ret = 0;
724 size_t metadata_size, extradata_size;
725 OGGContext *oggcontext = s->priv_data;
726 AVStream *st = s->streams[pkt->stream_index];
727 AVCodecParameters *par = st->codecpar;
728 OGGStreamContext *oggstream = st->priv_data;
729 const uint8_t *side_metadata = av_packet_get_side_data(pkt, AV_PKT_DATA_STRINGS_METADATA, &metadata_size);
730 const uint8_t *new_extradata = av_packet_get_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, &extradata_size);
731
732 if (new_extradata && extradata_size == par->extradata_size &&
733 !memcmp(new_extradata, par->extradata, extradata_size))
734 new_extradata = NULL;
735
736 if (!side_metadata && !new_extradata)
737 return 0;
738
739 /* The headers of the first link are written from codecpar before any packet. */
740 if (!oggstream->packet_seen) {
741 if (new_extradata)
742 av_log(s, AV_LOG_WARNING, "New extradata on the first packet ignored: "
743 "the stream headers are already written!\n");
744 return 0;
745 }
746
747 if (s->nb_streams > 1)
748 return ogg_skip_new_link(s, new_extradata, "Multiple streams present");
749
750 if (par->codec_id != AV_CODEC_ID_VORBIS &&
751 par->codec_id != AV_CODEC_ID_FLAC &&
753 return ogg_skip_new_link(s, new_extradata,
754 "New links are only supported for vorbis, flac and opus streams");
755
757 if (ret < 0)
758 goto end;
759
760 if (side_metadata) {
762 ret = av_packet_unpack_dictionary(side_metadata, metadata_size, &st->metadata);
763 if (ret < 0)
764 goto end;
765 }
766
767 if (new_extradata) {
768 if (extradata_size > INT_MAX - AV_INPUT_BUFFER_PADDING_SIZE) {
770 goto end;
771 }
772 ret = ff_alloc_extradata(par, extradata_size);
773 if (ret < 0)
774 goto end;
775 memcpy(par->extradata, new_extradata, extradata_size);
776 }
777
778 ret = ogg_init(s);
779 if (ret < 0)
780 goto end;
781
783
784end:
785 oggcontext->failed = ret < 0;
786 return ret;
787}
788
790{
791 AVStream *st = s->streams[pkt->stream_index];
792 OGGContext *oggcontext = s->priv_data;
793 OGGStreamContext *oggstream = st->priv_data;
794 int ret;
795 int64_t granule;
796
797 if (oggcontext->failed)
798 return AVERROR_INVALIDDATA;
799 if (oggcontext->ended)
800 return 0;
801
804 return ret;
805
807 int64_t pts = oggstream->vrev < 1 ? pkt->pts : pkt->pts + pkt->duration;
808 int pframe_count;
809 if (pkt->flags & AV_PKT_FLAG_KEY)
810 oggstream->last_kf_pts = pts;
811 pframe_count = pts - oggstream->last_kf_pts;
812 // prevent frame count from overflow if key frame flag is not set
813 if (pframe_count >= (1<<oggstream->kfgshift)) {
814 oggstream->last_kf_pts += pframe_count;
815 pframe_count = 0;
816 }
817 granule = (oggstream->last_kf_pts<<oggstream->kfgshift) | pframe_count;
818 } else if (st->codecpar->codec_id == AV_CODEC_ID_OPUS)
819 /* The pre-skip of the link's OpusHead, in the 48 kHz time base. */
820 granule = pkt->pts + pkt->duration + AV_RL16(oggstream->header[0] + 10);
821 else if (st->codecpar->codec_id == AV_CODEC_ID_VP8) {
822 int64_t pts, invcnt, dist;
823 int visible;
824
825 visible = (pkt->data[0] >> 4) & 1;
826 pts = pkt->pts + pkt->duration;
827 invcnt = (oggstream->last_granule >> 30) & 3;
828 invcnt = visible ? 3 : (invcnt == 3 ? 0 : invcnt + 1);
829 dist = (pkt->flags & AV_PKT_FLAG_KEY) ? 0 : ((oggstream->last_granule >> 3) & 0x07ffffff) + 1;
830
831 granule = (pts << 32) | (invcnt << 30) | (dist << 3);
832 } else
833 granule = pkt->pts + pkt->duration;
834
835 if (oggstream->page.start_granule == AV_NOPTS_VALUE)
836 oggstream->page.start_granule = pkt->pts;
837
838 ret = ogg_buffer_data(s, st, pkt->data, pkt->size, granule, 0);
839 if (ret < 0)
840 return ret;
841
842 ogg_write_pages(s, 0);
843
844 oggstream->last_granule = granule;
845 oggstream->packet_seen = 1;
846
847 return 0;
848}
849
851{
852 int i, ret;
853
854 if (pkt)
855 return pkt->size || !pkt->side_data_elems ? ogg_write_packet_internal(s, pkt) : 0;
856
857 for (i = 0; i < s->nb_streams; i++) {
858 OGGStreamContext *oggstream = s->streams[i]->priv_data;
859 if (oggstream->page.segments_count &&
860 (ret = ogg_buffer_page(s, oggstream)) < 0)
861 return ret;
862 }
863
864 ogg_write_pages(s, 2);
865 return 1;
866}
867
869{
870 int i, ret;
871
872 /* flush current page if needed */
873 for (i = 0; i < s->nb_streams; i++) {
874 OGGStreamContext *oggstream = s->streams[i]->priv_data;
875
876 if (oggstream->page.segments_count &&
877 (ret = ogg_buffer_page(s, oggstream)) < 0)
878 return ret;
879 }
880
881 ogg_write_pages(s, 1);
882
883 return 0;
884}
885
887{
888 OGGContext *ogg = s->priv_data;
889 OGGPageList *p = ogg->page_list;
890 int i;
891
892 for (i = 0; i < s->nb_streams; i++) {
893 AVStream *st = s->streams[i];
894 if (st->priv_data)
896 }
897
898 while (p) {
899 OGGPageList *next = p->next;
900 av_free(p);
901 p = next;
902 }
903 ogg->page_list = NULL;
904}
905
906#if CONFIG_OGG_MUXER
908 .p.name = "ogg",
909 .p.long_name = NULL_IF_CONFIG_SMALL("Ogg"),
910 .p.mime_type = "application/ogg",
911 .p.extensions = "ogg"
912#if !CONFIG_OGV_MUXER
913 ",ogv"
914#endif
915#if !CONFIG_SPX_MUXER
916 ",spx"
917#endif
918#if !CONFIG_OPUS_MUXER
919 ",opus"
920#endif
921 ,
922 .priv_data_size = sizeof(OGGContext),
923 .p.audio_codec = CONFIG_LIBVORBIS_ENCODER ?
925 .p.video_codec = AV_CODEC_ID_THEORA,
926 .init = ogg_init,
930 .deinit = ogg_free,
932 .p.priv_class = &ogg_muxer_class,
933 .flags_internal = FF_OFMT_FLAG_ALLOW_FLUSH,
934};
935#endif
936
937#if CONFIG_OGA_MUXER
939 .p.name = "oga",
940 .p.long_name = NULL_IF_CONFIG_SMALL("Ogg Audio"),
941 .p.mime_type = "audio/ogg",
942 .p.extensions = "oga",
943 .priv_data_size = sizeof(OGGContext),
944 .p.audio_codec = AV_CODEC_ID_FLAC,
945 .init = ogg_init,
946 .write_header = ogg_write_header,
947 .write_packet = ogg_write_packet,
948 .write_trailer = ogg_write_trailer,
949 .deinit = ogg_free,
950 .p.flags = AVFMT_TS_NEGATIVE,
951 .p.priv_class = &ogg_muxer_class,
952 .flags_internal = FF_OFMT_FLAG_ALLOW_FLUSH,
953};
954#endif
955
956#if CONFIG_OGV_MUXER
958 .p.name = "ogv",
959 .p.long_name = NULL_IF_CONFIG_SMALL("Ogg Video"),
960 .p.mime_type = "video/ogg",
961 .p.extensions = "ogv",
962 .priv_data_size = sizeof(OGGContext),
963 .p.audio_codec = CONFIG_LIBVORBIS_ENCODER ?
965 .p.video_codec = CONFIG_LIBTHEORA_ENCODER ?
967 .init = ogg_init,
971 .deinit = ogg_free,
973 .p.priv_class = &ogg_muxer_class,
974 .flags_internal = FF_OFMT_FLAG_ALLOW_FLUSH,
975};
976#endif
977
978#if CONFIG_SPX_MUXER
980 .p.name = "spx",
981 .p.long_name = NULL_IF_CONFIG_SMALL("Ogg Speex"),
982 .p.mime_type = "audio/ogg",
983 .p.extensions = "spx",
984 .priv_data_size = sizeof(OGGContext),
985 .p.audio_codec = AV_CODEC_ID_SPEEX,
986 .init = ogg_init,
987 .write_header = ogg_write_header,
988 .write_packet = ogg_write_packet,
989 .write_trailer = ogg_write_trailer,
990 .deinit = ogg_free,
991 .p.flags = AVFMT_TS_NEGATIVE,
992 .p.priv_class = &ogg_muxer_class,
993 .flags_internal = FF_OFMT_FLAG_ALLOW_FLUSH,
994};
995#endif
996
997#if CONFIG_OPUS_MUXER
999 .p.name = "opus",
1000 .p.long_name = NULL_IF_CONFIG_SMALL("Ogg Opus"),
1001 .p.mime_type = "audio/ogg",
1002 .p.extensions = "opus",
1003 .priv_data_size = sizeof(OGGContext),
1004 .p.audio_codec = AV_CODEC_ID_OPUS,
1005 .init = ogg_init,
1006 .write_header = ogg_write_header,
1007 .write_packet = ogg_write_packet,
1008 .write_trailer = ogg_write_trailer,
1009 .deinit = ogg_free,
1010 .p.flags = AVFMT_TS_NEGATIVE,
1011 .p.priv_class = &ogg_muxer_class,
1012 .flags_internal = FF_OFMT_FLAG_ALLOW_FLUSH,
1013};
1014#endif
const FFOutputFormat ff_ogv_muxer
const FFOutputFormat ff_ogg_muxer
const FFOutputFormat ff_opus_muxer
const FFOutputFormat ff_spx_muxer
const FFOutputFormat ff_oga_muxer
void avpriv_set_pts_info(AVStream *st, int pts_wrap_bits, unsigned int pts_num, unsigned int pts_den)
Set the time base and wrapping info for a given stream.
Definition avformat.c:865
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:1570
#define AVFMT_TS_NEGATIVE
Format allows muxing negative timestamps.
Definition avformat.h:512
#define AVFMT_TS_NONSTRICT
Format does not require strictly increasing timestamps, but they must still be monotonic.
Definition avformat.h:509
void avio_write_marker(AVIOContext *s, int64_t time, enum AVIODataMarkerType type)
Mark the written bytestream as a specific type.
Definition aviobuf.c:464
void avio_w8(AVIOContext *s, int b)
Definition aviobuf.c:184
@ AVIO_DATA_MARKER_FLUSH_POINT
A point in the output bytestream where the underlying AVIOContext might flush the buffer depending on...
Definition avio.h:145
void avio_write(AVIOContext *s, const unsigned char *buf, int size)
Definition aviobuf.c:206
void ffio_init_write_context(FFIOContext *s, uint8_t *buffer, int buffer_size)
Wrap a buffer in an AVIOContext for writing.
Definition aviobuf.c:104
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_h264.c:74
#define i(width, name, range_min, range_max)
Definition cbs_h264.c:63
#define s(width, name)
Definition cbs_vp9.c:198
static void deinit(AVFormatContext *s)
Definition chromaprint.c:53
int ff_vorbis_comment_length(const AVDictionary *m, const char *vendor_string, AVChapter **chapters, unsigned int nb_chapters)
Calculate the length in bytes of a VorbisComment.
Definition writer.c:44
const AVMetadataConv ff_vorbis_comment_metadata_conv[]
VorbisComment metadata conversion mapping.
Definition writer.c:34
int ff_vorbis_comment_write(AVIOContext *pb, const AVDictionary *m, const char *vendor_string, AVChapter **chapters, unsigned int nb_chapters)
Write a VorbisComment into an AVIOContext.
Definition writer.c:62
#define NULL
Definition coverity.c:32
long long int64_t
Definition coverity.c:34
Public header for CRC hash function implementation.
#define PARAM
Definition dcadec.c:450
static AVPacket * pkt
#define MAX_PAGE_SIZE
Definition demuxer.c:41
void(* flush)(AVBSFContext *ctx)
Definition dts2pts.c:615
int(* init)(AVBSFContext *ctx)
Definition dts2pts.c:613
static int write_packet(Muxer *mux, OutputStream *ost, AVPacket *pkt)
Definition ffmpeg_mux.c:203
int ret
Definition ffplay.c:391
static unsigned int nb_streams
Definition ffprobe.c:390
static void write_header(FFV1Context *f)
Definition ffv1enc.c:384
FLAC (Free Lossless Audio Codec) common stuff.
#define FLAC_STREAMINFO_SIZE
Definition flac.h:32
@ AV_OPT_TYPE_INT64
Underlying C type is int64_t.
Definition opt.h:262
@ AV_OPT_TYPE_INT
Underlying C type is int.
Definition opt.h:258
@ AV_CODEC_ID_VORBIS
Definition codec_id.h:464
@ AV_CODEC_ID_VP8
Definition codec_id.h:190
@ AV_CODEC_ID_THEORA
Definition codec_id.h:80
@ AV_CODEC_ID_FLAC
Definition codec_id.h:471
@ AV_CODEC_ID_SPEEX
Definition codec_id.h:494
@ AV_CODEC_ID_OPUS
Definition codec_id.h:519
#define AV_INPUT_BUFFER_PADDING_SIZE
Required number of additionally allocated bytes at the end of the input bitstream for decoding.
Definition defs.h:40
@ AV_PKT_DATA_STRINGS_METADATA
A list of zero terminated key/value strings.
Definition packet.h:169
@ AV_PKT_DATA_NEW_EXTRADATA
The AV_PKT_DATA_NEW_EXTRADATA is used to notify the codec or the format that the extradata buffer was...
Definition packet.h:56
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition packet.h:657
int av_packet_unpack_dictionary(const uint8_t *data, size_t size, AVDictionary **dict)
Unpack a dictionary from side_data.
Definition packet.c:355
uint8_t * av_packet_get_side_data(const AVPacket *pkt, enum AVPacketSideDataType type, size_t *size)
Get side information from packet.
Definition packet.c:252
const AVCRC * av_crc_get_table(AVCRCId crc_id)
Get an initialized standard CRC table.
Definition crc.c:389
uint32_t AVCRC
Definition crc.h:46
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:421
@ AV_CRC_32_IEEE
Definition crc.h:52
uint32_t av_get_random_seed(void)
Get a seed to use in conjunction with random functions.
void av_dict_free(AVDictionary **pm)
Free all the memory allocated for an AVDictionary struct and all keys and values.
Definition dict.c:236
int av_dict_copy(AVDictionary **dst, const AVDictionary *src, int flags)
Copy entries from one AVDictionary struct into another.
Definition dict.c:250
#define AV_DICT_DONT_OVERWRITE
Don't overwrite existing entries.
Definition dict.h:81
int av_dict_count(const AVDictionary *m)
Get number of entries in dictionary.
Definition dict.c:38
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition error.h:61
#define AVERROR(e)
Definition error.h:45
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition log.h:231
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition log.h:216
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition log.h:210
const char * av_default_item_name(void *ptr)
Return the context name.
Definition log.c:247
int64_t av_rescale_q(int64_t a, AVRational bq, AVRational cq)
Rescale a 64-bit integer by 2 rational numbers.
@ AVMEDIA_TYPE_AUDIO
Definition avutil.h:201
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition avutil.h:247
#define AV_TIME_BASE_Q
Internal time base represented as fractional value.
Definition avutil.h:263
#define LIBAVUTIL_VERSION_INT
Definition version.h:85
#define AV_WL32(p, v)
#define AV_RB32(p)
#define AV_RL16(p)
unsigned offset
Definition libaomenc.c:763
int ff_alloc_extradata(AVCodecParameters *par, int size)
Allocate extradata with additional AV_INPUT_BUFFER_PADDING_SIZE at end which is always set to 0.
Definition utils.c:237
#define VP8_HEADER_SIZE
Definition vp8.c:29
Libavformat version macros.
#define LIBAVFORMAT_IDENT
Definition version.h:45
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification.
Definition internal.h:97
#define FFMIN(a, b)
Definition macros.h:49
#define MKTAG(a, b, c, d)
Definition macros.h:55
Memory handling functions.
void ff_metadata_conv(AVDictionary **pm, const AVMetadataConv *d_conv, const AVMetadataConv *s_conv)
Definition metadata.c:26
#define FF_OFMT_FLAG_ALLOW_FLUSH
This flag indicates that the muxer stores data internally and supports flushing it.
Definition mux.h:38
#define OPUS_HEADER_SIZE
Definition muxer.c:394
static int ogg_write_header(AVFormatContext *s)
Definition muxer.c:662
static int ogg_build_opus_headers(AVCodecParameters *par, OGGStreamContext *oggstream, int bitexact, AVDictionary **m, AVChapter **chapters, unsigned int nb_chapters)
Definition muxer.c:396
static int ogg_compare_granule(AVFormatContext *s, OGGPage *next, OGGPage *page)
Definition muxer.c:165
static int ogg_build_vp8_headers(AVFormatContext *s, AVStream *st, OGGStreamContext *oggstream, int bitexact)
Definition muxer.c:426
static int ogg_write_packet_internal(AVFormatContext *s, AVPacket *pkt)
Definition muxer.c:789
static void ogg_cleanup_stream(AVStream *st)
Definition muxer.c:106
static int ogg_buffer_page(AVFormatContext *s, OGGStreamContext *oggstream)
Definition muxer.c:190
static void ogg_write_page(AVFormatContext *s, OGGPage *page, int extra_flags)
Definition muxer.c:120
static int ogg_reset_cur_page(OGGStreamContext *oggstream)
Definition muxer.c:181
static const AVClass ogg_muxer_class
Definition muxer.c:99
static int ogg_serial_in_use(AVFormatContext *s, int nb_streams, unsigned serial_num)
Definition muxer.c:513
static int ogg_build_flac_headers(AVCodecParameters *par, OGGStreamContext *oggstream, int bitexact, AVDictionary **m)
Definition muxer.c:329
#define SPEEX_HEADER_SIZE
Definition muxer.c:365
static unsigned ogg_bitexact_serial(const OGGStreamContext *oggstream, unsigned seed)
Derive a bitexact serial number from the stream's header packets, which makes links muxed apart unlik...
Definition muxer.c:501
static int ogg_skip_new_link(AVFormatContext *s, const uint8_t *new_extradata, const char *reason)
Keep the current link when a new one cannot be started.
Definition muxer.c:706
#define MAX_PAGE_SIZE
Definition muxer.c:41
static int ogg_write_packet(AVFormatContext *s, AVPacket *pkt)
Definition muxer.c:850
static int64_t ogg_granule_to_timestamp(OGGStreamContext *oggstream, int64_t granule)
Definition muxer.c:154
static int ogg_key_granule(OGGStreamContext *oggstream, int64_t granule)
Definition muxer.c:148
static int ogg_check_new_link(AVFormatContext *s, AVPacket *pkt)
Definition muxer.c:721
static int ogg_build_speex_headers(AVCodecParameters *par, OGGStreamContext *oggstream, int bitexact, AVDictionary **m)
Definition muxer.c:367
static void ogg_free(AVFormatContext *s)
Definition muxer.c:886
static void ogg_write_pages(AVFormatContext *s, int flush)
Definition muxer.c:475
static int ogg_init(AVFormatContext *s)
Definition muxer.c:525
static int ogg_write_trailer(AVFormatContext *s)
Definition muxer.c:868
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 muxer.c:299
#define OFFSET(x)
Definition muxer.c:86
static int ogg_buffer_data(AVFormatContext *s, AVStream *st, const uint8_t *data, unsigned size, int64_t granule, int header)
Definition muxer.c:217
const char data[16]
Definition mxf.c:149
IDirect3DDxgiInterfaceAccess _COM_Outptr_ void ** p
static uint8_t page[OGG_PAGE_MAX_SIZE]
Definition ogg_pages.c:29
AVOptions.
static const uint16_t table[]
Definition prosumer.c:203
static const uint8_t header[24]
Definition sdr2.c:68
Describe the class of an AVClass context structure.
Definition log.h:76
This struct describes the properties of an encoded stream.
Definition codec_par.h:49
int extradata_size
Size of the extradata content in bytes.
Definition codec_par.h:75
int height
The height of the video frame in pixels.
Definition codec_par.h:150
int width
The width of the video frame in pixels.
Definition codec_par.h:143
enum AVMediaType codec_type
General type of the encoded data.
Definition codec_par.h:53
AVRational sample_aspect_ratio
The aspect ratio (width/height) which a single pixel should have when displayed.
Definition codec_par.h:161
uint8_t * extradata
Extra binary data needed for initializing the decoder, codec-dependent.
Definition codec_par.h:71
enum AVCodecID codec_id
Specific type of the encoded data (the codec used).
Definition codec_par.h:57
int sample_rate
The number of audio samples per second.
Definition codec_par.h:213
Format I/O context.
Definition avformat.h:1401
AVOption.
Definition opt.h:428
This structure stores compressed data.
Definition packet.h:587
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:768
AVCodecParameters * codecpar
Codec parameters associated with this stream.
Definition avformat.h:791
AVDictionary * metadata
Definition avformat.h:848
void * priv_data
Definition avformat.h:793
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented.
Definition avformat.h:807
AVRational r_frame_rate
Real base framerate of the stream.
Definition avformat.h:902
AVIOContext pub
int64_t pref_duration
preferred page duration (0 => fill all segments)
Definition muxer.c:80
int serial_offset
Definition muxer.c:81
int failed
Definition muxer.c:82
int ended
a new link could not be started, the packets that follow are dropped
Definition muxer.c:83
OGGPageList * page_list
Definition muxer.c:79
OGGPage page
Definition muxer.c:73
struct OGGPageList * next
Definition muxer.c:74
uint8_t data[MAX_PAGE_SIZE]
Definition muxer.c:50
uint16_t size
Definition muxer.c:51
int stream_index
Definition muxer.c:46
uint8_t segments_count
Definition muxer.c:48
uint8_t segments[255]
Definition muxer.c:49
uint8_t flags
Definition muxer.c:47
int64_t start_granule
Definition muxer.c:44
int64_t granule
Definition muxer.c:45
int kfgshift
for theora granule
Definition muxer.c:59
unsigned serial_num
serial number
Definition muxer.c:67
unsigned page_count
number of page buffered
Definition muxer.c:65
int64_t last_kf_pts
Definition muxer.c:60
uint8_t * header[3]
Definition muxer.c:56
unsigned page_counter
Definition muxer.c:55
int packet_seen
true when packets have been submitted
Definition muxer.c:69
OGGPage page
current page
Definition muxer.c:66
int64_t last_granule
last packet granule
Definition muxer.c:68
int header_len[3]
Definition muxer.c:57
Definition mapping.h:112
#define av_free(p)
#define av_mallocz(s)
#define av_freep(p)
#define av_log(a,...)
int num
Definition error.c:23
static int64_t pts
int size
static int write_trailer(AVFormatContext *s1)
Definition v4l2enc.c:101
static unsigned int seed
Definition videogen.c:78
int len
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:26