]> git.sesse.net Git - ffmpeg/blob - libavformat/mux.c
Voxware MetaSound decoder
[ffmpeg] / libavformat / mux.c
1 /*
2  * muxing functions for use within Libav
3  * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
4  *
5  * This file is part of Libav.
6  *
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.
11  *
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.
16  *
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
20  */
21
22 #include "avformat.h"
23 #include "avio_internal.h"
24 #include "internal.h"
25 #include "libavcodec/internal.h"
26 #include "libavcodec/bytestream.h"
27 #include "libavutil/opt.h"
28 #include "libavutil/dict.h"
29 #include "libavutil/pixdesc.h"
30 #include "metadata.h"
31 #include "id3v2.h"
32 #include "libavutil/avassert.h"
33 #include "libavutil/avstring.h"
34 #include "libavutil/internal.h"
35 #include "libavutil/mathematics.h"
36 #include "libavutil/parseutils.h"
37 #include "libavutil/time.h"
38 #include "riff.h"
39 #include "audiointerleave.h"
40 #include "url.h"
41 #include <stdarg.h>
42 #if CONFIG_NETWORK
43 #include "network.h"
44 #endif
45
46 #undef NDEBUG
47 #include <assert.h>
48
49 /**
50  * @file
51  * muxing functions for use within Libav
52  */
53
54 /* fraction handling */
55
56 /**
57  * f = val + (num / den) + 0.5.
58  *
59  * 'num' is normalized so that it is such as 0 <= num < den.
60  *
61  * @param f fractional number
62  * @param val integer value
63  * @param num must be >= 0
64  * @param den must be >= 1
65  */
66 static void frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den)
67 {
68     num += (den >> 1);
69     if (num >= den) {
70         val += num / den;
71         num  = num % den;
72     }
73     f->val = val;
74     f->num = num;
75     f->den = den;
76 }
77
78 /**
79  * Fractional addition to f: f = f + (incr / f->den).
80  *
81  * @param f fractional number
82  * @param incr increment, can be positive or negative
83  */
84 static void frac_add(AVFrac *f, int64_t incr)
85 {
86     int64_t num, den;
87
88     num = f->num + incr;
89     den = f->den;
90     if (num < 0) {
91         f->val += num / den;
92         num     = num % den;
93         if (num < 0) {
94             num += den;
95             f->val--;
96         }
97     } else if (num >= den) {
98         f->val += num / den;
99         num     = num % den;
100     }
101     f->num = num;
102 }
103
104 static int validate_codec_tag(AVFormatContext *s, AVStream *st)
105 {
106     const AVCodecTag *avctag;
107     int n;
108     enum AVCodecID id = AV_CODEC_ID_NONE;
109     unsigned int tag  = 0;
110
111     /**
112      * Check that tag + id is in the table
113      * If neither is in the table -> OK
114      * If tag is in the table with another id -> FAIL
115      * If id is in the table with another tag -> FAIL unless strict < normal
116      */
117     for (n = 0; s->oformat->codec_tag[n]; n++) {
118         avctag = s->oformat->codec_tag[n];
119         while (avctag->id != AV_CODEC_ID_NONE) {
120             if (avpriv_toupper4(avctag->tag) == avpriv_toupper4(st->codec->codec_tag)) {
121                 id = avctag->id;
122                 if (id == st->codec->codec_id)
123                     return 1;
124             }
125             if (avctag->id == st->codec->codec_id)
126                 tag = avctag->tag;
127             avctag++;
128         }
129     }
130     if (id != AV_CODEC_ID_NONE)
131         return 0;
132     if (tag && (st->codec->strict_std_compliance >= FF_COMPLIANCE_NORMAL))
133         return 0;
134     return 1;
135 }
136
137
138 static int init_muxer(AVFormatContext *s, AVDictionary **options)
139 {
140     int ret = 0, i;
141     AVStream *st;
142     AVDictionary *tmp = NULL;
143     AVCodecContext *codec = NULL;
144     AVOutputFormat *of = s->oformat;
145
146     if (options)
147         av_dict_copy(&tmp, *options, 0);
148
149     if ((ret = av_opt_set_dict(s, &tmp)) < 0)
150         goto fail;
151
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);
156         goto fail;
157     }
158
159     for (i = 0; i < s->nb_streams; i++) {
160         st    = s->streams[i];
161         codec = st->codec;
162
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);
168                 goto fail;
169             }
170             if (!codec->block_align)
171                 codec->block_align = codec->channels *
172                                      av_get_bits_per_sample(codec->codec_id) >> 3;
173             break;
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);
179                 goto fail;
180             }
181
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);
186                 goto fail;
187             }
188
189             if (av_cmp_q(st->sample_aspect_ratio,
190                          codec->sample_aspect_ratio)) {
191                 if (st->sample_aspect_ratio.num != 0 &&
192                     st->sample_aspect_ratio.den != 0 &&
193                     codec->sample_aspect_ratio.den != 0 &&
194                     codec->sample_aspect_ratio.den != 0) {
195                     av_log(s, AV_LOG_ERROR, "Aspect ratio mismatch between muxer "
196                             "(%d/%d) and encoder layer (%d/%d)\n",
197                             st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
198                             codec->sample_aspect_ratio.num,
199                             codec->sample_aspect_ratio.den);
200                     ret = AVERROR(EINVAL);
201                     goto fail;
202                 }
203             }
204             break;
205         }
206
207         if (of->codec_tag) {
208             if (codec->codec_tag &&
209                 codec->codec_id == AV_CODEC_ID_RAWVIDEO &&
210                 !av_codec_get_tag(of->codec_tag, codec->codec_id) &&
211                 !validate_codec_tag(s, st)) {
212                 // the current rawvideo encoding system ends up setting
213                 // the wrong codec_tag for avi, we override it here
214                 codec->codec_tag = 0;
215             }
216             if (codec->codec_tag) {
217                 if (!validate_codec_tag(s, st)) {
218                     char tagbuf[32];
219                     av_get_codec_tag_string(tagbuf, sizeof(tagbuf), codec->codec_tag);
220                     av_log(s, AV_LOG_ERROR,
221                            "Tag %s/0x%08x incompatible with output codec id '%d'\n",
222                            tagbuf, codec->codec_tag, codec->codec_id);
223                     ret = AVERROR_INVALIDDATA;
224                     goto fail;
225                 }
226             } else
227                 codec->codec_tag = av_codec_get_tag(of->codec_tag, codec->codec_id);
228         }
229
230         if (of->flags & AVFMT_GLOBALHEADER &&
231             !(codec->flags & CODEC_FLAG_GLOBAL_HEADER))
232             av_log(s, AV_LOG_WARNING,
233                    "Codec for stream %d does not use global headers "
234                    "but container format requires global headers\n", i);
235     }
236
237     if (!s->priv_data && of->priv_data_size > 0) {
238         s->priv_data = av_mallocz(of->priv_data_size);
239         if (!s->priv_data) {
240             ret = AVERROR(ENOMEM);
241             goto fail;
242         }
243         if (of->priv_class) {
244             *(const AVClass **)s->priv_data = of->priv_class;
245             av_opt_set_defaults(s->priv_data);
246             if ((ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)
247                 goto fail;
248         }
249     }
250
251     /* set muxer identification string */
252     if (s->nb_streams && !(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)) {
253         av_dict_set(&s->metadata, "encoder", LIBAVFORMAT_IDENT, 0);
254     }
255
256     if (options) {
257          av_dict_free(options);
258          *options = tmp;
259     }
260
261     return 0;
262
263 fail:
264     av_dict_free(&tmp);
265     return ret;
266 }
267
268 static int init_pts(AVFormatContext *s)
269 {
270     int i;
271     AVStream *st;
272
273     /* init PTS generation */
274     for (i = 0; i < s->nb_streams; i++) {
275         int64_t den = AV_NOPTS_VALUE;
276         st = s->streams[i];
277
278         switch (st->codec->codec_type) {
279         case AVMEDIA_TYPE_AUDIO:
280             den = (int64_t)st->time_base.num * st->codec->sample_rate;
281             break;
282         case AVMEDIA_TYPE_VIDEO:
283             den = (int64_t)st->time_base.num * st->codec->time_base.den;
284             break;
285         default:
286             break;
287         }
288         if (den != AV_NOPTS_VALUE) {
289             if (den <= 0)
290                 return AVERROR_INVALIDDATA;
291
292             frac_init(&st->pts, 0, 0, den);
293         }
294     }
295
296     return 0;
297 }
298
299 int avformat_write_header(AVFormatContext *s, AVDictionary **options)
300 {
301     int ret = 0;
302
303     if (ret = init_muxer(s, options))
304         return ret;
305
306     if (s->oformat->write_header) {
307         ret = s->oformat->write_header(s);
308         if (ret < 0)
309             return ret;
310     }
311
312     if ((ret = init_pts(s)) < 0)
313         return ret;
314
315     return 0;
316 }
317
318 //FIXME merge with compute_pkt_fields
319 static int compute_pkt_fields2(AVFormatContext *s, AVStream *st, AVPacket *pkt)
320 {
321     int delay = FFMAX(st->codec->has_b_frames, !!st->codec->max_b_frames);
322     int num, den, frame_size, i;
323
324     av_dlog(s, "compute_pkt_fields2: pts:%" PRId64 " dts:%" PRId64 " cur_dts:%" PRId64 " b:%d size:%d st:%d\n",
325             pkt->pts, pkt->dts, st->cur_dts, delay, pkt->size, pkt->stream_index);
326
327 /*    if(pkt->pts == AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE)
328  *      return AVERROR(EINVAL);*/
329
330     /* duration field */
331     if (pkt->duration == 0) {
332         ff_compute_frame_duration(&num, &den, st, NULL, pkt);
333         if (den && num) {
334             pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den * st->codec->ticks_per_frame, den * (int64_t)st->time_base.num);
335         }
336     }
337
338     if (pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && delay == 0)
339         pkt->pts = pkt->dts;
340
341     //XXX/FIXME this is a temporary hack until all encoders output pts
342     if ((pkt->pts == 0 || pkt->pts == AV_NOPTS_VALUE) && pkt->dts == AV_NOPTS_VALUE && !delay) {
343         pkt->dts =
344 //        pkt->pts= st->cur_dts;
345             pkt->pts = st->pts.val;
346     }
347
348     //calculate dts from pts
349     if (pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY) {
350         st->pts_buffer[0] = pkt->pts;
351         for (i = 1; i < delay + 1 && st->pts_buffer[i] == AV_NOPTS_VALUE; i++)
352             st->pts_buffer[i] = pkt->pts + (i - delay - 1) * pkt->duration;
353         for (i = 0; i<delay && st->pts_buffer[i] > st->pts_buffer[i + 1]; i++)
354             FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i + 1]);
355
356         pkt->dts = st->pts_buffer[0];
357     }
358
359     if (st->cur_dts && st->cur_dts != AV_NOPTS_VALUE &&
360         ((!(s->oformat->flags & AVFMT_TS_NONSTRICT) &&
361           st->cur_dts >= pkt->dts) || st->cur_dts > pkt->dts)) {
362         av_log(s, AV_LOG_ERROR,
363                "Application provided invalid, non monotonically increasing dts to muxer in stream %d: %" PRId64 " >= %" PRId64 "\n",
364                st->index, st->cur_dts, pkt->dts);
365         return AVERROR(EINVAL);
366     }
367     if (pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts) {
368         av_log(s, AV_LOG_ERROR, "pts < dts in stream %d\n", st->index);
369         return AVERROR(EINVAL);
370     }
371
372     av_dlog(s, "av_write_frame: pts2:%"PRId64" dts2:%"PRId64"\n",
373             pkt->pts, pkt->dts);
374     st->cur_dts = pkt->dts;
375     st->pts.val = pkt->dts;
376
377     /* update pts */
378     switch (st->codec->codec_type) {
379     case AVMEDIA_TYPE_AUDIO:
380         frame_size = ff_get_audio_frame_size(st->codec, pkt->size, 1);
381
382         /* HACK/FIXME, we skip the initial 0 size packets as they are most
383          * likely equal to the encoder delay, but it would be better if we
384          * had the real timestamps from the encoder */
385         if (frame_size >= 0 && (pkt->size || st->pts.num != st->pts.den >> 1 || st->pts.val)) {
386             frac_add(&st->pts, (int64_t)st->time_base.den * frame_size);
387         }
388         break;
389     case AVMEDIA_TYPE_VIDEO:
390         frac_add(&st->pts, (int64_t)st->time_base.den * st->codec->time_base.num);
391         break;
392     default:
393         break;
394     }
395     return 0;
396 }
397
398 /*
399  * FIXME: this function should NEVER get undefined pts/dts beside when the
400  * AVFMT_NOTIMESTAMPS is set.
401  * Those additional safety checks should be dropped once the correct checks
402  * are set in the callers.
403  */
404
405 static int write_packet(AVFormatContext *s, AVPacket *pkt)
406 {
407     if (!(s->oformat->flags & (AVFMT_TS_NEGATIVE | AVFMT_NOTIMESTAMPS))) {
408         AVRational time_base = s->streams[pkt->stream_index]->time_base;
409         int64_t offset = 0;
410
411         if (!s->offset && pkt->dts != AV_NOPTS_VALUE && pkt->dts < 0) {
412             s->offset = -pkt->dts;
413             s->offset_timebase = time_base;
414         }
415         if (s->offset)
416             offset = av_rescale_q(s->offset, s->offset_timebase, time_base);
417
418         if (pkt->dts != AV_NOPTS_VALUE)
419             pkt->dts += offset;
420         if (pkt->pts != AV_NOPTS_VALUE)
421             pkt->pts += offset;
422     }
423     return s->oformat->write_packet(s, pkt);
424 }
425
426 int av_write_frame(AVFormatContext *s, AVPacket *pkt)
427 {
428     int ret;
429
430     if (!pkt) {
431         if (s->oformat->flags & AVFMT_ALLOW_FLUSH)
432             return s->oformat->write_packet(s, pkt);
433         return 1;
434     }
435
436     ret = compute_pkt_fields2(s, s->streams[pkt->stream_index], pkt);
437
438     if (ret < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
439         return ret;
440
441     ret = write_packet(s, pkt);
442
443     if (ret >= 0)
444         s->streams[pkt->stream_index]->nb_frames++;
445     return ret;
446 }
447
448 void ff_interleave_add_packet(AVFormatContext *s, AVPacket *pkt,
449                               int (*compare)(AVFormatContext *, AVPacket *, AVPacket *))
450 {
451     AVPacketList **next_point, *this_pktl;
452
453     this_pktl      = av_mallocz(sizeof(AVPacketList));
454     this_pktl->pkt = *pkt;
455 #if FF_API_DESTRUCT_PACKET
456 FF_DISABLE_DEPRECATION_WARNINGS
457     pkt->destruct  = NULL;           // do not free original but only the copy
458 FF_ENABLE_DEPRECATION_WARNINGS
459 #endif
460     pkt->buf       = NULL;
461     av_dup_packet(&this_pktl->pkt);  // duplicate the packet if it uses non-alloced memory
462
463     if (s->streams[pkt->stream_index]->last_in_packet_buffer) {
464         next_point = &(s->streams[pkt->stream_index]->last_in_packet_buffer->next);
465     } else
466         next_point = &s->packet_buffer;
467
468     if (*next_point) {
469         if (compare(s, &s->packet_buffer_end->pkt, pkt)) {
470             while (!compare(s, &(*next_point)->pkt, pkt))
471                 next_point = &(*next_point)->next;
472             goto next_non_null;
473         } else {
474             next_point = &(s->packet_buffer_end->next);
475         }
476     }
477     assert(!*next_point);
478
479     s->packet_buffer_end = this_pktl;
480 next_non_null:
481
482     this_pktl->next = *next_point;
483
484     s->streams[pkt->stream_index]->last_in_packet_buffer =
485         *next_point                                      = this_pktl;
486 }
487
488 static int interleave_compare_dts(AVFormatContext *s, AVPacket *next,
489                                   AVPacket *pkt)
490 {
491     AVStream *st  = s->streams[pkt->stream_index];
492     AVStream *st2 = s->streams[next->stream_index];
493     int comp      = av_compare_ts(next->dts, st2->time_base, pkt->dts,
494                                   st->time_base);
495
496     if (comp == 0)
497         return pkt->stream_index < next->stream_index;
498     return comp > 0;
499 }
500
501 int ff_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out,
502                                  AVPacket *pkt, int flush)
503 {
504     AVPacketList *pktl;
505     int stream_count = 0;
506     int i;
507
508     if (pkt) {
509         ff_interleave_add_packet(s, pkt, interleave_compare_dts);
510     }
511
512     for (i = 0; i < s->nb_streams; i++)
513         stream_count += !!s->streams[i]->last_in_packet_buffer;
514
515     if (stream_count && (s->nb_streams == stream_count || flush)) {
516         pktl = s->packet_buffer;
517         *out = pktl->pkt;
518
519         s->packet_buffer = pktl->next;
520         if (!s->packet_buffer)
521             s->packet_buffer_end = NULL;
522
523         if (s->streams[out->stream_index]->last_in_packet_buffer == pktl)
524             s->streams[out->stream_index]->last_in_packet_buffer = NULL;
525         av_freep(&pktl);
526         return 1;
527     } else {
528         av_init_packet(out);
529         return 0;
530     }
531 }
532
533 /**
534  * Interleave an AVPacket correctly so it can be muxed.
535  * @param out the interleaved packet will be output here
536  * @param in the input packet
537  * @param flush 1 if no further packets are available as input and all
538  *              remaining packets should be output
539  * @return 1 if a packet was output, 0 if no packet could be output,
540  *         < 0 if an error occurred
541  */
542 static int interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *in, int flush)
543 {
544     if (s->oformat->interleave_packet) {
545         int ret = s->oformat->interleave_packet(s, out, in, flush);
546         if (in)
547             av_free_packet(in);
548         return ret;
549     } else
550         return ff_interleave_packet_per_dts(s, out, in, flush);
551 }
552
553 int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt)
554 {
555     int ret, flush = 0;
556
557     if (pkt) {
558         AVStream *st = s->streams[pkt->stream_index];
559
560         //FIXME/XXX/HACK drop zero sized packets
561         if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO && pkt->size == 0)
562             return 0;
563
564         av_dlog(s, "av_interleaved_write_frame size:%d dts:%" PRId64 " pts:%" PRId64 "\n",
565                 pkt->size, pkt->dts, pkt->pts);
566         if ((ret = compute_pkt_fields2(s, st, pkt)) < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
567             return ret;
568
569         if (pkt->dts == AV_NOPTS_VALUE && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
570             return AVERROR(EINVAL);
571     } else {
572         av_dlog(s, "av_interleaved_write_frame FLUSH\n");
573         flush = 1;
574     }
575
576     for (;; ) {
577         AVPacket opkt;
578         int ret = interleave_packet(s, &opkt, pkt, flush);
579         if (ret <= 0) //FIXME cleanup needed for ret<0 ?
580             return ret;
581
582         ret = write_packet(s, &opkt);
583         if (ret >= 0)
584             s->streams[opkt.stream_index]->nb_frames++;
585
586         av_free_packet(&opkt);
587         pkt = NULL;
588
589         if (ret < 0)
590             return ret;
591     }
592 }
593
594 int av_write_trailer(AVFormatContext *s)
595 {
596     int ret, i;
597
598     for (;; ) {
599         AVPacket pkt;
600         ret = interleave_packet(s, &pkt, NULL, 1);
601         if (ret < 0) //FIXME cleanup needed for ret<0 ?
602             goto fail;
603         if (!ret)
604             break;
605
606         ret = write_packet(s, &pkt);
607         if (ret >= 0)
608             s->streams[pkt.stream_index]->nb_frames++;
609
610         av_free_packet(&pkt);
611
612         if (ret < 0)
613             goto fail;
614     }
615
616     if (s->oformat->write_trailer)
617         ret = s->oformat->write_trailer(s);
618
619     if (!(s->oformat->flags & AVFMT_NOFILE))
620         avio_flush(s->pb);
621
622 fail:
623     for (i = 0; i < s->nb_streams; i++) {
624         av_freep(&s->streams[i]->priv_data);
625         av_freep(&s->streams[i]->index_entries);
626     }
627     if (s->oformat->priv_class)
628         av_opt_free(s->priv_data);
629     av_freep(&s->priv_data);
630     return ret;
631 }
632
633 int ff_write_chained(AVFormatContext *dst, int dst_stream, AVPacket *pkt,
634                      AVFormatContext *src)
635 {
636     AVPacket local_pkt;
637
638     local_pkt = *pkt;
639     local_pkt.stream_index = dst_stream;
640     if (pkt->pts != AV_NOPTS_VALUE)
641         local_pkt.pts = av_rescale_q(pkt->pts,
642                                      src->streams[pkt->stream_index]->time_base,
643                                      dst->streams[dst_stream]->time_base);
644     if (pkt->dts != AV_NOPTS_VALUE)
645         local_pkt.dts = av_rescale_q(pkt->dts,
646                                      src->streams[pkt->stream_index]->time_base,
647                                      dst->streams[dst_stream]->time_base);
648     return av_write_frame(dst, &local_pkt);
649 }