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