FFmpeg
Loading...
Searching...
No Matches
ffmpeg_mux.c
Go to the documentation of this file.
1/*
2 * This file is part of FFmpeg.
3 *
4 * FFmpeg is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
8 *
9 * FFmpeg is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
13 *
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with FFmpeg; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17 */
18
19#include <stdatomic.h>
20#include <stdio.h>
21#include <string.h>
22
23#include "ffmpeg.h"
24#include "ffmpeg_mux.h"
25#include "ffmpeg_utils.h"
26#include "sync_queue.h"
27
28#include "libavutil/avstring.h"
29#include "libavutil/fifo.h"
31#include "libavutil/log.h"
32#include "libavutil/mem.h"
33#include "libavutil/stereo3d.h"
34#include "libavutil/time.h"
35#include "libavutil/timestamp.h"
36
37#include "libavcodec/packet.h"
38
40#include "libavformat/avio.h"
41
46
48{
49 return (Muxer*)of;
50}
51
53{
54 int64_t ret = -1;
55
56 if (pb) {
57 ret = avio_size(pb);
58 if (ret <= 0) // FIXME improve avio_size() so it works with non seekable output too
59 ret = avio_tell(pb);
60 }
61
62 return ret;
63}
64
66{
67 static const char *desc[] = {
68 [LATENCY_PROBE_DEMUX] = "demux",
69 [LATENCY_PROBE_DEC_PRE] = "decode",
70 [LATENCY_PROBE_DEC_POST] = "decode",
71 [LATENCY_PROBE_FILTER_PRE] = "filter",
72 [LATENCY_PROBE_FILTER_POST] = "filter",
73 [LATENCY_PROBE_ENC_PRE] = "encode",
74 [LATENCY_PROBE_ENC_POST] = "encode",
75 [LATENCY_PROBE_NB] = "mux",
76 };
77
78 char latency[512];
79
80 *latency = 0;
81 if (pkt->opaque_ref) {
82 const FrameData *fd = (FrameData*)pkt->opaque_ref->data;
84 int64_t total = INT64_MIN;
85
86 int next;
87
88 for (unsigned i = 0; i < FF_ARRAY_ELEMS(fd->wallclock); i = next) {
89 int64_t val = fd->wallclock[i];
90
91 next = i + 1;
92
93 if (val == INT64_MIN)
94 continue;
95
96 if (total == INT64_MIN) {
97 total = now - val;
98 snprintf(latency, sizeof(latency), "total:%gms", total / 1e3);
99 }
100
101 // find the next valid entry
102 for (; next <= FF_ARRAY_ELEMS(fd->wallclock); next++) {
103 int64_t val_next = (next == FF_ARRAY_ELEMS(fd->wallclock)) ?
104 now : fd->wallclock[next];
106
107 if (val_next == INT64_MIN)
108 continue;
109 diff = val_next - val;
110
111 // print those stages that take at least 5% of total
112 if (100. * diff > 5. * total) {
113 av_strlcat(latency, ", ", sizeof(latency));
114
115 if (!strcmp(desc[i], desc[next]))
116 av_strlcat(latency, desc[i], sizeof(latency));
117 else
118 av_strlcatf(latency, sizeof(latency), "%s-%s:",
119 desc[i], desc[next]);
120
121 av_strlcatf(latency, sizeof(latency), " %gms/%d%%",
122 diff / 1e3, (int)(100. * diff / total));
123 }
124
125 break;
126 }
127
128 }
129 }
130
131 av_log(ost, AV_LOG_INFO, "muxer <- pts:%s pts_time:%s dts:%s dts_time:%s "
132 "duration:%s duration_time:%s size:%d latency(%s)\n",
133 av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &ost->st->time_base),
134 av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &ost->st->time_base),
135 av_ts2str(pkt->duration), av_ts2timestr(pkt->duration, &ost->st->time_base),
136 pkt->size, *latency ? latency : "N/A");
137}
138
139static int mux_fixup_ts(Muxer *mux, MuxStream *ms, AVPacket *pkt)
140{
141 OutputStream *ost = &ms->ost;
142
143 // rescale timestamps to the stream timebase
144 if (ost->type == AVMEDIA_TYPE_AUDIO && !ost->enc) {
145 // use av_rescale_delta() for streamcopying audio, to preserve
146 // accuracy with coarse input timebases
147 int duration = av_get_audio_frame_duration2(ost->st->codecpar, pkt->size);
148
149 if (!duration)
150 duration = ost->st->codecpar->frame_size;
151
152 pkt->dts = av_rescale_delta(pkt->time_base, pkt->dts,
153 (AVRational){1, ost->st->codecpar->sample_rate}, duration,
154 &ms->ts_rescale_delta_last, ost->st->time_base);
155 pkt->pts = pkt->dts;
156
157 pkt->duration = av_rescale_q(pkt->duration, pkt->time_base, ost->st->time_base);
158 } else
159 av_packet_rescale_ts(pkt, pkt->time_base, ost->st->time_base);
160 pkt->time_base = ost->st->time_base;
161
162 if (!(mux->fc->oformat->flags & AVFMT_NOTIMESTAMPS)) {
163 if (pkt->dts != AV_NOPTS_VALUE &&
164 pkt->pts != AV_NOPTS_VALUE &&
165 pkt->dts > pkt->pts) {
166 av_log(ost, AV_LOG_WARNING, "Invalid DTS: %"PRId64" PTS: %"PRId64", replacing by guess\n",
167 pkt->dts, pkt->pts);
168 pkt->pts =
169 pkt->dts = av_clip64(ms->last_mux_dts, pkt->pts - 1, pkt->dts - 1) + 1;
170 }
171 if ((ost->type == AVMEDIA_TYPE_AUDIO || ost->type == AVMEDIA_TYPE_VIDEO || ost->type == AVMEDIA_TYPE_SUBTITLE) &&
172 pkt->dts != AV_NOPTS_VALUE &&
175 if (pkt->dts < max) {
176 int loglevel = max - pkt->dts > 2 || ost->type == AVMEDIA_TYPE_VIDEO ? AV_LOG_WARNING : AV_LOG_DEBUG;
177 if (exit_on_error)
178 loglevel = AV_LOG_ERROR;
179 av_log(ost, loglevel, "Non-monotonic DTS; "
180 "previous: %"PRId64", current: %"PRId64"; ",
181 ms->last_mux_dts, pkt->dts);
182 if (exit_on_error) {
183 return AVERROR(EINVAL);
184 }
185
186 av_log(ost, loglevel, "changing to %"PRId64". This may result "
187 "in incorrect timestamps in the output file.\n",
188 max);
189 if (pkt->pts >= pkt->dts)
190 pkt->pts = FFMAX(pkt->pts, max);
191 pkt->dts = max;
192 }
193 }
194 }
195 ms->last_mux_dts = pkt->dts;
196
197 if (debug_ts)
199
200 return 0;
201}
202
204{
206 AVFormatContext *s = mux->fc;
207 int64_t fs;
208 uint64_t frame_num;
209 int ret;
210
211 fs = filesize(s->pb);
213 if (fs >= mux->limit_filesize) {
214 ret = AVERROR_EOF;
215 goto fail;
216 }
217
218 ret = mux_fixup_ts(mux, ms, pkt);
219 if (ret < 0)
220 goto fail;
221
222 ms->data_size_mux += pkt->size;
223 frame_num = atomic_fetch_add(&ost->packets_written, 1);
224
225 pkt->stream_index = ost->index;
226
227 if (ms->stats.io)
228 enc_stats_write(ost, &ms->stats, NULL, pkt, frame_num);
229
231 if (ret < 0) {
233 "Error submitting a packet to the muxer: %s\n",
234 av_err2str(ret));
235 goto fail;
236 }
237
238 return 0;
239fail:
241 return ret;
242}
243
244static int sync_queue_process(Muxer *mux, MuxStream *ms, AVPacket *pkt, int *stream_eof)
245{
246 OutputFile *of = &mux->of;
247
248 if (ms->sq_idx_mux >= 0) {
249 int ret = sq_send(mux->sq_mux, ms->sq_idx_mux, SQPKT(pkt));
250 if (ret < 0) {
251 if (ret == AVERROR_EOF)
252 *stream_eof = 1;
253
254 return ret;
255 }
256
257 while (1) {
258 ret = sq_receive(mux->sq_mux, -1, SQPKT(mux->sq_pkt));
259 if (ret < 0) {
260 /* n.b.: We forward EOF from the sync queue, terminating muxing.
261 * This assumes that if a muxing sync queue is present, then all
262 * the streams use it. That is true currently, but may change in
263 * the future, then this code needs to be revisited.
264 */
265 return ret == AVERROR(EAGAIN) ? 0 : ret;
266 }
267
268 ret = write_packet(mux, of->streams[ret],
269 mux->sq_pkt);
270 if (ret < 0)
271 return ret;
272 }
273 } else if (pkt)
274 return write_packet(mux, &ms->ost, pkt);
275
276 return 0;
277}
278
280
281/* apply the output bitstream filters */
283 OutputStream *ost, AVPacket *pkt, int *stream_eof)
284{
286 const char *err_msg;
287 int ret;
288
289 if (pkt && !ost->enc) {
290 ret = of_streamcopy(&mux->of, ost, pkt);
291 if (ret == AVERROR(EAGAIN))
292 return 0;
293 else if (ret == AVERROR_EOF) {
295 pkt = NULL;
296 *stream_eof = 1;
297 } else if (ret < 0)
298 goto fail;
299 }
300
301 // emit heartbeat for -fix_sub_duration;
302 // we are only interested in heartbeats on on random access points.
303 if (pkt && (pkt->flags & AV_PKT_FLAG_KEY)) {
305 mt->fix_sub_duration_pkt->pts = pkt->pts;
306 mt->fix_sub_duration_pkt->time_base = pkt->time_base;
307
308 ret = sch_mux_sub_heartbeat(mux->sch, mux->sch_idx, ms->sch_idx,
310 if (ret < 0)
311 goto fail;
312 }
313
314 if (ms->bsf_ctx) {
315 int bsf_eof = 0;
316
317 if (pkt)
319
320 ret = av_bsf_send_packet(ms->bsf_ctx, pkt);
321 if (ret < 0) {
322 err_msg = "submitting a packet for bitstream filtering";
323 goto fail;
324 }
325
326 while (!bsf_eof) {
327 ret = av_bsf_receive_packet(ms->bsf_ctx, ms->bsf_pkt);
328 if (ret == AVERROR(EAGAIN))
329 return 0;
330 else if (ret == AVERROR_EOF)
331 bsf_eof = 1;
332 else if (ret < 0) {
334 "Error applying bitstream filters to a packet: %s",
335 av_err2str(ret));
336 if (exit_on_error)
337 return ret;
338 continue;
339 }
340
341 if (!bsf_eof)
343
344 ret = sync_queue_process(mux, ms, bsf_eof ? NULL : ms->bsf_pkt, stream_eof);
345 if (ret < 0)
346 goto mux_fail;
347 }
348 *stream_eof = 1;
349 } else {
350 ret = sync_queue_process(mux, ms, pkt, stream_eof);
351 if (ret < 0)
352 goto mux_fail;
353 }
354
355 return *stream_eof ? AVERROR_EOF : 0;
356
357mux_fail:
358 err_msg = "submitting a packet to the muxer";
359
360fail:
361 if (ret != AVERROR_EOF)
362 av_log(ost, AV_LOG_ERROR, "Error %s: %s\n", err_msg, av_err2str(ret));
363 return ret;
364}
365
366static void thread_set_name(Muxer *mux)
367{
368 char name[16];
369 snprintf(name, sizeof(name), "mux%d:%s",
370 mux->of.index, mux->fc->oformat->name);
372}
373
375{
376 av_packet_free(&mt->pkt);
378
379 memset(mt, 0, sizeof(*mt));
380}
381
383{
384 memset(mt, 0, sizeof(*mt));
385
386 mt->pkt = av_packet_alloc();
387 if (!mt->pkt)
388 goto fail;
389
391 if (!mt->fix_sub_duration_pkt)
392 goto fail;
393
394 return 0;
395
396fail:
398 return AVERROR(ENOMEM);
399}
400
402{
403 Muxer *mux = arg;
404 OutputFile *of = &mux->of;
405
407
408 int ret = 0;
409
410 ret = mux_thread_init(&mt);
411 if (ret < 0)
412 goto finish;
413
414 thread_set_name(mux);
415
416 while (1) {
418 int stream_idx, stream_eof = 0;
419
420 ret = sch_mux_receive(mux->sch, of->index, mt.pkt);
421 stream_idx = mt.pkt->stream_index;
422 if (stream_idx < 0) {
423 av_log(mux, AV_LOG_VERBOSE, "All streams finished\n");
424 ret = 0;
425 break;
426 }
427
428 ost = of->streams[mux->sch_stream_idx[stream_idx]];
429 mt.pkt->stream_index = ost->index;
431
432 ret = mux_packet_filter(mux, &mt, ost, ret < 0 ? NULL : mt.pkt, &stream_eof);
434 if (ret == AVERROR_EOF) {
435 if (stream_eof) {
436 sch_mux_receive_finish(mux->sch, of->index, stream_idx);
437 } else {
438 av_log(mux, AV_LOG_VERBOSE, "Muxer returned EOF\n");
439 ret = 0;
440 break;
441 }
442 } else if (ret < 0) {
443 av_log(mux, AV_LOG_ERROR, "Error muxing a packet\n");
444 break;
445 }
446 }
447
448finish:
450
451 return ret;
452}
453
455{
457 FrameData *fd = pkt->opaque_ref ? (FrameData*)pkt->opaque_ref->data : NULL;
458 int64_t dts = fd ? fd->dts_est : AV_NOPTS_VALUE;
460 int64_t ts_offset;
461
462 if (of->recording_time != INT64_MAX &&
463 dts >= of->recording_time + start_time)
464 return AVERROR_EOF;
465
466 if (!ms->streamcopy_started && !(pkt->flags & AV_PKT_FLAG_KEY) &&
468 return AVERROR(EAGAIN);
469
470 if (!ms->streamcopy_started) {
471 if (!ms->copy_prior_start &&
472 (pkt->pts == AV_NOPTS_VALUE ?
473 dts < ms->ts_copy_start :
474 pkt->pts < av_rescale_q(ms->ts_copy_start, AV_TIME_BASE_Q, pkt->time_base)))
475 return AVERROR(EAGAIN);
476
477 if (of->start_time != AV_NOPTS_VALUE && dts < of->start_time)
478 return AVERROR(EAGAIN);
479 }
480
481 ts_offset = av_rescale_q(start_time, AV_TIME_BASE_Q, pkt->time_base);
482
483 if (pkt->pts != AV_NOPTS_VALUE)
484 pkt->pts -= ts_offset;
485
486 if (pkt->dts == AV_NOPTS_VALUE) {
487 pkt->dts = av_rescale_q(dts, AV_TIME_BASE_Q, pkt->time_base);
488 } else if (ost->st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
489 pkt->pts = pkt->dts - ts_offset;
490 }
491
492 pkt->dts -= ts_offset;
493
494 ms->streamcopy_started = 1;
495
496 return 0;
497}
498
499int print_sdp(const char *filename);
500
501int print_sdp(const char *filename)
502{
503 char sdp[16384];
504 int j = 0, ret;
505 AVIOContext *sdp_pb;
506 AVFormatContext **avc;
507
508 avc = av_malloc_array(nb_output_files, sizeof(*avc));
509 if (!avc)
510 return AVERROR(ENOMEM);
511 for (int i = 0; i < nb_output_files; i++) {
513
514 if (!strcmp(mux->fc->oformat->name, "rtp")) {
515 avc[j] = mux->fc;
516 j++;
517 }
518 }
519
520 if (!j) {
521 av_log(NULL, AV_LOG_ERROR, "No output streams in the SDP.\n");
522 ret = AVERROR(EINVAL);
523 goto fail;
524 }
525
526 ret = av_sdp_create(avc, j, sdp, sizeof(sdp));
527 if (ret < 0)
528 goto fail;
529
530 if (!filename) {
531 printf("SDP:\n%s\n", sdp);
532 fflush(stdout);
533 } else {
534 ret = avio_open2(&sdp_pb, filename, AVIO_FLAG_WRITE, &int_cb, NULL);
535 if (ret < 0) {
536 av_log(NULL, AV_LOG_ERROR, "Failed to open sdp file '%s'\n", filename);
537 goto fail;
538 }
539
540 avio_print(sdp_pb, sdp);
541 avio_closep(&sdp_pb);
542 }
543
544fail:
545 av_freep(&avc);
546 return ret;
547}
548
550{
551 Muxer *mux = arg;
552 OutputFile *of = &mux->of;
553 AVFormatContext *fc = mux->fc;
554 int ret;
555
556 ret = avformat_write_header(fc, &mux->opts);
557 if (ret < 0) {
558 av_log(mux, AV_LOG_ERROR, "Could not write header (incorrect codec "
559 "parameters ?): %s\n", av_err2str(ret));
560 return ret;
561 }
562 //assert_avoptions(of->opts);
563 mux->header_written = 1;
564
565 av_dump_format(fc, of->index, fc->url, 1);
567
568 return 0;
569}
570
571static int bsf_init(MuxStream *ms)
572{
573 OutputStream *ost = &ms->ost;
574 AVBSFContext *ctx = ms->bsf_ctx;
575 int ret;
576
577 if (!ctx)
578 return avcodec_parameters_copy(ost->st->codecpar, ms->par_in);
579
580 ret = avcodec_parameters_copy(ctx->par_in, ms->par_in);
581 if (ret < 0)
582 return ret;
583
584 ctx->time_base_in = ost->st->time_base;
585
586 ret = av_bsf_init(ctx);
587 if (ret < 0) {
588 av_log(ms, AV_LOG_ERROR, "Error initializing bitstream filter: %s\n",
589 ctx->filter->name);
590 return ret;
591 }
592
593 ret = avcodec_parameters_copy(ost->st->codecpar, ctx->par_out);
594 if (ret < 0)
595 return ret;
596 ost->st->time_base = ctx->time_base_out;
597
598 ms->bsf_pkt = av_packet_alloc();
599 if (!ms->bsf_pkt)
600 return AVERROR(ENOMEM);
601
602 return 0;
603}
604
606 const AVCodecContext *enc_ctx)
607{
608 Muxer *mux = mux_from_of(of);
610 int ret;
611
612 if (enc_ctx) {
613 // use upstream time base unless it has been overridden previously
614 if (ost->st->time_base.num <= 0 || ost->st->time_base.den <= 0)
615 ost->st->time_base = av_add_q(enc_ctx->time_base, (AVRational){0, 1});
616
617 ost->st->avg_frame_rate = enc_ctx->framerate;
618 ost->st->sample_aspect_ratio = enc_ctx->sample_aspect_ratio;
619
620 ret = avcodec_parameters_from_context(ms->par_in, enc_ctx);
621 if (ret < 0) {
623 "Error initializing the output stream codec parameters.\n");
624 return ret;
625 }
626 }
627
628 /* initialize bitstream filters for the output stream
629 * needs to be done here, because the codec id for streamcopy is not
630 * known until now */
631 ret = bsf_init(ms);
632 if (ret < 0)
633 return ret;
634
635 if (ms->stereo3d_set) {
636 AVCodecParameters *par = ost->st->codecpar;
637 AVStereo3D *stereo;
638 size_t size;
639
640 stereo = av_stereo3d_alloc_size(&size);
641 if (!stereo)
642 return AVERROR(ENOMEM);
643 stereo->type = ms->stereo3d_type;
644
647 av_log(ost, AV_LOG_INFO, "Overriding existing stereoscopic 3D side data\n");
648
650 AV_PKT_DATA_STEREO3D, stereo, size, 0)) {
651 av_freep(&stereo);
652 return AVERROR(ENOMEM);
653 }
654
655 /* Keep Matroska/WebM metadata consistent with the explicit layout,
656 * as their muxer consults the tag before the side data. */
657 if (!strcmp(mux->fc->oformat->name, "matroska") ||
658 !strcmp(mux->fc->oformat->name, "webm")) {
659 const char *stereo_mode =
660 ms->stereo3d_type == AV_STEREO3D_2D ? "mono" :
661 ms->stereo3d_type == AV_STEREO3D_SIDEBYSIDE ? "left_right" :
662 "top_bottom";
663 ret = av_dict_set(&ost->st->metadata, "stereo_mode", stereo_mode, 0);
664 if (ret < 0)
665 return ret;
666 }
667 }
668
669 if (ms->stream_duration) {
670 ost->st->duration = av_rescale_q(ms->stream_duration, ms->stream_duration_tb,
671 ost->st->time_base);
672 }
673
674 if (ms->sch_idx >= 0)
675 return sch_mux_stream_ready(mux->sch, of->index, ms->sch_idx);
676
677 return 0;
678}
679
681{
682 int64_t total_packets_written = 0;
683 int pass1_used = 1;
684 int ret = 0;
685
686 for (int i = 0; i < of->nb_streams; i++) {
687 OutputStream *ost = of->streams[i];
688 uint64_t packets_written = atomic_load(&ost->packets_written);
689
690 total_packets_written += packets_written;
691
692 if (ost->enc &&
693 (ost->enc->enc_ctx->flags & (AV_CODEC_FLAG_PASS1 | AV_CODEC_FLAG_PASS2))
695 pass1_used = 0;
696
697 if (!packets_written &&
699 av_log(ost, AV_LOG_FATAL, "Empty output stream\n");
700 ret = err_merge(ret, AVERROR(EINVAL));
701 }
702 }
703
704 if (!total_packets_written) {
705 int level = AV_LOG_WARNING;
706
708 ret = err_merge(ret, AVERROR(EINVAL));
710 }
711
712 av_log(of, level, "Output file is empty, nothing was encoded%s\n",
713 pass1_used ? "" : "(check -ss / -t / -frames parameters if used)");
714 }
715
716 return ret;
717}
718
719static void mux_final_stats(Muxer *mux)
720{
721 OutputFile *of = &mux->of;
722 uint64_t total_packets = 0, total_size = 0;
723 uint64_t video_size = 0, audio_size = 0, subtitle_size = 0,
724 extra_size = 0, other_size = 0;
725
726 uint8_t overhead[16] = "unknown";
727 int64_t file_size = of_filesize(of);
728
729 av_log(of, AV_LOG_VERBOSE, "Output file #%d (%s):\n",
730 of->index, of->url);
731
732 for (int j = 0; j < of->nb_streams; j++) {
733 OutputStream *ost = of->streams[j];
735 const AVCodecParameters *par = ost->st->codecpar;
736 const enum AVMediaType type = par->codec_type;
737 const uint64_t s = ms->data_size_mux;
738
739 switch (type) {
740 case AVMEDIA_TYPE_VIDEO: video_size += s; break;
741 case AVMEDIA_TYPE_AUDIO: audio_size += s; break;
742 case AVMEDIA_TYPE_SUBTITLE: subtitle_size += s; break;
743 default: other_size += s; break;
744 }
745
746 extra_size += par->extradata_size;
747 total_size += s;
748 total_packets += atomic_load(&ost->packets_written);
749
750 av_log(of, AV_LOG_VERBOSE, " Output stream #%d:%d (%s): ",
752 if (ost->enc) {
753 av_log(of, AV_LOG_VERBOSE, "%"PRIu64" frames encoded",
754 ost->enc->frames_encoded);
756 av_log(of, AV_LOG_VERBOSE, " (%"PRIu64" samples)", ost->enc->samples_encoded);
757 av_log(of, AV_LOG_VERBOSE, "; ");
758 }
759
760 av_log(of, AV_LOG_VERBOSE, "%"PRIu64" packets muxed (%"PRIu64" bytes); ",
761 atomic_load(&ost->packets_written), s);
762
763 av_log(of, AV_LOG_VERBOSE, "\n");
764 }
765
766 av_log(of, AV_LOG_VERBOSE, " Total: %"PRIu64" packets (%"PRIu64" bytes) muxed\n",
767 total_packets, total_size);
768
769 if (total_size && file_size > 0 && file_size >= total_size) {
770 snprintf(overhead, sizeof(overhead), "%f%%",
771 100.0 * (file_size - total_size) / total_size);
772 }
773
775 "video:%1.0fKiB audio:%1.0fKiB subtitle:%1.0fKiB other streams:%1.0fKiB "
776 "global headers:%1.0fKiB muxing overhead: %s\n",
777 video_size / 1024.0,
778 audio_size / 1024.0,
779 subtitle_size / 1024.0,
780 other_size / 1024.0,
781 extra_size / 1024.0,
782 overhead);
783}
784
786{
787 Muxer *mux = mux_from_of(of);
788 AVFormatContext *fc = mux->fc;
789 int ret, mux_result = 0;
790
791 if (!mux->header_written) {
792 av_log(mux, AV_LOG_ERROR,
793 "Nothing was written into output file, because "
794 "at least one of its streams received no packets.\n");
795 return AVERROR(EINVAL);
796 }
797
798 ret = av_write_trailer(fc);
799 if (ret < 0) {
800 av_log(mux, AV_LOG_ERROR, "Error writing trailer: %s\n", av_err2str(ret));
801 mux_result = err_merge(mux_result, ret);
802 }
803
804 mux->last_filesize = filesize(fc->pb);
805
806 if (!(fc->oformat->flags & AVFMT_NOFILE)) {
807 ret = avio_closep(&fc->pb);
808 if (ret < 0) {
809 av_log(mux, AV_LOG_ERROR, "Error closing file: %s\n", av_err2str(ret));
810 mux_result = err_merge(mux_result, ret);
811 }
812 }
813
814 mux_final_stats(mux);
815
816 // check whether anything was actually written
817 ret = check_written(of);
818 mux_result = err_merge(mux_result, ret);
819
820 return mux_result;
821}
822
824{
825 for (int i = 0; i < es->nb_components; i++)
826 av_freep(&es->components[i].str);
827 av_freep(&es->components);
828
829 if (es->lock_initialized)
831 es->lock_initialized = 0;
832}
833
834static void ost_free(OutputStream **post)
835{
836 OutputStream *ost = *post;
837 MuxStream *ms;
838
839 if (!ost)
840 return;
841 ms = ms_from_ost(ost);
842
843 enc_free(&ost->enc);
844 fg_free(&ost->fg_simple);
845
846 if (ost->logfile) {
847 if (fclose(ost->logfile))
849 "Error closing logfile, loss of information possible: %s\n",
850 av_err2str(AVERROR(errno)));
851 ost->logfile = NULL;
852 }
853
855
856 av_bsf_free(&ms->bsf_ctx);
858
859 av_packet_free(&ms->pkt);
860
861 av_freep(&ost->kf.pts);
862 av_expr_free(ost->kf.pexpr);
863
864 av_freep(&ost->logfile_prefix);
865
866 av_freep(&ost->attachment_filename);
867
868 enc_stats_uninit(&ost->enc_stats_pre);
869 enc_stats_uninit(&ost->enc_stats_post);
871
872 av_freep(post);
873}
874
875static void fc_close(AVFormatContext **pfc)
876{
877 AVFormatContext *fc = *pfc;
878
879 if (!fc)
880 return;
881
882 if (!(fc->oformat->flags & AVFMT_NOFILE))
883 avio_closep(&fc->pb);
885
886 *pfc = NULL;
887}
888
890{
891 OutputFile *of = *pof;
892 Muxer *mux;
893
894 if (!of)
895 return;
896 mux = mux_from_of(of);
897
898 sq_free(&mux->sq_mux);
899
900 for (int i = 0; i < of->nb_streams; i++)
901 ost_free(&of->streams[i]);
902 av_freep(&of->streams);
903
905
906 av_dict_free(&mux->opts);
908
909 av_packet_free(&mux->sq_pkt);
910
911 fc_close(&mux->fc);
912
913 av_freep(pof);
914}
915
917{
918 Muxer *mux = mux_from_of(of);
919 return atomic_load(&mux->last_filesize);
920}
static double val(void *priv, double ch)
Definition aeval.c:77
static AVFormatContext * ctx
static void finish(void)
Main libavformat public API header.
#define AVFMT_NOFILE
Demuxer will use avio_open, no opened file should be provided by the caller.
Definition avformat.h:490
#define AVFMT_TS_NONSTRICT
Format does not require strictly increasing timestamps, but they must still be monotonic.
Definition avformat.h:509
#define AVFMT_NOTIMESTAMPS
Format does not need / have any timestamps.
Definition avformat.h:500
int avio_closep(AVIOContext **s)
Close the resource accessed by the AVIOContext *s, free it and set the pointer pointing to it to NULL...
Definition avio.c:724
int avio_open2(AVIOContext **s, const char *filename, int flags, const AVIOInterruptCB *int_cb, AVDictionary **options)
Create and initialize a AVIOContext for accessing the resource indicated by url.
Definition avio.c:566
Buffered I/O operations.
int64_t avio_size(AVIOContext *s)
Get the filesize.
Definition aviobuf.c:326
#define avio_print(s,...)
Write strings (const char *) to the context.
Definition avio.h:537
#define AVIO_FLAG_WRITE
write-only
Definition avio.h:618
static av_always_inline int64_t avio_tell(AVIOContext *s)
ftell() equivalent for AVIOContext.
Definition avio.h:494
size_t av_strlcatf(char *dst, size_t size, const char *fmt,...)
Definition avstring.c:103
#define i(width, name, range_min, range_max)
Definition cbs_h264.c:63
#define s(width, name)
Definition cbs_vp9.c:198
#define fs(width, name, subs,...)
Definition cbs_vp9.c:200
int avcodec_parameters_from_context(AVCodecParameters *par, const AVCodecContext *codec)
Definition codec_par.c:138
int avcodec_parameters_copy(AVCodecParameters *dst, const AVCodecParameters *src)
Definition codec_par.c:107
void avcodec_parameters_free(AVCodecParameters **ppar)
Definition codec_par.c:67
#define av_clip64
Definition common.h:103
#define NULL
Definition coverity.c:32
long long int64_t
Definition coverity.c:34
__device__ int printf(const char *,...)
#define max(a, b)
static const uint16_t fc[]
Definition dcaenc.h:43
static AVPacket * pkt
void av_expr_free(AVExpr *e)
Free a parsed expression previously created with av_expr_parse().
Definition eval.c:368
const AVIOInterruptCB int_cb
Definition ffmpeg.c:322
int nb_output_files
Definition ffmpeg.c:112
atomic_uint nb_output_dumped
Definition ffmpeg.c:103
OutputFile ** output_files
Definition ffmpeg.c:111
int debug_ts
Definition ffmpeg_opt.c:67
@ PKT_OPAQUE_FIX_SUB_DURATION
Definition ffmpeg.h:83
@ LATENCY_PROBE_FILTER_POST
Definition ffmpeg.h:91
@ LATENCY_PROBE_NB
Definition ffmpeg.h:94
@ LATENCY_PROBE_ENC_PRE
Definition ffmpeg.h:92
@ LATENCY_PROBE_DEC_PRE
Definition ffmpeg.h:88
@ LATENCY_PROBE_DEC_POST
Definition ffmpeg.h:89
@ LATENCY_PROBE_DEMUX
Definition ffmpeg.h:87
@ LATENCY_PROBE_ENC_POST
Definition ffmpeg.h:93
@ LATENCY_PROBE_FILTER_PRE
Definition ffmpeg.h:90
int abort_on_flags
Definition ffmpeg_opt.c:69
#define ABORT_ON_FLAG_EMPTY_OUTPUT
Definition ffmpeg.h:547
void enc_free(Encoder **penc)
Definition ffmpeg_enc.c:73
int exit_on_error
Definition ffmpeg_opt.c:68
#define ABORT_ON_FLAG_EMPTY_OUTPUT_STREAM
Definition ffmpeg.h:548
void fg_free(FilterGraph **pfg)
void enc_stats_write(OutputStream *ost, EncStats *es, const AVFrame *frame, const AVPacket *pkt, uint64_t frame_num)
Definition ffmpeg_enc.c:539
static int64_t filesize(AVIOContext *pb)
Definition ffmpeg_mux.c:52
static int check_written(OutputFile *of)
Definition ffmpeg_mux.c:680
static void fc_close(AVFormatContext **pfc)
Definition ffmpeg_mux.c:875
static void thread_set_name(Muxer *mux)
Definition ffmpeg_mux.c:366
int muxer_thread(void *arg)
Definition ffmpeg_mux.c:401
static int bsf_init(MuxStream *ms)
Definition ffmpeg_mux.c:571
int64_t of_filesize(OutputFile *of)
Definition ffmpeg_mux.c:916
static void mux_log_debug_ts(OutputStream *ost, const AVPacket *pkt)
Definition ffmpeg_mux.c:65
int of_stream_init(OutputFile *of, OutputStream *ost, const AVCodecContext *enc_ctx)
Definition ffmpeg_mux.c:605
static Muxer * mux_from_of(OutputFile *of)
Definition ffmpeg_mux.c:47
static int of_streamcopy(OutputFile *of, OutputStream *ost, AVPacket *pkt)
Definition ffmpeg_mux.c:454
int print_sdp(const char *filename)
Definition ffmpeg_mux.c:501
static int mux_packet_filter(Muxer *mux, MuxThreadContext *mt, OutputStream *ost, AVPacket *pkt, int *stream_eof)
Definition ffmpeg_mux.c:282
static void mux_final_stats(Muxer *mux)
Definition ffmpeg_mux.c:719
void of_free(OutputFile **pof)
Definition ffmpeg_mux.c:889
static int mux_fixup_ts(Muxer *mux, MuxStream *ms, AVPacket *pkt)
Definition ffmpeg_mux.c:139
int of_write_trailer(OutputFile *of)
Definition ffmpeg_mux.c:785
static void enc_stats_uninit(EncStats *es)
Definition ffmpeg_mux.c:823
static int mux_thread_init(MuxThreadContext *mt)
Definition ffmpeg_mux.c:382
static void mux_thread_uninit(MuxThreadContext *mt)
Definition ffmpeg_mux.c:374
static void ost_free(OutputStream **post)
Definition ffmpeg_mux.c:834
int mux_check_init(void *arg)
Definition ffmpeg_mux.c:549
static int sync_queue_process(Muxer *mux, MuxStream *ms, AVPacket *pkt, int *stream_eof)
Definition ffmpeg_mux.c:244
static int write_packet(Muxer *mux, OutputStream *ost, AVPacket *pkt)
Definition ffmpeg_mux.c:203
static MuxStream * ms_from_ost(OutputStream *ost)
Definition ffmpeg_mux.h:126
int sch_mux_stream_ready(Scheduler *sch, unsigned mux_idx, unsigned stream_idx)
Signal to the scheduler that the specified muxed stream is initialized and ready.
void sch_mux_receive_finish(Scheduler *sch, unsigned mux_idx, unsigned stream_idx)
Called by muxer tasks to signal that a stream will no longer accept input.
int sch_mux_sub_heartbeat(Scheduler *sch, unsigned mux_idx, unsigned stream_idx, const AVPacket *pkt)
int sch_mux_receive(Scheduler *sch, unsigned mux_idx, AVPacket *pkt)
Called by muxer tasks to obtain packets for muxing.
static int err_merge(int err0, int err1)
Merge two return codes - return one of the error codes if at least one of them was negative,...
static int64_t duration
Definition ffplay.c:411
static int64_t start_time
Definition ffplay.c:410
A generic FIFO API.
#define fail
Definition test.h:479
void av_bsf_free(AVBSFContext **pctx)
Free a bitstream filter context and everything associated with it; write NULL into the supplied point...
Definition bsf.c:47
int av_bsf_init(AVBSFContext *ctx)
Prepare the filter for use, after all the parameters and options have been set.
Definition bsf.c:147
int av_bsf_receive_packet(AVBSFContext *ctx, AVPacket *pkt)
Retrieve a filtered packet.
Definition bsf.c:228
int av_bsf_send_packet(AVBSFContext *ctx, AVPacket *pkt)
Submit a packet for filtering.
Definition bsf.c:200
#define AV_CODEC_FLAG_PASS2
Use internal 2pass ratecontrol in second pass mode.
Definition avcodec.h:294
#define AV_CODEC_FLAG_PASS1
Use internal 2pass ratecontrol in first pass mode.
Definition avcodec.h:290
AVPacketSideData * av_packet_side_data_add(AVPacketSideData **psd, int *pnb_sd, enum AVPacketSideDataType type, void *data, size_t size, int flags)
Wrap existing data as packet side data.
Definition packet.c:614
const AVPacketSideData * av_packet_side_data_get(const AVPacketSideData *sd, int nb_sd, enum AVPacketSideDataType type)
Get side information from a side data array.
Definition packet.c:571
@ AV_PKT_DATA_STEREO3D
This side data should be associated with a video stream and contains Stereoscopic 3D information in f...
Definition packet.h:111
void av_packet_free(AVPacket **pkt)
Free the packet, if the packet is reference counted, it will be unreferenced first.
Definition packet.c:74
void av_packet_unref(AVPacket *pkt)
Wipe the packet.
Definition packet.c:435
#define AV_PKT_FLAG_TRUSTED
The packet comes from a trusted source.
Definition packet.h:671
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition packet.h:657
AVPacket * av_packet_alloc(void)
Allocate an AVPacket and set its fields to default values.
Definition packet.c:63
void av_packet_rescale_ts(AVPacket *pkt, AVRational src_tb, AVRational dst_tb)
Convert valid timing fields (timestamps / durations) in a packet from one timebase to another.
Definition packet.c:539
void avformat_free_context(AVFormatContext *s)
Free an AVFormatContext and all its streams.
Definition avformat.c:164
av_warn_unused_result int avformat_write_header(AVFormatContext *s, AVDictionary **options)
Allocate the stream private data and write the stream header to an output media file.
Definition mux.c:505
int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt)
Write a packet to an output media file ensuring correct interleaving.
Definition mux.c:1261
int av_write_trailer(AVFormatContext *s)
Write the stream trailer to an output media file and free the file private data.
Definition mux.c:1276
int av_sdp_create(AVFormatContext *ac[], int n_files, char *buf, int size)
Generate an SDP for an RTP session.
Definition sdp.c:951
void av_dump_format(AVFormatContext *ic, int index, const char *url, int is_output)
Print detailed information about the input or output format, such as duration, bitrate,...
Definition dump.c:941
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_set(AVDictionary **pm, const char *key, const char *value, int flags)
Set the given entry in *pm, overwriting an existing entry.
Definition dict.c:87
#define AVERROR_EOF
End of file.
Definition error.h:57
#define av_err2str(errnum)
Convenience macro, the return value should be used only directly in function arguments but never stan...
Definition error.h:122
#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_FATAL
Something went wrong and recovery is not possible.
Definition log.h:204
#define AV_LOG_VERBOSE
Detailed information.
Definition log.h:226
#define AV_LOG_INFO
Standard information.
Definition log.h:221
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition log.h:210
AVRational av_add_q(AVRational b, AVRational c)
Add two rationals.
Definition rational.c:93
int64_t av_rescale_delta(AVRational in_tb, int64_t in_ts, AVRational fs_tb, int duration, int64_t *last, AVRational out_tb)
Rescale a timestamp while preserving known durations.
int64_t av_rescale_q(int64_t a, AVRational bq, AVRational cq)
Rescale a 64-bit integer by 2 rational numbers.
const char * av_get_media_type_string(enum AVMediaType media_type)
Return a string describing the media_type enum, NULL if media_type is unknown.
Definition utils.c:28
AVMediaType
Definition avutil.h:198
@ AVMEDIA_TYPE_AUDIO
Definition avutil.h:201
@ AVMEDIA_TYPE_SUBTITLE
Definition avutil.h:203
@ AVMEDIA_TYPE_VIDEO
Definition avutil.h:200
size_t av_strlcat(char *dst, const char *src, size_t size)
Append the string src to the string dst, but to a total length of no more than size - 1 bytes,...
Definition avstring.c:95
#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
AVStereo3D * av_stereo3d_alloc_size(size_t *size)
Allocate an AVStereo3D structure and set its fields to default values.
Definition stereo3d.c:39
@ AV_STEREO3D_2D
Video is not stereoscopic (and metadata has to be there).
Definition stereo3d.h:52
@ AV_STEREO3D_SIDEBYSIDE
Views are next to each other.
Definition stereo3d.h:64
uint32_t type
Definition jpegmpfenc.c:80
const char * arg
Definition jacosubdec.c:65
int av_get_audio_frame_duration2(AVCodecParameters *par, int frame_bytes)
Definition utils.c:830
Stereoscopic video.
static int ff_thread_setname(const char *name)
Definition thread.h:216
const char * desc
Definition libsvtav1.c:83
#define FFMAX(a, b)
Definition macros.h:47
Memory handling functions.
static av_always_inline int pthread_mutex_destroy(pthread_mutex_t *mutex)
Definition os2threads.h:112
const char * name
Definition qsvenc.c:142
#define FF_ARRAY_ELEMS(a)
#define atomic_store(object, desired)
Definition stdatomic.h:256
#define atomic_load(object)
Definition stdatomic.h:250
#define atomic_fetch_add(object, operand)
Definition stdatomic.h:312
The bitstream filter state.
Definition bsf.h:68
AVRational time_base_out
The timebase used for the timestamps of the output packets.
Definition bsf.h:108
AVRational time_base_in
The timebase used for the timestamps of the input packets.
Definition bsf.h:102
main external API structure.
Definition avcodec.h:443
AVRational framerate
Definition avcodec.h:563
AVRational sample_aspect_ratio
sample aspect ratio (0 if unknown) That is the width of a pixel divided by the height of the pixel.
Definition avcodec.h:628
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented.
Definition avcodec.h:547
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 nb_coded_side_data
Amount of entries in coded_side_data.
Definition codec_par.h:88
enum AVMediaType codec_type
General type of the encoded data.
Definition codec_par.h:53
AVPacketSideData * coded_side_data
Additional data associated with the entire stream.
Definition codec_par.h:83
Format I/O context.
Definition avformat.h:1400
const struct AVOutputFormat * oformat
The output container format.
Definition avformat.h:1419
Bytestream IO Context.
Definition avio.h:160
int flags
can use flags: AVFMT_NOFILE, AVFMT_NEEDNUMBER, AVFMT_EXPERIMENTAL, AVFMT_GLOBALHEADER,...
Definition avformat.h:548
const char * name
Definition avformat.h:529
This structure stores compressed data.
Definition packet.h:587
int stream_index
Definition packet.h:612
int flags
A combination of AV_PKT_FLAG values.
Definition packet.h:616
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
Definition packet.h:603
void * opaque
for some private data of the user
Definition packet.h:635
AVRational time_base
Time base of the packet's timestamps.
Definition packet.h:654
Rational number (pair of numerator and denominator).
Definition rational.h:58
Stereo 3D type: this structure describes how two videos are packed within a single video surface,...
Definition stereo3d.h:203
enum AVStereo3DType type
How views are packed within the video.
Definition stereo3d.h:207
uint8_t * str
Definition ffmpeg.h:575
int nb_components
Definition ffmpeg.h:581
AVIOContext * io
Definition ffmpeg.h:583
EncStatsComponent * components
Definition ffmpeg.h:580
pthread_mutex_t lock
Definition ffmpeg.h:585
int lock_initialized
Definition ffmpeg.h:586
int64_t dts_est
Definition ffmpeg.h:710
int64_t wallclock[LATENCY_PROBE_NB]
Definition ffmpeg.h:724
OutputStream ost
Definition ffmpeg_mux.h:37
int copy_prior_start
Definition ffmpeg_mux.h:82
AVPacket * pkt
Definition ffmpeg_mux.h:51
int stereo3d_type
Definition ffmpeg_mux.h:92
int sq_idx_mux
Definition ffmpeg_mux.h:59
int stereo3d_set
Definition ffmpeg_mux.h:91
AVBSFContext * bsf_ctx
Definition ffmpeg_mux.h:48
AVCodecParameters * par_in
Codec parameters for packets submitted to the muxer (i.e.
Definition ffmpeg_mux.h:43
AVPacket * bsf_pkt
Definition ffmpeg_mux.h:49
uint64_t data_size_mux
Definition ffmpeg_mux.h:79
int copy_initial_nonkeyframes
Definition ffmpeg_mux.h:81
int64_t ts_rescale_delta_last
Definition ffmpeg_mux.h:76
int64_t ts_copy_start
Definition ffmpeg_mux.h:66
int64_t stream_duration
Definition ffmpeg_mux.h:72
AVRational stream_duration_tb
Definition ffmpeg_mux.h:73
int64_t last_mux_dts
Definition ffmpeg_mux.h:70
EncStats stats
Definition ffmpeg_mux.h:53
int sch_idx
Definition ffmpeg_mux.h:55
int streamcopy_started
Definition ffmpeg_mux.h:83
AVPacket * pkt
Definition ffmpeg_mux.c:43
AVPacket * fix_sub_duration_pkt
Definition ffmpeg_mux.c:44
AVDictionary * opts
Definition ffmpeg_mux.h:110
AVDictionary * enc_opts_used
Definition ffmpeg_mux.h:113
OutputFile of
Definition ffmpeg_mux.h:96
atomic_int_least64_t last_filesize
Definition ffmpeg_mux.h:117
AVPacket * sq_pkt
Definition ffmpeg_mux.h:121
int header_written
Definition ffmpeg_mux.h:118
Scheduler * sch
Definition ffmpeg_mux.h:103
SyncQueue * sq_mux
Definition ffmpeg_mux.h:120
AVFormatContext * fc
Definition ffmpeg_mux.h:101
unsigned sch_idx
Definition ffmpeg_mux.h:104
int * sch_stream_idx
Definition ffmpeg_mux.h:107
int64_t limit_filesize
Definition ffmpeg_mux.h:116
int index
Definition ffmpeg.h:693
const char * url
Definition ffmpeg.h:695
OutputStream ** streams
Definition ffmpeg.h:697
int nb_streams
Definition ffmpeg.h:698
int64_t start_time
start time in microseconds == AV_TIME_BASE units
Definition ffmpeg.h:701
int64_t recording_time
desired length of the resulting file in microseconds == AV_TIME_BASE units
Definition ffmpeg.h:700
uint8_t level
Definition svq3.c:208
int sq_send(SyncQueue *sq, unsigned int stream_idx, SyncQueueFrame frame)
Submit a frame for the stream with index stream_idx.
Definition sync_queue.c:333
int sq_receive(SyncQueue *sq, int stream_idx, SyncQueueFrame frame)
Read a frame from the queue.
Definition sync_queue.c:586
void sq_free(SyncQueue **psq)
Definition sync_queue.c:671
#define SQPKT(pkt)
Definition sync_queue.h:39
#define av_malloc_array(a, b)
#define av_freep(p)
#define av_log(a,...)
int64_t av_gettime_relative(void)
Get the current time in microseconds since some unspecified starting point.
Definition time.c:57
timestamp utils, mostly useful for debugging/logging purposes
#define av_ts2str(ts)
Convenience macro, the return value should be used only directly in function arguments but never stan...
Definition timestamp.h:54
#define av_ts2timestr(ts, tb)
Convenience macro, the return value should be used only directly in function arguments but never stan...
Definition timestamp.h:83
int size
static AVStream * ost
static av_always_inline int diff(const struct color_info *a, const struct color_info *b, const int trans_thresh)