lavf: deprecate now unused AVStream.pts
[platform/upstream/libav.git] / 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 static int validate_codec_tag(AVFormatContext *s, AVStream *st)
55 {
56     const AVCodecTag *avctag;
57     int n;
58     enum AVCodecID id = AV_CODEC_ID_NONE;
59     unsigned int tag  = 0;
60
61     /**
62      * Check that tag + id is in the table
63      * If neither is in the table -> OK
64      * If tag is in the table with another id -> FAIL
65      * If id is in the table with another tag -> FAIL unless strict < normal
66      */
67     for (n = 0; s->oformat->codec_tag[n]; n++) {
68         avctag = s->oformat->codec_tag[n];
69         while (avctag->id != AV_CODEC_ID_NONE) {
70             if (avpriv_toupper4(avctag->tag) == avpriv_toupper4(st->codec->codec_tag)) {
71                 id = avctag->id;
72                 if (id == st->codec->codec_id)
73                     return 1;
74             }
75             if (avctag->id == st->codec->codec_id)
76                 tag = avctag->tag;
77             avctag++;
78         }
79     }
80     if (id != AV_CODEC_ID_NONE)
81         return 0;
82     if (tag && (st->codec->strict_std_compliance >= FF_COMPLIANCE_NORMAL))
83         return 0;
84     return 1;
85 }
86
87
88 static int init_muxer(AVFormatContext *s, AVDictionary **options)
89 {
90     int ret = 0, i;
91     AVStream *st;
92     AVDictionary *tmp = NULL;
93     AVCodecContext *codec = NULL;
94     AVOutputFormat *of = s->oformat;
95
96     if (options)
97         av_dict_copy(&tmp, *options, 0);
98
99     if ((ret = av_opt_set_dict(s, &tmp)) < 0)
100         goto fail;
101
102 #if FF_API_LAVF_BITEXACT
103     if (s->nb_streams && s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)
104         s->flags |= AVFMT_FLAG_BITEXACT;
105 #endif
106
107     // some sanity checks
108     if (s->nb_streams == 0 && !(of->flags & AVFMT_NOSTREAMS)) {
109         av_log(s, AV_LOG_ERROR, "no streams\n");
110         ret = AVERROR(EINVAL);
111         goto fail;
112     }
113
114     for (i = 0; i < s->nb_streams; i++) {
115         st    = s->streams[i];
116         codec = st->codec;
117
118         switch (codec->codec_type) {
119         case AVMEDIA_TYPE_AUDIO:
120             if (codec->sample_rate <= 0) {
121                 av_log(s, AV_LOG_ERROR, "sample rate not set\n");
122                 ret = AVERROR(EINVAL);
123                 goto fail;
124             }
125             if (!codec->block_align)
126                 codec->block_align = codec->channels *
127                                      av_get_bits_per_sample(codec->codec_id) >> 3;
128             break;
129         case AVMEDIA_TYPE_VIDEO:
130             if (codec->time_base.num <= 0 ||
131                 codec->time_base.den <= 0) { //FIXME audio too?
132                 av_log(s, AV_LOG_ERROR, "time base not set\n");
133                 ret = AVERROR(EINVAL);
134                 goto fail;
135             }
136
137             if ((codec->width <= 0 || codec->height <= 0) &&
138                 !(of->flags & AVFMT_NODIMENSIONS)) {
139                 av_log(s, AV_LOG_ERROR, "dimensions not set\n");
140                 ret = AVERROR(EINVAL);
141                 goto fail;
142             }
143
144             if (av_cmp_q(st->sample_aspect_ratio,
145                          codec->sample_aspect_ratio)) {
146                 if (st->sample_aspect_ratio.num != 0 &&
147                     st->sample_aspect_ratio.den != 0 &&
148                     codec->sample_aspect_ratio.den != 0 &&
149                     codec->sample_aspect_ratio.den != 0) {
150                     av_log(s, AV_LOG_ERROR, "Aspect ratio mismatch between muxer "
151                             "(%d/%d) and encoder layer (%d/%d)\n",
152                             st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,
153                             codec->sample_aspect_ratio.num,
154                             codec->sample_aspect_ratio.den);
155                     ret = AVERROR(EINVAL);
156                     goto fail;
157                 }
158             }
159             break;
160         }
161
162         if (of->codec_tag) {
163             if (codec->codec_tag &&
164                 codec->codec_id == AV_CODEC_ID_RAWVIDEO &&
165                 !av_codec_get_tag(of->codec_tag, codec->codec_id) &&
166                 !validate_codec_tag(s, st)) {
167                 // the current rawvideo encoding system ends up setting
168                 // the wrong codec_tag for avi, we override it here
169                 codec->codec_tag = 0;
170             }
171             if (codec->codec_tag) {
172                 if (!validate_codec_tag(s, st)) {
173                     char tagbuf[32];
174                     av_get_codec_tag_string(tagbuf, sizeof(tagbuf), codec->codec_tag);
175                     av_log(s, AV_LOG_ERROR,
176                            "Tag %s/0x%08x incompatible with output codec id '%d'\n",
177                            tagbuf, codec->codec_tag, codec->codec_id);
178                     ret = AVERROR_INVALIDDATA;
179                     goto fail;
180                 }
181             } else
182                 codec->codec_tag = av_codec_get_tag(of->codec_tag, codec->codec_id);
183         }
184
185         if (of->flags & AVFMT_GLOBALHEADER &&
186             !(codec->flags & CODEC_FLAG_GLOBAL_HEADER))
187             av_log(s, AV_LOG_WARNING,
188                    "Codec for stream %d does not use global headers "
189                    "but container format requires global headers\n", i);
190
191         if (codec->codec_type != AVMEDIA_TYPE_ATTACHMENT)
192             s->internal->nb_interleaved_streams++;
193     }
194
195     if (!s->priv_data && of->priv_data_size > 0) {
196         s->priv_data = av_mallocz(of->priv_data_size);
197         if (!s->priv_data) {
198             ret = AVERROR(ENOMEM);
199             goto fail;
200         }
201         if (of->priv_class) {
202             *(const AVClass **)s->priv_data = of->priv_class;
203             av_opt_set_defaults(s->priv_data);
204             if ((ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)
205                 goto fail;
206         }
207     }
208
209     /* set muxer identification string */
210     if (!(s->flags & AVFMT_FLAG_BITEXACT)) {
211         av_dict_set(&s->metadata, "encoder", LIBAVFORMAT_IDENT, 0);
212     }
213
214     if (options) {
215          av_dict_free(options);
216          *options = tmp;
217     }
218
219     return 0;
220
221 fail:
222     av_dict_free(&tmp);
223     return ret;
224 }
225
226 int avformat_write_header(AVFormatContext *s, AVDictionary **options)
227 {
228     int ret = 0;
229
230     if (ret = init_muxer(s, options))
231         return ret;
232
233     if (s->oformat->write_header) {
234         ret = s->oformat->write_header(s);
235         if (ret < 0)
236             return ret;
237     }
238
239     return 0;
240 }
241
242 //FIXME merge with compute_pkt_fields
243 static int compute_pkt_fields2(AVFormatContext *s, AVStream *st, AVPacket *pkt)
244 {
245     int delay = FFMAX(st->codec->has_b_frames, !!st->codec->max_b_frames);
246     int num, den, i;
247
248     av_dlog(s, "compute_pkt_fields2: pts:%" PRId64 " dts:%" PRId64 " cur_dts:%" PRId64 " b:%d size:%d st:%d\n",
249             pkt->pts, pkt->dts, st->cur_dts, delay, pkt->size, pkt->stream_index);
250
251 /*    if(pkt->pts == AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE)
252  *      return AVERROR(EINVAL);*/
253
254     /* duration field */
255     if (pkt->duration == 0) {
256         ff_compute_frame_duration(&num, &den, st, NULL, pkt);
257         if (den && num) {
258             pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den * st->codec->ticks_per_frame, den * (int64_t)st->time_base.num);
259         }
260     }
261
262     if (pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && delay == 0)
263         pkt->pts = pkt->dts;
264
265     //calculate dts from pts
266     if (pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY) {
267         st->pts_buffer[0] = pkt->pts;
268         for (i = 1; i < delay + 1 && st->pts_buffer[i] == AV_NOPTS_VALUE; i++)
269             st->pts_buffer[i] = pkt->pts + (i - delay - 1) * pkt->duration;
270         for (i = 0; i<delay && st->pts_buffer[i] > st->pts_buffer[i + 1]; i++)
271             FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i + 1]);
272
273         pkt->dts = st->pts_buffer[0];
274     }
275
276     if (st->cur_dts && st->cur_dts != AV_NOPTS_VALUE &&
277         ((!(s->oformat->flags & AVFMT_TS_NONSTRICT) &&
278           st->cur_dts >= pkt->dts) || st->cur_dts > pkt->dts)) {
279         av_log(s, AV_LOG_ERROR,
280                "Application provided invalid, non monotonically increasing dts to muxer in stream %d: %" PRId64 " >= %" PRId64 "\n",
281                st->index, st->cur_dts, pkt->dts);
282         return AVERROR(EINVAL);
283     }
284     if (pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts) {
285         av_log(s, AV_LOG_ERROR, "pts < dts in stream %d\n", st->index);
286         return AVERROR(EINVAL);
287     }
288
289     av_dlog(s, "av_write_frame: pts2:%"PRId64" dts2:%"PRId64"\n",
290             pkt->pts, pkt->dts);
291     st->cur_dts = pkt->dts;
292
293     return 0;
294 }
295
296 /*
297  * FIXME: this function should NEVER get undefined pts/dts beside when the
298  * AVFMT_NOTIMESTAMPS is set.
299  * Those additional safety checks should be dropped once the correct checks
300  * are set in the callers.
301  */
302
303 static int write_packet(AVFormatContext *s, AVPacket *pkt)
304 {
305     int ret;
306     if (!(s->oformat->flags & (AVFMT_TS_NEGATIVE | AVFMT_NOTIMESTAMPS))) {
307         AVRational time_base = s->streams[pkt->stream_index]->time_base;
308         int64_t offset = 0;
309
310         if (!s->offset && pkt->dts != AV_NOPTS_VALUE && pkt->dts < 0) {
311             s->offset = -pkt->dts;
312             s->offset_timebase = time_base;
313         }
314         if (s->offset)
315             offset = av_rescale_q(s->offset, s->offset_timebase, time_base);
316
317         if (pkt->dts != AV_NOPTS_VALUE)
318             pkt->dts += offset;
319         if (pkt->pts != AV_NOPTS_VALUE)
320             pkt->pts += offset;
321     }
322     ret = s->oformat->write_packet(s, pkt);
323
324     if (s->pb && ret >= 0 && s->flags & AVFMT_FLAG_FLUSH_PACKETS)
325         avio_flush(s->pb);
326
327     return ret;
328 }
329
330 static int check_packet(AVFormatContext *s, AVPacket *pkt)
331 {
332     if (!pkt)
333         return 0;
334
335     if (pkt->stream_index < 0 || pkt->stream_index >= s->nb_streams) {
336         av_log(s, AV_LOG_ERROR, "Invalid packet stream index: %d\n",
337                pkt->stream_index);
338         return AVERROR(EINVAL);
339     }
340
341     if (s->streams[pkt->stream_index]->codec->codec_type == AVMEDIA_TYPE_ATTACHMENT) {
342         av_log(s, AV_LOG_ERROR, "Received a packet for an attachment stream.\n");
343         return AVERROR(EINVAL);
344     }
345
346     return 0;
347 }
348
349 int av_write_frame(AVFormatContext *s, AVPacket *pkt)
350 {
351     int ret;
352
353     ret = check_packet(s, pkt);
354     if (ret < 0)
355         return ret;
356
357     if (!pkt) {
358         if (s->oformat->flags & AVFMT_ALLOW_FLUSH)
359             return s->oformat->write_packet(s, pkt);
360         return 1;
361     }
362
363     ret = compute_pkt_fields2(s, s->streams[pkt->stream_index], pkt);
364
365     if (ret < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
366         return ret;
367
368     ret = write_packet(s, pkt);
369
370     if (ret >= 0)
371         s->streams[pkt->stream_index]->nb_frames++;
372     return ret;
373 }
374
375 void ff_interleave_add_packet(AVFormatContext *s, AVPacket *pkt,
376                               int (*compare)(AVFormatContext *, AVPacket *, AVPacket *))
377 {
378     AVPacketList **next_point, *this_pktl;
379
380     this_pktl      = av_mallocz(sizeof(AVPacketList));
381     this_pktl->pkt = *pkt;
382 #if FF_API_DESTRUCT_PACKET
383 FF_DISABLE_DEPRECATION_WARNINGS
384     pkt->destruct  = NULL;           // do not free original but only the copy
385 FF_ENABLE_DEPRECATION_WARNINGS
386 #endif
387     pkt->buf       = NULL;
388     av_dup_packet(&this_pktl->pkt);  // duplicate the packet if it uses non-alloced memory
389
390     if (s->streams[pkt->stream_index]->last_in_packet_buffer) {
391         next_point = &(s->streams[pkt->stream_index]->last_in_packet_buffer->next);
392     } else
393         next_point = &s->packet_buffer;
394
395     if (*next_point) {
396         if (compare(s, &s->packet_buffer_end->pkt, pkt)) {
397             while (!compare(s, &(*next_point)->pkt, pkt))
398                 next_point = &(*next_point)->next;
399             goto next_non_null;
400         } else {
401             next_point = &(s->packet_buffer_end->next);
402         }
403     }
404     assert(!*next_point);
405
406     s->packet_buffer_end = this_pktl;
407 next_non_null:
408
409     this_pktl->next = *next_point;
410
411     s->streams[pkt->stream_index]->last_in_packet_buffer =
412         *next_point                                      = this_pktl;
413 }
414
415 static int interleave_compare_dts(AVFormatContext *s, AVPacket *next,
416                                   AVPacket *pkt)
417 {
418     AVStream *st  = s->streams[pkt->stream_index];
419     AVStream *st2 = s->streams[next->stream_index];
420     int comp      = av_compare_ts(next->dts, st2->time_base, pkt->dts,
421                                   st->time_base);
422
423     if (comp == 0)
424         return pkt->stream_index < next->stream_index;
425     return comp > 0;
426 }
427
428 int ff_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out,
429                                  AVPacket *pkt, int flush)
430 {
431     AVPacketList *pktl;
432     int stream_count = 0;
433     int i;
434
435     if (pkt) {
436         ff_interleave_add_packet(s, pkt, interleave_compare_dts);
437     }
438
439     if (s->max_interleave_delta > 0 && s->packet_buffer && !flush) {
440         AVPacket *top_pkt = &s->packet_buffer->pkt;
441         int64_t delta_dts = INT64_MIN;
442         int64_t top_dts = av_rescale_q(top_pkt->dts,
443                                        s->streams[top_pkt->stream_index]->time_base,
444                                        AV_TIME_BASE_Q);
445
446         for (i = 0; i < s->nb_streams; i++) {
447             int64_t last_dts;
448             const AVPacketList *last = s->streams[i]->last_in_packet_buffer;
449
450             if (!last)
451                 continue;
452
453             last_dts = av_rescale_q(last->pkt.dts,
454                                     s->streams[i]->time_base,
455                                     AV_TIME_BASE_Q);
456             delta_dts = FFMAX(delta_dts, last_dts - top_dts);
457             stream_count++;
458         }
459
460         if (delta_dts > s->max_interleave_delta) {
461             av_log(s, AV_LOG_DEBUG,
462                    "Delay between the first packet and last packet in the "
463                    "muxing queue is %"PRId64" > %"PRId64": forcing output\n",
464                    delta_dts, s->max_interleave_delta);
465             flush = 1;
466         }
467     } else {
468         for (i = 0; i < s->nb_streams; i++)
469             stream_count += !!s->streams[i]->last_in_packet_buffer;
470     }
471
472
473     if (stream_count && (s->internal->nb_interleaved_streams == stream_count || flush)) {
474         pktl = s->packet_buffer;
475         *out = pktl->pkt;
476
477         s->packet_buffer = pktl->next;
478         if (!s->packet_buffer)
479             s->packet_buffer_end = NULL;
480
481         if (s->streams[out->stream_index]->last_in_packet_buffer == pktl)
482             s->streams[out->stream_index]->last_in_packet_buffer = NULL;
483         av_freep(&pktl);
484         return 1;
485     } else {
486         av_init_packet(out);
487         return 0;
488     }
489 }
490
491 /**
492  * Interleave an AVPacket correctly so it can be muxed.
493  * @param out the interleaved packet will be output here
494  * @param in the input packet
495  * @param flush 1 if no further packets are available as input and all
496  *              remaining packets should be output
497  * @return 1 if a packet was output, 0 if no packet could be output,
498  *         < 0 if an error occurred
499  */
500 static int interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *in, int flush)
501 {
502     if (s->oformat->interleave_packet) {
503         int ret = s->oformat->interleave_packet(s, out, in, flush);
504         if (in)
505             av_free_packet(in);
506         return ret;
507     } else
508         return ff_interleave_packet_per_dts(s, out, in, flush);
509 }
510
511 int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt)
512 {
513     int ret, flush = 0;
514
515     ret = check_packet(s, pkt);
516     if (ret < 0)
517         goto fail;
518
519     if (pkt) {
520         AVStream *st = s->streams[pkt->stream_index];
521
522         av_dlog(s, "av_interleaved_write_frame size:%d dts:%" PRId64 " pts:%" PRId64 "\n",
523                 pkt->size, pkt->dts, pkt->pts);
524         if ((ret = compute_pkt_fields2(s, st, pkt)) < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
525             goto fail;
526
527         if (pkt->dts == AV_NOPTS_VALUE && !(s->oformat->flags & AVFMT_NOTIMESTAMPS)) {
528             ret = AVERROR(EINVAL);
529             goto fail;
530         }
531     } else {
532         av_dlog(s, "av_interleaved_write_frame FLUSH\n");
533         flush = 1;
534     }
535
536     for (;; ) {
537         AVPacket opkt;
538         int ret = interleave_packet(s, &opkt, pkt, flush);
539         if (pkt) {
540             memset(pkt, 0, sizeof(*pkt));
541             av_init_packet(pkt);
542             pkt = NULL;
543         }
544         if (ret <= 0) //FIXME cleanup needed for ret<0 ?
545             return ret;
546
547         ret = write_packet(s, &opkt);
548         if (ret >= 0)
549             s->streams[opkt.stream_index]->nb_frames++;
550
551         av_free_packet(&opkt);
552
553         if (ret < 0)
554             return ret;
555     }
556 fail:
557     av_packet_unref(pkt);
558     return ret;
559 }
560
561 int av_write_trailer(AVFormatContext *s)
562 {
563     int ret, i;
564
565     for (;; ) {
566         AVPacket pkt;
567         ret = interleave_packet(s, &pkt, NULL, 1);
568         if (ret < 0) //FIXME cleanup needed for ret<0 ?
569             goto fail;
570         if (!ret)
571             break;
572
573         ret = write_packet(s, &pkt);
574         if (ret >= 0)
575             s->streams[pkt.stream_index]->nb_frames++;
576
577         av_free_packet(&pkt);
578
579         if (ret < 0)
580             goto fail;
581     }
582
583     if (s->oformat->write_trailer)
584         ret = s->oformat->write_trailer(s);
585
586     if (!(s->oformat->flags & AVFMT_NOFILE))
587         avio_flush(s->pb);
588
589 fail:
590     for (i = 0; i < s->nb_streams; i++) {
591         av_freep(&s->streams[i]->priv_data);
592         av_freep(&s->streams[i]->index_entries);
593     }
594     if (s->oformat->priv_class)
595         av_opt_free(s->priv_data);
596     av_freep(&s->priv_data);
597     return ret;
598 }
599
600 int ff_write_chained(AVFormatContext *dst, int dst_stream, AVPacket *pkt,
601                      AVFormatContext *src)
602 {
603     AVPacket local_pkt;
604
605     local_pkt = *pkt;
606     local_pkt.stream_index = dst_stream;
607     if (pkt->pts != AV_NOPTS_VALUE)
608         local_pkt.pts = av_rescale_q(pkt->pts,
609                                      src->streams[pkt->stream_index]->time_base,
610                                      dst->streams[dst_stream]->time_base);
611     if (pkt->dts != AV_NOPTS_VALUE)
612         local_pkt.dts = av_rescale_q(pkt->dts,
613                                      src->streams[pkt->stream_index]->time_base,
614                                      dst->streams[dst_stream]->time_base);
615     return av_write_frame(dst, &local_pkt);
616 }