]> git.sesse.net Git - ffmpeg/blob - libavformat/dashenc.c
22ef3103dced655f670df4a49f29768ee64ffe14
[ffmpeg] / libavformat / dashenc.c
1 /*
2  * MPEG-DASH ISO BMFF segmenter
3  * Copyright (c) 2014 Martin Storsjo
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg 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  * FFmpeg 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 FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 #include "config.h"
23 #if HAVE_UNISTD_H
24 #include <unistd.h>
25 #endif
26
27 #include "libavutil/avassert.h"
28 #include "libavutil/avutil.h"
29 #include "libavutil/avstring.h"
30 #include "libavutil/intreadwrite.h"
31 #include "libavutil/mathematics.h"
32 #include "libavutil/opt.h"
33 #include "libavutil/rational.h"
34 #include "libavutil/time_internal.h"
35
36 #include "avc.h"
37 #include "avformat.h"
38 #include "avio_internal.h"
39 #include "hlsplaylist.h"
40 #include "internal.h"
41 #include "isom.h"
42 #include "os_support.h"
43 #include "url.h"
44 #include "dash.h"
45
46 typedef struct Segment {
47     char file[1024];
48     int64_t start_pos;
49     int range_length, index_length;
50     int64_t time;
51     int duration;
52     int n;
53 } Segment;
54
55 typedef struct AdaptationSet {
56     char id[10];
57     enum AVMediaType media_type;
58     AVDictionary *metadata;
59     AVRational min_frame_rate, max_frame_rate;
60     int ambiguous_frame_rate;
61 } AdaptationSet;
62
63 typedef struct OutputStream {
64     AVFormatContext *ctx;
65     int ctx_inited, as_idx;
66     AVIOContext *out;
67     char format_name[8];
68     int packets_written;
69     char initfile[1024];
70     int64_t init_start_pos, pos;
71     int init_range_length;
72     int nb_segments, segments_size, segment_index;
73     Segment **segments;
74     int64_t first_pts, start_pts, max_pts;
75     int64_t last_dts;
76     int bit_rate;
77     char bandwidth_str[64];
78
79     char codec_str[100];
80 } OutputStream;
81
82 typedef struct DASHContext {
83     const AVClass *class;  /* Class for private options. */
84     char *adaptation_sets;
85     AdaptationSet *as;
86     int nb_as;
87     int window_size;
88     int extra_window_size;
89     int min_seg_duration;
90     int remove_at_exit;
91     int use_template;
92     int use_timeline;
93     int single_file;
94     OutputStream *streams;
95     int has_video;
96     int64_t last_duration;
97     int64_t total_duration;
98     char availability_start_time[100];
99     char dirname[1024];
100     const char *single_file_name;
101     const char *init_seg_name;
102     const char *media_seg_name;
103     const char *utc_timing_url;
104     const char *user_agent;
105     int hls_playlist;
106     int master_playlist_created;
107 } DASHContext;
108
109 static struct codec_string {
110     int id;
111     const char *str;
112 } codecs[] = {
113     { AV_CODEC_ID_VP8, "vp8" },
114     { AV_CODEC_ID_VP9, "vp9" },
115     { AV_CODEC_ID_VORBIS, "vorbis" },
116     { AV_CODEC_ID_OPUS, "opus" },
117     { 0, NULL }
118 };
119
120 static void set_codec_str(AVFormatContext *s, AVCodecParameters *par,
121                           char *str, int size)
122 {
123     const AVCodecTag *tags[2] = { NULL, NULL };
124     uint32_t tag;
125     int i;
126
127     // common Webm codecs are not part of RFC 6381
128     for (i = 0; codecs[i].id; i++)
129         if (codecs[i].id == par->codec_id) {
130             av_strlcpy(str, codecs[i].str, size);
131             return;
132         }
133
134     // for codecs part of RFC 6381
135     if (par->codec_type == AVMEDIA_TYPE_VIDEO)
136         tags[0] = ff_codec_movvideo_tags;
137     else if (par->codec_type == AVMEDIA_TYPE_AUDIO)
138         tags[0] = ff_codec_movaudio_tags;
139     else
140         return;
141
142     tag = av_codec_get_tag(tags, par->codec_id);
143     if (!tag)
144         return;
145     if (size < 5)
146         return;
147
148     AV_WL32(str, tag);
149     str[4] = '\0';
150     if (!strcmp(str, "mp4a") || !strcmp(str, "mp4v")) {
151         uint32_t oti;
152         tags[0] = ff_mp4_obj_type;
153         oti = av_codec_get_tag(tags, par->codec_id);
154         if (oti)
155             av_strlcatf(str, size, ".%02"PRIx32, oti);
156         else
157             return;
158
159         if (tag == MKTAG('m', 'p', '4', 'a')) {
160             if (par->extradata_size >= 2) {
161                 int aot = par->extradata[0] >> 3;
162                 if (aot == 31)
163                     aot = ((AV_RB16(par->extradata) >> 5) & 0x3f) + 32;
164                 av_strlcatf(str, size, ".%d", aot);
165             }
166         } else if (tag == MKTAG('m', 'p', '4', 'v')) {
167             // Unimplemented, should output ProfileLevelIndication as a decimal number
168             av_log(s, AV_LOG_WARNING, "Incomplete RFC 6381 codec string for mp4v\n");
169         }
170     } else if (!strcmp(str, "avc1")) {
171         uint8_t *tmpbuf = NULL;
172         uint8_t *extradata = par->extradata;
173         int extradata_size = par->extradata_size;
174         if (!extradata_size)
175             return;
176         if (extradata[0] != 1) {
177             AVIOContext *pb;
178             if (avio_open_dyn_buf(&pb) < 0)
179                 return;
180             if (ff_isom_write_avcc(pb, extradata, extradata_size) < 0) {
181                 ffio_free_dyn_buf(&pb);
182                 return;
183             }
184             extradata_size = avio_close_dyn_buf(pb, &extradata);
185             tmpbuf = extradata;
186         }
187
188         if (extradata_size >= 4)
189             av_strlcatf(str, size, ".%02x%02x%02x",
190                         extradata[1], extradata[2], extradata[3]);
191         av_free(tmpbuf);
192     }
193 }
194
195 static int flush_dynbuf(OutputStream *os, int *range_length)
196 {
197     uint8_t *buffer;
198
199     if (!os->ctx->pb) {
200         return AVERROR(EINVAL);
201     }
202
203     // flush
204     av_write_frame(os->ctx, NULL);
205     avio_flush(os->ctx->pb);
206
207     // write out to file
208     *range_length = avio_close_dyn_buf(os->ctx->pb, &buffer);
209     os->ctx->pb = NULL;
210     avio_write(os->out, buffer, *range_length);
211     av_free(buffer);
212
213     // re-open buffer
214     return avio_open_dyn_buf(&os->ctx->pb);
215 }
216
217 static void set_http_options(AVDictionary **options, DASHContext *c)
218 {
219     if (c->user_agent)
220         av_dict_set(options, "user_agent", c->user_agent, 0);
221 }
222
223 static void get_hls_playlist_name(char *playlist_name, int string_size,
224                                   const char *base_url, int id) {
225     if (base_url)
226         snprintf(playlist_name, string_size, "%smedia_%d.m3u8", base_url, id);
227     else
228         snprintf(playlist_name, string_size, "media_%d.m3u8", id);
229 }
230
231 static int flush_init_segment(AVFormatContext *s, OutputStream *os)
232 {
233     DASHContext *c = s->priv_data;
234     int ret, range_length;
235
236     ret = flush_dynbuf(os, &range_length);
237     if (ret < 0)
238         return ret;
239
240     os->pos = os->init_range_length = range_length;
241     if (!c->single_file)
242         ff_format_io_close(s, &os->out);
243     return 0;
244 }
245
246 static void dash_free(AVFormatContext *s)
247 {
248     DASHContext *c = s->priv_data;
249     int i, j;
250
251     if (c->as) {
252         for (i = 0; i < c->nb_as; i++)
253             av_dict_free(&c->as[i].metadata);
254         av_freep(&c->as);
255         c->nb_as = 0;
256     }
257
258     if (!c->streams)
259         return;
260     for (i = 0; i < s->nb_streams; i++) {
261         OutputStream *os = &c->streams[i];
262         if (os->ctx && os->ctx_inited)
263             av_write_trailer(os->ctx);
264         if (os->ctx && os->ctx->pb)
265             ffio_free_dyn_buf(&os->ctx->pb);
266         ff_format_io_close(s, &os->out);
267         if (os->ctx)
268             avformat_free_context(os->ctx);
269         for (j = 0; j < os->nb_segments; j++)
270             av_free(os->segments[j]);
271         av_free(os->segments);
272     }
273     av_freep(&c->streams);
274 }
275
276 static void output_segment_list(OutputStream *os, AVIOContext *out, DASHContext *c,
277                                 int representation_id, int final)
278 {
279     int i, start_index = 0, start_number = 1;
280     if (c->window_size) {
281         start_index  = FFMAX(os->nb_segments   - c->window_size, 0);
282         start_number = FFMAX(os->segment_index - c->window_size, 1);
283     }
284
285     if (c->use_template) {
286         int timescale = c->use_timeline ? os->ctx->streams[0]->time_base.den : AV_TIME_BASE;
287         avio_printf(out, "\t\t\t\t<SegmentTemplate timescale=\"%d\" ", timescale);
288         if (!c->use_timeline)
289             avio_printf(out, "duration=\"%"PRId64"\" ", c->last_duration);
290         avio_printf(out, "initialization=\"%s\" media=\"%s\" startNumber=\"%d\">\n", c->init_seg_name, c->media_seg_name, c->use_timeline ? start_number : 1);
291         if (c->use_timeline) {
292             int64_t cur_time = 0;
293             avio_printf(out, "\t\t\t\t\t<SegmentTimeline>\n");
294             for (i = start_index; i < os->nb_segments; ) {
295                 Segment *seg = os->segments[i];
296                 int repeat = 0;
297                 avio_printf(out, "\t\t\t\t\t\t<S ");
298                 if (i == start_index || seg->time != cur_time) {
299                     cur_time = seg->time;
300                     avio_printf(out, "t=\"%"PRId64"\" ", seg->time);
301                 }
302                 avio_printf(out, "d=\"%d\" ", seg->duration);
303                 while (i + repeat + 1 < os->nb_segments &&
304                        os->segments[i + repeat + 1]->duration == seg->duration &&
305                        os->segments[i + repeat + 1]->time == os->segments[i + repeat]->time + os->segments[i + repeat]->duration)
306                     repeat++;
307                 if (repeat > 0)
308                     avio_printf(out, "r=\"%d\" ", repeat);
309                 avio_printf(out, "/>\n");
310                 i += 1 + repeat;
311                 cur_time += (1 + repeat) * seg->duration;
312             }
313             avio_printf(out, "\t\t\t\t\t</SegmentTimeline>\n");
314         }
315         avio_printf(out, "\t\t\t\t</SegmentTemplate>\n");
316     } else if (c->single_file) {
317         avio_printf(out, "\t\t\t\t<BaseURL>%s</BaseURL>\n", os->initfile);
318         avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%"PRId64"\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);
319         avio_printf(out, "\t\t\t\t\t<Initialization range=\"%"PRId64"-%"PRId64"\" />\n", os->init_start_pos, os->init_start_pos + os->init_range_length - 1);
320         for (i = start_index; i < os->nb_segments; i++) {
321             Segment *seg = os->segments[i];
322             avio_printf(out, "\t\t\t\t\t<SegmentURL mediaRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->range_length - 1);
323             if (seg->index_length)
324                 avio_printf(out, "indexRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->index_length - 1);
325             avio_printf(out, "/>\n");
326         }
327         avio_printf(out, "\t\t\t\t</SegmentList>\n");
328     } else {
329         avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%"PRId64"\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);
330         avio_printf(out, "\t\t\t\t\t<Initialization sourceURL=\"%s\" />\n", os->initfile);
331         for (i = start_index; i < os->nb_segments; i++) {
332             Segment *seg = os->segments[i];
333             avio_printf(out, "\t\t\t\t\t<SegmentURL media=\"%s\" />\n", seg->file);
334         }
335         avio_printf(out, "\t\t\t\t</SegmentList>\n");
336     }
337     if (c->hls_playlist && start_index < os->nb_segments)
338     {
339         int timescale = os->ctx->streams[0]->time_base.den;
340         char temp_filename_hls[1024];
341         char filename_hls[1024];
342         AVIOContext *out_hls = NULL;
343         AVDictionary *http_opts = NULL;
344         int target_duration = 0;
345         int ret = 0;
346         const char *proto = avio_find_protocol_name(c->dirname);
347         int use_rename = proto && !strcmp(proto, "file");
348
349         get_hls_playlist_name(filename_hls, sizeof(filename_hls),
350                               c->dirname, representation_id);
351
352         snprintf(temp_filename_hls, sizeof(temp_filename_hls), use_rename ? "%s.tmp" : "%s", filename_hls);
353
354         set_http_options(&http_opts, c);
355         avio_open2(&out_hls, temp_filename_hls, AVIO_FLAG_WRITE, NULL, &http_opts);
356         av_dict_free(&http_opts);
357         for (i = start_index; i < os->nb_segments; i++) {
358             Segment *seg = os->segments[i];
359             double duration = (double) seg->duration / timescale;
360             if (target_duration <= duration)
361                 target_duration = hls_get_int_from_double(duration);
362         }
363
364         ff_hls_write_playlist_header(out_hls, 6, -1, target_duration,
365                                      start_number, PLAYLIST_TYPE_NONE);
366
367         ff_hls_write_init_file(out_hls, os->initfile, c->single_file,
368                                os->init_range_length, os->init_start_pos);
369
370         for (i = start_index; i < os->nb_segments; i++) {
371             Segment *seg = os->segments[i];
372             ret = ff_hls_write_file_entry(out_hls, 0, c->single_file,
373                                     (double) seg->duration / timescale, 0,
374                                     seg->range_length, seg->start_pos, NULL,
375                                     c->single_file ? os->initfile : seg->file,
376                                     NULL);
377             if (ret < 0) {
378                 av_log(os->ctx, AV_LOG_WARNING, "ff_hls_write_file_entry get error\n");
379             }
380         }
381
382         if (final)
383             ff_hls_write_end_list(out_hls);
384
385         avio_close(out_hls);
386         if (use_rename)
387             avpriv_io_move(temp_filename_hls, filename_hls);
388     }
389
390 }
391
392 static char *xmlescape(const char *str) {
393     int outlen = strlen(str)*3/2 + 6;
394     char *out = av_realloc(NULL, outlen + 1);
395     int pos = 0;
396     if (!out)
397         return NULL;
398     for (; *str; str++) {
399         if (pos + 6 > outlen) {
400             char *tmp;
401             outlen = 2 * outlen + 6;
402             tmp = av_realloc(out, outlen + 1);
403             if (!tmp) {
404                 av_free(out);
405                 return NULL;
406             }
407             out = tmp;
408         }
409         if (*str == '&') {
410             memcpy(&out[pos], "&amp;", 5);
411             pos += 5;
412         } else if (*str == '<') {
413             memcpy(&out[pos], "&lt;", 4);
414             pos += 4;
415         } else if (*str == '>') {
416             memcpy(&out[pos], "&gt;", 4);
417             pos += 4;
418         } else if (*str == '\'') {
419             memcpy(&out[pos], "&apos;", 6);
420             pos += 6;
421         } else if (*str == '\"') {
422             memcpy(&out[pos], "&quot;", 6);
423             pos += 6;
424         } else {
425             out[pos++] = *str;
426         }
427     }
428     out[pos] = '\0';
429     return out;
430 }
431
432 static void write_time(AVIOContext *out, int64_t time)
433 {
434     int seconds = time / AV_TIME_BASE;
435     int fractions = time % AV_TIME_BASE;
436     int minutes = seconds / 60;
437     int hours = minutes / 60;
438     seconds %= 60;
439     minutes %= 60;
440     avio_printf(out, "PT");
441     if (hours)
442         avio_printf(out, "%dH", hours);
443     if (hours || minutes)
444         avio_printf(out, "%dM", minutes);
445     avio_printf(out, "%d.%dS", seconds, fractions / (AV_TIME_BASE / 10));
446 }
447
448 static void format_date_now(char *buf, int size)
449 {
450     time_t t = time(NULL);
451     struct tm *ptm, tmbuf;
452     ptm = gmtime_r(&t, &tmbuf);
453     if (ptm) {
454         if (!strftime(buf, size, "%Y-%m-%dT%H:%M:%SZ", ptm))
455             buf[0] = '\0';
456     }
457 }
458
459 static int write_adaptation_set(AVFormatContext *s, AVIOContext *out, int as_index,
460                                 int final)
461 {
462     DASHContext *c = s->priv_data;
463     AdaptationSet *as = &c->as[as_index];
464     AVDictionaryEntry *lang, *role;
465     int i;
466
467     avio_printf(out, "\t\t<AdaptationSet id=\"%s\" contentType=\"%s\" segmentAlignment=\"true\" bitstreamSwitching=\"true\"",
468                 as->id, as->media_type == AVMEDIA_TYPE_VIDEO ? "video" : "audio");
469     if (as->media_type == AVMEDIA_TYPE_VIDEO && as->max_frame_rate.num && !as->ambiguous_frame_rate && av_cmp_q(as->min_frame_rate, as->max_frame_rate) < 0)
470         avio_printf(out, " maxFrameRate=\"%d/%d\"", as->max_frame_rate.num, as->max_frame_rate.den);
471     lang = av_dict_get(as->metadata, "language", NULL, 0);
472     if (lang)
473         avio_printf(out, " lang=\"%s\"", lang->value);
474     avio_printf(out, ">\n");
475
476     role = av_dict_get(as->metadata, "role", NULL, 0);
477     if (role)
478         avio_printf(out, "\t\t\t<Role schemeIdUri=\"urn:mpeg:dash:role:2011\" value=\"%s\"/>\n", role->value);
479
480     for (i = 0; i < s->nb_streams; i++) {
481         OutputStream *os = &c->streams[i];
482
483         if (os->as_idx - 1 != as_index)
484             continue;
485
486         if (as->media_type == AVMEDIA_TYPE_VIDEO) {
487             AVStream *st = s->streams[i];
488             avio_printf(out, "\t\t\t<Representation id=\"%d\" mimeType=\"video/%s\" codecs=\"%s\"%s width=\"%d\" height=\"%d\"",
489                 i, os->format_name, os->codec_str, os->bandwidth_str, s->streams[i]->codecpar->width, s->streams[i]->codecpar->height);
490             if (st->avg_frame_rate.num)
491                 avio_printf(out, " frameRate=\"%d/%d\"", st->avg_frame_rate.num, st->avg_frame_rate.den);
492             avio_printf(out, ">\n");
493         } else {
494             avio_printf(out, "\t\t\t<Representation id=\"%d\" mimeType=\"audio/%s\" codecs=\"%s\"%s audioSamplingRate=\"%d\">\n",
495                 i, os->format_name, os->codec_str, os->bandwidth_str, s->streams[i]->codecpar->sample_rate);
496             avio_printf(out, "\t\t\t\t<AudioChannelConfiguration schemeIdUri=\"urn:mpeg:dash:23003:3:audio_channel_configuration:2011\" value=\"%d\" />\n",
497                 s->streams[i]->codecpar->channels);
498         }
499         output_segment_list(os, out, c, i, final);
500         avio_printf(out, "\t\t\t</Representation>\n");
501     }
502     avio_printf(out, "\t\t</AdaptationSet>\n");
503
504     return 0;
505 }
506
507 static int add_adaptation_set(AVFormatContext *s, AdaptationSet **as, enum AVMediaType type)
508 {
509     DASHContext *c = s->priv_data;
510
511     void *mem = av_realloc(c->as, sizeof(*c->as) * (c->nb_as + 1));
512     if (!mem)
513         return AVERROR(ENOMEM);
514     c->as = mem;
515     ++c->nb_as;
516
517     *as = &c->as[c->nb_as - 1];
518     memset(*as, 0, sizeof(**as));
519     (*as)->media_type = type;
520
521     return 0;
522 }
523
524 static int adaptation_set_add_stream(AVFormatContext *s, int as_idx, int i)
525 {
526     DASHContext *c = s->priv_data;
527     AdaptationSet *as = &c->as[as_idx - 1];
528     OutputStream *os = &c->streams[i];
529
530     if (as->media_type != s->streams[i]->codecpar->codec_type) {
531         av_log(s, AV_LOG_ERROR, "Codec type of stream %d doesn't match AdaptationSet's media type\n", i);
532         return AVERROR(EINVAL);
533     } else if (os->as_idx) {
534         av_log(s, AV_LOG_ERROR, "Stream %d is already assigned to an AdaptationSet\n", i);
535         return AVERROR(EINVAL);
536     }
537     os->as_idx = as_idx;
538
539     return 0;
540 }
541
542 static int parse_adaptation_sets(AVFormatContext *s)
543 {
544     DASHContext *c = s->priv_data;
545     const char *p = c->adaptation_sets;
546     enum { new_set, parse_id, parsing_streams } state;
547     AdaptationSet *as;
548     int i, n, ret;
549
550     // default: one AdaptationSet for each stream
551     if (!p) {
552         for (i = 0; i < s->nb_streams; i++) {
553             if ((ret = add_adaptation_set(s, &as, s->streams[i]->codecpar->codec_type)) < 0)
554                 return ret;
555             snprintf(as->id, sizeof(as->id), "%d", i);
556
557             c->streams[i].as_idx = c->nb_as;
558         }
559         goto end;
560     }
561
562     // syntax id=0,streams=0,1,2 id=1,streams=3,4 and so on
563     state = new_set;
564     while (*p) {
565         if (*p == ' ') {
566             p++;
567             continue;
568         } else if (state == new_set && av_strstart(p, "id=", &p)) {
569
570             if ((ret = add_adaptation_set(s, &as, AVMEDIA_TYPE_UNKNOWN)) < 0)
571                 return ret;
572
573             n = strcspn(p, ",");
574             snprintf(as->id, sizeof(as->id), "%.*s", n, p);
575
576             p += n;
577             if (*p)
578                 p++;
579             state = parse_id;
580         } else if (state == parse_id && av_strstart(p, "streams=", &p)) {
581             state = parsing_streams;
582         } else if (state == parsing_streams) {
583             AdaptationSet *as = &c->as[c->nb_as - 1];
584             char idx_str[8], *end_str;
585
586             n = strcspn(p, " ,");
587             snprintf(idx_str, sizeof(idx_str), "%.*s", n, p);
588             p += n;
589
590             // if value is "a" or "v", map all streams of that type
591             if (as->media_type == AVMEDIA_TYPE_UNKNOWN && (idx_str[0] == 'v' || idx_str[0] == 'a')) {
592                 enum AVMediaType type = (idx_str[0] == 'v') ? AVMEDIA_TYPE_VIDEO : AVMEDIA_TYPE_AUDIO;
593                 av_log(s, AV_LOG_DEBUG, "Map all streams of type %s\n", idx_str);
594
595                 for (i = 0; i < s->nb_streams; i++) {
596                     if (s->streams[i]->codecpar->codec_type != type)
597                         continue;
598
599                     as->media_type = s->streams[i]->codecpar->codec_type;
600
601                     if ((ret = adaptation_set_add_stream(s, c->nb_as, i)) < 0)
602                         return ret;
603                 }
604             } else { // select single stream
605                 i = strtol(idx_str, &end_str, 10);
606                 if (idx_str == end_str || i < 0 || i >= s->nb_streams) {
607                     av_log(s, AV_LOG_ERROR, "Selected stream \"%s\" not found!\n", idx_str);
608                     return AVERROR(EINVAL);
609                 }
610                 av_log(s, AV_LOG_DEBUG, "Map stream %d\n", i);
611
612                 if (as->media_type == AVMEDIA_TYPE_UNKNOWN) {
613                     as->media_type = s->streams[i]->codecpar->codec_type;
614                 }
615
616                 if ((ret = adaptation_set_add_stream(s, c->nb_as, i)) < 0)
617                     return ret;
618             }
619
620             if (*p == ' ')
621                 state = new_set;
622             if (*p)
623                 p++;
624         } else {
625             return AVERROR(EINVAL);
626         }
627     }
628
629 end:
630     // check for unassigned streams
631     for (i = 0; i < s->nb_streams; i++) {
632         OutputStream *os = &c->streams[i];
633         if (!os->as_idx) {
634             av_log(s, AV_LOG_ERROR, "Stream %d is not mapped to an AdaptationSet\n", i);
635             return AVERROR(EINVAL);
636         }
637     }
638     return 0;
639 }
640
641 static int write_manifest(AVFormatContext *s, int final)
642 {
643     DASHContext *c = s->priv_data;
644     AVIOContext *out;
645     char temp_filename[1024];
646     int ret, i;
647     const char *proto = avio_find_protocol_name(s->filename);
648     int use_rename = proto && !strcmp(proto, "file");
649     static unsigned int warned_non_file = 0;
650     AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
651     AVDictionary *opts = NULL;
652
653     if (!use_rename && !warned_non_file++)
654         av_log(s, AV_LOG_ERROR, "Cannot use rename on non file protocol, this may lead to races and temporary partial files\n");
655
656     snprintf(temp_filename, sizeof(temp_filename), use_rename ? "%s.tmp" : "%s", s->filename);
657     set_http_options(&opts, c);
658     ret = s->io_open(s, &out, temp_filename, AVIO_FLAG_WRITE, &opts);
659     if (ret < 0) {
660         av_log(s, AV_LOG_ERROR, "Unable to open %s for writing\n", temp_filename);
661         return ret;
662     }
663     av_dict_free(&opts);
664     avio_printf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
665     avio_printf(out, "<MPD xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
666                 "\txmlns=\"urn:mpeg:dash:schema:mpd:2011\"\n"
667                 "\txmlns:xlink=\"http://www.w3.org/1999/xlink\"\n"
668                 "\txsi:schemaLocation=\"urn:mpeg:DASH:schema:MPD:2011 http://standards.iso.org/ittf/PubliclyAvailableStandards/MPEG-DASH_schema_files/DASH-MPD.xsd\"\n"
669                 "\tprofiles=\"urn:mpeg:dash:profile:isoff-live:2011\"\n"
670                 "\ttype=\"%s\"\n", final ? "static" : "dynamic");
671     if (final) {
672         avio_printf(out, "\tmediaPresentationDuration=\"");
673         write_time(out, c->total_duration);
674         avio_printf(out, "\"\n");
675     } else {
676         int64_t update_period = c->last_duration / AV_TIME_BASE;
677         char now_str[100];
678         if (c->use_template && !c->use_timeline)
679             update_period = 500;
680         avio_printf(out, "\tminimumUpdatePeriod=\"PT%"PRId64"S\"\n", update_period);
681         avio_printf(out, "\tsuggestedPresentationDelay=\"PT%"PRId64"S\"\n", c->last_duration / AV_TIME_BASE);
682         if (!c->availability_start_time[0] && s->nb_streams > 0 && c->streams[0].nb_segments > 0) {
683             format_date_now(c->availability_start_time, sizeof(c->availability_start_time));
684         }
685         if (c->availability_start_time[0])
686             avio_printf(out, "\tavailabilityStartTime=\"%s\"\n", c->availability_start_time);
687         format_date_now(now_str, sizeof(now_str));
688         if (now_str[0])
689             avio_printf(out, "\tpublishTime=\"%s\"\n", now_str);
690         if (c->window_size && c->use_template) {
691             avio_printf(out, "\ttimeShiftBufferDepth=\"");
692             write_time(out, c->last_duration * c->window_size);
693             avio_printf(out, "\"\n");
694         }
695     }
696     avio_printf(out, "\tminBufferTime=\"");
697     write_time(out, c->last_duration * 2);
698     avio_printf(out, "\">\n");
699     avio_printf(out, "\t<ProgramInformation>\n");
700     if (title) {
701         char *escaped = xmlescape(title->value);
702         avio_printf(out, "\t\t<Title>%s</Title>\n", escaped);
703         av_free(escaped);
704     }
705     avio_printf(out, "\t</ProgramInformation>\n");
706
707     if (c->window_size && s->nb_streams > 0 && c->streams[0].nb_segments > 0 && !c->use_template) {
708         OutputStream *os = &c->streams[0];
709         int start_index = FFMAX(os->nb_segments - c->window_size, 0);
710         int64_t start_time = av_rescale_q(os->segments[start_index]->time, s->streams[0]->time_base, AV_TIME_BASE_Q);
711         avio_printf(out, "\t<Period id=\"0\" start=\"");
712         write_time(out, start_time);
713         avio_printf(out, "\">\n");
714     } else {
715         avio_printf(out, "\t<Period id=\"0\" start=\"PT0.0S\">\n");
716     }
717
718     for (i = 0; i < c->nb_as; i++) {
719         if ((ret = write_adaptation_set(s, out, i, final)) < 0)
720             return ret;
721     }
722     avio_printf(out, "\t</Period>\n");
723
724     if (c->utc_timing_url)
725         avio_printf(out, "\t<UTCTiming schemeIdUri=\"urn:mpeg:dash:utc:http-xsdate:2014\" value=\"%s\"/>\n", c->utc_timing_url);
726
727     avio_printf(out, "</MPD>\n");
728     avio_flush(out);
729     ff_format_io_close(s, &out);
730
731     if (use_rename) {
732         if ((ret = avpriv_io_move(temp_filename, s->filename)) < 0)
733             return ret;
734     }
735
736     if (c->hls_playlist && !c->master_playlist_created) {
737         char filename_hls[1024];
738
739         if (*c->dirname)
740             snprintf(filename_hls, sizeof(filename_hls), "%s/master.m3u8", c->dirname);
741         else
742             snprintf(filename_hls, sizeof(filename_hls), "master.m3u8");
743
744         snprintf(temp_filename, sizeof(temp_filename), use_rename ? "%s.tmp" : "%s", filename_hls);
745
746         set_http_options(&opts, c);
747         ret = avio_open2(&out, temp_filename, AVIO_FLAG_WRITE, NULL, &opts);
748         if (ret < 0) {
749             av_log(s, AV_LOG_ERROR, "Unable to open %s for writing\n", temp_filename);
750             return ret;
751         }
752         av_dict_free(&opts);
753
754         ff_hls_write_playlist_version(out, 6);
755
756         for (i = 0; i < s->nb_streams; i++) {
757             char playlist_file[64];
758             AVStream *st = s->streams[i];
759             get_hls_playlist_name(playlist_file, sizeof(playlist_file), NULL, i);
760             ff_hls_write_stream_info(st, out, st->codecpar->bit_rate, playlist_file);
761         }
762         avio_close(out);
763         if (use_rename)
764             if ((ret = avpriv_io_move(temp_filename, filename_hls)) < 0)
765                 return ret;
766         c->master_playlist_created = 1;
767     }
768
769     return 0;
770 }
771
772 static int dict_copy_entry(AVDictionary **dst, const AVDictionary *src, const char *key)
773 {
774     AVDictionaryEntry *entry = av_dict_get(src, key, NULL, 0);
775     if (entry)
776         av_dict_set(dst, key, entry->value, AV_DICT_DONT_OVERWRITE);
777     return 0;
778 }
779
780 static int dash_init(AVFormatContext *s)
781 {
782     DASHContext *c = s->priv_data;
783     int ret = 0, i;
784     char *ptr;
785     char basename[1024];
786
787     if (c->single_file_name)
788         c->single_file = 1;
789     if (c->single_file)
790         c->use_template = 0;
791
792     av_strlcpy(c->dirname, s->filename, sizeof(c->dirname));
793     ptr = strrchr(c->dirname, '/');
794     if (ptr) {
795         av_strlcpy(basename, &ptr[1], sizeof(basename));
796         ptr[1] = '\0';
797     } else {
798         c->dirname[0] = '\0';
799         av_strlcpy(basename, s->filename, sizeof(basename));
800     }
801
802     ptr = strrchr(basename, '.');
803     if (ptr)
804         *ptr = '\0';
805
806     c->streams = av_mallocz(sizeof(*c->streams) * s->nb_streams);
807     if (!c->streams)
808         return AVERROR(ENOMEM);
809
810     if ((ret = parse_adaptation_sets(s)) < 0)
811         return ret;
812
813     for (i = 0; i < s->nb_streams; i++) {
814         OutputStream *os = &c->streams[i];
815         AdaptationSet *as = &c->as[os->as_idx - 1];
816         AVFormatContext *ctx;
817         AVStream *st;
818         AVDictionary *opts = NULL;
819         char filename[1024];
820
821         os->bit_rate = s->streams[i]->codecpar->bit_rate;
822         if (os->bit_rate) {
823             snprintf(os->bandwidth_str, sizeof(os->bandwidth_str),
824                      " bandwidth=\"%d\"", os->bit_rate);
825         } else {
826             int level = s->strict_std_compliance >= FF_COMPLIANCE_STRICT ?
827                         AV_LOG_ERROR : AV_LOG_WARNING;
828             av_log(s, level, "No bit rate set for stream %d\n", i);
829             if (s->strict_std_compliance >= FF_COMPLIANCE_STRICT)
830                 return AVERROR(EINVAL);
831         }
832
833         // copy AdaptationSet language and role from stream metadata
834         dict_copy_entry(&as->metadata, s->streams[i]->metadata, "language");
835         dict_copy_entry(&as->metadata, s->streams[i]->metadata, "role");
836
837         ctx = avformat_alloc_context();
838         if (!ctx)
839             return AVERROR(ENOMEM);
840
841         // choose muxer based on codec: webm for VP8/9 and opus, mp4 otherwise
842         // note: os->format_name is also used as part of the mimetype of the
843         //       representation, e.g. video/<format_name>
844         if (s->streams[i]->codecpar->codec_id == AV_CODEC_ID_VP8 ||
845             s->streams[i]->codecpar->codec_id == AV_CODEC_ID_VP9 ||
846             s->streams[i]->codecpar->codec_id == AV_CODEC_ID_OPUS ||
847             s->streams[i]->codecpar->codec_id == AV_CODEC_ID_VORBIS) {
848             snprintf(os->format_name, sizeof(os->format_name), "webm");
849         } else {
850             snprintf(os->format_name, sizeof(os->format_name), "mp4");
851         }
852         ctx->oformat = av_guess_format(os->format_name, NULL, NULL);
853         if (!ctx->oformat)
854             return AVERROR_MUXER_NOT_FOUND;
855         os->ctx = ctx;
856         ctx->interrupt_callback = s->interrupt_callback;
857         ctx->opaque             = s->opaque;
858         ctx->io_close           = s->io_close;
859         ctx->io_open            = s->io_open;
860
861         if (!(st = avformat_new_stream(ctx, NULL)))
862             return AVERROR(ENOMEM);
863         avcodec_parameters_copy(st->codecpar, s->streams[i]->codecpar);
864         st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
865         st->time_base = s->streams[i]->time_base;
866         st->avg_frame_rate = s->streams[i]->avg_frame_rate;
867         ctx->avoid_negative_ts = s->avoid_negative_ts;
868         ctx->flags = s->flags;
869
870         if ((ret = avio_open_dyn_buf(&ctx->pb)) < 0)
871             return ret;
872
873         if (c->single_file) {
874             if (c->single_file_name)
875                 ff_dash_fill_tmpl_params(os->initfile, sizeof(os->initfile), c->single_file_name, i, 0, os->bit_rate, 0);
876             else
877                 snprintf(os->initfile, sizeof(os->initfile), "%s-stream%d.m4s", basename, i);
878         } else {
879             ff_dash_fill_tmpl_params(os->initfile, sizeof(os->initfile), c->init_seg_name, i, 0, os->bit_rate, 0);
880         }
881         snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
882         set_http_options(&opts, c);
883         ret = s->io_open(s, &os->out, filename, AVIO_FLAG_WRITE, &opts);
884         if (ret < 0)
885             return ret;
886         av_dict_free(&opts);
887         os->init_start_pos = 0;
888
889         if (!strcmp(os->format_name, "mp4")) {
890             av_dict_set(&opts, "movflags", "frag_custom+dash+delay_moov", 0);
891         } else {
892             av_dict_set_int(&opts, "cluster_time_limit", c->min_seg_duration / 1000, 0);
893             av_dict_set_int(&opts, "cluster_size_limit", 5 * 1024 * 1024, 0); // set a large cluster size limit
894             av_dict_set_int(&opts, "dash", 1, 0);
895             av_dict_set_int(&opts, "dash_track_number", i + 1, 0);
896             av_dict_set_int(&opts, "live", 1, 0);
897         }
898         if ((ret = avformat_init_output(ctx, &opts)) < 0)
899             return ret;
900         os->ctx_inited = 1;
901         avio_flush(ctx->pb);
902         av_dict_free(&opts);
903
904         av_log(s, AV_LOG_VERBOSE, "Representation %d init segment will be written to: %s\n", i, filename);
905
906         // Flush init segment
907         // except for mp4, since delay_moov is set and the init segment
908         // is then flushed after the first packets
909         if (strcmp(os->format_name, "mp4")) {
910             flush_init_segment(s, os);
911         }
912
913         s->streams[i]->time_base = st->time_base;
914         // If the muxer wants to shift timestamps, request to have them shifted
915         // already before being handed to this muxer, so we don't have mismatches
916         // between the MPD and the actual segments.
917         s->avoid_negative_ts = ctx->avoid_negative_ts;
918         if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
919             AVRational avg_frame_rate = s->streams[i]->avg_frame_rate;
920             if (avg_frame_rate.num > 0) {
921                 if (av_cmp_q(avg_frame_rate, as->min_frame_rate) < 0)
922                     as->min_frame_rate = avg_frame_rate;
923                 if (av_cmp_q(as->max_frame_rate, avg_frame_rate) < 0)
924                     as->max_frame_rate = avg_frame_rate;
925             } else {
926                 as->ambiguous_frame_rate = 1;
927             }
928             c->has_video = 1;
929         }
930
931         set_codec_str(s, st->codecpar, os->codec_str, sizeof(os->codec_str));
932         os->first_pts = AV_NOPTS_VALUE;
933         os->max_pts = AV_NOPTS_VALUE;
934         os->last_dts = AV_NOPTS_VALUE;
935         os->segment_index = 1;
936     }
937
938     if (!c->has_video && c->min_seg_duration <= 0) {
939         av_log(s, AV_LOG_WARNING, "no video stream and no min seg duration set\n");
940         return AVERROR(EINVAL);
941     }
942     return 0;
943 }
944
945 static int dash_write_header(AVFormatContext *s)
946 {
947     DASHContext *c = s->priv_data;
948     int i, ret;
949     for (i = 0; i < s->nb_streams; i++) {
950         OutputStream *os = &c->streams[i];
951         if ((ret = avformat_write_header(os->ctx, NULL)) < 0) {
952             dash_free(s);
953             return ret;
954         }
955     }
956     ret = write_manifest(s, 0);
957     if (!ret)
958         av_log(s, AV_LOG_VERBOSE, "Manifest written to: %s\n", s->filename);
959     return ret;
960 }
961
962 static int add_segment(OutputStream *os, const char *file,
963                        int64_t time, int duration,
964                        int64_t start_pos, int64_t range_length,
965                        int64_t index_length)
966 {
967     int err;
968     Segment *seg;
969     if (os->nb_segments >= os->segments_size) {
970         os->segments_size = (os->segments_size + 1) * 2;
971         if ((err = av_reallocp(&os->segments, sizeof(*os->segments) *
972                                os->segments_size)) < 0) {
973             os->segments_size = 0;
974             os->nb_segments = 0;
975             return err;
976         }
977     }
978     seg = av_mallocz(sizeof(*seg));
979     if (!seg)
980         return AVERROR(ENOMEM);
981     av_strlcpy(seg->file, file, sizeof(seg->file));
982     seg->time = time;
983     seg->duration = duration;
984     if (seg->time < 0) { // If pts<0, it is expected to be cut away with an edit list
985         seg->duration += seg->time;
986         seg->time = 0;
987     }
988     seg->start_pos = start_pos;
989     seg->range_length = range_length;
990     seg->index_length = index_length;
991     os->segments[os->nb_segments++] = seg;
992     os->segment_index++;
993     return 0;
994 }
995
996 static void write_styp(AVIOContext *pb)
997 {
998     avio_wb32(pb, 24);
999     ffio_wfourcc(pb, "styp");
1000     ffio_wfourcc(pb, "msdh");
1001     avio_wb32(pb, 0); /* minor */
1002     ffio_wfourcc(pb, "msdh");
1003     ffio_wfourcc(pb, "msix");
1004 }
1005
1006 static void find_index_range(AVFormatContext *s, const char *full_path,
1007                              int64_t pos, int *index_length)
1008 {
1009     uint8_t buf[8];
1010     AVIOContext *pb;
1011     int ret;
1012
1013     ret = s->io_open(s, &pb, full_path, AVIO_FLAG_READ, NULL);
1014     if (ret < 0)
1015         return;
1016     if (avio_seek(pb, pos, SEEK_SET) != pos) {
1017         ff_format_io_close(s, &pb);
1018         return;
1019     }
1020     ret = avio_read(pb, buf, 8);
1021     ff_format_io_close(s, &pb);
1022     if (ret < 8)
1023         return;
1024     if (AV_RL32(&buf[4]) != MKTAG('s', 'i', 'd', 'x'))
1025         return;
1026     *index_length = AV_RB32(&buf[0]);
1027 }
1028
1029 static int update_stream_extradata(AVFormatContext *s, OutputStream *os,
1030                                    AVCodecParameters *par)
1031 {
1032     uint8_t *extradata;
1033
1034     if (os->ctx->streams[0]->codecpar->extradata_size || !par->extradata_size)
1035         return 0;
1036
1037     extradata = av_malloc(par->extradata_size);
1038
1039     if (!extradata)
1040         return AVERROR(ENOMEM);
1041
1042     memcpy(extradata, par->extradata, par->extradata_size);
1043
1044     os->ctx->streams[0]->codecpar->extradata = extradata;
1045     os->ctx->streams[0]->codecpar->extradata_size = par->extradata_size;
1046
1047     set_codec_str(s, par, os->codec_str, sizeof(os->codec_str));
1048
1049     return 0;
1050 }
1051
1052 static int dash_flush(AVFormatContext *s, int final, int stream)
1053 {
1054     DASHContext *c = s->priv_data;
1055     int i, ret = 0;
1056
1057     const char *proto = avio_find_protocol_name(s->filename);
1058     int use_rename = proto && !strcmp(proto, "file");
1059
1060     int cur_flush_segment_index = 0;
1061     if (stream >= 0)
1062         cur_flush_segment_index = c->streams[stream].segment_index;
1063
1064     for (i = 0; i < s->nb_streams; i++) {
1065         OutputStream *os = &c->streams[i];
1066         AVStream *st = s->streams[i];
1067         char filename[1024] = "", full_path[1024], temp_path[1024];
1068         int range_length, index_length = 0;
1069
1070         if (!os->packets_written)
1071             continue;
1072
1073         // Flush the single stream that got a keyframe right now.
1074         // Flush all audio streams as well, in sync with video keyframes,
1075         // but not the other video streams.
1076         if (stream >= 0 && i != stream) {
1077             if (s->streams[i]->codecpar->codec_type != AVMEDIA_TYPE_AUDIO)
1078                 continue;
1079             // Make sure we don't flush audio streams multiple times, when
1080             // all video streams are flushed one at a time.
1081             if (c->has_video && os->segment_index > cur_flush_segment_index)
1082                 continue;
1083         }
1084
1085         if (!os->init_range_length) {
1086             flush_init_segment(s, os);
1087         }
1088
1089         if (!c->single_file) {
1090             AVDictionary *opts = NULL;
1091             ff_dash_fill_tmpl_params(filename, sizeof(filename), c->media_seg_name, i, os->segment_index, os->bit_rate, os->start_pts);
1092             snprintf(full_path, sizeof(full_path), "%s%s", c->dirname, filename);
1093             snprintf(temp_path, sizeof(temp_path), use_rename ? "%s.tmp" : "%s", full_path);
1094             set_http_options(&opts, c);
1095             ret = s->io_open(s, &os->out, temp_path, AVIO_FLAG_WRITE, &opts);
1096             if (ret < 0)
1097                 break;
1098             av_dict_free(&opts);
1099             if (!strcmp(os->format_name, "mp4"))
1100                 write_styp(os->ctx->pb);
1101         } else {
1102             snprintf(full_path, sizeof(full_path), "%s%s", c->dirname, os->initfile);
1103         }
1104
1105         ret = flush_dynbuf(os, &range_length);
1106         if (ret < 0)
1107             break;
1108         os->packets_written = 0;
1109
1110         if (c->single_file) {
1111             find_index_range(s, full_path, os->pos, &index_length);
1112         } else {
1113             ff_format_io_close(s, &os->out);
1114
1115             if (use_rename) {
1116                 ret = avpriv_io_move(temp_path, full_path);
1117                 if (ret < 0)
1118                     break;
1119             }
1120         }
1121
1122         if (!os->bit_rate) {
1123             // calculate average bitrate of first segment
1124             int64_t bitrate = (int64_t) range_length * 8 * AV_TIME_BASE / av_rescale_q(os->max_pts - os->start_pts,
1125                                                                                        st->time_base,
1126                                                                                        AV_TIME_BASE_Q);
1127             if (bitrate >= 0) {
1128                 os->bit_rate = bitrate;
1129                 snprintf(os->bandwidth_str, sizeof(os->bandwidth_str),
1130                      " bandwidth=\"%d\"", os->bit_rate);
1131             }
1132         }
1133         add_segment(os, filename, os->start_pts, os->max_pts - os->start_pts, os->pos, range_length, index_length);
1134         av_log(s, AV_LOG_VERBOSE, "Representation %d media segment %d written to: %s\n", i, os->segment_index, full_path);
1135
1136         os->pos += range_length;
1137     }
1138
1139     if (c->window_size || (final && c->remove_at_exit)) {
1140         for (i = 0; i < s->nb_streams; i++) {
1141             OutputStream *os = &c->streams[i];
1142             int j;
1143             int remove = os->nb_segments - c->window_size - c->extra_window_size;
1144             if (final && c->remove_at_exit)
1145                 remove = os->nb_segments;
1146             if (remove > 0) {
1147                 for (j = 0; j < remove; j++) {
1148                     char filename[1024];
1149                     snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->segments[j]->file);
1150                     unlink(filename);
1151                     av_free(os->segments[j]);
1152                 }
1153                 os->nb_segments -= remove;
1154                 memmove(os->segments, os->segments + remove, os->nb_segments * sizeof(*os->segments));
1155             }
1156         }
1157     }
1158
1159     if (ret >= 0)
1160         ret = write_manifest(s, final);
1161     return ret;
1162 }
1163
1164 static int dash_write_packet(AVFormatContext *s, AVPacket *pkt)
1165 {
1166     DASHContext *c = s->priv_data;
1167     AVStream *st = s->streams[pkt->stream_index];
1168     OutputStream *os = &c->streams[pkt->stream_index];
1169     int ret;
1170
1171     ret = update_stream_extradata(s, os, st->codecpar);
1172     if (ret < 0)
1173         return ret;
1174
1175     // Fill in a heuristic guess of the packet duration, if none is available.
1176     // The mp4 muxer will do something similar (for the last packet in a fragment)
1177     // if nothing is set (setting it for the other packets doesn't hurt).
1178     // By setting a nonzero duration here, we can be sure that the mp4 muxer won't
1179     // invoke its heuristic (this doesn't have to be identical to that algorithm),
1180     // so that we know the exact timestamps of fragments.
1181     if (!pkt->duration && os->last_dts != AV_NOPTS_VALUE)
1182         pkt->duration = pkt->dts - os->last_dts;
1183     os->last_dts = pkt->dts;
1184
1185     // If forcing the stream to start at 0, the mp4 muxer will set the start
1186     // timestamps to 0. Do the same here, to avoid mismatches in duration/timestamps.
1187     if (os->first_pts == AV_NOPTS_VALUE &&
1188         s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
1189         pkt->pts -= pkt->dts;
1190         pkt->dts  = 0;
1191     }
1192
1193     if (os->first_pts == AV_NOPTS_VALUE)
1194         os->first_pts = pkt->pts;
1195
1196     if ((!c->has_video || st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) &&
1197         pkt->flags & AV_PKT_FLAG_KEY && os->packets_written &&
1198         av_compare_ts(pkt->pts - os->start_pts, st->time_base,
1199                       c->min_seg_duration, AV_TIME_BASE_Q) >= 0) {
1200         int64_t prev_duration = c->last_duration;
1201
1202         c->last_duration = av_rescale_q(pkt->pts - os->start_pts,
1203                                         st->time_base,
1204                                         AV_TIME_BASE_Q);
1205         c->total_duration = av_rescale_q(pkt->pts - os->first_pts,
1206                                          st->time_base,
1207                                          AV_TIME_BASE_Q);
1208
1209         if ((!c->use_timeline || !c->use_template) && prev_duration) {
1210             if (c->last_duration < prev_duration*9/10 ||
1211                 c->last_duration > prev_duration*11/10) {
1212                 av_log(s, AV_LOG_WARNING,
1213                        "Segment durations differ too much, enable use_timeline "
1214                        "and use_template, or keep a stricter keyframe interval\n");
1215             }
1216         }
1217
1218         if ((ret = dash_flush(s, 0, pkt->stream_index)) < 0)
1219             return ret;
1220     }
1221
1222     if (!os->packets_written) {
1223         // If we wrote a previous segment, adjust the start time of the segment
1224         // to the end of the previous one (which is the same as the mp4 muxer
1225         // does). This avoids gaps in the timeline.
1226         if (os->max_pts != AV_NOPTS_VALUE)
1227             os->start_pts = os->max_pts;
1228         else
1229             os->start_pts = pkt->pts;
1230     }
1231     if (os->max_pts == AV_NOPTS_VALUE)
1232         os->max_pts = pkt->pts + pkt->duration;
1233     else
1234         os->max_pts = FFMAX(os->max_pts, pkt->pts + pkt->duration);
1235     os->packets_written++;
1236     return ff_write_chained(os->ctx, 0, pkt, s, 0);
1237 }
1238
1239 static int dash_write_trailer(AVFormatContext *s)
1240 {
1241     DASHContext *c = s->priv_data;
1242
1243     if (s->nb_streams > 0) {
1244         OutputStream *os = &c->streams[0];
1245         // If no segments have been written so far, try to do a crude
1246         // guess of the segment duration
1247         if (!c->last_duration)
1248             c->last_duration = av_rescale_q(os->max_pts - os->start_pts,
1249                                             s->streams[0]->time_base,
1250                                             AV_TIME_BASE_Q);
1251         c->total_duration = av_rescale_q(os->max_pts - os->first_pts,
1252                                          s->streams[0]->time_base,
1253                                          AV_TIME_BASE_Q);
1254     }
1255     dash_flush(s, 1, -1);
1256
1257     if (c->remove_at_exit) {
1258         char filename[1024];
1259         int i;
1260         for (i = 0; i < s->nb_streams; i++) {
1261             OutputStream *os = &c->streams[i];
1262             snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
1263             unlink(filename);
1264         }
1265         unlink(s->filename);
1266     }
1267
1268     return 0;
1269 }
1270
1271 static int dash_check_bitstream(struct AVFormatContext *s, const AVPacket *avpkt)
1272 {
1273     DASHContext *c = s->priv_data;
1274     OutputStream *os = &c->streams[avpkt->stream_index];
1275     AVFormatContext *oc = os->ctx;
1276     if (oc->oformat->check_bitstream) {
1277         int ret;
1278         AVPacket pkt = *avpkt;
1279         pkt.stream_index = 0;
1280         ret = oc->oformat->check_bitstream(oc, &pkt);
1281         if (ret == 1) {
1282             AVStream *st = s->streams[avpkt->stream_index];
1283             AVStream *ost = oc->streams[0];
1284             st->internal->bsfcs = ost->internal->bsfcs;
1285             st->internal->nb_bsfcs = ost->internal->nb_bsfcs;
1286             ost->internal->bsfcs = NULL;
1287             ost->internal->nb_bsfcs = 0;
1288         }
1289         return ret;
1290     }
1291     return 1;
1292 }
1293
1294 #define OFFSET(x) offsetof(DASHContext, x)
1295 #define E AV_OPT_FLAG_ENCODING_PARAM
1296 static const AVOption options[] = {
1297     { "adaptation_sets", "Adaptation sets. Syntax: id=0,streams=0,1,2 id=1,streams=3,4 and so on", OFFSET(adaptation_sets), AV_OPT_TYPE_STRING, { 0 }, 0, 0, AV_OPT_FLAG_ENCODING_PARAM },
1298     { "window_size", "number of segments kept in the manifest", OFFSET(window_size), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, E },
1299     { "extra_window_size", "number of segments kept outside of the manifest before removing from disk", OFFSET(extra_window_size), AV_OPT_TYPE_INT, { .i64 = 5 }, 0, INT_MAX, E },
1300     { "min_seg_duration", "minimum segment duration (in microseconds)", OFFSET(min_seg_duration), AV_OPT_TYPE_INT, { .i64 = 5000000 }, 0, INT_MAX, E },
1301     { "remove_at_exit", "remove all segments when finished", OFFSET(remove_at_exit), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
1302     { "use_template", "Use SegmentTemplate instead of SegmentList", OFFSET(use_template), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, E },
1303     { "use_timeline", "Use SegmentTimeline in SegmentTemplate", OFFSET(use_timeline), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, E },
1304     { "single_file", "Store all segments in one file, accessed using byte ranges", OFFSET(single_file), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
1305     { "single_file_name", "DASH-templated name to be used for baseURL. Implies storing all segments in one file, accessed using byte ranges", OFFSET(single_file_name), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, E },
1306     { "init_seg_name", "DASH-templated name to used for the initialization segment", OFFSET(init_seg_name), AV_OPT_TYPE_STRING, {.str = "init-stream$RepresentationID$.m4s"}, 0, 0, E },
1307     { "media_seg_name", "DASH-templated name to used for the media segments", OFFSET(media_seg_name), AV_OPT_TYPE_STRING, {.str = "chunk-stream$RepresentationID$-$Number%05d$.m4s"}, 0, 0, E },
1308     { "utc_timing_url", "URL of the page that will return the UTC timestamp in ISO format", OFFSET(utc_timing_url), AV_OPT_TYPE_STRING, { 0 }, 0, 0, E },
1309     { "http_user_agent", "override User-Agent field in HTTP header", OFFSET(user_agent), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
1310     { "hls_playlist", "Generate HLS playlist files(master.m3u8, media_%d.m3u8)", OFFSET(hls_playlist), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
1311     { NULL },
1312 };
1313
1314 static const AVClass dash_class = {
1315     .class_name = "dash muxer",
1316     .item_name  = av_default_item_name,
1317     .option     = options,
1318     .version    = LIBAVUTIL_VERSION_INT,
1319 };
1320
1321 AVOutputFormat ff_dash_muxer = {
1322     .name           = "dash",
1323     .long_name      = NULL_IF_CONFIG_SMALL("DASH Muxer"),
1324     .extensions     = "mpd",
1325     .priv_data_size = sizeof(DASHContext),
1326     .audio_codec    = AV_CODEC_ID_AAC,
1327     .video_codec    = AV_CODEC_ID_H264,
1328     .flags          = AVFMT_GLOBALHEADER | AVFMT_NOFILE | AVFMT_TS_NEGATIVE,
1329     .init           = dash_init,
1330     .write_header   = dash_write_header,
1331     .write_packet   = dash_write_packet,
1332     .write_trailer  = dash_write_trailer,
1333     .deinit         = dash_free,
1334     .check_bitstream = dash_check_bitstream,
1335     .priv_class     = &dash_class,
1336 };