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