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