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