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