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