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