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