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.h"
36 #include "libavutil/time_internal.h"
40 #include "avio_internal.h"
41 #include "hlsplaylist.h"
42 #if CONFIG_HTTP_PROTOCOL
47 #include "os_support.h"
53 SEGMENT_TYPE_AUTO = 0,
59 typedef struct Segment {
62 int range_length, index_length;
64 double prog_date_time;
69 typedef struct AdaptationSet {
72 enum AVMediaType media_type;
73 AVDictionary *metadata;
74 AVRational min_frame_rate, max_frame_rate;
75 int ambiguous_frame_rate;
78 typedef struct OutputStream {
80 int ctx_inited, as_idx;
84 int64_t init_start_pos, pos;
85 int init_range_length;
86 int nb_segments, segments_size, segment_index;
88 int64_t first_pts, start_pts, max_pts;
89 int64_t last_dts, last_pts;
91 SegmentType segment_type; /* segment type selected for this particular stream */
92 const char *format_name;
93 const char *extension_name;
94 const char *single_file_name; /* file names selected for this particular stream */
95 const char *init_seg_name;
96 const char *media_seg_name;
101 char full_path[1024];
102 char temp_path[1024];
103 double availability_time_offset;
108 typedef struct DASHContext {
109 const AVClass *class; /* Class for private options. */
110 char *adaptation_sets;
114 int extra_window_size;
115 #if FF_API_DASH_MIN_SEG_DURATION
116 int min_seg_duration;
118 int64_t seg_duration;
123 OutputStream *streams;
125 int64_t last_duration;
126 int64_t total_duration;
127 char availability_start_time[100];
130 const char *single_file_name; /* file names as specified in options */
131 const char *init_seg_name;
132 const char *media_seg_name;
133 const char *utc_timing_url;
135 const char *user_agent;
138 int master_playlist_created;
139 AVIOContext *mpd_out;
140 AVIOContext *m3u8_out;
143 int index_correction;
144 char *format_options_str;
146 SegmentType segment_type_option; /* segment type as specified in options */
147 int ignore_io_errors;
149 int master_publish_rate;
150 int nr_of_streams_to_flush;
151 int nr_of_streams_flushed;
154 static struct codec_string {
158 { AV_CODEC_ID_VP8, "vp8" },
159 { AV_CODEC_ID_VP9, "vp9" },
160 { AV_CODEC_ID_VORBIS, "vorbis" },
161 { AV_CODEC_ID_OPUS, "opus" },
162 { AV_CODEC_ID_FLAC, "flac" },
166 static struct format_string {
167 SegmentType segment_type;
170 { SEGMENT_TYPE_AUTO, "auto" },
171 { SEGMENT_TYPE_MP4, "mp4" },
172 { SEGMENT_TYPE_WEBM, "webm" },
176 static int dashenc_io_open(AVFormatContext *s, AVIOContext **pb, char *filename,
177 AVDictionary **options) {
178 DASHContext *c = s->priv_data;
179 int http_base_proto = filename ? ff_is_http_proto(filename) : 0;
180 int err = AVERROR_MUXER_NOT_FOUND;
181 if (!*pb || !http_base_proto || !c->http_persistent) {
182 err = s->io_open(s, pb, filename, AVIO_FLAG_WRITE, options);
183 #if CONFIG_HTTP_PROTOCOL
185 URLContext *http_url_context = ffio_geturlcontext(*pb);
186 av_assert0(http_url_context);
187 err = ff_http_do_new_request(http_url_context, filename);
189 ff_format_io_close(s, pb);
195 static void dashenc_io_close(AVFormatContext *s, AVIOContext **pb, char *filename) {
196 DASHContext *c = s->priv_data;
197 int http_base_proto = filename ? ff_is_http_proto(filename) : 0;
202 if (!http_base_proto || !c->http_persistent) {
203 ff_format_io_close(s, pb);
204 #if CONFIG_HTTP_PROTOCOL
206 URLContext *http_url_context = ffio_geturlcontext(*pb);
207 av_assert0(http_url_context);
209 ffurl_shutdown(http_url_context, AVIO_FLAG_WRITE);
214 static const char *get_format_str(SegmentType segment_type) {
216 for (i = 0; i < SEGMENT_TYPE_NB; i++)
217 if (formats[i].segment_type == segment_type)
218 return formats[i].str;
222 static const char *get_extension_str(SegmentType type, int single_file)
226 case SEGMENT_TYPE_MP4: return single_file ? "mp4" : "m4s";
227 case SEGMENT_TYPE_WEBM: return "webm";
228 default: return NULL;
232 static int handle_io_open_error(AVFormatContext *s, int err, char *url) {
233 DASHContext *c = s->priv_data;
234 char errbuf[AV_ERROR_MAX_STRING_SIZE];
235 av_strerror(err, errbuf, sizeof(errbuf));
236 av_log(s, c->ignore_io_errors ? AV_LOG_WARNING : AV_LOG_ERROR,
237 "Unable to open %s for writing: %s\n", url, errbuf);
238 return c->ignore_io_errors ? 0 : err;
241 static inline SegmentType select_segment_type(SegmentType segment_type, enum AVCodecID codec_id)
243 if (segment_type == SEGMENT_TYPE_AUTO) {
244 if (codec_id == AV_CODEC_ID_OPUS || codec_id == AV_CODEC_ID_VORBIS ||
245 codec_id == AV_CODEC_ID_VP8 || codec_id == AV_CODEC_ID_VP9) {
246 segment_type = SEGMENT_TYPE_WEBM;
248 segment_type = SEGMENT_TYPE_MP4;
255 static int init_segment_types(AVFormatContext *s)
257 DASHContext *c = s->priv_data;
258 int has_mp4_streams = 0;
259 for (int i = 0; i < s->nb_streams; ++i) {
260 OutputStream *os = &c->streams[i];
261 SegmentType segment_type = select_segment_type(
262 c->segment_type_option, s->streams[i]->codecpar->codec_id);
263 os->segment_type = segment_type;
264 os->format_name = get_format_str(segment_type);
265 if (!os->format_name) {
266 av_log(s, AV_LOG_ERROR, "Could not select DASH segment type for stream %d\n", i);
267 return AVERROR_MUXER_NOT_FOUND;
269 os->extension_name = get_extension_str(segment_type, c->single_file);
270 if (!os->extension_name) {
271 av_log(s, AV_LOG_ERROR, "Could not get extension type for stream %d\n", i);
272 return AVERROR_MUXER_NOT_FOUND;
275 has_mp4_streams |= segment_type == SEGMENT_TYPE_MP4;
278 if (c->hls_playlist && !has_mp4_streams) {
279 av_log(s, AV_LOG_WARNING, "No mp4 streams, disabling HLS manifest generation\n");
286 static int check_file_extension(const char *filename, const char *extension) {
288 if (!filename || !extension)
290 dot = strrchr(filename, '.');
291 if (dot && !strcmp(dot + 1, extension))
296 static void set_vp9_codec_str(AVFormatContext *s, AVCodecParameters *par,
297 AVRational *frame_rate, char *str, int size) {
299 int ret = ff_isom_get_vpcc_features(s, par, frame_rate, &vpcc);
301 av_strlcatf(str, size, "vp09.%02d.%02d.%02d",
302 vpcc.profile, vpcc.level, vpcc.bitdepth);
304 // Default to just vp9 in case of error while finding out profile or level
305 av_log(s, AV_LOG_WARNING, "Could not find VP9 profile and/or level\n");
306 av_strlcpy(str, "vp9", size);
311 static void set_codec_str(AVFormatContext *s, AVCodecParameters *par,
312 AVRational *frame_rate, char *str, int size)
314 const AVCodecTag *tags[2] = { NULL, NULL };
318 // common Webm codecs are not part of RFC 6381
319 for (i = 0; codecs[i].id; i++)
320 if (codecs[i].id == par->codec_id) {
321 if (codecs[i].id == AV_CODEC_ID_VP9) {
322 set_vp9_codec_str(s, par, frame_rate, str, size);
324 av_strlcpy(str, codecs[i].str, size);
329 // for codecs part of RFC 6381
330 if (par->codec_type == AVMEDIA_TYPE_VIDEO)
331 tags[0] = ff_codec_movvideo_tags;
332 else if (par->codec_type == AVMEDIA_TYPE_AUDIO)
333 tags[0] = ff_codec_movaudio_tags;
337 tag = par->codec_tag;
339 tag = av_codec_get_tag(tags, par->codec_id);
347 if (!strcmp(str, "mp4a") || !strcmp(str, "mp4v")) {
349 tags[0] = ff_mp4_obj_type;
350 oti = av_codec_get_tag(tags, par->codec_id);
352 av_strlcatf(str, size, ".%02"PRIx32, oti);
356 if (tag == MKTAG('m', 'p', '4', 'a')) {
357 if (par->extradata_size >= 2) {
358 int aot = par->extradata[0] >> 3;
360 aot = ((AV_RB16(par->extradata) >> 5) & 0x3f) + 32;
361 av_strlcatf(str, size, ".%d", aot);
363 } else if (tag == MKTAG('m', 'p', '4', 'v')) {
364 // Unimplemented, should output ProfileLevelIndication as a decimal number
365 av_log(s, AV_LOG_WARNING, "Incomplete RFC 6381 codec string for mp4v\n");
367 } else if (!strcmp(str, "avc1")) {
368 uint8_t *tmpbuf = NULL;
369 uint8_t *extradata = par->extradata;
370 int extradata_size = par->extradata_size;
373 if (extradata[0] != 1) {
375 if (avio_open_dyn_buf(&pb) < 0)
377 if (ff_isom_write_avcc(pb, extradata, extradata_size) < 0) {
378 ffio_free_dyn_buf(&pb);
381 extradata_size = avio_close_dyn_buf(pb, &extradata);
385 if (extradata_size >= 4)
386 av_strlcatf(str, size, ".%02x%02x%02x",
387 extradata[1], extradata[2], extradata[3]);
392 static int flush_dynbuf(DASHContext *c, OutputStream *os, int *range_length)
397 return AVERROR(EINVAL);
401 av_write_frame(os->ctx, NULL);
402 avio_flush(os->ctx->pb);
404 if (!c->single_file) {
406 *range_length = avio_close_dyn_buf(os->ctx->pb, &buffer);
409 avio_write(os->out, buffer + os->written_len, *range_length - os->written_len);
414 return avio_open_dyn_buf(&os->ctx->pb);
416 *range_length = avio_tell(os->ctx->pb) - os->pos;
421 static void set_http_options(AVDictionary **options, DASHContext *c)
424 av_dict_set(options, "method", c->method, 0);
426 av_dict_set(options, "user_agent", c->user_agent, 0);
427 if (c->http_persistent)
428 av_dict_set_int(options, "multiple_requests", 1, 0);
430 av_dict_set_int(options, "timeout", c->timeout, 0);
433 static void get_hls_playlist_name(char *playlist_name, int string_size,
434 const char *base_url, int id) {
436 snprintf(playlist_name, string_size, "%smedia_%d.m3u8", base_url, id);
438 snprintf(playlist_name, string_size, "media_%d.m3u8", id);
441 static void get_start_index_number(OutputStream *os, DASHContext *c,
442 int *start_index, int *start_number) {
445 if (c->window_size) {
446 *start_index = FFMAX(os->nb_segments - c->window_size, 0);
447 *start_number = FFMAX(os->segment_index - c->window_size, 1);
451 static void write_hls_media_playlist(OutputStream *os, AVFormatContext *s,
452 int representation_id, int final,
453 char *prefetch_url) {
454 DASHContext *c = s->priv_data;
455 int timescale = os->ctx->streams[0]->time_base.den;
456 char temp_filename_hls[1024];
457 char filename_hls[1024];
458 AVDictionary *http_opts = NULL;
459 int target_duration = 0;
461 const char *proto = avio_find_protocol_name(c->dirname);
462 int use_rename = proto && !strcmp(proto, "file");
463 int i, start_index, start_number;
464 double prog_date_time = 0;
466 get_start_index_number(os, c, &start_index, &start_number);
468 if (!c->hls_playlist || start_index >= os->nb_segments ||
469 os->segment_type != SEGMENT_TYPE_MP4)
472 get_hls_playlist_name(filename_hls, sizeof(filename_hls),
473 c->dirname, representation_id);
475 snprintf(temp_filename_hls, sizeof(temp_filename_hls), use_rename ? "%s.tmp" : "%s", filename_hls);
477 set_http_options(&http_opts, c);
478 ret = dashenc_io_open(s, &c->m3u8_out, temp_filename_hls, &http_opts);
479 av_dict_free(&http_opts);
481 handle_io_open_error(s, ret, temp_filename_hls);
484 for (i = start_index; i < os->nb_segments; i++) {
485 Segment *seg = os->segments[i];
486 double duration = (double) seg->duration / timescale;
487 if (target_duration <= duration)
488 target_duration = lrint(duration);
491 ff_hls_write_playlist_header(c->m3u8_out, 6, -1, target_duration,
492 start_number, PLAYLIST_TYPE_NONE, 0);
494 ff_hls_write_init_file(c->m3u8_out, os->initfile, c->single_file,
495 os->init_range_length, os->init_start_pos);
497 for (i = start_index; i < os->nb_segments; i++) {
498 Segment *seg = os->segments[i];
500 if (prog_date_time == 0) {
501 if (os->nb_segments == 1)
502 prog_date_time = c->start_time_s;
504 prog_date_time = seg->prog_date_time;
506 seg->prog_date_time = prog_date_time;
508 ret = ff_hls_write_file_entry(c->m3u8_out, 0, c->single_file,
509 (double) seg->duration / timescale, 0,
510 seg->range_length, seg->start_pos, NULL,
511 c->single_file ? os->initfile : seg->file,
512 &prog_date_time, 0, 0, 0);
514 av_log(os->ctx, AV_LOG_WARNING, "ff_hls_write_file_entry get error\n");
519 avio_printf(c->m3u8_out, "#EXT-X-PREFETCH:%s\n", prefetch_url);
522 ff_hls_write_end_list(c->m3u8_out);
524 dashenc_io_close(s, &c->m3u8_out, temp_filename_hls);
527 if (avpriv_io_move(temp_filename_hls, filename_hls) < 0) {
528 av_log(os->ctx, AV_LOG_WARNING, "renaming file %s to %s failed\n\n", temp_filename_hls, filename_hls);
532 static int flush_init_segment(AVFormatContext *s, OutputStream *os)
534 DASHContext *c = s->priv_data;
535 int ret, range_length;
537 ret = flush_dynbuf(c, os, &range_length);
541 os->pos = os->init_range_length = range_length;
542 if (!c->single_file) {
544 snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
545 dashenc_io_close(s, &os->out, filename);
550 static void dash_free(AVFormatContext *s)
552 DASHContext *c = s->priv_data;
556 for (i = 0; i < c->nb_as; i++) {
557 av_dict_free(&c->as[i].metadata);
558 av_freep(&c->as[i].descriptor);
566 for (i = 0; i < s->nb_streams; i++) {
567 OutputStream *os = &c->streams[i];
568 if (os->ctx && os->ctx->pb) {
570 ffio_free_dyn_buf(&os->ctx->pb);
572 avio_close(os->ctx->pb);
574 ff_format_io_close(s, &os->out);
576 avformat_free_context(os->ctx);
577 for (j = 0; j < os->nb_segments; j++)
578 av_free(os->segments[j]);
579 av_free(os->segments);
580 av_freep(&os->single_file_name);
581 av_freep(&os->init_seg_name);
582 av_freep(&os->media_seg_name);
584 av_freep(&c->streams);
586 ff_format_io_close(s, &c->mpd_out);
587 ff_format_io_close(s, &c->m3u8_out);
590 static void output_segment_list(OutputStream *os, AVIOContext *out, AVFormatContext *s,
591 int representation_id, int final)
593 DASHContext *c = s->priv_data;
594 int i, start_index, start_number;
595 get_start_index_number(os, c, &start_index, &start_number);
597 if (c->use_template) {
598 int timescale = c->use_timeline ? os->ctx->streams[0]->time_base.den : AV_TIME_BASE;
599 avio_printf(out, "\t\t\t\t<SegmentTemplate timescale=\"%d\" ", timescale);
600 if (!c->use_timeline) {
601 avio_printf(out, "duration=\"%"PRId64"\" ", c->seg_duration);
602 if (c->streaming && os->availability_time_offset)
603 avio_printf(out, "availabilityTimeOffset=\"%.3f\" ",
604 os->availability_time_offset);
606 avio_printf(out, "initialization=\"%s\" media=\"%s\" startNumber=\"%d\">\n", os->init_seg_name, os->media_seg_name, c->use_timeline ? start_number : 1);
607 if (c->use_timeline) {
608 int64_t cur_time = 0;
609 avio_printf(out, "\t\t\t\t\t<SegmentTimeline>\n");
610 for (i = start_index; i < os->nb_segments; ) {
611 Segment *seg = os->segments[i];
613 avio_printf(out, "\t\t\t\t\t\t<S ");
614 if (i == start_index || seg->time != cur_time) {
615 cur_time = seg->time;
616 avio_printf(out, "t=\"%"PRId64"\" ", seg->time);
618 avio_printf(out, "d=\"%"PRId64"\" ", seg->duration);
619 while (i + repeat + 1 < os->nb_segments &&
620 os->segments[i + repeat + 1]->duration == seg->duration &&
621 os->segments[i + repeat + 1]->time == os->segments[i + repeat]->time + os->segments[i + repeat]->duration)
624 avio_printf(out, "r=\"%d\" ", repeat);
625 avio_printf(out, "/>\n");
627 cur_time += (1 + repeat) * seg->duration;
629 avio_printf(out, "\t\t\t\t\t</SegmentTimeline>\n");
631 avio_printf(out, "\t\t\t\t</SegmentTemplate>\n");
632 } else if (c->single_file) {
633 avio_printf(out, "\t\t\t\t<BaseURL>%s</BaseURL>\n", os->initfile);
634 avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%"PRId64"\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);
635 avio_printf(out, "\t\t\t\t\t<Initialization range=\"%"PRId64"-%"PRId64"\" />\n", os->init_start_pos, os->init_start_pos + os->init_range_length - 1);
636 for (i = start_index; i < os->nb_segments; i++) {
637 Segment *seg = os->segments[i];
638 avio_printf(out, "\t\t\t\t\t<SegmentURL mediaRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->range_length - 1);
639 if (seg->index_length)
640 avio_printf(out, "indexRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->index_length - 1);
641 avio_printf(out, "/>\n");
643 avio_printf(out, "\t\t\t\t</SegmentList>\n");
645 avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%"PRId64"\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);
646 avio_printf(out, "\t\t\t\t\t<Initialization sourceURL=\"%s\" />\n", os->initfile);
647 for (i = start_index; i < os->nb_segments; i++) {
648 Segment *seg = os->segments[i];
649 avio_printf(out, "\t\t\t\t\t<SegmentURL media=\"%s\" />\n", seg->file);
651 avio_printf(out, "\t\t\t\t</SegmentList>\n");
653 if (!c->lhls || final) {
654 write_hls_media_playlist(os, s, representation_id, final, NULL);
659 static char *xmlescape(const char *str) {
660 int outlen = strlen(str)*3/2 + 6;
661 char *out = av_realloc(NULL, outlen + 1);
665 for (; *str; str++) {
666 if (pos + 6 > outlen) {
668 outlen = 2 * outlen + 6;
669 tmp = av_realloc(out, outlen + 1);
677 memcpy(&out[pos], "&", 5);
679 } else if (*str == '<') {
680 memcpy(&out[pos], "<", 4);
682 } else if (*str == '>') {
683 memcpy(&out[pos], ">", 4);
685 } else if (*str == '\'') {
686 memcpy(&out[pos], "'", 6);
688 } else if (*str == '\"') {
689 memcpy(&out[pos], """, 6);
699 static void write_time(AVIOContext *out, int64_t time)
701 int seconds = time / AV_TIME_BASE;
702 int fractions = time % AV_TIME_BASE;
703 int minutes = seconds / 60;
704 int hours = minutes / 60;
707 avio_printf(out, "PT");
709 avio_printf(out, "%dH", hours);
710 if (hours || minutes)
711 avio_printf(out, "%dM", minutes);
712 avio_printf(out, "%d.%dS", seconds, fractions / (AV_TIME_BASE / 10));
715 static void format_date_now(char *buf, int size)
717 struct tm *ptm, tmbuf;
718 int64_t time_us = av_gettime();
719 int64_t time_ms = time_us / 1000;
720 const time_t time_s = time_ms / 1000;
721 int millisec = time_ms - (time_s * 1000);
722 ptm = gmtime_r(&time_s, &tmbuf);
725 if (!strftime(buf, size, "%Y-%m-%dT%H:%M:%S", ptm)) {
730 snprintf(buf + len, size - len, ".%03dZ", millisec);
734 static int write_adaptation_set(AVFormatContext *s, AVIOContext *out, int as_index,
737 DASHContext *c = s->priv_data;
738 AdaptationSet *as = &c->as[as_index];
739 AVDictionaryEntry *lang, *role;
742 avio_printf(out, "\t\t<AdaptationSet id=\"%s\" contentType=\"%s\" segmentAlignment=\"true\" bitstreamSwitching=\"true\"",
743 as->id, as->media_type == AVMEDIA_TYPE_VIDEO ? "video" : "audio");
744 if (as->media_type == AVMEDIA_TYPE_VIDEO && as->max_frame_rate.num && !as->ambiguous_frame_rate && av_cmp_q(as->min_frame_rate, as->max_frame_rate) < 0)
745 avio_printf(out, " maxFrameRate=\"%d/%d\"", as->max_frame_rate.num, as->max_frame_rate.den);
746 lang = av_dict_get(as->metadata, "language", NULL, 0);
748 avio_printf(out, " lang=\"%s\"", lang->value);
749 avio_printf(out, ">\n");
751 role = av_dict_get(as->metadata, "role", NULL, 0);
753 avio_printf(out, "\t\t\t<Role schemeIdUri=\"urn:mpeg:dash:role:2011\" value=\"%s\"/>\n", role->value);
755 avio_printf(out, "\t\t\t%s\n", as->descriptor);
756 for (i = 0; i < s->nb_streams; i++) {
757 OutputStream *os = &c->streams[i];
758 char bandwidth_str[64] = {'\0'};
760 if (os->as_idx - 1 != as_index)
763 if (os->bit_rate > 0)
764 snprintf(bandwidth_str, sizeof(bandwidth_str), " bandwidth=\"%d\"",
767 if (as->media_type == AVMEDIA_TYPE_VIDEO) {
768 AVStream *st = s->streams[i];
769 avio_printf(out, "\t\t\t<Representation id=\"%d\" mimeType=\"video/%s\" codecs=\"%s\"%s width=\"%d\" height=\"%d\"",
770 i, os->format_name, os->codec_str, bandwidth_str, s->streams[i]->codecpar->width, s->streams[i]->codecpar->height);
771 if (st->avg_frame_rate.num)
772 avio_printf(out, " frameRate=\"%d/%d\"", st->avg_frame_rate.num, st->avg_frame_rate.den);
773 avio_printf(out, ">\n");
775 avio_printf(out, "\t\t\t<Representation id=\"%d\" mimeType=\"audio/%s\" codecs=\"%s\"%s audioSamplingRate=\"%d\">\n",
776 i, os->format_name, os->codec_str, bandwidth_str, s->streams[i]->codecpar->sample_rate);
777 avio_printf(out, "\t\t\t\t<AudioChannelConfiguration schemeIdUri=\"urn:mpeg:dash:23003:3:audio_channel_configuration:2011\" value=\"%d\" />\n",
778 s->streams[i]->codecpar->channels);
780 output_segment_list(os, out, s, i, final);
781 avio_printf(out, "\t\t\t</Representation>\n");
783 avio_printf(out, "\t\t</AdaptationSet>\n");
788 static int add_adaptation_set(AVFormatContext *s, AdaptationSet **as, enum AVMediaType type)
790 DASHContext *c = s->priv_data;
792 void *mem = av_realloc(c->as, sizeof(*c->as) * (c->nb_as + 1));
794 return AVERROR(ENOMEM);
798 *as = &c->as[c->nb_as - 1];
799 memset(*as, 0, sizeof(**as));
800 (*as)->media_type = type;
805 static int adaptation_set_add_stream(AVFormatContext *s, int as_idx, int i)
807 DASHContext *c = s->priv_data;
808 AdaptationSet *as = &c->as[as_idx - 1];
809 OutputStream *os = &c->streams[i];
811 if (as->media_type != s->streams[i]->codecpar->codec_type) {
812 av_log(s, AV_LOG_ERROR, "Codec type of stream %d doesn't match AdaptationSet's media type\n", i);
813 return AVERROR(EINVAL);
814 } else if (os->as_idx) {
815 av_log(s, AV_LOG_ERROR, "Stream %d is already assigned to an AdaptationSet\n", i);
816 return AVERROR(EINVAL);
823 static int parse_adaptation_sets(AVFormatContext *s)
825 DASHContext *c = s->priv_data;
826 const char *p = c->adaptation_sets;
827 enum { new_set, parse_id, parsing_streams, parse_descriptor } state;
831 // default: one AdaptationSet for each stream
833 for (i = 0; i < s->nb_streams; i++) {
834 if ((ret = add_adaptation_set(s, &as, s->streams[i]->codecpar->codec_type)) < 0)
836 snprintf(as->id, sizeof(as->id), "%d", i);
838 c->streams[i].as_idx = c->nb_as;
843 // syntax id=0,streams=0,1,2 id=1,streams=3,4 and so on
844 // option id=0,descriptor=descriptor_str,streams=0,1,2 and so on
845 // descriptor is useful to the scheme defined by ISO/IEC 23009-1:2014/Amd.2:2015
846 // descriptor_str should be a self-closing xml tag.
852 } else if (state == new_set && av_strstart(p, "id=", &p)) {
854 if ((ret = add_adaptation_set(s, &as, AVMEDIA_TYPE_UNKNOWN)) < 0)
858 snprintf(as->id, sizeof(as->id), "%.*s", n, p);
864 } else if (state == parse_id && av_strstart(p, "descriptor=", &p)) {
865 n = strcspn(p, ">") + 1; //followed by one comma, so plus 1
867 as->descriptor = av_strndup(p, n);
869 av_log(s, AV_LOG_ERROR, "Parse error, descriptor string should be a self-closing xml tag\n");
870 return AVERROR(EINVAL);
875 state = parse_descriptor;
876 } else if ((state == parse_id || state == parse_descriptor) && av_strstart(p, "streams=", &p)) { //descriptor is optional
877 state = parsing_streams;
878 } else if (state == parsing_streams) {
879 AdaptationSet *as = &c->as[c->nb_as - 1];
880 char idx_str[8], *end_str;
882 n = strcspn(p, " ,");
883 snprintf(idx_str, sizeof(idx_str), "%.*s", n, p);
886 // if value is "a" or "v", map all streams of that type
887 if (as->media_type == AVMEDIA_TYPE_UNKNOWN && (idx_str[0] == 'v' || idx_str[0] == 'a')) {
888 enum AVMediaType type = (idx_str[0] == 'v') ? AVMEDIA_TYPE_VIDEO : AVMEDIA_TYPE_AUDIO;
889 av_log(s, AV_LOG_DEBUG, "Map all streams of type %s\n", idx_str);
891 for (i = 0; i < s->nb_streams; i++) {
892 if (s->streams[i]->codecpar->codec_type != type)
895 as->media_type = s->streams[i]->codecpar->codec_type;
897 if ((ret = adaptation_set_add_stream(s, c->nb_as, i)) < 0)
900 } else { // select single stream
901 i = strtol(idx_str, &end_str, 10);
902 if (idx_str == end_str || i < 0 || i >= s->nb_streams) {
903 av_log(s, AV_LOG_ERROR, "Selected stream \"%s\" not found!\n", idx_str);
904 return AVERROR(EINVAL);
906 av_log(s, AV_LOG_DEBUG, "Map stream %d\n", i);
908 if (as->media_type == AVMEDIA_TYPE_UNKNOWN) {
909 as->media_type = s->streams[i]->codecpar->codec_type;
912 if ((ret = adaptation_set_add_stream(s, c->nb_as, i)) < 0)
921 return AVERROR(EINVAL);
926 // check for unassigned streams
927 for (i = 0; i < s->nb_streams; i++) {
928 OutputStream *os = &c->streams[i];
930 av_log(s, AV_LOG_ERROR, "Stream %d is not mapped to an AdaptationSet\n", i);
931 return AVERROR(EINVAL);
937 static int write_manifest(AVFormatContext *s, int final)
939 DASHContext *c = s->priv_data;
941 char temp_filename[1024];
943 const char *proto = avio_find_protocol_name(s->url);
944 int use_rename = proto && !strcmp(proto, "file");
945 static unsigned int warned_non_file = 0;
946 AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
947 AVDictionary *opts = NULL;
949 if (!use_rename && !warned_non_file++)
950 av_log(s, AV_LOG_ERROR, "Cannot use rename on non file protocol, this may lead to races and temporary partial files\n");
952 snprintf(temp_filename, sizeof(temp_filename), use_rename ? "%s.tmp" : "%s", s->url);
953 set_http_options(&opts, c);
954 ret = dashenc_io_open(s, &c->mpd_out, temp_filename, &opts);
957 return handle_io_open_error(s, ret, temp_filename);
960 avio_printf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
961 avio_printf(out, "<MPD xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
962 "\txmlns=\"urn:mpeg:dash:schema:mpd:2011\"\n"
963 "\txmlns:xlink=\"http://www.w3.org/1999/xlink\"\n"
964 "\txsi:schemaLocation=\"urn:mpeg:DASH:schema:MPD:2011 http://standards.iso.org/ittf/PubliclyAvailableStandards/MPEG-DASH_schema_files/DASH-MPD.xsd\"\n"
965 "\tprofiles=\"urn:mpeg:dash:profile:isoff-live:2011\"\n"
966 "\ttype=\"%s\"\n", final ? "static" : "dynamic");
968 avio_printf(out, "\tmediaPresentationDuration=\"");
969 write_time(out, c->total_duration);
970 avio_printf(out, "\"\n");
972 int64_t update_period = c->last_duration / AV_TIME_BASE;
974 if (c->use_template && !c->use_timeline)
976 avio_printf(out, "\tminimumUpdatePeriod=\"PT%"PRId64"S\"\n", update_period);
977 avio_printf(out, "\tsuggestedPresentationDelay=\"PT%"PRId64"S\"\n", c->last_duration / AV_TIME_BASE);
978 if (c->availability_start_time[0])
979 avio_printf(out, "\tavailabilityStartTime=\"%s\"\n", c->availability_start_time);
980 format_date_now(now_str, sizeof(now_str));
982 avio_printf(out, "\tpublishTime=\"%s\"\n", now_str);
983 if (c->window_size && c->use_template) {
984 avio_printf(out, "\ttimeShiftBufferDepth=\"");
985 write_time(out, c->last_duration * c->window_size);
986 avio_printf(out, "\"\n");
989 avio_printf(out, "\tminBufferTime=\"");
990 write_time(out, c->last_duration * 2);
991 avio_printf(out, "\">\n");
992 avio_printf(out, "\t<ProgramInformation>\n");
994 char *escaped = xmlescape(title->value);
995 avio_printf(out, "\t\t<Title>%s</Title>\n", escaped);
998 avio_printf(out, "\t</ProgramInformation>\n");
1000 if (c->window_size && s->nb_streams > 0 && c->streams[0].nb_segments > 0 && !c->use_template) {
1001 OutputStream *os = &c->streams[0];
1002 int start_index = FFMAX(os->nb_segments - c->window_size, 0);
1003 int64_t start_time = av_rescale_q(os->segments[start_index]->time, s->streams[0]->time_base, AV_TIME_BASE_Q);
1004 avio_printf(out, "\t<Period id=\"0\" start=\"");
1005 write_time(out, start_time);
1006 avio_printf(out, "\">\n");
1008 avio_printf(out, "\t<Period id=\"0\" start=\"PT0.0S\">\n");
1011 for (i = 0; i < c->nb_as; i++) {
1012 if ((ret = write_adaptation_set(s, out, i, final)) < 0)
1015 avio_printf(out, "\t</Period>\n");
1017 if (c->utc_timing_url)
1018 avio_printf(out, "\t<UTCTiming schemeIdUri=\"urn:mpeg:dash:utc:http-xsdate:2014\" value=\"%s\"/>\n", c->utc_timing_url);
1020 avio_printf(out, "</MPD>\n");
1022 dashenc_io_close(s, &c->mpd_out, temp_filename);
1025 if ((ret = avpriv_io_move(temp_filename, s->url)) < 0)
1029 if (c->hls_playlist) {
1030 char filename_hls[1024];
1031 const char *audio_group = "A1";
1032 char audio_codec_str[128] = "\0";
1034 int max_audio_bitrate = 0;
1036 // Publish master playlist only the configured rate
1037 if (c->master_playlist_created && (!c->master_publish_rate ||
1038 c->streams[0].segment_index % c->master_publish_rate))
1042 snprintf(filename_hls, sizeof(filename_hls), "%smaster.m3u8", c->dirname);
1044 snprintf(filename_hls, sizeof(filename_hls), "master.m3u8");
1046 snprintf(temp_filename, sizeof(temp_filename), use_rename ? "%s.tmp" : "%s", filename_hls);
1048 set_http_options(&opts, c);
1049 ret = dashenc_io_open(s, &c->m3u8_out, temp_filename, &opts);
1050 av_dict_free(&opts);
1052 return handle_io_open_error(s, ret, temp_filename);
1055 ff_hls_write_playlist_version(c->m3u8_out, 7);
1057 for (i = 0; i < s->nb_streams; i++) {
1058 char playlist_file[64];
1059 AVStream *st = s->streams[i];
1060 OutputStream *os = &c->streams[i];
1061 if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO)
1063 if (os->segment_type != SEGMENT_TYPE_MP4)
1065 get_hls_playlist_name(playlist_file, sizeof(playlist_file), NULL, i);
1066 ff_hls_write_audio_rendition(c->m3u8_out, (char *)audio_group,
1067 playlist_file, NULL, i, is_default);
1068 max_audio_bitrate = FFMAX(st->codecpar->bit_rate +
1069 os->muxer_overhead, max_audio_bitrate);
1070 if (!av_strnstr(audio_codec_str, os->codec_str, sizeof(audio_codec_str))) {
1071 if (strlen(audio_codec_str))
1072 av_strlcat(audio_codec_str, ",", sizeof(audio_codec_str));
1073 av_strlcat(audio_codec_str, os->codec_str, sizeof(audio_codec_str));
1078 for (i = 0; i < s->nb_streams; i++) {
1079 char playlist_file[64];
1080 char codec_str[128];
1081 AVStream *st = s->streams[i];
1082 OutputStream *os = &c->streams[i];
1083 char *agroup = NULL;
1084 char *codec_str_ptr = NULL;
1085 int stream_bitrate = st->codecpar->bit_rate + os->muxer_overhead;
1086 if (st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO)
1088 if (os->segment_type != SEGMENT_TYPE_MP4)
1090 av_strlcpy(codec_str, os->codec_str, sizeof(codec_str));
1091 if (max_audio_bitrate) {
1092 agroup = (char *)audio_group;
1093 stream_bitrate += max_audio_bitrate;
1094 av_strlcat(codec_str, ",", sizeof(codec_str));
1095 av_strlcat(codec_str, audio_codec_str, sizeof(codec_str));
1097 if (st->codecpar->codec_id != AV_CODEC_ID_HEVC) {
1098 codec_str_ptr = codec_str;
1100 get_hls_playlist_name(playlist_file, sizeof(playlist_file), NULL, i);
1101 ff_hls_write_stream_info(st, c->m3u8_out, stream_bitrate,
1102 playlist_file, agroup,
1103 codec_str_ptr, NULL);
1105 dashenc_io_close(s, &c->m3u8_out, temp_filename);
1107 if ((ret = avpriv_io_move(temp_filename, filename_hls)) < 0)
1109 c->master_playlist_created = 1;
1115 static int dict_copy_entry(AVDictionary **dst, const AVDictionary *src, const char *key)
1117 AVDictionaryEntry *entry = av_dict_get(src, key, NULL, 0);
1119 av_dict_set(dst, key, entry->value, AV_DICT_DONT_OVERWRITE);
1123 static int dash_init(AVFormatContext *s)
1125 DASHContext *c = s->priv_data;
1128 char basename[1024];
1130 c->nr_of_streams_to_flush = 0;
1131 if (c->single_file_name)
1134 c->use_template = 0;
1136 #if FF_API_DASH_MIN_SEG_DURATION
1137 if (c->min_seg_duration != 5000000) {
1138 av_log(s, AV_LOG_WARNING, "The min_seg_duration option is deprecated and will be removed. Please use the -seg_duration\n");
1139 c->seg_duration = c->min_seg_duration;
1142 if (c->lhls && s->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
1143 av_log(s, AV_LOG_ERROR,
1144 "LHLS is experimental, Please set -strict experimental in order to enable it.\n");
1145 return AVERROR_EXPERIMENTAL;
1148 if (c->lhls && !c->streaming) {
1149 av_log(s, AV_LOG_WARNING, "LHLS option will be ignored as streaming is not enabled\n");
1153 if (c->lhls && !c->hls_playlist) {
1154 av_log(s, AV_LOG_WARNING, "LHLS option will be ignored as hls_playlist is not enabled\n");
1158 if (c->global_sidx && !c->single_file) {
1159 av_log(s, AV_LOG_WARNING, "Global SIDX option will be ignored as single_file is not enabled\n");
1163 if (c->global_sidx && c->streaming) {
1164 av_log(s, AV_LOG_WARNING, "Global SIDX option will be ignored as streaming is enabled\n");
1168 av_strlcpy(c->dirname, s->url, sizeof(c->dirname));
1169 ptr = strrchr(c->dirname, '/');
1171 av_strlcpy(basename, &ptr[1], sizeof(basename));
1174 c->dirname[0] = '\0';
1175 av_strlcpy(basename, s->url, sizeof(basename));
1178 ptr = strrchr(basename, '.');
1182 c->streams = av_mallocz(sizeof(*c->streams) * s->nb_streams);
1184 return AVERROR(ENOMEM);
1186 if ((ret = parse_adaptation_sets(s)) < 0)
1189 if ((ret = init_segment_types(s)) < 0)
1192 for (i = 0; i < s->nb_streams; i++) {
1193 OutputStream *os = &c->streams[i];
1194 AdaptationSet *as = &c->as[os->as_idx - 1];
1195 AVFormatContext *ctx;
1197 AVDictionary *opts = NULL;
1198 char filename[1024];
1200 os->bit_rate = s->streams[i]->codecpar->bit_rate;
1201 if (!os->bit_rate) {
1202 int level = s->strict_std_compliance >= FF_COMPLIANCE_STRICT ?
1203 AV_LOG_ERROR : AV_LOG_WARNING;
1204 av_log(s, level, "No bit rate set for stream %d\n", i);
1205 if (s->strict_std_compliance >= FF_COMPLIANCE_STRICT)
1206 return AVERROR(EINVAL);
1209 // copy AdaptationSet language and role from stream metadata
1210 dict_copy_entry(&as->metadata, s->streams[i]->metadata, "language");
1211 dict_copy_entry(&as->metadata, s->streams[i]->metadata, "role");
1213 ctx = avformat_alloc_context();
1215 return AVERROR(ENOMEM);
1217 if (c->init_seg_name) {
1218 os->init_seg_name = av_strireplace(c->init_seg_name, "$ext$", os->extension_name);
1219 if (!os->init_seg_name)
1220 return AVERROR(ENOMEM);
1222 if (c->media_seg_name) {
1223 os->media_seg_name = av_strireplace(c->media_seg_name, "$ext$", os->extension_name);
1224 if (!os->media_seg_name)
1225 return AVERROR(ENOMEM);
1227 if (c->single_file_name) {
1228 os->single_file_name = av_strireplace(c->single_file_name, "$ext$", os->extension_name);
1229 if (!os->single_file_name)
1230 return AVERROR(ENOMEM);
1233 if (os->segment_type == SEGMENT_TYPE_WEBM) {
1234 if ((!c->single_file && check_file_extension(os->init_seg_name, os->format_name) != 0) ||
1235 (!c->single_file && check_file_extension(os->media_seg_name, os->format_name) != 0) ||
1236 (c->single_file && check_file_extension(os->single_file_name, os->format_name) != 0)) {
1237 av_log(s, AV_LOG_WARNING,
1238 "One or many segment file names doesn't end with .webm. "
1239 "Override -init_seg_name and/or -media_seg_name and/or "
1240 "-single_file_name to end with the extension .webm\n");
1243 // Streaming not supported as matroskaenc buffers internally before writing the output
1244 av_log(s, AV_LOG_WARNING, "One or more streams in WebM output format. Streaming option will be ignored\n");
1249 ctx->oformat = av_guess_format(os->format_name, NULL, NULL);
1251 return AVERROR_MUXER_NOT_FOUND;
1253 ctx->interrupt_callback = s->interrupt_callback;
1254 ctx->opaque = s->opaque;
1255 ctx->io_close = s->io_close;
1256 ctx->io_open = s->io_open;
1257 ctx->strict_std_compliance = s->strict_std_compliance;
1259 if (!(st = avformat_new_stream(ctx, NULL)))
1260 return AVERROR(ENOMEM);
1261 avcodec_parameters_copy(st->codecpar, s->streams[i]->codecpar);
1262 st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
1263 st->time_base = s->streams[i]->time_base;
1264 st->avg_frame_rate = s->streams[i]->avg_frame_rate;
1265 ctx->avoid_negative_ts = s->avoid_negative_ts;
1266 ctx->flags = s->flags;
1268 if (c->single_file) {
1269 if (os->single_file_name)
1270 ff_dash_fill_tmpl_params(os->initfile, sizeof(os->initfile), os->single_file_name, i, 0, os->bit_rate, 0);
1272 snprintf(os->initfile, sizeof(os->initfile), "%s-stream%d.%s", basename, i, os->format_name);
1274 ff_dash_fill_tmpl_params(os->initfile, sizeof(os->initfile), os->init_seg_name, i, 0, os->bit_rate, 0);
1276 snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
1277 set_http_options(&opts, c);
1278 if (!c->single_file) {
1279 if ((ret = avio_open_dyn_buf(&ctx->pb)) < 0)
1281 ret = s->io_open(s, &os->out, filename, AVIO_FLAG_WRITE, &opts);
1283 ctx->url = av_strdup(filename);
1284 ret = avio_open2(&ctx->pb, filename, AVIO_FLAG_WRITE, NULL, &opts);
1286 av_dict_free(&opts);
1289 os->init_start_pos = 0;
1291 if (c->format_options_str) {
1292 ret = av_dict_parse_string(&opts, c->format_options_str, "=", ":", 0);
1297 if (os->segment_type == SEGMENT_TYPE_MP4) {
1299 // frag_every_frame : Allows lower latency streaming
1300 // skip_sidx : Reduce bitrate overhead
1301 // skip_trailer : Avoids growing memory usage with time
1302 av_dict_set(&opts, "movflags", "frag_every_frame+dash+delay_moov+skip_sidx+skip_trailer", 0);
1305 av_dict_set(&opts, "movflags", "frag_custom+dash+delay_moov+global_sidx+skip_trailer", 0);
1307 av_dict_set(&opts, "movflags", "frag_custom+dash+delay_moov+skip_trailer", 0);
1310 av_dict_set_int(&opts, "cluster_time_limit", c->seg_duration / 1000, 0);
1311 av_dict_set_int(&opts, "cluster_size_limit", 5 * 1024 * 1024, 0); // set a large cluster size limit
1312 av_dict_set_int(&opts, "dash", 1, 0);
1313 av_dict_set_int(&opts, "dash_track_number", i + 1, 0);
1314 av_dict_set_int(&opts, "live", 1, 0);
1316 ret = avformat_init_output(ctx, &opts);
1317 av_dict_free(&opts);
1321 avio_flush(ctx->pb);
1323 av_log(s, AV_LOG_VERBOSE, "Representation %d init segment will be written to: %s\n", i, filename);
1325 s->streams[i]->time_base = st->time_base;
1326 // If the muxer wants to shift timestamps, request to have them shifted
1327 // already before being handed to this muxer, so we don't have mismatches
1328 // between the MPD and the actual segments.
1329 s->avoid_negative_ts = ctx->avoid_negative_ts;
1330 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
1331 AVRational avg_frame_rate = s->streams[i]->avg_frame_rate;
1332 if (avg_frame_rate.num > 0) {
1333 if (av_cmp_q(avg_frame_rate, as->min_frame_rate) < 0)
1334 as->min_frame_rate = avg_frame_rate;
1335 if (av_cmp_q(as->max_frame_rate, avg_frame_rate) < 0)
1336 as->max_frame_rate = avg_frame_rate;
1338 as->ambiguous_frame_rate = 1;
1343 set_codec_str(s, st->codecpar, &st->avg_frame_rate, os->codec_str,
1344 sizeof(os->codec_str));
1345 os->first_pts = AV_NOPTS_VALUE;
1346 os->max_pts = AV_NOPTS_VALUE;
1347 os->last_dts = AV_NOPTS_VALUE;
1348 os->segment_index = 1;
1350 if (s->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
1351 c->nr_of_streams_to_flush++;
1354 if (!c->has_video && c->seg_duration <= 0) {
1355 av_log(s, AV_LOG_WARNING, "no video stream and no seg duration set\n");
1356 return AVERROR(EINVAL);
1359 c->nr_of_streams_flushed = 0;
1364 static int dash_write_header(AVFormatContext *s)
1366 DASHContext *c = s->priv_data;
1368 for (i = 0; i < s->nb_streams; i++) {
1369 OutputStream *os = &c->streams[i];
1370 if ((ret = avformat_write_header(os->ctx, NULL)) < 0)
1373 // Flush init segment
1374 // Only for WebM segment, since for mp4 delay_moov is set and
1375 // the init segment is thus flushed after the first packets.
1376 if (os->segment_type == SEGMENT_TYPE_WEBM &&
1377 (ret = flush_init_segment(s, os)) < 0)
1383 static int add_segment(OutputStream *os, const char *file,
1384 int64_t time, int64_t duration,
1385 int64_t start_pos, int64_t range_length,
1386 int64_t index_length, int next_exp_index)
1390 if (os->nb_segments >= os->segments_size) {
1391 os->segments_size = (os->segments_size + 1) * 2;
1392 if ((err = av_reallocp(&os->segments, sizeof(*os->segments) *
1393 os->segments_size)) < 0) {
1394 os->segments_size = 0;
1395 os->nb_segments = 0;
1399 seg = av_mallocz(sizeof(*seg));
1401 return AVERROR(ENOMEM);
1402 av_strlcpy(seg->file, file, sizeof(seg->file));
1404 seg->duration = duration;
1405 if (seg->time < 0) { // If pts<0, it is expected to be cut away with an edit list
1406 seg->duration += seg->time;
1409 seg->start_pos = start_pos;
1410 seg->range_length = range_length;
1411 seg->index_length = index_length;
1412 os->segments[os->nb_segments++] = seg;
1413 os->segment_index++;
1414 //correcting the segment index if it has fallen behind the expected value
1415 if (os->segment_index < next_exp_index) {
1416 av_log(NULL, AV_LOG_WARNING, "Correcting the segment index after file %s: current=%d corrected=%d\n",
1417 file, os->segment_index, next_exp_index);
1418 os->segment_index = next_exp_index;
1423 static void write_styp(AVIOContext *pb)
1426 ffio_wfourcc(pb, "styp");
1427 ffio_wfourcc(pb, "msdh");
1428 avio_wb32(pb, 0); /* minor */
1429 ffio_wfourcc(pb, "msdh");
1430 ffio_wfourcc(pb, "msix");
1433 static void find_index_range(AVFormatContext *s, const char *full_path,
1434 int64_t pos, int *index_length)
1440 ret = s->io_open(s, &pb, full_path, AVIO_FLAG_READ, NULL);
1443 if (avio_seek(pb, pos, SEEK_SET) != pos) {
1444 ff_format_io_close(s, &pb);
1447 ret = avio_read(pb, buf, 8);
1448 ff_format_io_close(s, &pb);
1451 if (AV_RL32(&buf[4]) != MKTAG('s', 'i', 'd', 'x'))
1453 *index_length = AV_RB32(&buf[0]);
1456 static int update_stream_extradata(AVFormatContext *s, OutputStream *os,
1457 AVCodecParameters *par,
1458 AVRational *frame_rate)
1462 if (os->ctx->streams[0]->codecpar->extradata_size || !par->extradata_size)
1465 extradata = av_malloc(par->extradata_size);
1468 return AVERROR(ENOMEM);
1470 memcpy(extradata, par->extradata, par->extradata_size);
1472 os->ctx->streams[0]->codecpar->extradata = extradata;
1473 os->ctx->streams[0]->codecpar->extradata_size = par->extradata_size;
1475 set_codec_str(s, par, frame_rate, os->codec_str, sizeof(os->codec_str));
1480 static void dashenc_delete_file(AVFormatContext *s, char *filename) {
1481 DASHContext *c = s->priv_data;
1482 int http_base_proto = ff_is_http_proto(filename);
1484 if (http_base_proto) {
1485 AVIOContext *out = NULL;
1486 AVDictionary *http_opts = NULL;
1488 set_http_options(&http_opts, c);
1489 av_dict_set(&http_opts, "method", "DELETE", 0);
1491 if (dashenc_io_open(s, &out, filename, &http_opts) < 0) {
1492 av_log(s, AV_LOG_ERROR, "failed to delete %s\n", filename);
1495 av_dict_free(&http_opts);
1496 ff_format_io_close(s, &out);
1498 int res = avpriv_io_delete(filename);
1500 char errbuf[AV_ERROR_MAX_STRING_SIZE];
1501 av_strerror(res, errbuf, sizeof(errbuf));
1502 av_log(s, (res == AVERROR(ENOENT) ? AV_LOG_WARNING : AV_LOG_ERROR), "failed to delete %s: %s\n", filename, errbuf);
1507 static int dashenc_delete_segment_file(AVFormatContext *s, const char* file)
1509 DASHContext *c = s->priv_data;
1510 size_t dirname_len, file_len;
1511 char filename[1024];
1513 dirname_len = strlen(c->dirname);
1514 if (dirname_len >= sizeof(filename)) {
1515 av_log(s, AV_LOG_WARNING, "Cannot delete segments as the directory path is too long: %"PRIu64" characters: %s\n",
1516 (uint64_t)dirname_len, c->dirname);
1517 return AVERROR(ENAMETOOLONG);
1520 memcpy(filename, c->dirname, dirname_len);
1522 file_len = strlen(file);
1523 if ((dirname_len + file_len) >= sizeof(filename)) {
1524 av_log(s, AV_LOG_WARNING, "Cannot delete segments as the path is too long: %"PRIu64" characters: %s%s\n",
1525 (uint64_t)(dirname_len + file_len), c->dirname, file);
1526 return AVERROR(ENAMETOOLONG);
1529 memcpy(filename + dirname_len, file, file_len + 1); // include the terminating zero
1530 dashenc_delete_file(s, filename);
1535 static inline void dashenc_delete_media_segments(AVFormatContext *s, OutputStream *os, int remove_count)
1537 for (int i = 0; i < remove_count; ++i) {
1538 dashenc_delete_segment_file(s, os->segments[i]->file);
1540 // Delete the segment regardless of whether the file was successfully deleted
1541 av_free(os->segments[i]);
1544 os->nb_segments -= remove_count;
1545 memmove(os->segments, os->segments + remove_count, os->nb_segments * sizeof(*os->segments));
1548 static int dash_flush(AVFormatContext *s, int final, int stream)
1550 DASHContext *c = s->priv_data;
1553 const char *proto = avio_find_protocol_name(s->url);
1554 int use_rename = proto && !strcmp(proto, "file");
1556 int cur_flush_segment_index = 0, next_exp_index = -1;
1558 cur_flush_segment_index = c->streams[stream].segment_index;
1560 //finding the next segment's expected index, based on the current pts value
1561 if (c->use_template && !c->use_timeline && c->index_correction &&
1562 c->streams[stream].last_pts != AV_NOPTS_VALUE &&
1563 c->streams[stream].first_pts != AV_NOPTS_VALUE) {
1564 int64_t pts_diff = av_rescale_q(c->streams[stream].last_pts -
1565 c->streams[stream].first_pts,
1566 s->streams[stream]->time_base,
1568 next_exp_index = (pts_diff / c->seg_duration) + 1;
1572 for (i = 0; i < s->nb_streams; i++) {
1573 OutputStream *os = &c->streams[i];
1574 AVStream *st = s->streams[i];
1575 int range_length, index_length = 0;
1577 if (!os->packets_written)
1580 // Flush the single stream that got a keyframe right now.
1581 // Flush all audio streams as well, in sync with video keyframes,
1582 // but not the other video streams.
1583 if (stream >= 0 && i != stream) {
1584 if (s->streams[i]->codecpar->codec_type != AVMEDIA_TYPE_AUDIO)
1586 // Make sure we don't flush audio streams multiple times, when
1587 // all video streams are flushed one at a time.
1588 if (c->has_video && os->segment_index > cur_flush_segment_index)
1592 if (!c->single_file) {
1593 if (os->segment_type == SEGMENT_TYPE_MP4 && !os->written_len)
1594 write_styp(os->ctx->pb);
1596 snprintf(os->full_path, sizeof(os->full_path), "%s%s", c->dirname, os->initfile);
1599 ret = flush_dynbuf(c, os, &range_length);
1602 os->packets_written = 0;
1604 if (c->single_file) {
1605 find_index_range(s, os->full_path, os->pos, &index_length);
1607 dashenc_io_close(s, &os->out, os->temp_path);
1610 ret = avpriv_io_move(os->temp_path, os->full_path);
1616 if (!os->muxer_overhead)
1617 os->muxer_overhead = ((int64_t) (range_length - os->total_pkt_size) *
1619 av_rescale_q(os->max_pts - os->start_pts,
1620 st->time_base, AV_TIME_BASE_Q);
1621 os->total_pkt_size = 0;
1623 if (!os->bit_rate) {
1624 // calculate average bitrate of first segment
1625 int64_t bitrate = (int64_t) range_length * 8 * AV_TIME_BASE / av_rescale_q(os->max_pts - os->start_pts,
1629 os->bit_rate = bitrate;
1631 add_segment(os, os->filename, os->start_pts, os->max_pts - os->start_pts, os->pos, range_length, index_length, next_exp_index);
1632 av_log(s, AV_LOG_VERBOSE, "Representation %d media segment %d written to: %s\n", i, os->segment_index, os->full_path);
1634 os->pos += range_length;
1637 if (c->window_size) {
1638 for (i = 0; i < s->nb_streams; i++) {
1639 OutputStream *os = &c->streams[i];
1640 int remove_count = os->nb_segments - c->window_size - c->extra_window_size;
1641 if (remove_count > 0)
1642 dashenc_delete_media_segments(s, os, remove_count);
1647 for (i = 0; i < s->nb_streams; i++) {
1648 OutputStream *os = &c->streams[i];
1649 if (os->ctx && os->ctx_inited) {
1650 int64_t file_size = avio_tell(os->ctx->pb);
1651 av_write_trailer(os->ctx);
1652 if (c->global_sidx) {
1653 int j, start_index, start_number;
1654 int64_t sidx_size = avio_tell(os->ctx->pb) - file_size;
1655 get_start_index_number(os, c, &start_index, &start_number);
1656 if (start_index >= os->nb_segments ||
1657 os->segment_type != SEGMENT_TYPE_MP4)
1659 os->init_range_length += sidx_size;
1660 for (j = start_index; j < os->nb_segments; j++) {
1661 Segment *seg = os->segments[j];
1662 seg->start_pos += sidx_size;
1670 if (c->has_video && !final) {
1671 c->nr_of_streams_flushed++;
1672 if (c->nr_of_streams_flushed != c->nr_of_streams_to_flush)
1675 c->nr_of_streams_flushed = 0;
1677 ret = write_manifest(s, final);
1682 static int dash_write_packet(AVFormatContext *s, AVPacket *pkt)
1684 DASHContext *c = s->priv_data;
1685 AVStream *st = s->streams[pkt->stream_index];
1686 OutputStream *os = &c->streams[pkt->stream_index];
1687 int64_t seg_end_duration, elapsed_duration;
1690 ret = update_stream_extradata(s, os, st->codecpar, &st->avg_frame_rate);
1694 // Fill in a heuristic guess of the packet duration, if none is available.
1695 // The mp4 muxer will do something similar (for the last packet in a fragment)
1696 // if nothing is set (setting it for the other packets doesn't hurt).
1697 // By setting a nonzero duration here, we can be sure that the mp4 muxer won't
1698 // invoke its heuristic (this doesn't have to be identical to that algorithm),
1699 // so that we know the exact timestamps of fragments.
1700 if (!pkt->duration && os->last_dts != AV_NOPTS_VALUE)
1701 pkt->duration = pkt->dts - os->last_dts;
1702 os->last_dts = pkt->dts;
1704 // If forcing the stream to start at 0, the mp4 muxer will set the start
1705 // timestamps to 0. Do the same here, to avoid mismatches in duration/timestamps.
1706 if (os->first_pts == AV_NOPTS_VALUE &&
1707 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
1708 pkt->pts -= pkt->dts;
1712 if (os->first_pts == AV_NOPTS_VALUE)
1713 os->first_pts = pkt->pts;
1714 os->last_pts = pkt->pts;
1716 if (!c->availability_start_time[0]) {
1717 int64_t start_time_us = av_gettime();
1718 c->start_time_s = start_time_us / 1000000;
1719 format_date_now(c->availability_start_time,
1720 sizeof(c->availability_start_time));
1723 if (!os->availability_time_offset && pkt->duration) {
1724 int64_t frame_duration = av_rescale_q(pkt->duration, st->time_base,
1726 os->availability_time_offset = ((double) c->seg_duration -
1727 frame_duration) / AV_TIME_BASE;
1730 if (c->use_template && !c->use_timeline) {
1731 elapsed_duration = pkt->pts - os->first_pts;
1732 seg_end_duration = (int64_t) os->segment_index * c->seg_duration;
1734 elapsed_duration = pkt->pts - os->start_pts;
1735 seg_end_duration = c->seg_duration;
1738 if ((!c->has_video || st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) &&
1739 pkt->flags & AV_PKT_FLAG_KEY && os->packets_written &&
1740 av_compare_ts(elapsed_duration, st->time_base,
1741 seg_end_duration, AV_TIME_BASE_Q) >= 0) {
1742 int64_t prev_duration = c->last_duration;
1744 c->last_duration = av_rescale_q(pkt->pts - os->start_pts,
1747 c->total_duration = av_rescale_q(pkt->pts - os->first_pts,
1751 if ((!c->use_timeline || !c->use_template) && prev_duration) {
1752 if (c->last_duration < prev_duration*9/10 ||
1753 c->last_duration > prev_duration*11/10) {
1754 av_log(s, AV_LOG_WARNING,
1755 "Segment durations differ too much, enable use_timeline "
1756 "and use_template, or keep a stricter keyframe interval\n");
1760 if ((ret = dash_flush(s, 0, pkt->stream_index)) < 0)
1764 if (!os->packets_written) {
1765 // If we wrote a previous segment, adjust the start time of the segment
1766 // to the end of the previous one (which is the same as the mp4 muxer
1767 // does). This avoids gaps in the timeline.
1768 if (os->max_pts != AV_NOPTS_VALUE)
1769 os->start_pts = os->max_pts;
1771 os->start_pts = pkt->pts;
1773 if (os->max_pts == AV_NOPTS_VALUE)
1774 os->max_pts = pkt->pts + pkt->duration;
1776 os->max_pts = FFMAX(os->max_pts, pkt->pts + pkt->duration);
1777 os->packets_written++;
1778 os->total_pkt_size += pkt->size;
1779 if ((ret = ff_write_chained(os->ctx, 0, pkt, s, 0)) < 0)
1782 if (!os->init_range_length)
1783 flush_init_segment(s, os);
1785 //open the output context when the first frame of a segment is ready
1786 if (!c->single_file && os->packets_written == 1) {
1787 AVDictionary *opts = NULL;
1788 const char *proto = avio_find_protocol_name(s->url);
1789 int use_rename = proto && !strcmp(proto, "file");
1790 os->filename[0] = os->full_path[0] = os->temp_path[0] = '\0';
1791 ff_dash_fill_tmpl_params(os->filename, sizeof(os->filename),
1792 os->media_seg_name, pkt->stream_index,
1793 os->segment_index, os->bit_rate, os->start_pts);
1794 snprintf(os->full_path, sizeof(os->full_path), "%s%s", c->dirname,
1796 snprintf(os->temp_path, sizeof(os->temp_path),
1797 use_rename ? "%s.tmp" : "%s", os->full_path);
1798 set_http_options(&opts, c);
1799 ret = dashenc_io_open(s, &os->out, os->temp_path, &opts);
1800 av_dict_free(&opts);
1802 return handle_io_open_error(s, ret, os->temp_path);
1805 char *prefetch_url = use_rename ? NULL : os->filename;
1806 write_hls_media_playlist(os, s, pkt->stream_index, 0, prefetch_url);
1810 //write out the data immediately in streaming mode
1811 if (c->streaming && os->segment_type == SEGMENT_TYPE_MP4) {
1813 uint8_t *buf = NULL;
1814 if (!os->written_len)
1815 write_styp(os->ctx->pb);
1816 avio_flush(os->ctx->pb);
1817 len = avio_get_dyn_buf (os->ctx->pb, &buf);
1819 avio_write(os->out, buf + os->written_len, len - os->written_len);
1820 avio_flush(os->out);
1822 os->written_len = len;
1828 static int dash_write_trailer(AVFormatContext *s)
1830 DASHContext *c = s->priv_data;
1833 if (s->nb_streams > 0) {
1834 OutputStream *os = &c->streams[0];
1835 // If no segments have been written so far, try to do a crude
1836 // guess of the segment duration
1837 if (!c->last_duration)
1838 c->last_duration = av_rescale_q(os->max_pts - os->start_pts,
1839 s->streams[0]->time_base,
1841 c->total_duration = av_rescale_q(os->max_pts - os->first_pts,
1842 s->streams[0]->time_base,
1845 dash_flush(s, 1, -1);
1847 if (c->remove_at_exit) {
1848 for (i = 0; i < s->nb_streams; ++i) {
1849 OutputStream *os = &c->streams[i];
1850 dashenc_delete_media_segments(s, os, os->nb_segments);
1851 dashenc_delete_segment_file(s, os->initfile);
1852 if (c->hls_playlist && os->segment_type == SEGMENT_TYPE_MP4) {
1853 char filename[1024];
1854 get_hls_playlist_name(filename, sizeof(filename), c->dirname, i);
1855 dashenc_delete_file(s, filename);
1858 dashenc_delete_file(s, s->url);
1860 if (c->hls_playlist && c->master_playlist_created) {
1861 char filename[1024];
1862 snprintf(filename, sizeof(filename), "%smaster.m3u8", c->dirname);
1863 dashenc_delete_file(s, filename);
1870 static int dash_check_bitstream(struct AVFormatContext *s, const AVPacket *avpkt)
1872 DASHContext *c = s->priv_data;
1873 OutputStream *os = &c->streams[avpkt->stream_index];
1874 AVFormatContext *oc = os->ctx;
1875 if (oc->oformat->check_bitstream) {
1877 AVPacket pkt = *avpkt;
1878 pkt.stream_index = 0;
1879 ret = oc->oformat->check_bitstream(oc, &pkt);
1881 AVStream *st = s->streams[avpkt->stream_index];
1882 AVStream *ost = oc->streams[0];
1883 st->internal->bsfcs = ost->internal->bsfcs;
1884 st->internal->nb_bsfcs = ost->internal->nb_bsfcs;
1885 ost->internal->bsfcs = NULL;
1886 ost->internal->nb_bsfcs = 0;
1893 #define OFFSET(x) offsetof(DASHContext, x)
1894 #define E AV_OPT_FLAG_ENCODING_PARAM
1895 static const AVOption options[] = {
1896 { "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 },
1897 { "window_size", "number of segments kept in the manifest", OFFSET(window_size), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, E },
1898 { "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 },
1899 #if FF_API_DASH_MIN_SEG_DURATION
1900 { "min_seg_duration", "minimum segment duration (in microseconds) (will be deprecated)", OFFSET(min_seg_duration), AV_OPT_TYPE_INT, { .i64 = 5000000 }, 0, INT_MAX, E },
1902 { "seg_duration", "segment duration (in seconds, fractional value can be set)", OFFSET(seg_duration), AV_OPT_TYPE_DURATION, { .i64 = 5000000 }, 0, INT_MAX, E },
1903 { "remove_at_exit", "remove all segments when finished", OFFSET(remove_at_exit), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
1904 { "use_template", "Use SegmentTemplate instead of SegmentList", OFFSET(use_template), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, E },
1905 { "use_timeline", "Use SegmentTimeline in SegmentTemplate", OFFSET(use_timeline), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, E },
1906 { "single_file", "Store all segments in one file, accessed using byte ranges", OFFSET(single_file), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
1907 { "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 },
1908 { "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 },
1909 { "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 },
1910 { "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 },
1911 { "method", "set the HTTP method", OFFSET(method), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
1912 { "http_user_agent", "override User-Agent field in HTTP header", OFFSET(user_agent), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
1913 { "http_persistent", "Use persistent HTTP connections", OFFSET(http_persistent), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, E },
1914 { "hls_playlist", "Generate HLS playlist files(master.m3u8, media_%d.m3u8)", OFFSET(hls_playlist), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
1915 { "streaming", "Enable/Disable streaming mode of output. Each frame will be moof fragment", OFFSET(streaming), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
1916 { "timeout", "set timeout for socket I/O operations", OFFSET(timeout), AV_OPT_TYPE_DURATION, { .i64 = -1 }, -1, INT_MAX, .flags = E },
1917 { "index_correction", "Enable/Disable segment index correction logic", OFFSET(index_correction), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
1918 { "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},
1919 { "global_sidx", "Write global SIDX atom. Applicable only for single file, mp4 output, non-streaming mode", OFFSET(global_sidx), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
1920 { "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"},
1921 { "auto", "select segment file format based on codec", 0, AV_OPT_TYPE_CONST, {.i64 = SEGMENT_TYPE_AUTO }, 0, UINT_MAX, E, "segment_type"},
1922 { "mp4", "make segment file in ISOBMFF format", 0, AV_OPT_TYPE_CONST, {.i64 = SEGMENT_TYPE_MP4 }, 0, UINT_MAX, E, "segment_type"},
1923 { "webm", "make segment file in WebM format", 0, AV_OPT_TYPE_CONST, {.i64 = SEGMENT_TYPE_WEBM }, 0, UINT_MAX, E, "segment_type"},
1924 { "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 },
1925 { "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 },
1926 { "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},
1930 static const AVClass dash_class = {
1931 .class_name = "dash muxer",
1932 .item_name = av_default_item_name,
1934 .version = LIBAVUTIL_VERSION_INT,
1937 AVOutputFormat ff_dash_muxer = {
1939 .long_name = NULL_IF_CONFIG_SMALL("DASH Muxer"),
1940 .extensions = "mpd",
1941 .priv_data_size = sizeof(DASHContext),
1942 .audio_codec = AV_CODEC_ID_AAC,
1943 .video_codec = AV_CODEC_ID_H264,
1944 .flags = AVFMT_GLOBALHEADER | AVFMT_NOFILE | AVFMT_TS_NEGATIVE,
1946 .write_header = dash_write_header,
1947 .write_packet = dash_write_packet,
1948 .write_trailer = dash_write_trailer,
1949 .deinit = dash_free,
1950 .check_bitstream = dash_check_bitstream,
1951 .priv_class = &dash_class,