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