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 <stdio.h>
20 #include <string.h>
21
22 #include "ffmpeg.h"
23
24 #include "libavutil/fifo.h"
25 #include "libavutil/intreadwrite.h"
26 #include "libavutil/log.h"
27 #include "libavutil/mem.h"
28 #include "libavutil/timestamp.h"
29
30 #include "libavcodec/packet.h"
31
32 #include "libavformat/avformat.h"
33 #include "libavformat/avio.h"
34
close_all_output_streams(OutputStream * ost,OSTFinished this_stream,OSTFinished others)35 static void close_all_output_streams(OutputStream *ost, OSTFinished this_stream, OSTFinished others)
36 {
37 int i;
38 for (i = 0; i < nb_output_streams; i++) {
39 OutputStream *ost2 = output_streams[i];
40 ost2->finished |= ost == ost2 ? this_stream : others;
41 }
42 }
43
of_write_packet(OutputFile * of,AVPacket * pkt,OutputStream * ost,int unqueue)44 void of_write_packet(OutputFile *of, AVPacket *pkt, OutputStream *ost,
45 int unqueue)
46 {
47 AVFormatContext *s = of->ctx;
48 AVStream *st = ost->st;
49 int ret;
50
51 /*
52 * Audio encoders may split the packets -- #frames in != #packets out.
53 * But there is no reordering, so we can limit the number of output packets
54 * by simply dropping them here.
55 * Counting encoded video frames needs to be done separately because of
56 * reordering, see do_video_out().
57 * Do not count the packet when unqueued because it has been counted when queued.
58 */
59 if (!(st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && ost->encoding_needed) && !unqueue) {
60 if (ost->frame_number >= ost->max_frames) {
61 av_packet_unref(pkt);
62 return;
63 }
64 ost->frame_number++;
65 }
66
67 if (!of->header_written) {
68 AVPacket *tmp_pkt;
69 /* the muxer is not initialized yet, buffer the packet */
70 if (!av_fifo_can_write(ost->muxing_queue)) {
71 size_t cur_size = av_fifo_can_read(ost->muxing_queue);
72 unsigned int are_we_over_size =
73 (ost->muxing_queue_data_size + pkt->size) > ost->muxing_queue_data_threshold;
74 size_t limit = are_we_over_size ? ost->max_muxing_queue_size : SIZE_MAX;
75 size_t new_size = FFMIN(2 * cur_size, limit);
76
77 if (new_size <= cur_size) {
78 av_log(NULL, AV_LOG_ERROR,
79 "Too many packets buffered for output stream %d:%d.\n",
80 ost->file_index, ost->st->index);
81 exit_program(1);
82 }
83 ret = av_fifo_grow2(ost->muxing_queue, new_size - cur_size);
84 if (ret < 0)
85 exit_program(1);
86 }
87 ret = av_packet_make_refcounted(pkt);
88 if (ret < 0)
89 exit_program(1);
90 tmp_pkt = av_packet_alloc();
91 if (!tmp_pkt)
92 exit_program(1);
93 av_packet_move_ref(tmp_pkt, pkt);
94 ost->muxing_queue_data_size += tmp_pkt->size;
95 av_fifo_write(ost->muxing_queue, &tmp_pkt, 1);
96 return;
97 }
98
99 if ((st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && ost->vsync_method == VSYNC_DROP) ||
100 (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && audio_sync_method < 0))
101 pkt->pts = pkt->dts = AV_NOPTS_VALUE;
102
103 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
104 if (ost->frame_rate.num && ost->is_cfr) {
105 if (pkt->duration > 0)
106 av_log(NULL, AV_LOG_WARNING, "Overriding packet duration by frame rate, this should not happen\n");
107 pkt->duration = av_rescale_q(1, av_inv_q(ost->frame_rate),
108 ost->mux_timebase);
109 }
110 }
111
112 av_packet_rescale_ts(pkt, ost->mux_timebase, ost->st->time_base);
113
114 if (!(s->oformat->flags & AVFMT_NOTIMESTAMPS)) {
115 if (pkt->dts != AV_NOPTS_VALUE &&
116 pkt->pts != AV_NOPTS_VALUE &&
117 pkt->dts > pkt->pts) {
118 av_log(s, AV_LOG_WARNING, "Invalid DTS: %"PRId64" PTS: %"PRId64" in output stream %d:%d, replacing by guess\n",
119 pkt->dts, pkt->pts,
120 ost->file_index, ost->st->index);
121 pkt->pts =
122 pkt->dts = pkt->pts + pkt->dts + ost->last_mux_dts + 1
123 - FFMIN3(pkt->pts, pkt->dts, ost->last_mux_dts + 1)
124 - FFMAX3(pkt->pts, pkt->dts, ost->last_mux_dts + 1);
125 }
126 if ((st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO || st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO || st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) &&
127 pkt->dts != AV_NOPTS_VALUE &&
128 ost->last_mux_dts != AV_NOPTS_VALUE) {
129 int64_t max = ost->last_mux_dts + !(s->oformat->flags & AVFMT_TS_NONSTRICT);
130 if (pkt->dts < max) {
131 int loglevel = max - pkt->dts > 2 || st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ? AV_LOG_WARNING : AV_LOG_DEBUG;
132 if (exit_on_error)
133 loglevel = AV_LOG_ERROR;
134 av_log(s, loglevel, "Non-monotonous DTS in output stream "
135 "%d:%d; previous: %"PRId64", current: %"PRId64"; ",
136 ost->file_index, ost->st->index, ost->last_mux_dts, pkt->dts);
137 if (exit_on_error) {
138 av_log(NULL, AV_LOG_FATAL, "aborting.\n");
139 exit_program(1);
140 }
141 av_log(s, loglevel, "changing to %"PRId64". This may result "
142 "in incorrect timestamps in the output file.\n",
143 max);
144 if (pkt->pts >= pkt->dts)
145 pkt->pts = FFMAX(pkt->pts, max);
146 pkt->dts = max;
147 }
148 }
149 }
150 ost->last_mux_dts = pkt->dts;
151
152 ost->data_size += pkt->size;
153 ost->packets_written++;
154
155 pkt->stream_index = ost->index;
156
157 if (debug_ts) {
158 av_log(NULL, AV_LOG_INFO, "muxer <- type:%s "
159 "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s duration:%s duration_time:%s size:%d\n",
160 av_get_media_type_string(ost->enc_ctx->codec_type),
161 av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &ost->st->time_base),
162 av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &ost->st->time_base),
163 av_ts2str(pkt->duration), av_ts2timestr(pkt->duration, &ost->st->time_base),
164 pkt->size
165 );
166 }
167
168 ret = av_interleaved_write_frame(s, pkt);
169 if (ret < 0) {
170 print_error("av_interleaved_write_frame()", ret);
171 main_return_code = 1;
172 close_all_output_streams(ost, MUXER_FINISHED | ENCODER_FINISHED, ENCODER_FINISHED);
173 }
174 }
175
print_sdp(void)176 static int print_sdp(void)
177 {
178 char sdp[16384];
179 int i;
180 int j, ret;
181 AVIOContext *sdp_pb;
182 AVFormatContext **avc;
183
184 for (i = 0; i < nb_output_files; i++) {
185 if (!output_files[i]->header_written)
186 return 0;
187 }
188
189 avc = av_malloc_array(nb_output_files, sizeof(*avc));
190 if (!avc)
191 exit_program(1);
192 for (i = 0, j = 0; i < nb_output_files; i++) {
193 if (!strcmp(output_files[i]->ctx->oformat->name, "rtp")) {
194 avc[j] = output_files[i]->ctx;
195 j++;
196 }
197 }
198
199 if (!j) {
200 av_log(NULL, AV_LOG_ERROR, "No output streams in the SDP.\n");
201 ret = AVERROR(EINVAL);
202 goto fail;
203 }
204
205 ret = av_sdp_create(avc, j, sdp, sizeof(sdp));
206 if (ret < 0)
207 goto fail;
208
209 if (!sdp_filename) {
210 printf("SDP:\n%s\n", sdp);
211 fflush(stdout);
212 } else {
213 ret = avio_open2(&sdp_pb, sdp_filename, AVIO_FLAG_WRITE, &int_cb, NULL);
214 if (ret < 0) {
215 av_log(NULL, AV_LOG_ERROR, "Failed to open sdp file '%s'\n", sdp_filename);
216 goto fail;
217 }
218
219 avio_print(sdp_pb, sdp);
220 avio_closep(&sdp_pb);
221 av_freep(&sdp_filename);
222 }
223
224 fail:
225 av_freep(&avc);
226 return ret;
227 }
228
229 /* open the muxer when all the streams are initialized */
of_check_init(OutputFile * of)230 int of_check_init(OutputFile *of)
231 {
232 int ret, i;
233
234 for (i = 0; i < of->ctx->nb_streams; i++) {
235 OutputStream *ost = output_streams[of->ost_index + i];
236 if (!ost->initialized)
237 return 0;
238 }
239
240 ret = avformat_write_header(of->ctx, &of->opts);
241 if (ret < 0) {
242 av_log(NULL, AV_LOG_ERROR,
243 "Could not write header for output file #%d "
244 "(incorrect codec parameters ?): %s\n",
245 of->index, av_err2str(ret));
246 return ret;
247 }
248 //assert_avoptions(of->opts);
249 of->header_written = 1;
250
251 av_dump_format(of->ctx, of->index, of->ctx->url, 1);
252 nb_output_dumped++;
253
254 if (sdp_filename || want_sdp) {
255 ret = print_sdp();
256 if (ret < 0) {
257 av_log(NULL, AV_LOG_ERROR, "Error writing the SDP.\n");
258 return ret;
259 }
260 }
261
262 /* flush the muxing queues */
263 for (i = 0; i < of->ctx->nb_streams; i++) {
264 OutputStream *ost = output_streams[of->ost_index + i];
265 AVPacket *pkt;
266
267 /* try to improve muxing time_base (only possible if nothing has been written yet) */
268 if (!av_fifo_can_read(ost->muxing_queue))
269 ost->mux_timebase = ost->st->time_base;
270
271 while (av_fifo_read(ost->muxing_queue, &pkt, 1) >= 0) {
272 ost->muxing_queue_data_size -= pkt->size;
273 of_write_packet(of, pkt, ost, 1);
274 av_packet_free(&pkt);
275 }
276 }
277
278 return 0;
279 }
280
of_write_trailer(OutputFile * of)281 int of_write_trailer(OutputFile *of)
282 {
283 int ret;
284
285 if (!of->header_written) {
286 av_log(NULL, AV_LOG_ERROR,
287 "Nothing was written into output file %d (%s), because "
288 "at least one of its streams received no packets.\n",
289 of->index, of->ctx->url);
290 return AVERROR(EINVAL);
291 }
292
293 ret = av_write_trailer(of->ctx);
294 if (ret < 0) {
295 av_log(NULL, AV_LOG_ERROR, "Error writing trailer of %s: %s\n", of->ctx->url, av_err2str(ret));
296 return ret;
297 }
298
299 return 0;
300 }
301
of_close(OutputFile ** pof)302 void of_close(OutputFile **pof)
303 {
304 OutputFile *of = *pof;
305 AVFormatContext *s;
306
307 if (!of)
308 return;
309
310 s = of->ctx;
311 if (s && s->oformat && !(s->oformat->flags & AVFMT_NOFILE))
312 avio_closep(&s->pb);
313 avformat_free_context(s);
314 av_dict_free(&of->opts);
315
316 av_freep(pof);
317 }
318