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