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/time.h"
34#include "libavutil/timestamp.h"
35
36#include "libavcodec/packet.h"
37
39#include "libavformat/avio.h"
40
45
47{
48 return (Muxer*)of;
49}
50
52{
53 int64_t ret = -1;
54
55 if (pb) {
56 ret = avio_size(pb);
57 if (ret <= 0) // FIXME improve avio_size() so it works with non seekable output too
58 ret = avio_tell(pb);
59 }
60
61 return ret;
62}
63
65{
66 static const char *desc[] = {
67 [LATENCY_PROBE_DEMUX] = "demux",
68 [LATENCY_PROBE_DEC_PRE] = "decode",
69 [LATENCY_PROBE_DEC_POST] = "decode",
70 [LATENCY_PROBE_FILTER_PRE] = "filter",
71 [LATENCY_PROBE_FILTER_POST] = "filter",
72 [LATENCY_PROBE_ENC_PRE] = "encode",
73 [LATENCY_PROBE_ENC_POST] = "encode",
74 [LATENCY_PROBE_NB] = "mux",
75 };
76
77 char latency[512];
78
79 *latency = 0;
80 if (pkt->opaque_ref) {
81 const FrameData *fd = (FrameData*)pkt->opaque_ref->data;
83 int64_t total = INT64_MIN;
84
85 int next;
86
87 for (unsigned i = 0; i < FF_ARRAY_ELEMS(fd->wallclock); i = next) {
88 int64_t val = fd->wallclock[i];
89
90 next = i + 1;
91
92 if (val == INT64_MIN)
93 continue;
94
95 if (total == INT64_MIN) {
96 total = now - val;
97 snprintf(latency, sizeof(latency), "total:%gms", total / 1e3);
98 }
99
100 // find the next valid entry
101 for (; next <= FF_ARRAY_ELEMS(fd->wallclock); next++) {
102 int64_t val_next = (next == FF_ARRAY_ELEMS(fd->wallclock)) ?
103 now : fd->wallclock[next];
105
106 if (val_next == INT64_MIN)
107 continue;
108 diff = val_next - val;
109
110 // print those stages that take at least 5% of total
111 if (100. * diff > 5. * total) {
112 av_strlcat(latency, ", ", sizeof(latency));
113
114 if (!strcmp(desc[i], desc[next]))
115 av_strlcat(latency, desc[i], sizeof(latency));
116 else
117 av_strlcatf(latency, sizeof(latency), "%s-%s:",
118 desc[i], desc[next]);
119
120 av_strlcatf(latency, sizeof(latency), " %gms/%d%%",
121 diff / 1e3, (int)(100. * diff / total));
122 }
123
124 break;
125 }
126
127 }
128 }
129
130 av_log(ost, AV_LOG_INFO, "muxer <- pts:%s pts_time:%s dts:%s dts_time:%s "
131 "duration:%s duration_time:%s size:%d latency(%s)\n",
132 av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &ost->st->time_base),
133 av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &ost->st->time_base),
134 av_ts2str(pkt->duration), av_ts2timestr(pkt->duration, &ost->st->time_base),
135 pkt->size, *latency ? latency : "N/A");
136}
137
138static int mux_fixup_ts(Muxer *mux, MuxStream *ms, AVPacket *pkt)
139{
140 OutputStream *ost = &ms->ost;
141
142 // rescale timestamps to the stream timebase
143 if (ost->type == AVMEDIA_TYPE_AUDIO && !ost->enc) {
144 // use av_rescale_delta() for streamcopying audio, to preserve
145 // accuracy with coarse input timebases
146 int duration = av_get_audio_frame_duration2(ost->st->codecpar, pkt->size);
147
148 if (!duration)
149 duration = ost->st->codecpar->frame_size;
150
151 pkt->dts = av_rescale_delta(pkt->time_base, pkt->dts,
152 (AVRational){1, ost->st->codecpar->sample_rate}, duration,
153 &ms->ts_rescale_delta_last, ost->st->time_base);
154 pkt->pts = pkt->dts;
155
156 pkt->duration = av_rescale_q(pkt->duration, pkt->time_base, ost->st->time_base);
157 } else
158 av_packet_rescale_ts(pkt, pkt->time_base, ost->st->time_base);
159 pkt->time_base = ost->st->time_base;
160
161 if (!(mux->fc->oformat->flags & AVFMT_NOTIMESTAMPS)) {
162 if (pkt->dts != AV_NOPTS_VALUE &&
163 pkt->pts != AV_NOPTS_VALUE &&
164 pkt->dts > pkt->pts) {
165 av_log(ost, AV_LOG_WARNING, "Invalid DTS: %"PRId64" PTS: %"PRId64", replacing by guess\n",
166 pkt->dts, pkt->pts);
167 pkt->pts =
168 pkt->dts = pkt->pts + pkt->dts + ms->last_mux_dts + 1
169 - FFMIN3(pkt->pts, pkt->dts, ms->last_mux_dts + 1)
170 - FFMAX3(pkt->pts, pkt->dts, ms->last_mux_dts + 1);
171 }
172 if ((ost->type == AVMEDIA_TYPE_AUDIO || ost->type == AVMEDIA_TYPE_VIDEO || ost->type == AVMEDIA_TYPE_SUBTITLE) &&
173 pkt->dts != AV_NOPTS_VALUE &&
176 if (pkt->dts < max) {
177 int loglevel = max - pkt->dts > 2 || ost->type == AVMEDIA_TYPE_VIDEO ? AV_LOG_WARNING : AV_LOG_DEBUG;
178 if (exit_on_error)
179 loglevel = AV_LOG_ERROR;
180 av_log(ost, loglevel, "Non-monotonic DTS; "
181 "previous: %"PRId64", current: %"PRId64"; ",
182 ms->last_mux_dts, pkt->dts);
183 if (exit_on_error) {
184 return AVERROR(EINVAL);
185 }
186
187 av_log(ost, loglevel, "changing to %"PRId64". This may result "
188 "in incorrect timestamps in the output file.\n",
189 max);
190 if (pkt->pts >= pkt->dts)
191 pkt->pts = FFMAX(pkt->pts, max);
192 pkt->dts = max;
193 }
194 }
195 }
196 ms->last_mux_dts = pkt->dts;
197
198 if (debug_ts)
200
201 return 0;
202}
203
205{
207 AVFormatContext *s = mux->fc;
208 int64_t fs;
209 uint64_t frame_num;
210 int ret;
211
212 fs = filesize(s->pb);
214 if (fs >= mux->limit_filesize) {
215 ret = AVERROR_EOF;
216 goto fail;
217 }
218
219 ret = mux_fixup_ts(mux, ms, pkt);
220 if (ret < 0)
221 goto fail;
222
223 ms->data_size_mux += pkt->size;
224 frame_num = atomic_fetch_add(&ost->packets_written, 1);
225
226 pkt->stream_index = ost->index;
227
228 if (ms->stats.io)
229 enc_stats_write(ost, &ms->stats, NULL, pkt, frame_num);
230
232 if (ret < 0) {
234 "Error submitting a packet to the muxer: %s\n",
235 av_err2str(ret));
236 goto fail;
237 }
238
239 return 0;
240fail:
242 return ret;
243}
244
245static int sync_queue_process(Muxer *mux, MuxStream *ms, AVPacket *pkt, int *stream_eof)
246{
247 OutputFile *of = &mux->of;
248
249 if (ms->sq_idx_mux >= 0) {
250 int ret = sq_send(mux->sq_mux, ms->sq_idx_mux, SQPKT(pkt));
251 if (ret < 0) {
252 if (ret == AVERROR_EOF)
253 *stream_eof = 1;
254
255 return ret;
256 }
257
258 while (1) {
259 ret = sq_receive(mux->sq_mux, -1, SQPKT(mux->sq_pkt));
260 if (ret < 0) {
261 /* n.b.: We forward EOF from the sync queue, terminating muxing.
262 * This assumes that if a muxing sync queue is present, then all
263 * the streams use it. That is true currently, but may change in
264 * the future, then this code needs to be revisited.
265 */
266 return ret == AVERROR(EAGAIN) ? 0 : ret;
267 }
268
269 ret = write_packet(mux, of->streams[ret],
270 mux->sq_pkt);
271 if (ret < 0)
272 return ret;
273 }
274 } else if (pkt)
275 return write_packet(mux, &ms->ost, pkt);
276
277 return 0;
278}
279
281
282/* apply the output bitstream filters */
284 OutputStream *ost, AVPacket *pkt, int *stream_eof)
285{
287 const char *err_msg;
288 int ret;
289
290 if (pkt && !ost->enc) {
291 ret = of_streamcopy(&mux->of, ost, pkt);
292 if (ret == AVERROR(EAGAIN))
293 return 0;
294 else if (ret == AVERROR_EOF) {
296 pkt = NULL;
297 *stream_eof = 1;
298 } else if (ret < 0)
299 goto fail;
300 }
301
302 // emit heartbeat for -fix_sub_duration;
303 // we are only interested in heartbeats on on random access points.
304 if (pkt && (pkt->flags & AV_PKT_FLAG_KEY)) {
306 mt->fix_sub_duration_pkt->pts = pkt->pts;
307 mt->fix_sub_duration_pkt->time_base = pkt->time_base;
308
309 ret = sch_mux_sub_heartbeat(mux->sch, mux->sch_idx, ms->sch_idx,
311 if (ret < 0)
312 goto fail;
313 }
314
315 if (ms->bsf_ctx) {
316 int bsf_eof = 0;
317
318 if (pkt)
320
321 ret = av_bsf_send_packet(ms->bsf_ctx, pkt);
322 if (ret < 0) {
323 err_msg = "submitting a packet for bitstream filtering";
324 goto fail;
325 }
326
327 while (!bsf_eof) {
328 ret = av_bsf_receive_packet(ms->bsf_ctx, ms->bsf_pkt);
329 if (ret == AVERROR(EAGAIN))
330 return 0;
331 else if (ret == AVERROR_EOF)
332 bsf_eof = 1;
333 else if (ret < 0) {
335 "Error applying bitstream filters to a packet: %s",
336 av_err2str(ret));
337 if (exit_on_error)
338 return ret;
339 continue;
340 }
341
342 if (!bsf_eof)
344
345 ret = sync_queue_process(mux, ms, bsf_eof ? NULL : ms->bsf_pkt, stream_eof);
346 if (ret < 0)
347 goto mux_fail;
348 }
349 *stream_eof = 1;
350 } else {
351 ret = sync_queue_process(mux, ms, pkt, stream_eof);
352 if (ret < 0)
353 goto mux_fail;
354 }
355
356 return *stream_eof ? AVERROR_EOF : 0;
357
358mux_fail:
359 err_msg = "submitting a packet to the muxer";
360
361fail:
362 if (ret != AVERROR_EOF)
363 av_log(ost, AV_LOG_ERROR, "Error %s: %s\n", err_msg, av_err2str(ret));
364 return ret;
365}
366
367static void thread_set_name(Muxer *mux)
368{
369 char name[16];
370 snprintf(name, sizeof(name), "mux%d:%s",
371 mux->of.index, mux->fc->oformat->name);
373}
374
376{
377 av_packet_free(&mt->pkt);
379
380 memset(mt, 0, sizeof(*mt));
381}
382
384{
385 memset(mt, 0, sizeof(*mt));
386
387 mt->pkt = av_packet_alloc();
388 if (!mt->pkt)
389 goto fail;
390
392 if (!mt->fix_sub_duration_pkt)
393 goto fail;
394
395 return 0;
396
397fail:
399 return AVERROR(ENOMEM);
400}
401
403{
404 Muxer *mux = arg;
405 OutputFile *of = &mux->of;
406
408
409 int ret = 0;
410
411 ret = mux_thread_init(&mt);
412 if (ret < 0)
413 goto finish;
414
415 thread_set_name(mux);
416
417 while (1) {
419 int stream_idx, stream_eof = 0;
420
421 ret = sch_mux_receive(mux->sch, of->index, mt.pkt);
422 stream_idx = mt.pkt->stream_index;
423 if (stream_idx < 0) {
424 av_log(mux, AV_LOG_VERBOSE, "All streams finished\n");
425 ret = 0;
426 break;
427 }
428
429 ost = of->streams[mux->sch_stream_idx[stream_idx]];
430 mt.pkt->stream_index = ost->index;
432
433 ret = mux_packet_filter(mux, &mt, ost, ret < 0 ? NULL : mt.pkt, &stream_eof);
435 if (ret == AVERROR_EOF) {
436 if (stream_eof) {
437 sch_mux_receive_finish(mux->sch, of->index, stream_idx);
438 } else {
439 av_log(mux, AV_LOG_VERBOSE, "Muxer returned EOF\n");
440 ret = 0;
441 break;
442 }
443 } else if (ret < 0) {
444 av_log(mux, AV_LOG_ERROR, "Error muxing a packet\n");
445 break;
446 }
447 }
448
449finish:
451
452 return ret;
453}
454
456{
458 FrameData *fd = pkt->opaque_ref ? (FrameData*)pkt->opaque_ref->data : NULL;
459 int64_t dts = fd ? fd->dts_est : AV_NOPTS_VALUE;
461 int64_t ts_offset;
462
463 if (of->recording_time != INT64_MAX &&
464 dts >= of->recording_time + start_time)
465 return AVERROR_EOF;
466
467 if (!ms->streamcopy_started && !(pkt->flags & AV_PKT_FLAG_KEY) &&
469 return AVERROR(EAGAIN);
470
471 if (!ms->streamcopy_started) {
472 if (!ms->copy_prior_start &&
473 (pkt->pts == AV_NOPTS_VALUE ?
474 dts < ms->ts_copy_start :
475 pkt->pts < av_rescale_q(ms->ts_copy_start, AV_TIME_BASE_Q, pkt->time_base)))
476 return AVERROR(EAGAIN);
477
478 if (of->start_time != AV_NOPTS_VALUE && dts < of->start_time)
479 return AVERROR(EAGAIN);
480 }
481
482 ts_offset = av_rescale_q(start_time, AV_TIME_BASE_Q, pkt->time_base);
483
484 if (pkt->pts != AV_NOPTS_VALUE)
485 pkt->pts -= ts_offset;
486
487 if (pkt->dts == AV_NOPTS_VALUE) {
488 pkt->dts = av_rescale_q(dts, AV_TIME_BASE_Q, pkt->time_base);
489 } else if (ost->st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
490 pkt->pts = pkt->dts - ts_offset;
491 }
492
493 pkt->dts -= ts_offset;
494
495 ms->streamcopy_started = 1;
496
497 return 0;
498}
499
500int print_sdp(const char *filename);
501
502int print_sdp(const char *filename)
503{
504 char sdp[16384];
505 int j = 0, ret;
506 AVIOContext *sdp_pb;
507 AVFormatContext **avc;
508
509 avc = av_malloc_array(nb_output_files, sizeof(*avc));
510 if (!avc)
511 return AVERROR(ENOMEM);
512 for (int i = 0; i < nb_output_files; i++) {
514
515 if (!strcmp(mux->fc->oformat->name, "rtp")) {
516 avc[j] = mux->fc;
517 j++;
518 }
519 }
520
521 if (!j) {
522 av_log(NULL, AV_LOG_ERROR, "No output streams in the SDP.\n");
523 ret = AVERROR(EINVAL);
524 goto fail;
525 }
526
527 ret = av_sdp_create(avc, j, sdp, sizeof(sdp));
528 if (ret < 0)
529 goto fail;
530
531 if (!filename) {
532 printf("SDP:\n%s\n", sdp);
533 fflush(stdout);
534 } else {
535 ret = avio_open2(&sdp_pb, filename, AVIO_FLAG_WRITE, &int_cb, NULL);
536 if (ret < 0) {
537 av_log(NULL, AV_LOG_ERROR, "Failed to open sdp file '%s'\n", filename);
538 goto fail;
539 }
540
541 avio_print(sdp_pb, sdp);
542 avio_closep(&sdp_pb);
543 }
544
545fail:
546 av_freep(&avc);
547 return ret;
548}
549
551{
552 Muxer *mux = arg;
553 OutputFile *of = &mux->of;
554 AVFormatContext *fc = mux->fc;
555 int ret;
556
557 ret = avformat_write_header(fc, &mux->opts);
558 if (ret < 0) {
559 av_log(mux, AV_LOG_ERROR, "Could not write header (incorrect codec "
560 "parameters ?): %s\n", av_err2str(ret));
561 return ret;
562 }
563 //assert_avoptions(of->opts);
564 mux->header_written = 1;
565
566 av_dump_format(fc, of->index, fc->url, 1);
568
569 return 0;
570}
571
572static int bsf_init(MuxStream *ms)
573{
574 OutputStream *ost = &ms->ost;
575 AVBSFContext *ctx = ms->bsf_ctx;
576 int ret;
577
578 if (!ctx)
579 return avcodec_parameters_copy(ost->st->codecpar, ms->par_in);
580
581 ret = avcodec_parameters_copy(ctx->par_in, ms->par_in);
582 if (ret < 0)
583 return ret;
584
585 ctx->time_base_in = ost->st->time_base;
586
587 ret = av_bsf_init(ctx);
588 if (ret < 0) {
589 av_log(ms, AV_LOG_ERROR, "Error initializing bitstream filter: %s\n",
590 ctx->filter->name);
591 return ret;
592 }
593
594 ret = avcodec_parameters_copy(ost->st->codecpar, ctx->par_out);
595 if (ret < 0)
596 return ret;
597 ost->st->time_base = ctx->time_base_out;
598
599 ms->bsf_pkt = av_packet_alloc();
600 if (!ms->bsf_pkt)
601 return AVERROR(ENOMEM);
602
603 return 0;
604}
605
607 const AVCodecContext *enc_ctx)
608{
609 Muxer *mux = mux_from_of(of);
611 int ret;
612
613 if (enc_ctx) {
614 // use upstream time base unless it has been overridden previously
615 if (ost->st->time_base.num <= 0 || ost->st->time_base.den <= 0)
616 ost->st->time_base = av_add_q(enc_ctx->time_base, (AVRational){0, 1});
617
618 ost->st->avg_frame_rate = enc_ctx->framerate;
619 ost->st->sample_aspect_ratio = enc_ctx->sample_aspect_ratio;
620
621 ret = avcodec_parameters_from_context(ms->par_in, enc_ctx);
622 if (ret < 0) {
624 "Error initializing the output stream codec parameters.\n");
625 return ret;
626 }
627 }
628
629 /* initialize bitstream filters for the output stream
630 * needs to be done here, because the codec id for streamcopy is not
631 * known until now */
632 ret = bsf_init(ms);
633 if (ret < 0)
634 return ret;
635
636 if (ms->stream_duration) {
637 ost->st->duration = av_rescale_q(ms->stream_duration, ms->stream_duration_tb,
638 ost->st->time_base);
639 }
640
641 if (ms->sch_idx >= 0)
642 return sch_mux_stream_ready(mux->sch, of->index, ms->sch_idx);
643
644 return 0;
645}
646
648{
649 int64_t total_packets_written = 0;
650 int pass1_used = 1;
651 int ret = 0;
652
653 for (int i = 0; i < of->nb_streams; i++) {
654 OutputStream *ost = of->streams[i];
655 uint64_t packets_written = atomic_load(&ost->packets_written);
656
657 total_packets_written += packets_written;
658
659 if (ost->enc &&
660 (ost->enc->enc_ctx->flags & (AV_CODEC_FLAG_PASS1 | AV_CODEC_FLAG_PASS2))
662 pass1_used = 0;
663
664 if (!packets_written &&
666 av_log(ost, AV_LOG_FATAL, "Empty output stream\n");
667 ret = err_merge(ret, AVERROR(EINVAL));
668 }
669 }
670
671 if (!total_packets_written) {
672 int level = AV_LOG_WARNING;
673
675 ret = err_merge(ret, AVERROR(EINVAL));
677 }
678
679 av_log(of, level, "Output file is empty, nothing was encoded%s\n",
680 pass1_used ? "" : "(check -ss / -t / -frames parameters if used)");
681 }
682
683 return ret;
684}
685
686static void mux_final_stats(Muxer *mux)
687{
688 OutputFile *of = &mux->of;
689 uint64_t total_packets = 0, total_size = 0;
690 uint64_t video_size = 0, audio_size = 0, subtitle_size = 0,
691 extra_size = 0, other_size = 0;
692
693 uint8_t overhead[16] = "unknown";
694 int64_t file_size = of_filesize(of);
695
696 av_log(of, AV_LOG_VERBOSE, "Output file #%d (%s):\n",
697 of->index, of->url);
698
699 for (int j = 0; j < of->nb_streams; j++) {
700 OutputStream *ost = of->streams[j];
702 const AVCodecParameters *par = ost->st->codecpar;
703 const enum AVMediaType type = par->codec_type;
704 const uint64_t s = ms->data_size_mux;
705
706 switch (type) {
707 case AVMEDIA_TYPE_VIDEO: video_size += s; break;
708 case AVMEDIA_TYPE_AUDIO: audio_size += s; break;
709 case AVMEDIA_TYPE_SUBTITLE: subtitle_size += s; break;
710 default: other_size += s; break;
711 }
712
713 extra_size += par->extradata_size;
714 total_size += s;
715 total_packets += atomic_load(&ost->packets_written);
716
717 av_log(of, AV_LOG_VERBOSE, " Output stream #%d:%d (%s): ",
719 if (ost->enc) {
720 av_log(of, AV_LOG_VERBOSE, "%"PRIu64" frames encoded",
721 ost->enc->frames_encoded);
723 av_log(of, AV_LOG_VERBOSE, " (%"PRIu64" samples)", ost->enc->samples_encoded);
724 av_log(of, AV_LOG_VERBOSE, "; ");
725 }
726
727 av_log(of, AV_LOG_VERBOSE, "%"PRIu64" packets muxed (%"PRIu64" bytes); ",
728 atomic_load(&ost->packets_written), s);
729
730 av_log(of, AV_LOG_VERBOSE, "\n");
731 }
732
733 av_log(of, AV_LOG_VERBOSE, " Total: %"PRIu64" packets (%"PRIu64" bytes) muxed\n",
734 total_packets, total_size);
735
736 if (total_size && file_size > 0 && file_size >= total_size) {
737 snprintf(overhead, sizeof(overhead), "%f%%",
738 100.0 * (file_size - total_size) / total_size);
739 }
740
742 "video:%1.0fKiB audio:%1.0fKiB subtitle:%1.0fKiB other streams:%1.0fKiB "
743 "global headers:%1.0fKiB muxing overhead: %s\n",
744 video_size / 1024.0,
745 audio_size / 1024.0,
746 subtitle_size / 1024.0,
747 other_size / 1024.0,
748 extra_size / 1024.0,
749 overhead);
750}
751
753{
754 Muxer *mux = mux_from_of(of);
755 AVFormatContext *fc = mux->fc;
756 int ret, mux_result = 0;
757
758 if (!mux->header_written) {
759 av_log(mux, AV_LOG_ERROR,
760 "Nothing was written into output file, because "
761 "at least one of its streams received no packets.\n");
762 return AVERROR(EINVAL);
763 }
764
765 ret = av_write_trailer(fc);
766 if (ret < 0) {
767 av_log(mux, AV_LOG_ERROR, "Error writing trailer: %s\n", av_err2str(ret));
768 mux_result = err_merge(mux_result, ret);
769 }
770
771 mux->last_filesize = filesize(fc->pb);
772
773 if (!(fc->oformat->flags & AVFMT_NOFILE)) {
774 ret = avio_closep(&fc->pb);
775 if (ret < 0) {
776 av_log(mux, AV_LOG_ERROR, "Error closing file: %s\n", av_err2str(ret));
777 mux_result = err_merge(mux_result, ret);
778 }
779 }
780
781 mux_final_stats(mux);
782
783 // check whether anything was actually written
784 ret = check_written(of);
785 mux_result = err_merge(mux_result, ret);
786
787 return mux_result;
788}
789
791{
792 for (int i = 0; i < es->nb_components; i++)
793 av_freep(&es->components[i].str);
794 av_freep(&es->components);
795
796 if (es->lock_initialized)
798 es->lock_initialized = 0;
799}
800
801static void ost_free(OutputStream **post)
802{
803 OutputStream *ost = *post;
804 MuxStream *ms;
805
806 if (!ost)
807 return;
808 ms = ms_from_ost(ost);
809
810 enc_free(&ost->enc);
811 fg_free(&ost->fg_simple);
812
813 if (ost->logfile) {
814 if (fclose(ost->logfile))
816 "Error closing logfile, loss of information possible: %s\n",
817 av_err2str(AVERROR(errno)));
818 ost->logfile = NULL;
819 }
820
822
823 av_bsf_free(&ms->bsf_ctx);
825
826 av_packet_free(&ms->pkt);
827
828 av_freep(&ost->kf.pts);
829 av_expr_free(ost->kf.pexpr);
830
831 av_freep(&ost->logfile_prefix);
832
833 av_freep(&ost->attachment_filename);
834
835 enc_stats_uninit(&ost->enc_stats_pre);
836 enc_stats_uninit(&ost->enc_stats_post);
838
839 av_freep(post);
840}
841
842static void fc_close(AVFormatContext **pfc)
843{
844 AVFormatContext *fc = *pfc;
845
846 if (!fc)
847 return;
848
849 if (!(fc->oformat->flags & AVFMT_NOFILE))
850 avio_closep(&fc->pb);
852
853 *pfc = NULL;
854}
855
857{
858 OutputFile *of = *pof;
859 Muxer *mux;
860
861 if (!of)
862 return;
863 mux = mux_from_of(of);
864
865 sq_free(&mux->sq_mux);
866
867 for (int i = 0; i < of->nb_streams; i++)
868 ost_free(&of->streams[i]);
869 av_freep(&of->streams);
870
872
873 av_dict_free(&mux->opts);
875
876 av_packet_free(&mux->sq_pkt);
877
878 fc_close(&mux->fc);
879
880 av_freep(pof);
881}
882
884{
885 Muxer *mux = mux_from_of(of);
886 return atomic_load(&mux->last_filesize);
887}
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:488
#define AVFMT_TS_NONSTRICT
Format does not require strictly increasing timestamps, but they must still be monotonic.
Definition avformat.h:507
#define AVFMT_NOTIMESTAMPS
Format does not need / have any timestamps.
Definition avformat.h:498
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:717
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:559
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 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
#define atomic_store(object, desired)
Definition stdatomic.h:85
#define atomic_load(object)
Definition stdatomic.h:93
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:544
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:545
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:550
static int64_t filesize(AVIOContext *pb)
Definition ffmpeg_mux.c:51
static int check_written(OutputFile *of)
Definition ffmpeg_mux.c:647
static void fc_close(AVFormatContext **pfc)
Definition ffmpeg_mux.c:842
static void thread_set_name(Muxer *mux)
Definition ffmpeg_mux.c:367
int muxer_thread(void *arg)
Definition ffmpeg_mux.c:402
static int bsf_init(MuxStream *ms)
Definition ffmpeg_mux.c:572
int64_t of_filesize(OutputFile *of)
Definition ffmpeg_mux.c:883
static void mux_log_debug_ts(OutputStream *ost, const AVPacket *pkt)
Definition ffmpeg_mux.c:64
int of_stream_init(OutputFile *of, OutputStream *ost, const AVCodecContext *enc_ctx)
Definition ffmpeg_mux.c:606
static Muxer * mux_from_of(OutputFile *of)
Definition ffmpeg_mux.c:46
static int of_streamcopy(OutputFile *of, OutputStream *ost, AVPacket *pkt)
Definition ffmpeg_mux.c:455
int print_sdp(const char *filename)
Definition ffmpeg_mux.c:502
static int mux_packet_filter(Muxer *mux, MuxThreadContext *mt, OutputStream *ost, AVPacket *pkt, int *stream_eof)
Definition ffmpeg_mux.c:283
static void mux_final_stats(Muxer *mux)
Definition ffmpeg_mux.c:686
void of_free(OutputFile **pof)
Definition ffmpeg_mux.c:856
static int mux_fixup_ts(Muxer *mux, MuxStream *ms, AVPacket *pkt)
Definition ffmpeg_mux.c:138
int of_write_trailer(OutputFile *of)
Definition ffmpeg_mux.c:752
static void enc_stats_uninit(EncStats *es)
Definition ffmpeg_mux.c:790
static int mux_thread_init(MuxThreadContext *mt)
Definition ffmpeg_mux.c:383
static void mux_thread_uninit(MuxThreadContext *mt)
Definition ffmpeg_mux.c:375
static void ost_free(OutputStream **post)
Definition ffmpeg_mux.c:801
int mux_check_init(void *arg)
Definition ffmpeg_mux.c:550
static int sync_queue_process(Muxer *mux, MuxStream *ms, AVPacket *pkt, int *stream_eof)
Definition ffmpeg_mux.c:245
static int write_packet(Muxer *mux, OutputStream *ost, AVPacket *pkt)
Definition ffmpeg_mux.c:204
static MuxStream * ms_from_ost(OutputStream *ost)
Definition ffmpeg_mux.h:123
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:330
static int64_t start_time
Definition ffplay.c:329
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
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:434
#define AV_PKT_FLAG_TRUSTED
The packet comes from a trusted source.
Definition packet.h:664
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition packet.h:650
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:538
void avformat_free_context(AVFormatContext *s)
Free an AVFormatContext and all its streams.
Definition avformat.c:150
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:467
int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt)
Write a packet to an output media file ensuring correct interleaving.
Definition mux.c:1223
int av_write_trailer(AVFormatContext *s)
Write the stream trailer to an output media file and free the file private data.
Definition mux.c:1238
int av_sdp_create(AVFormatContext *ac[], int n_files, char *buf, int size)
Generate an SDP for an RTP session.
Definition sdp.c:950
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:852
void av_dict_free(AVDictionary **pm)
Free all the memory allocated for an AVDictionary struct and all keys and values.
Definition dict.c:233
#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
cl_device_type type
const char * arg
Definition jacosubdec.c:65
int av_get_audio_frame_duration2(AVCodecParameters *par, int frame_bytes)
Definition utils.c:823
static int ff_thread_setname(const char *name)
Definition thread.h:216
const char * desc
Definition libsvtav1.c:83
#define FFMAX3(a, b, c)
Definition macros.h:48
#define FFMAX(a, b)
Definition macros.h:47
#define FFMIN3(a, b, c)
Definition macros.h:50
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 snprintf
Definition snprintf.h:34
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
enum AVMediaType codec_type
General type of the encoded data.
Definition codec_par.h:53
Format I/O context.
Definition avformat.h:1333
const struct AVOutputFormat * oformat
The output container format.
Definition avformat.h:1352
Bytestream IO Context.
Definition avio.h:160
int flags
can use flags: AVFMT_NOFILE, AVFMT_NEEDNUMBER, AVFMT_EXPERIMENTAL, AVFMT_GLOBALHEADER,...
Definition avformat.h:546
const char * name
Definition avformat.h:527
This structure stores compressed data.
Definition packet.h:580
int stream_index
Definition packet.h:605
int flags
A combination of AV_PKT_FLAG values.
Definition packet.h:609
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
Definition packet.h:596
void * opaque
for some private data of the user
Definition packet.h:628
AVRational time_base
Time base of the packet's timestamps.
Definition packet.h:647
Rational number (pair of numerator and denominator).
Definition rational.h:58
uint8_t * str
Definition ffmpeg.h:572
int nb_components
Definition ffmpeg.h:578
AVIOContext * io
Definition ffmpeg.h:580
EncStatsComponent * components
Definition ffmpeg.h:577
pthread_mutex_t lock
Definition ffmpeg.h:582
int lock_initialized
Definition ffmpeg.h:583
int64_t dts_est
Definition ffmpeg.h:707
int64_t wallclock[LATENCY_PROBE_NB]
Definition ffmpeg.h:721
OutputStream ost
Definition ffmpeg_mux.h:37
int copy_prior_start
Definition ffmpeg_mux.h:82
AVPacket * pkt
Definition ffmpeg_mux.h:51
int sq_idx_mux
Definition ffmpeg_mux.h:59
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:42
AVPacket * fix_sub_duration_pkt
Definition ffmpeg_mux.c:43
AVDictionary * opts
Definition ffmpeg_mux.h:107
AVDictionary * enc_opts_used
Definition ffmpeg_mux.h:110
OutputFile of
Definition ffmpeg_mux.h:93
atomic_int_least64_t last_filesize
Definition ffmpeg_mux.h:114
AVPacket * sq_pkt
Definition ffmpeg_mux.h:118
int header_written
Definition ffmpeg_mux.h:115
Scheduler * sch
Definition ffmpeg_mux.h:100
SyncQueue * sq_mux
Definition ffmpeg_mux.h:117
AVFormatContext * fc
Definition ffmpeg_mux.h:98
unsigned sch_idx
Definition ffmpeg_mux.h:101
int * sch_stream_idx
Definition ffmpeg_mux.h:104
int64_t limit_filesize
Definition ffmpeg_mux.h:113
int index
Definition ffmpeg.h:690
const char * url
Definition ffmpeg.h:692
OutputStream ** streams
Definition ffmpeg.h:694
int nb_streams
Definition ffmpeg.h:695
int64_t start_time
start time in microseconds == AV_TIME_BASE units
Definition ffmpeg.h:698
int64_t recording_time
desired length of the resulting file in microseconds == AV_TIME_BASE units
Definition ffmpeg.h:697
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
static AVStream * ost
static av_always_inline int diff(const struct color_info *a, const struct color_info *b, const int trans_thresh)
#define atomic_fetch_add(object, operand)
Definition stdatomic.h:137