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