2 * muxing functions for use within Libav
3 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
5 * This file is part of Libav.
7 * Libav 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.
12 * Libav 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.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with Libav; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
25 #include "avio_internal.h"
27 #include "libavcodec/internal.h"
28 #include "libavcodec/bytestream.h"
29 #include "libavutil/opt.h"
30 #include "libavutil/dict.h"
31 #include "libavutil/pixdesc.h"
34 #include "libavutil/avassert.h"
35 #include "libavutil/avstring.h"
36 #include "libavutil/mathematics.h"
37 #include "libavutil/parseutils.h"
38 #include "libavutil/time.h"
40 #include "audiointerleave.h"
52 * muxing functions for use within Libav
55 /* fraction handling */
58 * f = val + (num / den) + 0.5.
60 * 'num' is normalized so that it is such as 0 <= num < den.
62 * @param f fractional number
63 * @param val integer value
64 * @param num must be >= 0
65 * @param den must be >= 1
67 static void frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den)
80 * Fractional addition to f: f = f + (incr / f->den).
82 * @param f fractional number
83 * @param incr increment, can be positive or negative
85 static void frac_add(AVFrac *f, int64_t incr)
98 } else if (num >= den) {
105 static int validate_codec_tag(AVFormatContext *s, AVStream *st)
107 const AVCodecTag *avctag;
109 enum AVCodecID id = AV_CODEC_ID_NONE;
110 unsigned int tag = 0;
113 * Check that tag + id is in the table
114 * If neither is in the table -> OK
115 * If tag is in the table with another id -> FAIL
116 * If id is in the table with another tag -> FAIL unless strict < normal
118 for (n = 0; s->oformat->codec_tag[n]; n++) {
119 avctag = s->oformat->codec_tag[n];
120 while (avctag->id != AV_CODEC_ID_NONE) {
121 if (avpriv_toupper4(avctag->tag) == avpriv_toupper4(st->codec->codec_tag)) {
123 if (id == st->codec->codec_id)
126 if (avctag->id == st->codec->codec_id)
131 if (id != AV_CODEC_ID_NONE)
133 if (tag && (st->codec->strict_std_compliance >= FF_COMPLIANCE_NORMAL))
138 int avformat_write_header(AVFormatContext *s, AVDictionary **options)
142 AVDictionary *tmp = NULL;
143 AVCodecContext *codec = NULL;
144 AVOutputFormat *of = s->oformat;
147 av_dict_copy(&tmp, *options, 0);
149 if ((ret = av_opt_set_dict(s, &tmp)) < 0)
152 // some sanity checks
153 if (s->nb_streams == 0 && !(of->flags & AVFMT_NOSTREAMS)) {
154 av_log(s, AV_LOG_ERROR, "no streams\n");
155 ret = AVERROR(EINVAL);
159 for (i = 0; i < s->nb_streams; i++) {
163 switch (codec->codec_type) {
164 case AVMEDIA_TYPE_AUDIO:
165 if (codec->sample_rate <= 0) {
166 av_log(s, AV_LOG_ERROR, "sample rate not set\n");
167 ret = AVERROR(EINVAL);
170 if (!codec->block_align)
171 codec->block_align = codec->channels *
172 av_get_bits_per_sample(codec->codec_id) >> 3;
174 case AVMEDIA_TYPE_VIDEO:
175 if (codec->time_base.num <= 0 ||
176 codec->time_base.den <= 0) { //FIXME audio too?
177 av_log(s, AV_LOG_ERROR, "time base not set\n");
178 ret = AVERROR(EINVAL);
182 if ((codec->width <= 0 || codec->height <= 0) &&
183 !(of->flags & AVFMT_NODIMENSIONS)) {
184 av_log(s, AV_LOG_ERROR, "dimensions not set\n");
185 ret = AVERROR(EINVAL);
189 if (av_cmp_q(st->sample_aspect_ratio,
190 codec->sample_aspect_ratio)) {
191 av_log(s, AV_LOG_ERROR, "Aspect ratio mismatch between muxer "
192 "(%d/%d) and encoder layer (%d/%d)\n",
193 st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
194 codec->sample_aspect_ratio.num,
195 codec->sample_aspect_ratio.den);
196 ret = AVERROR(EINVAL);
203 if (codec->codec_tag &&
204 codec->codec_id == AV_CODEC_ID_RAWVIDEO &&
205 !av_codec_get_tag(of->codec_tag, codec->codec_id) &&
206 !validate_codec_tag(s, st)) {
207 // the current rawvideo encoding system ends up setting
208 // the wrong codec_tag for avi, we override it here
209 codec->codec_tag = 0;
211 if (codec->codec_tag) {
212 if (!validate_codec_tag(s, st)) {
214 av_get_codec_tag_string(tagbuf, sizeof(tagbuf), codec->codec_tag);
215 av_log(s, AV_LOG_ERROR,
216 "Tag %s/0x%08x incompatible with output codec id '%d'\n",
217 tagbuf, codec->codec_tag, codec->codec_id);
218 ret = AVERROR_INVALIDDATA;
222 codec->codec_tag = av_codec_get_tag(of->codec_tag, codec->codec_id);
225 if (of->flags & AVFMT_GLOBALHEADER &&
226 !(codec->flags & CODEC_FLAG_GLOBAL_HEADER))
227 av_log(s, AV_LOG_WARNING,
228 "Codec for stream %d does not use global headers "
229 "but container format requires global headers\n", i);
232 if (!s->priv_data && of->priv_data_size > 0) {
233 s->priv_data = av_mallocz(of->priv_data_size);
235 ret = AVERROR(ENOMEM);
238 if (of->priv_class) {
239 *(const AVClass **)s->priv_data = of->priv_class;
240 av_opt_set_defaults(s->priv_data);
241 if ((ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)
246 /* set muxer identification string */
247 if (s->nb_streams && !(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)) {
248 av_dict_set(&s->metadata, "encoder", LIBAVFORMAT_IDENT, 0);
251 if (s->oformat->write_header) {
252 ret = s->oformat->write_header(s);
257 /* init PTS generation */
258 for (i = 0; i < s->nb_streams; i++) {
259 int64_t den = AV_NOPTS_VALUE;
262 switch (st->codec->codec_type) {
263 case AVMEDIA_TYPE_AUDIO:
264 den = (int64_t)st->time_base.num * st->codec->sample_rate;
266 case AVMEDIA_TYPE_VIDEO:
267 den = (int64_t)st->time_base.num * st->codec->time_base.den;
272 if (den != AV_NOPTS_VALUE) {
274 ret = AVERROR_INVALIDDATA;
277 frac_init(&st->pts, 0, 0, den);
282 av_dict_free(options);
291 //FIXME merge with compute_pkt_fields
292 static int compute_pkt_fields2(AVFormatContext *s, AVStream *st, AVPacket *pkt)
294 int delay = FFMAX(st->codec->has_b_frames, !!st->codec->max_b_frames);
295 int num, den, frame_size, i;
297 av_dlog(s, "compute_pkt_fields2: pts:%" PRId64 " dts:%" PRId64 " cur_dts:%" PRId64 " b:%d size:%d st:%d\n",
298 pkt->pts, pkt->dts, st->cur_dts, delay, pkt->size, pkt->stream_index);
300 /* if(pkt->pts == AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE)
301 * return AVERROR(EINVAL);*/
304 if (pkt->duration == 0) {
305 ff_compute_frame_duration(&num, &den, st, NULL, pkt);
307 pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den * st->codec->ticks_per_frame, den * (int64_t)st->time_base.num);
311 if (pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && delay == 0)
314 //XXX/FIXME this is a temporary hack until all encoders output pts
315 if ((pkt->pts == 0 || pkt->pts == AV_NOPTS_VALUE) && pkt->dts == AV_NOPTS_VALUE && !delay) {
317 // pkt->pts= st->cur_dts;
318 pkt->pts = st->pts.val;
321 //calculate dts from pts
322 if (pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY) {
323 st->pts_buffer[0] = pkt->pts;
324 for (i = 1; i < delay + 1 && st->pts_buffer[i] == AV_NOPTS_VALUE; i++)
325 st->pts_buffer[i] = pkt->pts + (i - delay - 1) * pkt->duration;
326 for (i = 0; i<delay && st->pts_buffer[i] > st->pts_buffer[i + 1]; i++)
327 FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i + 1]);
329 pkt->dts = st->pts_buffer[0];
332 if (st->cur_dts && st->cur_dts != AV_NOPTS_VALUE &&
333 ((!(s->oformat->flags & AVFMT_TS_NONSTRICT) &&
334 st->cur_dts >= pkt->dts) || st->cur_dts > pkt->dts)) {
335 av_log(s, AV_LOG_ERROR,
336 "Application provided invalid, non monotonically increasing dts to muxer in stream %d: %" PRId64 " >= %" PRId64 "\n",
337 st->index, st->cur_dts, pkt->dts);
338 return AVERROR(EINVAL);
340 if (pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts) {
341 av_log(s, AV_LOG_ERROR, "pts < dts in stream %d\n", st->index);
342 return AVERROR(EINVAL);
345 av_dlog(s, "av_write_frame: pts2:%"PRId64" dts2:%"PRId64"\n",
347 st->cur_dts = pkt->dts;
348 st->pts.val = pkt->dts;
351 switch (st->codec->codec_type) {
352 case AVMEDIA_TYPE_AUDIO:
353 frame_size = ff_get_audio_frame_size(st->codec, pkt->size, 1);
355 /* HACK/FIXME, we skip the initial 0 size packets as they are most
356 * likely equal to the encoder delay, but it would be better if we
357 * had the real timestamps from the encoder */
358 if (frame_size >= 0 && (pkt->size || st->pts.num != st->pts.den >> 1 || st->pts.val)) {
359 frac_add(&st->pts, (int64_t)st->time_base.den * frame_size);
362 case AVMEDIA_TYPE_VIDEO:
363 frac_add(&st->pts, (int64_t)st->time_base.den * st->codec->time_base.num);
371 int av_write_frame(AVFormatContext *s, AVPacket *pkt)
376 if (s->oformat->flags & AVFMT_ALLOW_FLUSH)
377 return s->oformat->write_packet(s, pkt);
381 ret = compute_pkt_fields2(s, s->streams[pkt->stream_index], pkt);
383 if (ret < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
386 ret = s->oformat->write_packet(s, pkt);
389 s->streams[pkt->stream_index]->nb_frames++;
393 void ff_interleave_add_packet(AVFormatContext *s, AVPacket *pkt,
394 int (*compare)(AVFormatContext *, AVPacket *, AVPacket *))
396 AVPacketList **next_point, *this_pktl;
398 this_pktl = av_mallocz(sizeof(AVPacketList));
399 this_pktl->pkt = *pkt;
400 pkt->destruct = NULL; // do not free original but only the copy
401 av_dup_packet(&this_pktl->pkt); // duplicate the packet if it uses non-alloced memory
403 if (s->streams[pkt->stream_index]->last_in_packet_buffer) {
404 next_point = &(s->streams[pkt->stream_index]->last_in_packet_buffer->next);
406 next_point = &s->packet_buffer;
409 if (compare(s, &s->packet_buffer_end->pkt, pkt)) {
410 while (!compare(s, &(*next_point)->pkt, pkt))
411 next_point = &(*next_point)->next;
414 next_point = &(s->packet_buffer_end->next);
417 assert(!*next_point);
419 s->packet_buffer_end = this_pktl;
422 this_pktl->next = *next_point;
424 s->streams[pkt->stream_index]->last_in_packet_buffer =
425 *next_point = this_pktl;
428 static int ff_interleave_compare_dts(AVFormatContext *s, AVPacket *next, AVPacket *pkt)
430 AVStream *st = s->streams[pkt->stream_index];
431 AVStream *st2 = s->streams[next->stream_index];
432 int comp = av_compare_ts(next->dts, st2->time_base, pkt->dts,
436 return pkt->stream_index < next->stream_index;
440 int ff_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out,
441 AVPacket *pkt, int flush)
444 int stream_count = 0;
448 ff_interleave_add_packet(s, pkt, ff_interleave_compare_dts);
451 for (i = 0; i < s->nb_streams; i++)
452 stream_count += !!s->streams[i]->last_in_packet_buffer;
454 if (stream_count && (s->nb_streams == stream_count || flush)) {
455 pktl = s->packet_buffer;
458 s->packet_buffer = pktl->next;
459 if (!s->packet_buffer)
460 s->packet_buffer_end = NULL;
462 if (s->streams[out->stream_index]->last_in_packet_buffer == pktl)
463 s->streams[out->stream_index]->last_in_packet_buffer = NULL;
472 #if FF_API_INTERLEAVE_PACKET
473 int av_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out,
474 AVPacket *pkt, int flush)
476 return ff_interleave_packet_per_dts(s, out, pkt, flush);
482 * Interleave an AVPacket correctly so it can be muxed.
483 * @param out the interleaved packet will be output here
484 * @param in the input packet
485 * @param flush 1 if no further packets are available as input and all
486 * remaining packets should be output
487 * @return 1 if a packet was output, 0 if no packet could be output,
488 * < 0 if an error occurred
490 static int interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *in, int flush)
492 if (s->oformat->interleave_packet) {
493 int ret = s->oformat->interleave_packet(s, out, in, flush);
498 return ff_interleave_packet_per_dts(s, out, in, flush);
501 int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt)
506 AVStream *st = s->streams[pkt->stream_index];
508 //FIXME/XXX/HACK drop zero sized packets
509 if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO && pkt->size == 0)
512 av_dlog(s, "av_interleaved_write_frame size:%d dts:%" PRId64 " pts:%" PRId64 "\n",
513 pkt->size, pkt->dts, pkt->pts);
514 if ((ret = compute_pkt_fields2(s, st, pkt)) < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
517 if (pkt->dts == AV_NOPTS_VALUE && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
518 return AVERROR(EINVAL);
520 av_dlog(s, "av_interleaved_write_frame FLUSH\n");
526 int ret = interleave_packet(s, &opkt, pkt, flush);
527 if (ret <= 0) //FIXME cleanup needed for ret<0 ?
530 ret = s->oformat->write_packet(s, &opkt);
532 s->streams[opkt.stream_index]->nb_frames++;
534 av_free_packet(&opkt);
542 int av_write_trailer(AVFormatContext *s)
548 ret = interleave_packet(s, &pkt, NULL, 1);
549 if (ret < 0) //FIXME cleanup needed for ret<0 ?
554 ret = s->oformat->write_packet(s, &pkt);
556 s->streams[pkt.stream_index]->nb_frames++;
558 av_free_packet(&pkt);
564 if (s->oformat->write_trailer)
565 ret = s->oformat->write_trailer(s);
567 if (!(s->oformat->flags & AVFMT_NOFILE))
571 for (i = 0; i < s->nb_streams; i++) {
572 av_freep(&s->streams[i]->priv_data);
573 av_freep(&s->streams[i]->index_entries);
575 if (s->oformat->priv_class)
576 av_opt_free(s->priv_data);
577 av_freep(&s->priv_data);