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