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