2 * MPEG-DASH ISO BMFF segmenter
3 * Copyright (c) 2014 Martin Storsjo
4 * Copyright (c) 2018 Akamai Technologies, Inc.
6 * This file is part of FFmpeg.
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.
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.
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
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_internal.h"
39 #include "avio_internal.h"
40 #include "hlsplaylist.h"
41 #if CONFIG_HTTP_PROTOCOL
46 #include "os_support.h"
50 typedef struct Segment {
53 int range_length, index_length;
59 typedef struct AdaptationSet {
61 enum AVMediaType media_type;
62 AVDictionary *metadata;
63 AVRational min_frame_rate, max_frame_rate;
64 int ambiguous_frame_rate;
67 typedef struct OutputStream {
69 int ctx_inited, as_idx;
74 int64_t init_start_pos, pos;
75 int init_range_length;
76 int nb_segments, segments_size, segment_index;
78 int64_t first_pts, start_pts, max_pts;
81 char bandwidth_str[64];
90 typedef struct DASHContext {
91 const AVClass *class; /* Class for private options. */
92 char *adaptation_sets;
96 int extra_window_size;
102 OutputStream *streams;
104 int64_t last_duration;
105 int64_t total_duration;
106 char availability_start_time[100];
108 const char *single_file_name;
109 const char *init_seg_name;
110 const char *media_seg_name;
111 const char *utc_timing_url;
113 const char *user_agent;
116 int master_playlist_created;
117 AVIOContext *mpd_out;
118 AVIOContext *m3u8_out;
122 static struct codec_string {
126 { AV_CODEC_ID_VP8, "vp8" },
127 { AV_CODEC_ID_VP9, "vp9" },
128 { AV_CODEC_ID_VORBIS, "vorbis" },
129 { AV_CODEC_ID_OPUS, "opus" },
133 static int dashenc_io_open(AVFormatContext *s, AVIOContext **pb, char *filename,
134 AVDictionary **options) {
135 DASHContext *c = s->priv_data;
136 int http_base_proto = filename ? ff_is_http_proto(filename) : 0;
137 int err = AVERROR_MUXER_NOT_FOUND;
138 if (!*pb || !http_base_proto || !c->http_persistent) {
139 err = s->io_open(s, pb, filename, AVIO_FLAG_WRITE, options);
140 #if CONFIG_HTTP_PROTOCOL
142 URLContext *http_url_context = ffio_geturlcontext(*pb);
143 av_assert0(http_url_context);
144 err = ff_http_do_new_request(http_url_context, filename);
150 static void dashenc_io_close(AVFormatContext *s, AVIOContext **pb, char *filename) {
151 DASHContext *c = s->priv_data;
152 int http_base_proto = filename ? ff_is_http_proto(filename) : 0;
154 if (!http_base_proto || !c->http_persistent) {
155 ff_format_io_close(s, pb);
156 #if CONFIG_HTTP_PROTOCOL
158 URLContext *http_url_context = ffio_geturlcontext(*pb);
159 av_assert0(http_url_context);
161 ffurl_shutdown(http_url_context, AVIO_FLAG_WRITE);
166 static void set_codec_str(AVFormatContext *s, AVCodecParameters *par,
169 const AVCodecTag *tags[2] = { NULL, NULL };
173 // common Webm codecs are not part of RFC 6381
174 for (i = 0; codecs[i].id; i++)
175 if (codecs[i].id == par->codec_id) {
176 av_strlcpy(str, codecs[i].str, size);
180 // for codecs part of RFC 6381
181 if (par->codec_type == AVMEDIA_TYPE_VIDEO)
182 tags[0] = ff_codec_movvideo_tags;
183 else if (par->codec_type == AVMEDIA_TYPE_AUDIO)
184 tags[0] = ff_codec_movaudio_tags;
188 tag = av_codec_get_tag(tags, par->codec_id);
196 if (!strcmp(str, "mp4a") || !strcmp(str, "mp4v")) {
198 tags[0] = ff_mp4_obj_type;
199 oti = av_codec_get_tag(tags, par->codec_id);
201 av_strlcatf(str, size, ".%02"PRIx32, oti);
205 if (tag == MKTAG('m', 'p', '4', 'a')) {
206 if (par->extradata_size >= 2) {
207 int aot = par->extradata[0] >> 3;
209 aot = ((AV_RB16(par->extradata) >> 5) & 0x3f) + 32;
210 av_strlcatf(str, size, ".%d", aot);
212 } else if (tag == MKTAG('m', 'p', '4', 'v')) {
213 // Unimplemented, should output ProfileLevelIndication as a decimal number
214 av_log(s, AV_LOG_WARNING, "Incomplete RFC 6381 codec string for mp4v\n");
216 } else if (!strcmp(str, "avc1")) {
217 uint8_t *tmpbuf = NULL;
218 uint8_t *extradata = par->extradata;
219 int extradata_size = par->extradata_size;
222 if (extradata[0] != 1) {
224 if (avio_open_dyn_buf(&pb) < 0)
226 if (ff_isom_write_avcc(pb, extradata, extradata_size) < 0) {
227 ffio_free_dyn_buf(&pb);
230 extradata_size = avio_close_dyn_buf(pb, &extradata);
234 if (extradata_size >= 4)
235 av_strlcatf(str, size, ".%02x%02x%02x",
236 extradata[1], extradata[2], extradata[3]);
241 static int flush_dynbuf(OutputStream *os, int *range_length)
246 return AVERROR(EINVAL);
250 av_write_frame(os->ctx, NULL);
251 avio_flush(os->ctx->pb);
254 *range_length = avio_close_dyn_buf(os->ctx->pb, &buffer);
256 avio_write(os->out, buffer + os->written_len, *range_length - os->written_len);
261 return avio_open_dyn_buf(&os->ctx->pb);
264 static void set_http_options(AVDictionary **options, DASHContext *c)
267 av_dict_set(options, "method", c->method, 0);
269 av_dict_set(options, "user_agent", c->user_agent, 0);
270 if (c->http_persistent)
271 av_dict_set_int(options, "multiple_requests", 1, 0);
274 static void get_hls_playlist_name(char *playlist_name, int string_size,
275 const char *base_url, int id) {
277 snprintf(playlist_name, string_size, "%smedia_%d.m3u8", base_url, id);
279 snprintf(playlist_name, string_size, "media_%d.m3u8", id);
282 static int flush_init_segment(AVFormatContext *s, OutputStream *os)
284 DASHContext *c = s->priv_data;
285 int ret, range_length;
287 ret = flush_dynbuf(os, &range_length);
291 os->pos = os->init_range_length = range_length;
293 ff_format_io_close(s, &os->out);
297 static void dash_free(AVFormatContext *s)
299 DASHContext *c = s->priv_data;
303 for (i = 0; i < c->nb_as; i++)
304 av_dict_free(&c->as[i].metadata);
311 for (i = 0; i < s->nb_streams; i++) {
312 OutputStream *os = &c->streams[i];
313 if (os->ctx && os->ctx_inited)
314 av_write_trailer(os->ctx);
315 if (os->ctx && os->ctx->pb)
316 ffio_free_dyn_buf(&os->ctx->pb);
317 ff_format_io_close(s, &os->out);
319 avformat_free_context(os->ctx);
320 for (j = 0; j < os->nb_segments; j++)
321 av_free(os->segments[j]);
322 av_free(os->segments);
324 av_freep(&c->streams);
326 ff_format_io_close(s, &c->mpd_out);
327 ff_format_io_close(s, &c->m3u8_out);
330 static void output_segment_list(OutputStream *os, AVIOContext *out, AVFormatContext *s,
331 int representation_id, int final)
333 DASHContext *c = s->priv_data;
334 int i, start_index = 0, start_number = 1;
335 if (c->window_size) {
336 start_index = FFMAX(os->nb_segments - c->window_size, 0);
337 start_number = FFMAX(os->segment_index - c->window_size, 1);
340 if (c->use_template) {
341 int timescale = c->use_timeline ? os->ctx->streams[0]->time_base.den : AV_TIME_BASE;
342 avio_printf(out, "\t\t\t\t<SegmentTemplate timescale=\"%d\" ", timescale);
343 if (!c->use_timeline)
344 avio_printf(out, "duration=\"%"PRId64"\" ", c->last_duration);
345 avio_printf(out, "initialization=\"%s\" media=\"%s\" startNumber=\"%d\">\n", c->init_seg_name, c->media_seg_name, c->use_timeline ? start_number : 1);
346 if (c->use_timeline) {
347 int64_t cur_time = 0;
348 avio_printf(out, "\t\t\t\t\t<SegmentTimeline>\n");
349 for (i = start_index; i < os->nb_segments; ) {
350 Segment *seg = os->segments[i];
352 avio_printf(out, "\t\t\t\t\t\t<S ");
353 if (i == start_index || seg->time != cur_time) {
354 cur_time = seg->time;
355 avio_printf(out, "t=\"%"PRId64"\" ", seg->time);
357 avio_printf(out, "d=\"%d\" ", seg->duration);
358 while (i + repeat + 1 < os->nb_segments &&
359 os->segments[i + repeat + 1]->duration == seg->duration &&
360 os->segments[i + repeat + 1]->time == os->segments[i + repeat]->time + os->segments[i + repeat]->duration)
363 avio_printf(out, "r=\"%d\" ", repeat);
364 avio_printf(out, "/>\n");
366 cur_time += (1 + repeat) * seg->duration;
368 avio_printf(out, "\t\t\t\t\t</SegmentTimeline>\n");
370 avio_printf(out, "\t\t\t\t</SegmentTemplate>\n");
371 } else if (c->single_file) {
372 avio_printf(out, "\t\t\t\t<BaseURL>%s</BaseURL>\n", os->initfile);
373 avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%"PRId64"\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);
374 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);
375 for (i = start_index; i < os->nb_segments; i++) {
376 Segment *seg = os->segments[i];
377 avio_printf(out, "\t\t\t\t\t<SegmentURL mediaRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->range_length - 1);
378 if (seg->index_length)
379 avio_printf(out, "indexRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->index_length - 1);
380 avio_printf(out, "/>\n");
382 avio_printf(out, "\t\t\t\t</SegmentList>\n");
384 avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%"PRId64"\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);
385 avio_printf(out, "\t\t\t\t\t<Initialization sourceURL=\"%s\" />\n", os->initfile);
386 for (i = start_index; i < os->nb_segments; i++) {
387 Segment *seg = os->segments[i];
388 avio_printf(out, "\t\t\t\t\t<SegmentURL media=\"%s\" />\n", seg->file);
390 avio_printf(out, "\t\t\t\t</SegmentList>\n");
392 if (c->hls_playlist && start_index < os->nb_segments)
394 int timescale = os->ctx->streams[0]->time_base.den;
395 char temp_filename_hls[1024];
396 char filename_hls[1024];
397 AVDictionary *http_opts = NULL;
398 int target_duration = 0;
400 const char *proto = avio_find_protocol_name(c->dirname);
401 int use_rename = proto && !strcmp(proto, "file");
403 get_hls_playlist_name(filename_hls, sizeof(filename_hls),
404 c->dirname, representation_id);
406 snprintf(temp_filename_hls, sizeof(temp_filename_hls), use_rename ? "%s.tmp" : "%s", filename_hls);
408 set_http_options(&http_opts, c);
409 dashenc_io_open(s, &c->m3u8_out, temp_filename_hls, &http_opts);
410 av_dict_free(&http_opts);
411 for (i = start_index; i < os->nb_segments; i++) {
412 Segment *seg = os->segments[i];
413 double duration = (double) seg->duration / timescale;
414 if (target_duration <= duration)
415 target_duration = lrint(duration);
418 ff_hls_write_playlist_header(c->m3u8_out, 6, -1, target_duration,
419 start_number, PLAYLIST_TYPE_NONE);
421 ff_hls_write_init_file(c->m3u8_out, os->initfile, c->single_file,
422 os->init_range_length, os->init_start_pos);
424 for (i = start_index; i < os->nb_segments; i++) {
425 Segment *seg = os->segments[i];
426 ret = ff_hls_write_file_entry(c->m3u8_out, 0, c->single_file,
427 (double) seg->duration / timescale, 0,
428 seg->range_length, seg->start_pos, NULL,
429 c->single_file ? os->initfile : seg->file,
432 av_log(os->ctx, AV_LOG_WARNING, "ff_hls_write_file_entry get error\n");
437 ff_hls_write_end_list(c->m3u8_out);
439 dashenc_io_close(s, &c->m3u8_out, temp_filename_hls);
442 if (avpriv_io_move(temp_filename_hls, filename_hls) < 0) {
443 av_log(os->ctx, AV_LOG_WARNING, "renaming file %s to %s failed\n\n", temp_filename_hls, filename_hls);
449 static char *xmlescape(const char *str) {
450 int outlen = strlen(str)*3/2 + 6;
451 char *out = av_realloc(NULL, outlen + 1);
455 for (; *str; str++) {
456 if (pos + 6 > outlen) {
458 outlen = 2 * outlen + 6;
459 tmp = av_realloc(out, outlen + 1);
467 memcpy(&out[pos], "&", 5);
469 } else if (*str == '<') {
470 memcpy(&out[pos], "<", 4);
472 } else if (*str == '>') {
473 memcpy(&out[pos], ">", 4);
475 } else if (*str == '\'') {
476 memcpy(&out[pos], "'", 6);
478 } else if (*str == '\"') {
479 memcpy(&out[pos], """, 6);
489 static void write_time(AVIOContext *out, int64_t time)
491 int seconds = time / AV_TIME_BASE;
492 int fractions = time % AV_TIME_BASE;
493 int minutes = seconds / 60;
494 int hours = minutes / 60;
497 avio_printf(out, "PT");
499 avio_printf(out, "%dH", hours);
500 if (hours || minutes)
501 avio_printf(out, "%dM", minutes);
502 avio_printf(out, "%d.%dS", seconds, fractions / (AV_TIME_BASE / 10));
505 static void format_date_now(char *buf, int size)
507 time_t t = time(NULL);
508 struct tm *ptm, tmbuf;
509 ptm = gmtime_r(&t, &tmbuf);
511 if (!strftime(buf, size, "%Y-%m-%dT%H:%M:%SZ", ptm))
516 static int write_adaptation_set(AVFormatContext *s, AVIOContext *out, int as_index,
519 DASHContext *c = s->priv_data;
520 AdaptationSet *as = &c->as[as_index];
521 AVDictionaryEntry *lang, *role;
524 avio_printf(out, "\t\t<AdaptationSet id=\"%s\" contentType=\"%s\" segmentAlignment=\"true\" bitstreamSwitching=\"true\"",
525 as->id, as->media_type == AVMEDIA_TYPE_VIDEO ? "video" : "audio");
526 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)
527 avio_printf(out, " maxFrameRate=\"%d/%d\"", as->max_frame_rate.num, as->max_frame_rate.den);
528 lang = av_dict_get(as->metadata, "language", NULL, 0);
530 avio_printf(out, " lang=\"%s\"", lang->value);
531 avio_printf(out, ">\n");
533 role = av_dict_get(as->metadata, "role", NULL, 0);
535 avio_printf(out, "\t\t\t<Role schemeIdUri=\"urn:mpeg:dash:role:2011\" value=\"%s\"/>\n", role->value);
537 for (i = 0; i < s->nb_streams; i++) {
538 OutputStream *os = &c->streams[i];
540 if (os->as_idx - 1 != as_index)
543 if (as->media_type == AVMEDIA_TYPE_VIDEO) {
544 AVStream *st = s->streams[i];
545 avio_printf(out, "\t\t\t<Representation id=\"%d\" mimeType=\"video/%s\" codecs=\"%s\"%s width=\"%d\" height=\"%d\"",
546 i, os->format_name, os->codec_str, os->bandwidth_str, s->streams[i]->codecpar->width, s->streams[i]->codecpar->height);
547 if (st->avg_frame_rate.num)
548 avio_printf(out, " frameRate=\"%d/%d\"", st->avg_frame_rate.num, st->avg_frame_rate.den);
549 avio_printf(out, ">\n");
551 avio_printf(out, "\t\t\t<Representation id=\"%d\" mimeType=\"audio/%s\" codecs=\"%s\"%s audioSamplingRate=\"%d\">\n",
552 i, os->format_name, os->codec_str, os->bandwidth_str, s->streams[i]->codecpar->sample_rate);
553 avio_printf(out, "\t\t\t\t<AudioChannelConfiguration schemeIdUri=\"urn:mpeg:dash:23003:3:audio_channel_configuration:2011\" value=\"%d\" />\n",
554 s->streams[i]->codecpar->channels);
556 output_segment_list(os, out, s, i, final);
557 avio_printf(out, "\t\t\t</Representation>\n");
559 avio_printf(out, "\t\t</AdaptationSet>\n");
564 static int add_adaptation_set(AVFormatContext *s, AdaptationSet **as, enum AVMediaType type)
566 DASHContext *c = s->priv_data;
568 void *mem = av_realloc(c->as, sizeof(*c->as) * (c->nb_as + 1));
570 return AVERROR(ENOMEM);
574 *as = &c->as[c->nb_as - 1];
575 memset(*as, 0, sizeof(**as));
576 (*as)->media_type = type;
581 static int adaptation_set_add_stream(AVFormatContext *s, int as_idx, int i)
583 DASHContext *c = s->priv_data;
584 AdaptationSet *as = &c->as[as_idx - 1];
585 OutputStream *os = &c->streams[i];
587 if (as->media_type != s->streams[i]->codecpar->codec_type) {
588 av_log(s, AV_LOG_ERROR, "Codec type of stream %d doesn't match AdaptationSet's media type\n", i);
589 return AVERROR(EINVAL);
590 } else if (os->as_idx) {
591 av_log(s, AV_LOG_ERROR, "Stream %d is already assigned to an AdaptationSet\n", i);
592 return AVERROR(EINVAL);
599 static int parse_adaptation_sets(AVFormatContext *s)
601 DASHContext *c = s->priv_data;
602 const char *p = c->adaptation_sets;
603 enum { new_set, parse_id, parsing_streams } state;
607 // default: one AdaptationSet for each stream
609 for (i = 0; i < s->nb_streams; i++) {
610 if ((ret = add_adaptation_set(s, &as, s->streams[i]->codecpar->codec_type)) < 0)
612 snprintf(as->id, sizeof(as->id), "%d", i);
614 c->streams[i].as_idx = c->nb_as;
619 // syntax id=0,streams=0,1,2 id=1,streams=3,4 and so on
625 } else if (state == new_set && av_strstart(p, "id=", &p)) {
627 if ((ret = add_adaptation_set(s, &as, AVMEDIA_TYPE_UNKNOWN)) < 0)
631 snprintf(as->id, sizeof(as->id), "%.*s", n, p);
637 } else if (state == parse_id && av_strstart(p, "streams=", &p)) {
638 state = parsing_streams;
639 } else if (state == parsing_streams) {
640 AdaptationSet *as = &c->as[c->nb_as - 1];
641 char idx_str[8], *end_str;
643 n = strcspn(p, " ,");
644 snprintf(idx_str, sizeof(idx_str), "%.*s", n, p);
647 // if value is "a" or "v", map all streams of that type
648 if (as->media_type == AVMEDIA_TYPE_UNKNOWN && (idx_str[0] == 'v' || idx_str[0] == 'a')) {
649 enum AVMediaType type = (idx_str[0] == 'v') ? AVMEDIA_TYPE_VIDEO : AVMEDIA_TYPE_AUDIO;
650 av_log(s, AV_LOG_DEBUG, "Map all streams of type %s\n", idx_str);
652 for (i = 0; i < s->nb_streams; i++) {
653 if (s->streams[i]->codecpar->codec_type != type)
656 as->media_type = s->streams[i]->codecpar->codec_type;
658 if ((ret = adaptation_set_add_stream(s, c->nb_as, i)) < 0)
661 } else { // select single stream
662 i = strtol(idx_str, &end_str, 10);
663 if (idx_str == end_str || i < 0 || i >= s->nb_streams) {
664 av_log(s, AV_LOG_ERROR, "Selected stream \"%s\" not found!\n", idx_str);
665 return AVERROR(EINVAL);
667 av_log(s, AV_LOG_DEBUG, "Map stream %d\n", i);
669 if (as->media_type == AVMEDIA_TYPE_UNKNOWN) {
670 as->media_type = s->streams[i]->codecpar->codec_type;
673 if ((ret = adaptation_set_add_stream(s, c->nb_as, i)) < 0)
682 return AVERROR(EINVAL);
687 // check for unassigned streams
688 for (i = 0; i < s->nb_streams; i++) {
689 OutputStream *os = &c->streams[i];
691 av_log(s, AV_LOG_ERROR, "Stream %d is not mapped to an AdaptationSet\n", i);
692 return AVERROR(EINVAL);
698 static int write_manifest(AVFormatContext *s, int final)
700 DASHContext *c = s->priv_data;
702 char temp_filename[1024];
704 const char *proto = avio_find_protocol_name(s->url);
705 int use_rename = proto && !strcmp(proto, "file");
706 static unsigned int warned_non_file = 0;
707 AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
708 AVDictionary *opts = NULL;
710 if (!use_rename && !warned_non_file++)
711 av_log(s, AV_LOG_ERROR, "Cannot use rename on non file protocol, this may lead to races and temporary partial files\n");
713 snprintf(temp_filename, sizeof(temp_filename), use_rename ? "%s.tmp" : "%s", s->url);
714 set_http_options(&opts, c);
715 ret = dashenc_io_open(s, &c->mpd_out, temp_filename, &opts);
717 av_log(s, AV_LOG_ERROR, "Unable to open %s for writing\n", temp_filename);
722 avio_printf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
723 avio_printf(out, "<MPD xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
724 "\txmlns=\"urn:mpeg:dash:schema:mpd:2011\"\n"
725 "\txmlns:xlink=\"http://www.w3.org/1999/xlink\"\n"
726 "\txsi:schemaLocation=\"urn:mpeg:DASH:schema:MPD:2011 http://standards.iso.org/ittf/PubliclyAvailableStandards/MPEG-DASH_schema_files/DASH-MPD.xsd\"\n"
727 "\tprofiles=\"urn:mpeg:dash:profile:isoff-live:2011\"\n"
728 "\ttype=\"%s\"\n", final ? "static" : "dynamic");
730 avio_printf(out, "\tmediaPresentationDuration=\"");
731 write_time(out, c->total_duration);
732 avio_printf(out, "\"\n");
734 int64_t update_period = c->last_duration / AV_TIME_BASE;
736 if (c->use_template && !c->use_timeline)
738 avio_printf(out, "\tminimumUpdatePeriod=\"PT%"PRId64"S\"\n", update_period);
739 avio_printf(out, "\tsuggestedPresentationDelay=\"PT%"PRId64"S\"\n", c->last_duration / AV_TIME_BASE);
740 if (!c->availability_start_time[0] && s->nb_streams > 0 && c->streams[0].nb_segments > 0) {
741 format_date_now(c->availability_start_time, sizeof(c->availability_start_time));
743 if (c->availability_start_time[0])
744 avio_printf(out, "\tavailabilityStartTime=\"%s\"\n", c->availability_start_time);
745 format_date_now(now_str, sizeof(now_str));
747 avio_printf(out, "\tpublishTime=\"%s\"\n", now_str);
748 if (c->window_size && c->use_template) {
749 avio_printf(out, "\ttimeShiftBufferDepth=\"");
750 write_time(out, c->last_duration * c->window_size);
751 avio_printf(out, "\"\n");
754 avio_printf(out, "\tminBufferTime=\"");
755 write_time(out, c->last_duration * 2);
756 avio_printf(out, "\">\n");
757 avio_printf(out, "\t<ProgramInformation>\n");
759 char *escaped = xmlescape(title->value);
760 avio_printf(out, "\t\t<Title>%s</Title>\n", escaped);
763 avio_printf(out, "\t</ProgramInformation>\n");
765 if (c->window_size && s->nb_streams > 0 && c->streams[0].nb_segments > 0 && !c->use_template) {
766 OutputStream *os = &c->streams[0];
767 int start_index = FFMAX(os->nb_segments - c->window_size, 0);
768 int64_t start_time = av_rescale_q(os->segments[start_index]->time, s->streams[0]->time_base, AV_TIME_BASE_Q);
769 avio_printf(out, "\t<Period id=\"0\" start=\"");
770 write_time(out, start_time);
771 avio_printf(out, "\">\n");
773 avio_printf(out, "\t<Period id=\"0\" start=\"PT0.0S\">\n");
776 for (i = 0; i < c->nb_as; i++) {
777 if ((ret = write_adaptation_set(s, out, i, final)) < 0)
780 avio_printf(out, "\t</Period>\n");
782 if (c->utc_timing_url)
783 avio_printf(out, "\t<UTCTiming schemeIdUri=\"urn:mpeg:dash:utc:http-xsdate:2014\" value=\"%s\"/>\n", c->utc_timing_url);
785 avio_printf(out, "</MPD>\n");
787 dashenc_io_close(s, &c->mpd_out, temp_filename);
790 if ((ret = avpriv_io_move(temp_filename, s->url)) < 0)
794 if (c->hls_playlist && !c->master_playlist_created) {
795 char filename_hls[1024];
796 const char *audio_group = "A1";
798 int max_audio_bitrate = 0;
801 snprintf(filename_hls, sizeof(filename_hls), "%s/master.m3u8", c->dirname);
803 snprintf(filename_hls, sizeof(filename_hls), "master.m3u8");
805 snprintf(temp_filename, sizeof(temp_filename), use_rename ? "%s.tmp" : "%s", filename_hls);
807 set_http_options(&opts, c);
808 ret = avio_open2(&out, temp_filename, AVIO_FLAG_WRITE, NULL, &opts);
810 av_log(s, AV_LOG_ERROR, "Unable to open %s for writing\n", temp_filename);
815 ff_hls_write_playlist_version(out, 6);
817 for (i = 0; i < s->nb_streams; i++) {
818 char playlist_file[64];
819 AVStream *st = s->streams[i];
820 if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO)
822 get_hls_playlist_name(playlist_file, sizeof(playlist_file), NULL, i);
823 ff_hls_write_audio_rendition(out, (char *)audio_group,
824 playlist_file, i, is_default);
825 max_audio_bitrate = FFMAX(st->codecpar->bit_rate, max_audio_bitrate);
829 for (i = 0; i < s->nb_streams; i++) {
830 char playlist_file[64];
831 AVStream *st = s->streams[i];
833 int stream_bitrate = st->codecpar->bit_rate;
834 if ((st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) && max_audio_bitrate) {
835 agroup = (char *)audio_group;
836 stream_bitrate += max_audio_bitrate;
838 get_hls_playlist_name(playlist_file, sizeof(playlist_file), NULL, i);
839 ff_hls_write_stream_info(st, out, stream_bitrate, playlist_file, agroup, NULL, NULL);
843 if ((ret = avpriv_io_move(temp_filename, filename_hls)) < 0)
845 c->master_playlist_created = 1;
851 static int dict_copy_entry(AVDictionary **dst, const AVDictionary *src, const char *key)
853 AVDictionaryEntry *entry = av_dict_get(src, key, NULL, 0);
855 av_dict_set(dst, key, entry->value, AV_DICT_DONT_OVERWRITE);
859 static int dash_init(AVFormatContext *s)
861 DASHContext *c = s->priv_data;
866 if (c->single_file_name)
871 av_strlcpy(c->dirname, s->url, sizeof(c->dirname));
872 ptr = strrchr(c->dirname, '/');
874 av_strlcpy(basename, &ptr[1], sizeof(basename));
877 c->dirname[0] = '\0';
878 av_strlcpy(basename, s->url, sizeof(basename));
881 ptr = strrchr(basename, '.');
885 c->streams = av_mallocz(sizeof(*c->streams) * s->nb_streams);
887 return AVERROR(ENOMEM);
889 if ((ret = parse_adaptation_sets(s)) < 0)
892 for (i = 0; i < s->nb_streams; i++) {
893 OutputStream *os = &c->streams[i];
894 AdaptationSet *as = &c->as[os->as_idx - 1];
895 AVFormatContext *ctx;
897 AVDictionary *opts = NULL;
900 os->bit_rate = s->streams[i]->codecpar->bit_rate;
902 snprintf(os->bandwidth_str, sizeof(os->bandwidth_str),
903 " bandwidth=\"%d\"", os->bit_rate);
905 int level = s->strict_std_compliance >= FF_COMPLIANCE_STRICT ?
906 AV_LOG_ERROR : AV_LOG_WARNING;
907 av_log(s, level, "No bit rate set for stream %d\n", i);
908 if (s->strict_std_compliance >= FF_COMPLIANCE_STRICT)
909 return AVERROR(EINVAL);
912 // copy AdaptationSet language and role from stream metadata
913 dict_copy_entry(&as->metadata, s->streams[i]->metadata, "language");
914 dict_copy_entry(&as->metadata, s->streams[i]->metadata, "role");
916 ctx = avformat_alloc_context();
918 return AVERROR(ENOMEM);
920 // choose muxer based on codec: webm for VP8/9 and opus, mp4 otherwise
921 // note: os->format_name is also used as part of the mimetype of the
922 // representation, e.g. video/<format_name>
923 if (s->streams[i]->codecpar->codec_id == AV_CODEC_ID_VP8 ||
924 s->streams[i]->codecpar->codec_id == AV_CODEC_ID_VP9 ||
925 s->streams[i]->codecpar->codec_id == AV_CODEC_ID_OPUS ||
926 s->streams[i]->codecpar->codec_id == AV_CODEC_ID_VORBIS) {
927 snprintf(os->format_name, sizeof(os->format_name), "webm");
929 snprintf(os->format_name, sizeof(os->format_name), "mp4");
931 ctx->oformat = av_guess_format(os->format_name, NULL, NULL);
933 return AVERROR_MUXER_NOT_FOUND;
935 ctx->interrupt_callback = s->interrupt_callback;
936 ctx->opaque = s->opaque;
937 ctx->io_close = s->io_close;
938 ctx->io_open = s->io_open;
940 if (!(st = avformat_new_stream(ctx, NULL)))
941 return AVERROR(ENOMEM);
942 avcodec_parameters_copy(st->codecpar, s->streams[i]->codecpar);
943 st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
944 st->time_base = s->streams[i]->time_base;
945 st->avg_frame_rate = s->streams[i]->avg_frame_rate;
946 ctx->avoid_negative_ts = s->avoid_negative_ts;
947 ctx->flags = s->flags;
949 if ((ret = avio_open_dyn_buf(&ctx->pb)) < 0)
952 if (c->single_file) {
953 if (c->single_file_name)
954 ff_dash_fill_tmpl_params(os->initfile, sizeof(os->initfile), c->single_file_name, i, 0, os->bit_rate, 0);
956 snprintf(os->initfile, sizeof(os->initfile), "%s-stream%d.m4s", basename, i);
958 ff_dash_fill_tmpl_params(os->initfile, sizeof(os->initfile), c->init_seg_name, i, 0, os->bit_rate, 0);
960 snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
961 set_http_options(&opts, c);
962 ret = s->io_open(s, &os->out, filename, AVIO_FLAG_WRITE, &opts);
966 os->init_start_pos = 0;
968 if (!strcmp(os->format_name, "mp4")) {
970 av_dict_set(&opts, "movflags", "frag_every_frame+dash+delay_moov", 0);
972 av_dict_set(&opts, "movflags", "frag_custom+dash+delay_moov", 0);
974 av_dict_set_int(&opts, "cluster_time_limit", c->min_seg_duration / 1000, 0);
975 av_dict_set_int(&opts, "cluster_size_limit", 5 * 1024 * 1024, 0); // set a large cluster size limit
976 av_dict_set_int(&opts, "dash", 1, 0);
977 av_dict_set_int(&opts, "dash_track_number", i + 1, 0);
978 av_dict_set_int(&opts, "live", 1, 0);
980 if ((ret = avformat_init_output(ctx, &opts)) < 0)
986 av_log(s, AV_LOG_VERBOSE, "Representation %d init segment will be written to: %s\n", i, filename);
988 // Flush init segment
989 // except for mp4, since delay_moov is set and the init segment
990 // is then flushed after the first packets
991 if (strcmp(os->format_name, "mp4")) {
992 flush_init_segment(s, os);
995 s->streams[i]->time_base = st->time_base;
996 // If the muxer wants to shift timestamps, request to have them shifted
997 // already before being handed to this muxer, so we don't have mismatches
998 // between the MPD and the actual segments.
999 s->avoid_negative_ts = ctx->avoid_negative_ts;
1000 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
1001 AVRational avg_frame_rate = s->streams[i]->avg_frame_rate;
1002 if (avg_frame_rate.num > 0) {
1003 if (av_cmp_q(avg_frame_rate, as->min_frame_rate) < 0)
1004 as->min_frame_rate = avg_frame_rate;
1005 if (av_cmp_q(as->max_frame_rate, avg_frame_rate) < 0)
1006 as->max_frame_rate = avg_frame_rate;
1008 as->ambiguous_frame_rate = 1;
1013 set_codec_str(s, st->codecpar, os->codec_str, sizeof(os->codec_str));
1014 os->first_pts = AV_NOPTS_VALUE;
1015 os->max_pts = AV_NOPTS_VALUE;
1016 os->last_dts = AV_NOPTS_VALUE;
1017 os->segment_index = 1;
1020 if (!c->has_video && c->min_seg_duration <= 0) {
1021 av_log(s, AV_LOG_WARNING, "no video stream and no min seg duration set\n");
1022 return AVERROR(EINVAL);
1027 static int dash_write_header(AVFormatContext *s)
1029 DASHContext *c = s->priv_data;
1031 for (i = 0; i < s->nb_streams; i++) {
1032 OutputStream *os = &c->streams[i];
1033 if ((ret = avformat_write_header(os->ctx, NULL)) < 0) {
1038 ret = write_manifest(s, 0);
1040 av_log(s, AV_LOG_VERBOSE, "Manifest written to: %s\n", s->url);
1044 static int add_segment(OutputStream *os, const char *file,
1045 int64_t time, int duration,
1046 int64_t start_pos, int64_t range_length,
1047 int64_t index_length)
1051 if (os->nb_segments >= os->segments_size) {
1052 os->segments_size = (os->segments_size + 1) * 2;
1053 if ((err = av_reallocp(&os->segments, sizeof(*os->segments) *
1054 os->segments_size)) < 0) {
1055 os->segments_size = 0;
1056 os->nb_segments = 0;
1060 seg = av_mallocz(sizeof(*seg));
1062 return AVERROR(ENOMEM);
1063 av_strlcpy(seg->file, file, sizeof(seg->file));
1065 seg->duration = duration;
1066 if (seg->time < 0) { // If pts<0, it is expected to be cut away with an edit list
1067 seg->duration += seg->time;
1070 seg->start_pos = start_pos;
1071 seg->range_length = range_length;
1072 seg->index_length = index_length;
1073 os->segments[os->nb_segments++] = seg;
1074 os->segment_index++;
1078 static void write_styp(AVIOContext *pb)
1081 ffio_wfourcc(pb, "styp");
1082 ffio_wfourcc(pb, "msdh");
1083 avio_wb32(pb, 0); /* minor */
1084 ffio_wfourcc(pb, "msdh");
1085 ffio_wfourcc(pb, "msix");
1088 static void find_index_range(AVFormatContext *s, const char *full_path,
1089 int64_t pos, int *index_length)
1095 ret = s->io_open(s, &pb, full_path, AVIO_FLAG_READ, NULL);
1098 if (avio_seek(pb, pos, SEEK_SET) != pos) {
1099 ff_format_io_close(s, &pb);
1102 ret = avio_read(pb, buf, 8);
1103 ff_format_io_close(s, &pb);
1106 if (AV_RL32(&buf[4]) != MKTAG('s', 'i', 'd', 'x'))
1108 *index_length = AV_RB32(&buf[0]);
1111 static int update_stream_extradata(AVFormatContext *s, OutputStream *os,
1112 AVCodecParameters *par)
1116 if (os->ctx->streams[0]->codecpar->extradata_size || !par->extradata_size)
1119 extradata = av_malloc(par->extradata_size);
1122 return AVERROR(ENOMEM);
1124 memcpy(extradata, par->extradata, par->extradata_size);
1126 os->ctx->streams[0]->codecpar->extradata = extradata;
1127 os->ctx->streams[0]->codecpar->extradata_size = par->extradata_size;
1129 set_codec_str(s, par, os->codec_str, sizeof(os->codec_str));
1134 static void dashenc_delete_file(AVFormatContext *s, char *filename) {
1135 DASHContext *c = s->priv_data;
1136 int http_base_proto = ff_is_http_proto(filename);
1138 if (http_base_proto) {
1139 AVIOContext *out = NULL;
1140 AVDictionary *http_opts = NULL;
1142 set_http_options(&http_opts, c);
1143 av_dict_set(&http_opts, "method", "DELETE", 0);
1145 if (dashenc_io_open(s, &out, filename, &http_opts) < 0) {
1146 av_log(s, AV_LOG_ERROR, "failed to delete %s\n", filename);
1149 av_dict_free(&http_opts);
1150 dashenc_io_close(s, &out, filename);
1151 } else if (unlink(filename) < 0) {
1152 av_log(s, AV_LOG_ERROR, "failed to delete %s: %s\n", filename, strerror(errno));
1156 static int dash_flush(AVFormatContext *s, int final, int stream)
1158 DASHContext *c = s->priv_data;
1161 const char *proto = avio_find_protocol_name(s->url);
1162 int use_rename = proto && !strcmp(proto, "file");
1164 int cur_flush_segment_index = 0;
1166 cur_flush_segment_index = c->streams[stream].segment_index;
1168 for (i = 0; i < s->nb_streams; i++) {
1169 OutputStream *os = &c->streams[i];
1170 AVStream *st = s->streams[i];
1171 int range_length, index_length = 0;
1173 if (!os->packets_written)
1176 // Flush the single stream that got a keyframe right now.
1177 // Flush all audio streams as well, in sync with video keyframes,
1178 // but not the other video streams.
1179 if (stream >= 0 && i != stream) {
1180 if (s->streams[i]->codecpar->codec_type != AVMEDIA_TYPE_AUDIO)
1182 // Make sure we don't flush audio streams multiple times, when
1183 // all video streams are flushed one at a time.
1184 if (c->has_video && os->segment_index > cur_flush_segment_index)
1188 if (!c->single_file) {
1189 if (!strcmp(os->format_name, "mp4") && !os->written_len)
1190 write_styp(os->ctx->pb);
1192 snprintf(os->full_path, sizeof(os->full_path), "%s%s", c->dirname, os->initfile);
1195 ret = flush_dynbuf(os, &range_length);
1198 os->packets_written = 0;
1200 if (c->single_file) {
1201 find_index_range(s, os->full_path, os->pos, &index_length);
1203 dashenc_io_close(s, &os->out, os->temp_path);
1206 ret = avpriv_io_move(os->temp_path, os->full_path);
1212 if (!os->bit_rate) {
1213 // calculate average bitrate of first segment
1214 int64_t bitrate = (int64_t) range_length * 8 * AV_TIME_BASE / av_rescale_q(os->max_pts - os->start_pts,
1218 os->bit_rate = bitrate;
1219 snprintf(os->bandwidth_str, sizeof(os->bandwidth_str),
1220 " bandwidth=\"%d\"", os->bit_rate);
1223 add_segment(os, os->filename, os->start_pts, os->max_pts - os->start_pts, os->pos, range_length, index_length);
1224 av_log(s, AV_LOG_VERBOSE, "Representation %d media segment %d written to: %s\n", i, os->segment_index, os->full_path);
1226 os->pos += range_length;
1229 if (c->window_size || (final && c->remove_at_exit)) {
1230 for (i = 0; i < s->nb_streams; i++) {
1231 OutputStream *os = &c->streams[i];
1233 int remove = os->nb_segments - c->window_size - c->extra_window_size;
1234 if (final && c->remove_at_exit)
1235 remove = os->nb_segments;
1237 for (j = 0; j < remove; j++) {
1238 char filename[1024];
1239 snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->segments[j]->file);
1240 dashenc_delete_file(s, filename);
1241 av_free(os->segments[j]);
1243 os->nb_segments -= remove;
1244 memmove(os->segments, os->segments + remove, os->nb_segments * sizeof(*os->segments));
1250 ret = write_manifest(s, final);
1254 static int dash_write_packet(AVFormatContext *s, AVPacket *pkt)
1256 DASHContext *c = s->priv_data;
1257 AVStream *st = s->streams[pkt->stream_index];
1258 OutputStream *os = &c->streams[pkt->stream_index];
1261 ret = update_stream_extradata(s, os, st->codecpar);
1265 // Fill in a heuristic guess of the packet duration, if none is available.
1266 // The mp4 muxer will do something similar (for the last packet in a fragment)
1267 // if nothing is set (setting it for the other packets doesn't hurt).
1268 // By setting a nonzero duration here, we can be sure that the mp4 muxer won't
1269 // invoke its heuristic (this doesn't have to be identical to that algorithm),
1270 // so that we know the exact timestamps of fragments.
1271 if (!pkt->duration && os->last_dts != AV_NOPTS_VALUE)
1272 pkt->duration = pkt->dts - os->last_dts;
1273 os->last_dts = pkt->dts;
1275 // If forcing the stream to start at 0, the mp4 muxer will set the start
1276 // timestamps to 0. Do the same here, to avoid mismatches in duration/timestamps.
1277 if (os->first_pts == AV_NOPTS_VALUE &&
1278 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
1279 pkt->pts -= pkt->dts;
1283 if (os->first_pts == AV_NOPTS_VALUE)
1284 os->first_pts = pkt->pts;
1286 if ((!c->has_video || st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) &&
1287 pkt->flags & AV_PKT_FLAG_KEY && os->packets_written &&
1288 av_compare_ts(pkt->pts - os->start_pts, st->time_base,
1289 c->min_seg_duration, AV_TIME_BASE_Q) >= 0) {
1290 int64_t prev_duration = c->last_duration;
1292 c->last_duration = av_rescale_q(pkt->pts - os->start_pts,
1295 c->total_duration = av_rescale_q(pkt->pts - os->first_pts,
1299 if ((!c->use_timeline || !c->use_template) && prev_duration) {
1300 if (c->last_duration < prev_duration*9/10 ||
1301 c->last_duration > prev_duration*11/10) {
1302 av_log(s, AV_LOG_WARNING,
1303 "Segment durations differ too much, enable use_timeline "
1304 "and use_template, or keep a stricter keyframe interval\n");
1308 if ((ret = dash_flush(s, 0, pkt->stream_index)) < 0)
1312 if (!os->packets_written) {
1313 // If we wrote a previous segment, adjust the start time of the segment
1314 // to the end of the previous one (which is the same as the mp4 muxer
1315 // does). This avoids gaps in the timeline.
1316 if (os->max_pts != AV_NOPTS_VALUE)
1317 os->start_pts = os->max_pts;
1319 os->start_pts = pkt->pts;
1321 if (os->max_pts == AV_NOPTS_VALUE)
1322 os->max_pts = pkt->pts + pkt->duration;
1324 os->max_pts = FFMAX(os->max_pts, pkt->pts + pkt->duration);
1325 os->packets_written++;
1326 if ((ret = ff_write_chained(os->ctx, 0, pkt, s, 0)) < 0)
1329 if (!os->init_range_length)
1330 flush_init_segment(s, os);
1332 //open the output context when the first frame of a segment is ready
1333 if (!c->single_file && os->packets_written == 1) {
1334 AVDictionary *opts = NULL;
1335 const char *proto = avio_find_protocol_name(s->url);
1336 int use_rename = proto && !strcmp(proto, "file");
1337 os->filename[0] = os->full_path[0] = os->temp_path[0] = '\0';
1338 ff_dash_fill_tmpl_params(os->filename, sizeof(os->filename),
1339 c->media_seg_name, pkt->stream_index,
1340 os->segment_index, os->bit_rate, os->start_pts);
1341 snprintf(os->full_path, sizeof(os->full_path), "%s%s", c->dirname,
1343 snprintf(os->temp_path, sizeof(os->temp_path),
1344 use_rename ? "%s.tmp" : "%s", os->full_path);
1345 set_http_options(&opts, c);
1346 ret = dashenc_io_open(s, &os->out, os->temp_path, &opts);
1349 av_dict_free(&opts);
1352 //write out the data immediately in streaming mode
1353 if (c->streaming && !strcmp(os->format_name, "mp4")) {
1355 uint8_t *buf = NULL;
1356 if (!os->written_len)
1357 write_styp(os->ctx->pb);
1358 avio_flush(os->ctx->pb);
1359 len = avio_get_dyn_buf (os->ctx->pb, &buf);
1360 avio_write(os->out, buf + os->written_len, len - os->written_len);
1361 os->written_len = len;
1362 avio_flush(os->out);
1368 static int dash_write_trailer(AVFormatContext *s)
1370 DASHContext *c = s->priv_data;
1372 if (s->nb_streams > 0) {
1373 OutputStream *os = &c->streams[0];
1374 // If no segments have been written so far, try to do a crude
1375 // guess of the segment duration
1376 if (!c->last_duration)
1377 c->last_duration = av_rescale_q(os->max_pts - os->start_pts,
1378 s->streams[0]->time_base,
1380 c->total_duration = av_rescale_q(os->max_pts - os->first_pts,
1381 s->streams[0]->time_base,
1384 dash_flush(s, 1, -1);
1386 if (c->remove_at_exit) {
1387 char filename[1024];
1389 for (i = 0; i < s->nb_streams; i++) {
1390 OutputStream *os = &c->streams[i];
1391 snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
1392 dashenc_delete_file(s, filename);
1394 dashenc_delete_file(s, s->url);
1400 static int dash_check_bitstream(struct AVFormatContext *s, const AVPacket *avpkt)
1402 DASHContext *c = s->priv_data;
1403 OutputStream *os = &c->streams[avpkt->stream_index];
1404 AVFormatContext *oc = os->ctx;
1405 if (oc->oformat->check_bitstream) {
1407 AVPacket pkt = *avpkt;
1408 pkt.stream_index = 0;
1409 ret = oc->oformat->check_bitstream(oc, &pkt);
1411 AVStream *st = s->streams[avpkt->stream_index];
1412 AVStream *ost = oc->streams[0];
1413 st->internal->bsfcs = ost->internal->bsfcs;
1414 st->internal->nb_bsfcs = ost->internal->nb_bsfcs;
1415 ost->internal->bsfcs = NULL;
1416 ost->internal->nb_bsfcs = 0;
1423 #define OFFSET(x) offsetof(DASHContext, x)
1424 #define E AV_OPT_FLAG_ENCODING_PARAM
1425 static const AVOption options[] = {
1426 { "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 },
1427 { "window_size", "number of segments kept in the manifest", OFFSET(window_size), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, E },
1428 { "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 },
1429 { "min_seg_duration", "minimum segment duration (in microseconds)", OFFSET(min_seg_duration), AV_OPT_TYPE_INT, { .i64 = 5000000 }, 0, INT_MAX, E },
1430 { "remove_at_exit", "remove all segments when finished", OFFSET(remove_at_exit), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
1431 { "use_template", "Use SegmentTemplate instead of SegmentList", OFFSET(use_template), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, E },
1432 { "use_timeline", "Use SegmentTimeline in SegmentTemplate", OFFSET(use_timeline), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, E },
1433 { "single_file", "Store all segments in one file, accessed using byte ranges", OFFSET(single_file), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
1434 { "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 },
1435 { "init_seg_name", "DASH-templated name to used for the initialization segment", OFFSET(init_seg_name), AV_OPT_TYPE_STRING, {.str = "init-stream$RepresentationID$.m4s"}, 0, 0, E },
1436 { "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$.m4s"}, 0, 0, E },
1437 { "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 },
1438 { "method", "set the HTTP method", OFFSET(method), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
1439 { "http_user_agent", "override User-Agent field in HTTP header", OFFSET(user_agent), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
1440 { "http_persistent", "Use persistent HTTP connections", OFFSET(http_persistent), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, E },
1441 { "hls_playlist", "Generate HLS playlist files(master.m3u8, media_%d.m3u8)", OFFSET(hls_playlist), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
1442 { "streaming", "Enable/Disable streaming mode of output. Each frame will be moof fragment", OFFSET(streaming), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
1446 static const AVClass dash_class = {
1447 .class_name = "dash muxer",
1448 .item_name = av_default_item_name,
1450 .version = LIBAVUTIL_VERSION_INT,
1453 AVOutputFormat ff_dash_muxer = {
1455 .long_name = NULL_IF_CONFIG_SMALL("DASH Muxer"),
1456 .extensions = "mpd",
1457 .priv_data_size = sizeof(DASHContext),
1458 .audio_codec = AV_CODEC_ID_AAC,
1459 .video_codec = AV_CODEC_ID_H264,
1460 .flags = AVFMT_GLOBALHEADER | AVFMT_NOFILE | AVFMT_TS_NEGATIVE,
1462 .write_header = dash_write_header,
1463 .write_packet = dash_write_packet,
1464 .write_trailer = dash_write_trailer,
1465 .deinit = dash_free,
1466 .check_bitstream = dash_check_bitstream,
1467 .priv_class = &dash_class,