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