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;
68 typedef struct AdaptationSet {
70 enum AVMediaType media_type;
71 AVDictionary *metadata;
72 AVRational min_frame_rate, max_frame_rate;
73 int ambiguous_frame_rate;
76 typedef struct OutputStream {
78 int ctx_inited, as_idx;
82 int64_t init_start_pos, pos;
83 int init_range_length;
84 int nb_segments, segments_size, segment_index;
86 int64_t first_pts, start_pts, max_pts;
87 int64_t last_dts, last_pts;
89 SegmentType segment_type; /* segment type selected for this particular stream */
90 const char *format_name;
91 const char *single_file_name; /* file names selected for this particular stream */
92 const char *init_seg_name;
93 const char *media_seg_name;
100 double availability_time_offset;
105 typedef struct DASHContext {
106 const AVClass *class; /* Class for private options. */
107 char *adaptation_sets;
111 int extra_window_size;
112 #if FF_API_DASH_MIN_SEG_DURATION
113 int min_seg_duration;
115 int64_t seg_duration;
120 OutputStream *streams;
122 int64_t last_duration;
123 int64_t total_duration;
124 char availability_start_time[100];
126 const char *single_file_name; /* file names as specified in options */
127 const char *init_seg_name;
128 const char *media_seg_name;
129 const char *utc_timing_url;
131 const char *user_agent;
134 int master_playlist_created;
135 AVIOContext *mpd_out;
136 AVIOContext *m3u8_out;
139 int index_correction;
140 char *format_options_str;
141 SegmentType segment_type_option; /* segment type as specified in options */
142 int ignore_io_errors;
146 static struct codec_string {
150 { AV_CODEC_ID_VP8, "vp8" },
151 { AV_CODEC_ID_VP9, "vp9" },
152 { AV_CODEC_ID_VORBIS, "vorbis" },
153 { AV_CODEC_ID_OPUS, "opus" },
154 { AV_CODEC_ID_FLAC, "flac" },
158 static struct format_string {
159 SegmentType segment_type;
162 { SEGMENT_TYPE_AUTO, "auto" },
163 { SEGMENT_TYPE_MP4, "mp4" },
164 { SEGMENT_TYPE_WEBM, "webm" },
168 static int dashenc_io_open(AVFormatContext *s, AVIOContext **pb, char *filename,
169 AVDictionary **options) {
170 DASHContext *c = s->priv_data;
171 int http_base_proto = filename ? ff_is_http_proto(filename) : 0;
172 int err = AVERROR_MUXER_NOT_FOUND;
173 if (!*pb || !http_base_proto || !c->http_persistent) {
174 err = s->io_open(s, pb, filename, AVIO_FLAG_WRITE, options);
175 #if CONFIG_HTTP_PROTOCOL
177 URLContext *http_url_context = ffio_geturlcontext(*pb);
178 av_assert0(http_url_context);
179 err = ff_http_do_new_request(http_url_context, filename);
181 ff_format_io_close(s, pb);
187 static void dashenc_io_close(AVFormatContext *s, AVIOContext **pb, char *filename) {
188 DASHContext *c = s->priv_data;
189 int http_base_proto = filename ? ff_is_http_proto(filename) : 0;
194 if (!http_base_proto || !c->http_persistent) {
195 ff_format_io_close(s, pb);
196 #if CONFIG_HTTP_PROTOCOL
198 URLContext *http_url_context = ffio_geturlcontext(*pb);
199 av_assert0(http_url_context);
201 ffurl_shutdown(http_url_context, AVIO_FLAG_WRITE);
206 static const char *get_format_str(SegmentType segment_type) {
208 for (i = 0; i < SEGMENT_TYPE_NB; i++)
209 if (formats[i].segment_type == segment_type)
210 return formats[i].str;
214 static int handle_io_open_error(AVFormatContext *s, int err, char *url) {
215 DASHContext *c = s->priv_data;
216 char errbuf[AV_ERROR_MAX_STRING_SIZE];
217 av_strerror(err, errbuf, sizeof(errbuf));
218 av_log(s, c->ignore_io_errors ? AV_LOG_WARNING : AV_LOG_ERROR,
219 "Unable to open %s for writing: %s\n", url, errbuf);
220 return c->ignore_io_errors ? 0 : err;
223 static inline SegmentType select_segment_type(SegmentType segment_type, enum AVCodecID codec_id)
225 if (segment_type == SEGMENT_TYPE_AUTO) {
226 if (codec_id == AV_CODEC_ID_OPUS || codec_id == AV_CODEC_ID_VORBIS ||
227 codec_id == AV_CODEC_ID_VP8 || codec_id == AV_CODEC_ID_VP9) {
228 segment_type = SEGMENT_TYPE_WEBM;
230 segment_type = SEGMENT_TYPE_MP4;
237 static int init_segment_types(AVFormatContext *s)
239 DASHContext *c = s->priv_data;
240 int has_mp4_streams = 0;
241 for (int i = 0; i < s->nb_streams; ++i) {
242 OutputStream *os = &c->streams[i];
243 SegmentType segment_type = select_segment_type(
244 c->segment_type_option, s->streams[i]->codecpar->codec_id);
245 os->segment_type = segment_type;
246 os->format_name = get_format_str(segment_type);
247 if (!os->format_name) {
248 av_log(s, AV_LOG_ERROR, "Could not select DASH segment type for stream %d\n", i);
249 return AVERROR_MUXER_NOT_FOUND;
251 has_mp4_streams |= segment_type == SEGMENT_TYPE_MP4;
254 if (c->hls_playlist && !has_mp4_streams) {
255 av_log(s, AV_LOG_WARNING, "No mp4 streams, disabling HLS manifest generation\n");
262 static int check_file_extension(const char *filename, const char *extension) {
264 if (!filename || !extension)
266 dot = strrchr(filename, '.');
267 if (dot && !strcmp(dot + 1, extension))
272 static void set_vp9_codec_str(AVFormatContext *s, AVCodecParameters *par,
273 AVRational *frame_rate, char *str, int size) {
275 int ret = ff_isom_get_vpcc_features(s, par, frame_rate, &vpcc);
277 av_strlcatf(str, size, "vp09.%02d.%02d.%02d",
278 vpcc.profile, vpcc.level, vpcc.bitdepth);
280 // Default to just vp9 in case of error while finding out profile or level
281 av_log(s, AV_LOG_WARNING, "Could not find VP9 profile and/or level\n");
282 av_strlcpy(str, "vp9", size);
287 static void set_codec_str(AVFormatContext *s, AVCodecParameters *par,
288 AVRational *frame_rate, char *str, int size)
290 const AVCodecTag *tags[2] = { NULL, NULL };
294 // common Webm codecs are not part of RFC 6381
295 for (i = 0; codecs[i].id; i++)
296 if (codecs[i].id == par->codec_id) {
297 if (codecs[i].id == AV_CODEC_ID_VP9) {
298 set_vp9_codec_str(s, par, frame_rate, str, size);
300 av_strlcpy(str, codecs[i].str, size);
305 // for codecs part of RFC 6381
306 if (par->codec_type == AVMEDIA_TYPE_VIDEO)
307 tags[0] = ff_codec_movvideo_tags;
308 else if (par->codec_type == AVMEDIA_TYPE_AUDIO)
309 tags[0] = ff_codec_movaudio_tags;
313 tag = par->codec_tag;
315 tag = av_codec_get_tag(tags, par->codec_id);
323 if (!strcmp(str, "mp4a") || !strcmp(str, "mp4v")) {
325 tags[0] = ff_mp4_obj_type;
326 oti = av_codec_get_tag(tags, par->codec_id);
328 av_strlcatf(str, size, ".%02"PRIx32, oti);
332 if (tag == MKTAG('m', 'p', '4', 'a')) {
333 if (par->extradata_size >= 2) {
334 int aot = par->extradata[0] >> 3;
336 aot = ((AV_RB16(par->extradata) >> 5) & 0x3f) + 32;
337 av_strlcatf(str, size, ".%d", aot);
339 } else if (tag == MKTAG('m', 'p', '4', 'v')) {
340 // Unimplemented, should output ProfileLevelIndication as a decimal number
341 av_log(s, AV_LOG_WARNING, "Incomplete RFC 6381 codec string for mp4v\n");
343 } else if (!strcmp(str, "avc1")) {
344 uint8_t *tmpbuf = NULL;
345 uint8_t *extradata = par->extradata;
346 int extradata_size = par->extradata_size;
349 if (extradata[0] != 1) {
351 if (avio_open_dyn_buf(&pb) < 0)
353 if (ff_isom_write_avcc(pb, extradata, extradata_size) < 0) {
354 ffio_free_dyn_buf(&pb);
357 extradata_size = avio_close_dyn_buf(pb, &extradata);
361 if (extradata_size >= 4)
362 av_strlcatf(str, size, ".%02x%02x%02x",
363 extradata[1], extradata[2], extradata[3]);
368 static int flush_dynbuf(OutputStream *os, int *range_length)
373 return AVERROR(EINVAL);
377 av_write_frame(os->ctx, NULL);
378 avio_flush(os->ctx->pb);
381 *range_length = avio_close_dyn_buf(os->ctx->pb, &buffer);
384 avio_write(os->out, buffer + os->written_len, *range_length - os->written_len);
389 return avio_open_dyn_buf(&os->ctx->pb);
392 static void set_http_options(AVDictionary **options, DASHContext *c)
395 av_dict_set(options, "method", c->method, 0);
397 av_dict_set(options, "user_agent", c->user_agent, 0);
398 if (c->http_persistent)
399 av_dict_set_int(options, "multiple_requests", 1, 0);
401 av_dict_set_int(options, "timeout", c->timeout, 0);
404 static void get_hls_playlist_name(char *playlist_name, int string_size,
405 const char *base_url, int id) {
407 snprintf(playlist_name, string_size, "%smedia_%d.m3u8", base_url, id);
409 snprintf(playlist_name, string_size, "media_%d.m3u8", id);
412 static void get_start_index_number(OutputStream *os, DASHContext *c,
413 int *start_index, int *start_number) {
416 if (c->window_size) {
417 *start_index = FFMAX(os->nb_segments - c->window_size, 0);
418 *start_number = FFMAX(os->segment_index - c->window_size, 1);
422 static void write_hls_media_playlist(OutputStream *os, AVFormatContext *s,
423 int representation_id, int final,
424 char *prefetch_url) {
425 DASHContext *c = s->priv_data;
426 int timescale = os->ctx->streams[0]->time_base.den;
427 char temp_filename_hls[1024];
428 char filename_hls[1024];
429 AVDictionary *http_opts = NULL;
430 int target_duration = 0;
432 const char *proto = avio_find_protocol_name(c->dirname);
433 int use_rename = proto && !strcmp(proto, "file");
434 int i, start_index, start_number;
436 get_start_index_number(os, c, &start_index, &start_number);
438 if (!c->hls_playlist || start_index >= os->nb_segments ||
439 os->segment_type != SEGMENT_TYPE_MP4)
442 get_hls_playlist_name(filename_hls, sizeof(filename_hls),
443 c->dirname, representation_id);
445 snprintf(temp_filename_hls, sizeof(temp_filename_hls), use_rename ? "%s.tmp" : "%s", filename_hls);
447 set_http_options(&http_opts, c);
448 ret = dashenc_io_open(s, &c->m3u8_out, temp_filename_hls, &http_opts);
449 av_dict_free(&http_opts);
451 handle_io_open_error(s, ret, temp_filename_hls);
454 for (i = start_index; i < os->nb_segments; i++) {
455 Segment *seg = os->segments[i];
456 double duration = (double) seg->duration / timescale;
457 if (target_duration <= duration)
458 target_duration = lrint(duration);
461 ff_hls_write_playlist_header(c->m3u8_out, 6, -1, target_duration,
462 start_number, PLAYLIST_TYPE_NONE);
464 ff_hls_write_init_file(c->m3u8_out, os->initfile, c->single_file,
465 os->init_range_length, os->init_start_pos);
467 for (i = start_index; i < os->nb_segments; i++) {
468 Segment *seg = os->segments[i];
469 ret = ff_hls_write_file_entry(c->m3u8_out, 0, c->single_file,
470 (double) seg->duration / timescale, 0,
471 seg->range_length, seg->start_pos, NULL,
472 c->single_file ? os->initfile : seg->file,
475 av_log(os->ctx, AV_LOG_WARNING, "ff_hls_write_file_entry get error\n");
480 avio_printf(c->m3u8_out, "#EXT-X-PREFETCH:%s\n", prefetch_url);
483 ff_hls_write_end_list(c->m3u8_out);
485 dashenc_io_close(s, &c->m3u8_out, temp_filename_hls);
488 if (avpriv_io_move(temp_filename_hls, filename_hls) < 0) {
489 av_log(os->ctx, AV_LOG_WARNING, "renaming file %s to %s failed\n\n", temp_filename_hls, filename_hls);
493 static int flush_init_segment(AVFormatContext *s, OutputStream *os)
495 DASHContext *c = s->priv_data;
496 int ret, range_length;
498 ret = flush_dynbuf(os, &range_length);
502 os->pos = os->init_range_length = range_length;
503 if (!c->single_file) {
505 snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
506 dashenc_io_close(s, &os->out, filename);
511 static void dash_free(AVFormatContext *s)
513 DASHContext *c = s->priv_data;
517 for (i = 0; i < c->nb_as; i++)
518 av_dict_free(&c->as[i].metadata);
525 for (i = 0; i < s->nb_streams; i++) {
526 OutputStream *os = &c->streams[i];
527 if (os->ctx && os->ctx->pb)
528 ffio_free_dyn_buf(&os->ctx->pb);
529 ff_format_io_close(s, &os->out);
531 avformat_free_context(os->ctx);
532 for (j = 0; j < os->nb_segments; j++)
533 av_free(os->segments[j]);
534 av_free(os->segments);
535 av_freep(&os->single_file_name);
536 av_freep(&os->init_seg_name);
537 av_freep(&os->media_seg_name);
539 av_freep(&c->streams);
541 ff_format_io_close(s, &c->mpd_out);
542 ff_format_io_close(s, &c->m3u8_out);
545 static void output_segment_list(OutputStream *os, AVIOContext *out, AVFormatContext *s,
546 int representation_id, int final)
548 DASHContext *c = s->priv_data;
549 int i, start_index, start_number;
550 get_start_index_number(os, c, &start_index, &start_number);
552 if (c->use_template) {
553 int timescale = c->use_timeline ? os->ctx->streams[0]->time_base.den : AV_TIME_BASE;
554 avio_printf(out, "\t\t\t\t<SegmentTemplate timescale=\"%d\" ", timescale);
555 if (!c->use_timeline) {
556 avio_printf(out, "duration=\"%"PRId64"\" ", c->seg_duration);
557 if (c->streaming && os->availability_time_offset)
558 avio_printf(out, "availabilityTimeOffset=\"%.3f\" ",
559 os->availability_time_offset);
561 avio_printf(out, "initialization=\"%s\" media=\"%s\" startNumber=\"%d\">\n", os->init_seg_name, os->media_seg_name, c->use_timeline ? start_number : 1);
562 if (c->use_timeline) {
563 int64_t cur_time = 0;
564 avio_printf(out, "\t\t\t\t\t<SegmentTimeline>\n");
565 for (i = start_index; i < os->nb_segments; ) {
566 Segment *seg = os->segments[i];
568 avio_printf(out, "\t\t\t\t\t\t<S ");
569 if (i == start_index || seg->time != cur_time) {
570 cur_time = seg->time;
571 avio_printf(out, "t=\"%"PRId64"\" ", seg->time);
573 avio_printf(out, "d=\"%"PRId64"\" ", seg->duration);
574 while (i + repeat + 1 < os->nb_segments &&
575 os->segments[i + repeat + 1]->duration == seg->duration &&
576 os->segments[i + repeat + 1]->time == os->segments[i + repeat]->time + os->segments[i + repeat]->duration)
579 avio_printf(out, "r=\"%d\" ", repeat);
580 avio_printf(out, "/>\n");
582 cur_time += (1 + repeat) * seg->duration;
584 avio_printf(out, "\t\t\t\t\t</SegmentTimeline>\n");
586 avio_printf(out, "\t\t\t\t</SegmentTemplate>\n");
587 } else if (c->single_file) {
588 avio_printf(out, "\t\t\t\t<BaseURL>%s</BaseURL>\n", os->initfile);
589 avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%"PRId64"\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);
590 avio_printf(out, "\t\t\t\t\t<Initialization range=\"%"PRId64"-%"PRId64"\" />\n", os->init_start_pos, os->init_start_pos + os->init_range_length - 1);
591 for (i = start_index; i < os->nb_segments; i++) {
592 Segment *seg = os->segments[i];
593 avio_printf(out, "\t\t\t\t\t<SegmentURL mediaRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->range_length - 1);
594 if (seg->index_length)
595 avio_printf(out, "indexRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->index_length - 1);
596 avio_printf(out, "/>\n");
598 avio_printf(out, "\t\t\t\t</SegmentList>\n");
600 avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%"PRId64"\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);
601 avio_printf(out, "\t\t\t\t\t<Initialization sourceURL=\"%s\" />\n", os->initfile);
602 for (i = start_index; i < os->nb_segments; i++) {
603 Segment *seg = os->segments[i];
604 avio_printf(out, "\t\t\t\t\t<SegmentURL media=\"%s\" />\n", seg->file);
606 avio_printf(out, "\t\t\t\t</SegmentList>\n");
608 if (!c->lhls || final) {
609 write_hls_media_playlist(os, s, representation_id, final, NULL);
614 static char *xmlescape(const char *str) {
615 int outlen = strlen(str)*3/2 + 6;
616 char *out = av_realloc(NULL, outlen + 1);
620 for (; *str; str++) {
621 if (pos + 6 > outlen) {
623 outlen = 2 * outlen + 6;
624 tmp = av_realloc(out, outlen + 1);
632 memcpy(&out[pos], "&", 5);
634 } else if (*str == '<') {
635 memcpy(&out[pos], "<", 4);
637 } else if (*str == '>') {
638 memcpy(&out[pos], ">", 4);
640 } else if (*str == '\'') {
641 memcpy(&out[pos], "'", 6);
643 } else if (*str == '\"') {
644 memcpy(&out[pos], """, 6);
654 static void write_time(AVIOContext *out, int64_t time)
656 int seconds = time / AV_TIME_BASE;
657 int fractions = time % AV_TIME_BASE;
658 int minutes = seconds / 60;
659 int hours = minutes / 60;
662 avio_printf(out, "PT");
664 avio_printf(out, "%dH", hours);
665 if (hours || minutes)
666 avio_printf(out, "%dM", minutes);
667 avio_printf(out, "%d.%dS", seconds, fractions / (AV_TIME_BASE / 10));
670 static void format_date_now(char *buf, int size)
672 struct tm *ptm, tmbuf;
673 int64_t time_us = av_gettime();
674 int64_t time_ms = time_us / 1000;
675 const time_t time_s = time_ms / 1000;
676 int millisec = time_ms - (time_s * 1000);
677 ptm = gmtime_r(&time_s, &tmbuf);
680 if (!strftime(buf, size, "%Y-%m-%dT%H:%M:%S", ptm)) {
685 snprintf(buf + len, size - len, ".%03dZ", millisec);
689 static int write_adaptation_set(AVFormatContext *s, AVIOContext *out, int as_index,
692 DASHContext *c = s->priv_data;
693 AdaptationSet *as = &c->as[as_index];
694 AVDictionaryEntry *lang, *role;
697 avio_printf(out, "\t\t<AdaptationSet id=\"%s\" contentType=\"%s\" segmentAlignment=\"true\" bitstreamSwitching=\"true\"",
698 as->id, as->media_type == AVMEDIA_TYPE_VIDEO ? "video" : "audio");
699 if (as->media_type == AVMEDIA_TYPE_VIDEO && as->max_frame_rate.num && !as->ambiguous_frame_rate && av_cmp_q(as->min_frame_rate, as->max_frame_rate) < 0)
700 avio_printf(out, " maxFrameRate=\"%d/%d\"", as->max_frame_rate.num, as->max_frame_rate.den);
701 lang = av_dict_get(as->metadata, "language", NULL, 0);
703 avio_printf(out, " lang=\"%s\"", lang->value);
704 avio_printf(out, ">\n");
706 role = av_dict_get(as->metadata, "role", NULL, 0);
708 avio_printf(out, "\t\t\t<Role schemeIdUri=\"urn:mpeg:dash:role:2011\" value=\"%s\"/>\n", role->value);
710 for (i = 0; i < s->nb_streams; i++) {
711 OutputStream *os = &c->streams[i];
712 char bandwidth_str[64] = {'\0'};
714 if (os->as_idx - 1 != as_index)
717 if (os->bit_rate > 0)
718 snprintf(bandwidth_str, sizeof(bandwidth_str), " bandwidth=\"%d\"",
721 if (as->media_type == AVMEDIA_TYPE_VIDEO) {
722 AVStream *st = s->streams[i];
723 avio_printf(out, "\t\t\t<Representation id=\"%d\" mimeType=\"video/%s\" codecs=\"%s\"%s width=\"%d\" height=\"%d\"",
724 i, os->format_name, os->codec_str, bandwidth_str, s->streams[i]->codecpar->width, s->streams[i]->codecpar->height);
725 if (st->avg_frame_rate.num)
726 avio_printf(out, " frameRate=\"%d/%d\"", st->avg_frame_rate.num, st->avg_frame_rate.den);
727 avio_printf(out, ">\n");
729 avio_printf(out, "\t\t\t<Representation id=\"%d\" mimeType=\"audio/%s\" codecs=\"%s\"%s audioSamplingRate=\"%d\">\n",
730 i, os->format_name, os->codec_str, bandwidth_str, s->streams[i]->codecpar->sample_rate);
731 avio_printf(out, "\t\t\t\t<AudioChannelConfiguration schemeIdUri=\"urn:mpeg:dash:23003:3:audio_channel_configuration:2011\" value=\"%d\" />\n",
732 s->streams[i]->codecpar->channels);
734 output_segment_list(os, out, s, i, final);
735 avio_printf(out, "\t\t\t</Representation>\n");
737 avio_printf(out, "\t\t</AdaptationSet>\n");
742 static int add_adaptation_set(AVFormatContext *s, AdaptationSet **as, enum AVMediaType type)
744 DASHContext *c = s->priv_data;
746 void *mem = av_realloc(c->as, sizeof(*c->as) * (c->nb_as + 1));
748 return AVERROR(ENOMEM);
752 *as = &c->as[c->nb_as - 1];
753 memset(*as, 0, sizeof(**as));
754 (*as)->media_type = type;
759 static int adaptation_set_add_stream(AVFormatContext *s, int as_idx, int i)
761 DASHContext *c = s->priv_data;
762 AdaptationSet *as = &c->as[as_idx - 1];
763 OutputStream *os = &c->streams[i];
765 if (as->media_type != s->streams[i]->codecpar->codec_type) {
766 av_log(s, AV_LOG_ERROR, "Codec type of stream %d doesn't match AdaptationSet's media type\n", i);
767 return AVERROR(EINVAL);
768 } else if (os->as_idx) {
769 av_log(s, AV_LOG_ERROR, "Stream %d is already assigned to an AdaptationSet\n", i);
770 return AVERROR(EINVAL);
777 static int parse_adaptation_sets(AVFormatContext *s)
779 DASHContext *c = s->priv_data;
780 const char *p = c->adaptation_sets;
781 enum { new_set, parse_id, parsing_streams } state;
785 // default: one AdaptationSet for each stream
787 for (i = 0; i < s->nb_streams; i++) {
788 if ((ret = add_adaptation_set(s, &as, s->streams[i]->codecpar->codec_type)) < 0)
790 snprintf(as->id, sizeof(as->id), "%d", i);
792 c->streams[i].as_idx = c->nb_as;
797 // syntax id=0,streams=0,1,2 id=1,streams=3,4 and so on
803 } else if (state == new_set && av_strstart(p, "id=", &p)) {
805 if ((ret = add_adaptation_set(s, &as, AVMEDIA_TYPE_UNKNOWN)) < 0)
809 snprintf(as->id, sizeof(as->id), "%.*s", n, p);
815 } else if (state == parse_id && av_strstart(p, "streams=", &p)) {
816 state = parsing_streams;
817 } else if (state == parsing_streams) {
818 AdaptationSet *as = &c->as[c->nb_as - 1];
819 char idx_str[8], *end_str;
821 n = strcspn(p, " ,");
822 snprintf(idx_str, sizeof(idx_str), "%.*s", n, p);
825 // if value is "a" or "v", map all streams of that type
826 if (as->media_type == AVMEDIA_TYPE_UNKNOWN && (idx_str[0] == 'v' || idx_str[0] == 'a')) {
827 enum AVMediaType type = (idx_str[0] == 'v') ? AVMEDIA_TYPE_VIDEO : AVMEDIA_TYPE_AUDIO;
828 av_log(s, AV_LOG_DEBUG, "Map all streams of type %s\n", idx_str);
830 for (i = 0; i < s->nb_streams; i++) {
831 if (s->streams[i]->codecpar->codec_type != type)
834 as->media_type = s->streams[i]->codecpar->codec_type;
836 if ((ret = adaptation_set_add_stream(s, c->nb_as, i)) < 0)
839 } else { // select single stream
840 i = strtol(idx_str, &end_str, 10);
841 if (idx_str == end_str || i < 0 || i >= s->nb_streams) {
842 av_log(s, AV_LOG_ERROR, "Selected stream \"%s\" not found!\n", idx_str);
843 return AVERROR(EINVAL);
845 av_log(s, AV_LOG_DEBUG, "Map stream %d\n", i);
847 if (as->media_type == AVMEDIA_TYPE_UNKNOWN) {
848 as->media_type = s->streams[i]->codecpar->codec_type;
851 if ((ret = adaptation_set_add_stream(s, c->nb_as, i)) < 0)
860 return AVERROR(EINVAL);
865 // check for unassigned streams
866 for (i = 0; i < s->nb_streams; i++) {
867 OutputStream *os = &c->streams[i];
869 av_log(s, AV_LOG_ERROR, "Stream %d is not mapped to an AdaptationSet\n", i);
870 return AVERROR(EINVAL);
876 static int write_manifest(AVFormatContext *s, int final)
878 DASHContext *c = s->priv_data;
880 char temp_filename[1024];
882 const char *proto = avio_find_protocol_name(s->url);
883 int use_rename = proto && !strcmp(proto, "file");
884 static unsigned int warned_non_file = 0;
885 AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
886 AVDictionary *opts = NULL;
888 if (!use_rename && !warned_non_file++)
889 av_log(s, AV_LOG_ERROR, "Cannot use rename on non file protocol, this may lead to races and temporary partial files\n");
891 snprintf(temp_filename, sizeof(temp_filename), use_rename ? "%s.tmp" : "%s", s->url);
892 set_http_options(&opts, c);
893 ret = dashenc_io_open(s, &c->mpd_out, temp_filename, &opts);
896 return handle_io_open_error(s, ret, temp_filename);
899 avio_printf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
900 avio_printf(out, "<MPD xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
901 "\txmlns=\"urn:mpeg:dash:schema:mpd:2011\"\n"
902 "\txmlns:xlink=\"http://www.w3.org/1999/xlink\"\n"
903 "\txsi:schemaLocation=\"urn:mpeg:DASH:schema:MPD:2011 http://standards.iso.org/ittf/PubliclyAvailableStandards/MPEG-DASH_schema_files/DASH-MPD.xsd\"\n"
904 "\tprofiles=\"urn:mpeg:dash:profile:isoff-live:2011\"\n"
905 "\ttype=\"%s\"\n", final ? "static" : "dynamic");
907 avio_printf(out, "\tmediaPresentationDuration=\"");
908 write_time(out, c->total_duration);
909 avio_printf(out, "\"\n");
911 int64_t update_period = c->last_duration / AV_TIME_BASE;
913 if (c->use_template && !c->use_timeline)
915 avio_printf(out, "\tminimumUpdatePeriod=\"PT%"PRId64"S\"\n", update_period);
916 avio_printf(out, "\tsuggestedPresentationDelay=\"PT%"PRId64"S\"\n", c->last_duration / AV_TIME_BASE);
917 if (c->availability_start_time[0])
918 avio_printf(out, "\tavailabilityStartTime=\"%s\"\n", c->availability_start_time);
919 format_date_now(now_str, sizeof(now_str));
921 avio_printf(out, "\tpublishTime=\"%s\"\n", now_str);
922 if (c->window_size && c->use_template) {
923 avio_printf(out, "\ttimeShiftBufferDepth=\"");
924 write_time(out, c->last_duration * c->window_size);
925 avio_printf(out, "\"\n");
928 avio_printf(out, "\tminBufferTime=\"");
929 write_time(out, c->last_duration * 2);
930 avio_printf(out, "\">\n");
931 avio_printf(out, "\t<ProgramInformation>\n");
933 char *escaped = xmlescape(title->value);
934 avio_printf(out, "\t\t<Title>%s</Title>\n", escaped);
937 avio_printf(out, "\t</ProgramInformation>\n");
939 if (c->window_size && s->nb_streams > 0 && c->streams[0].nb_segments > 0 && !c->use_template) {
940 OutputStream *os = &c->streams[0];
941 int start_index = FFMAX(os->nb_segments - c->window_size, 0);
942 int64_t start_time = av_rescale_q(os->segments[start_index]->time, s->streams[0]->time_base, AV_TIME_BASE_Q);
943 avio_printf(out, "\t<Period id=\"0\" start=\"");
944 write_time(out, start_time);
945 avio_printf(out, "\">\n");
947 avio_printf(out, "\t<Period id=\"0\" start=\"PT0.0S\">\n");
950 for (i = 0; i < c->nb_as; i++) {
951 if ((ret = write_adaptation_set(s, out, i, final)) < 0)
954 avio_printf(out, "\t</Period>\n");
956 if (c->utc_timing_url)
957 avio_printf(out, "\t<UTCTiming schemeIdUri=\"urn:mpeg:dash:utc:http-xsdate:2014\" value=\"%s\"/>\n", c->utc_timing_url);
959 avio_printf(out, "</MPD>\n");
961 dashenc_io_close(s, &c->mpd_out, temp_filename);
964 if ((ret = avpriv_io_move(temp_filename, s->url)) < 0)
968 if (c->hls_playlist && !c->master_playlist_created) {
969 char filename_hls[1024];
970 const char *audio_group = "A1";
971 char audio_codec_str[128] = "\0";
973 int max_audio_bitrate = 0;
976 snprintf(filename_hls, sizeof(filename_hls), "%smaster.m3u8", c->dirname);
978 snprintf(filename_hls, sizeof(filename_hls), "master.m3u8");
980 snprintf(temp_filename, sizeof(temp_filename), use_rename ? "%s.tmp" : "%s", filename_hls);
982 set_http_options(&opts, c);
983 ret = dashenc_io_open(s, &c->m3u8_out, temp_filename, &opts);
986 return handle_io_open_error(s, ret, temp_filename);
989 ff_hls_write_playlist_version(c->m3u8_out, 7);
991 for (i = 0; i < s->nb_streams; i++) {
992 char playlist_file[64];
993 AVStream *st = s->streams[i];
994 OutputStream *os = &c->streams[i];
995 if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO)
997 if (os->segment_type != SEGMENT_TYPE_MP4)
999 get_hls_playlist_name(playlist_file, sizeof(playlist_file), NULL, i);
1000 ff_hls_write_audio_rendition(c->m3u8_out, (char *)audio_group,
1001 playlist_file, NULL, i, is_default);
1002 max_audio_bitrate = FFMAX(st->codecpar->bit_rate +
1003 os->muxer_overhead, max_audio_bitrate);
1004 if (!av_strnstr(audio_codec_str, os->codec_str, sizeof(audio_codec_str))) {
1005 if (strlen(audio_codec_str))
1006 av_strlcat(audio_codec_str, ",", sizeof(audio_codec_str));
1007 av_strlcat(audio_codec_str, os->codec_str, sizeof(audio_codec_str));
1012 for (i = 0; i < s->nb_streams; i++) {
1013 char playlist_file[64];
1014 char codec_str[128];
1015 AVStream *st = s->streams[i];
1016 OutputStream *os = &c->streams[i];
1017 char *agroup = NULL;
1018 char *codec_str_ptr = NULL;
1019 int stream_bitrate = st->codecpar->bit_rate + os->muxer_overhead;
1020 if (st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO)
1022 if (os->segment_type != SEGMENT_TYPE_MP4)
1024 av_strlcpy(codec_str, os->codec_str, sizeof(codec_str));
1025 if (max_audio_bitrate) {
1026 agroup = (char *)audio_group;
1027 stream_bitrate += max_audio_bitrate;
1028 av_strlcat(codec_str, ",", sizeof(codec_str));
1029 av_strlcat(codec_str, audio_codec_str, sizeof(codec_str));
1031 if (st->codecpar->codec_id != AV_CODEC_ID_HEVC) {
1032 codec_str_ptr = codec_str;
1034 get_hls_playlist_name(playlist_file, sizeof(playlist_file), NULL, i);
1035 ff_hls_write_stream_info(st, c->m3u8_out, stream_bitrate,
1036 playlist_file, agroup,
1037 codec_str_ptr, NULL);
1039 dashenc_io_close(s, &c->m3u8_out, temp_filename);
1041 if ((ret = avpriv_io_move(temp_filename, filename_hls)) < 0)
1043 c->master_playlist_created = 1;
1049 static int dict_copy_entry(AVDictionary **dst, const AVDictionary *src, const char *key)
1051 AVDictionaryEntry *entry = av_dict_get(src, key, NULL, 0);
1053 av_dict_set(dst, key, entry->value, AV_DICT_DONT_OVERWRITE);
1057 static int dash_init(AVFormatContext *s)
1059 DASHContext *c = s->priv_data;
1062 char basename[1024];
1064 if (c->single_file_name)
1067 c->use_template = 0;
1069 #if FF_API_DASH_MIN_SEG_DURATION
1070 if (c->min_seg_duration != 5000000) {
1071 av_log(s, AV_LOG_WARNING, "The min_seg_duration option is deprecated and will be removed. Please use the -seg_duration\n");
1072 c->seg_duration = c->min_seg_duration;
1075 if (c->lhls && s->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
1076 av_log(s, AV_LOG_ERROR,
1077 "LHLS is experimental, Please set -strict experimental in order to enable it.\n");
1078 return AVERROR_EXPERIMENTAL;
1081 if (c->lhls && !c->streaming) {
1082 av_log(s, AV_LOG_WARNING, "LHLS option will be ignored as streaming is not enabled\n");
1086 if (c->lhls && !c->hls_playlist) {
1087 av_log(s, AV_LOG_WARNING, "LHLS option will be ignored as hls_playlist is not enabled\n");
1091 av_strlcpy(c->dirname, s->url, sizeof(c->dirname));
1092 ptr = strrchr(c->dirname, '/');
1094 av_strlcpy(basename, &ptr[1], sizeof(basename));
1097 c->dirname[0] = '\0';
1098 av_strlcpy(basename, s->url, sizeof(basename));
1101 ptr = strrchr(basename, '.');
1105 c->streams = av_mallocz(sizeof(*c->streams) * s->nb_streams);
1107 return AVERROR(ENOMEM);
1109 if ((ret = parse_adaptation_sets(s)) < 0)
1112 if ((ret = init_segment_types(s)) < 0)
1115 for (i = 0; i < s->nb_streams; i++) {
1116 OutputStream *os = &c->streams[i];
1117 AdaptationSet *as = &c->as[os->as_idx - 1];
1118 AVFormatContext *ctx;
1120 AVDictionary *opts = NULL;
1121 char filename[1024];
1123 os->bit_rate = s->streams[i]->codecpar->bit_rate;
1124 if (!os->bit_rate) {
1125 int level = s->strict_std_compliance >= FF_COMPLIANCE_STRICT ?
1126 AV_LOG_ERROR : AV_LOG_WARNING;
1127 av_log(s, level, "No bit rate set for stream %d\n", i);
1128 if (s->strict_std_compliance >= FF_COMPLIANCE_STRICT)
1129 return AVERROR(EINVAL);
1132 // copy AdaptationSet language and role from stream metadata
1133 dict_copy_entry(&as->metadata, s->streams[i]->metadata, "language");
1134 dict_copy_entry(&as->metadata, s->streams[i]->metadata, "role");
1136 ctx = avformat_alloc_context();
1138 return AVERROR(ENOMEM);
1140 if (c->init_seg_name) {
1141 os->init_seg_name = av_strireplace(c->init_seg_name, "$ext$", os->format_name);
1142 if (!os->init_seg_name)
1143 return AVERROR(ENOMEM);
1145 if (c->media_seg_name) {
1146 os->media_seg_name = av_strireplace(c->media_seg_name, "$ext$", os->format_name);
1147 if (!os->media_seg_name)
1148 return AVERROR(ENOMEM);
1150 if (c->single_file_name) {
1151 os->single_file_name = av_strireplace(c->single_file_name, "$ext$", os->format_name);
1152 if (!os->single_file_name)
1153 return AVERROR(ENOMEM);
1156 if (os->segment_type == SEGMENT_TYPE_WEBM) {
1157 if ((!c->single_file && check_file_extension(os->init_seg_name, os->format_name) != 0) ||
1158 (!c->single_file && check_file_extension(os->media_seg_name, os->format_name) != 0) ||
1159 (c->single_file && check_file_extension(os->single_file_name, os->format_name) != 0)) {
1160 av_log(s, AV_LOG_WARNING,
1161 "One or many segment file names doesn't end with .webm. "
1162 "Override -init_seg_name and/or -media_seg_name and/or "
1163 "-single_file_name to end with the extension .webm\n");
1167 ctx->oformat = av_guess_format(os->format_name, NULL, NULL);
1169 return AVERROR_MUXER_NOT_FOUND;
1171 ctx->interrupt_callback = s->interrupt_callback;
1172 ctx->opaque = s->opaque;
1173 ctx->io_close = s->io_close;
1174 ctx->io_open = s->io_open;
1175 ctx->strict_std_compliance = s->strict_std_compliance;
1177 if (!(st = avformat_new_stream(ctx, NULL)))
1178 return AVERROR(ENOMEM);
1179 avcodec_parameters_copy(st->codecpar, s->streams[i]->codecpar);
1180 st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
1181 st->time_base = s->streams[i]->time_base;
1182 st->avg_frame_rate = s->streams[i]->avg_frame_rate;
1183 ctx->avoid_negative_ts = s->avoid_negative_ts;
1184 ctx->flags = s->flags;
1186 if ((ret = avio_open_dyn_buf(&ctx->pb)) < 0)
1189 if (c->single_file) {
1190 if (os->single_file_name)
1191 ff_dash_fill_tmpl_params(os->initfile, sizeof(os->initfile), os->single_file_name, i, 0, os->bit_rate, 0);
1193 snprintf(os->initfile, sizeof(os->initfile), "%s-stream%d.%s", basename, i, os->format_name);
1195 ff_dash_fill_tmpl_params(os->initfile, sizeof(os->initfile), os->init_seg_name, i, 0, os->bit_rate, 0);
1197 snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
1198 set_http_options(&opts, c);
1199 ret = s->io_open(s, &os->out, filename, AVIO_FLAG_WRITE, &opts);
1200 av_dict_free(&opts);
1203 os->init_start_pos = 0;
1205 if (c->format_options_str) {
1206 ret = av_dict_parse_string(&opts, c->format_options_str, "=", ":", 0);
1211 if (os->segment_type == SEGMENT_TYPE_MP4) {
1213 av_dict_set(&opts, "movflags", "frag_every_frame+dash+delay_moov+skip_sidx+skip_trailer", 0);
1215 av_dict_set(&opts, "movflags", "frag_custom+dash+delay_moov", 0);
1217 av_dict_set_int(&opts, "cluster_time_limit", c->seg_duration / 1000, 0);
1218 av_dict_set_int(&opts, "cluster_size_limit", 5 * 1024 * 1024, 0); // set a large cluster size limit
1219 av_dict_set_int(&opts, "dash", 1, 0);
1220 av_dict_set_int(&opts, "dash_track_number", i + 1, 0);
1221 av_dict_set_int(&opts, "live", 1, 0);
1223 ret = avformat_init_output(ctx, &opts);
1224 av_dict_free(&opts);
1228 avio_flush(ctx->pb);
1230 av_log(s, AV_LOG_VERBOSE, "Representation %d init segment will be written to: %s\n", i, filename);
1232 s->streams[i]->time_base = st->time_base;
1233 // If the muxer wants to shift timestamps, request to have them shifted
1234 // already before being handed to this muxer, so we don't have mismatches
1235 // between the MPD and the actual segments.
1236 s->avoid_negative_ts = ctx->avoid_negative_ts;
1237 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
1238 AVRational avg_frame_rate = s->streams[i]->avg_frame_rate;
1239 if (avg_frame_rate.num > 0) {
1240 if (av_cmp_q(avg_frame_rate, as->min_frame_rate) < 0)
1241 as->min_frame_rate = avg_frame_rate;
1242 if (av_cmp_q(as->max_frame_rate, avg_frame_rate) < 0)
1243 as->max_frame_rate = avg_frame_rate;
1245 as->ambiguous_frame_rate = 1;
1250 set_codec_str(s, st->codecpar, &st->avg_frame_rate, os->codec_str,
1251 sizeof(os->codec_str));
1252 os->first_pts = AV_NOPTS_VALUE;
1253 os->max_pts = AV_NOPTS_VALUE;
1254 os->last_dts = AV_NOPTS_VALUE;
1255 os->segment_index = 1;
1258 if (!c->has_video && c->seg_duration <= 0) {
1259 av_log(s, AV_LOG_WARNING, "no video stream and no seg duration set\n");
1260 return AVERROR(EINVAL);
1265 static int dash_write_header(AVFormatContext *s)
1267 DASHContext *c = s->priv_data;
1269 for (i = 0; i < s->nb_streams; i++) {
1270 OutputStream *os = &c->streams[i];
1271 if ((ret = avformat_write_header(os->ctx, NULL)) < 0)
1274 // Flush init segment
1275 // Only for WebM segment, since for mp4 delay_moov is set and
1276 // the init segment is thus flushed after the first packets.
1277 if (os->segment_type == SEGMENT_TYPE_WEBM &&
1278 (ret = flush_init_segment(s, os)) < 0)
1284 static int add_segment(OutputStream *os, const char *file,
1285 int64_t time, int64_t duration,
1286 int64_t start_pos, int64_t range_length,
1287 int64_t index_length, int next_exp_index)
1291 if (os->nb_segments >= os->segments_size) {
1292 os->segments_size = (os->segments_size + 1) * 2;
1293 if ((err = av_reallocp(&os->segments, sizeof(*os->segments) *
1294 os->segments_size)) < 0) {
1295 os->segments_size = 0;
1296 os->nb_segments = 0;
1300 seg = av_mallocz(sizeof(*seg));
1302 return AVERROR(ENOMEM);
1303 av_strlcpy(seg->file, file, sizeof(seg->file));
1305 seg->duration = duration;
1306 if (seg->time < 0) { // If pts<0, it is expected to be cut away with an edit list
1307 seg->duration += seg->time;
1310 seg->start_pos = start_pos;
1311 seg->range_length = range_length;
1312 seg->index_length = index_length;
1313 os->segments[os->nb_segments++] = seg;
1314 os->segment_index++;
1315 //correcting the segment index if it has fallen behind the expected value
1316 if (os->segment_index < next_exp_index) {
1317 av_log(NULL, AV_LOG_WARNING, "Correcting the segment index after file %s: current=%d corrected=%d\n",
1318 file, os->segment_index, next_exp_index);
1319 os->segment_index = next_exp_index;
1324 static void write_styp(AVIOContext *pb)
1327 ffio_wfourcc(pb, "styp");
1328 ffio_wfourcc(pb, "msdh");
1329 avio_wb32(pb, 0); /* minor */
1330 ffio_wfourcc(pb, "msdh");
1331 ffio_wfourcc(pb, "msix");
1334 static void find_index_range(AVFormatContext *s, const char *full_path,
1335 int64_t pos, int *index_length)
1341 ret = s->io_open(s, &pb, full_path, AVIO_FLAG_READ, NULL);
1344 if (avio_seek(pb, pos, SEEK_SET) != pos) {
1345 ff_format_io_close(s, &pb);
1348 ret = avio_read(pb, buf, 8);
1349 ff_format_io_close(s, &pb);
1352 if (AV_RL32(&buf[4]) != MKTAG('s', 'i', 'd', 'x'))
1354 *index_length = AV_RB32(&buf[0]);
1357 static int update_stream_extradata(AVFormatContext *s, OutputStream *os,
1358 AVCodecParameters *par,
1359 AVRational *frame_rate)
1363 if (os->ctx->streams[0]->codecpar->extradata_size || !par->extradata_size)
1366 extradata = av_malloc(par->extradata_size);
1369 return AVERROR(ENOMEM);
1371 memcpy(extradata, par->extradata, par->extradata_size);
1373 os->ctx->streams[0]->codecpar->extradata = extradata;
1374 os->ctx->streams[0]->codecpar->extradata_size = par->extradata_size;
1376 set_codec_str(s, par, frame_rate, os->codec_str, sizeof(os->codec_str));
1381 static void dashenc_delete_file(AVFormatContext *s, char *filename) {
1382 DASHContext *c = s->priv_data;
1383 int http_base_proto = ff_is_http_proto(filename);
1385 if (http_base_proto) {
1386 AVIOContext *out = NULL;
1387 AVDictionary *http_opts = NULL;
1389 set_http_options(&http_opts, c);
1390 av_dict_set(&http_opts, "method", "DELETE", 0);
1392 if (dashenc_io_open(s, &out, filename, &http_opts) < 0) {
1393 av_log(s, AV_LOG_ERROR, "failed to delete %s\n", filename);
1396 av_dict_free(&http_opts);
1397 ff_format_io_close(s, &out);
1399 int res = avpriv_io_delete(filename);
1401 char errbuf[AV_ERROR_MAX_STRING_SIZE];
1402 av_strerror(res, errbuf, sizeof(errbuf));
1403 av_log(s, (res == AVERROR(ENOENT) ? AV_LOG_WARNING : AV_LOG_ERROR), "failed to delete %s: %s\n", filename, errbuf);
1408 static int dashenc_delete_segment_file(AVFormatContext *s, const char* file)
1410 DASHContext *c = s->priv_data;
1411 size_t dirname_len, file_len;
1412 char filename[1024];
1414 dirname_len = strlen(c->dirname);
1415 if (dirname_len >= sizeof(filename)) {
1416 av_log(s, AV_LOG_WARNING, "Cannot delete segments as the directory path is too long: %"PRIu64" characters: %s\n",
1417 (uint64_t)dirname_len, c->dirname);
1418 return AVERROR(ENAMETOOLONG);
1421 memcpy(filename, c->dirname, dirname_len);
1423 file_len = strlen(file);
1424 if ((dirname_len + file_len) >= sizeof(filename)) {
1425 av_log(s, AV_LOG_WARNING, "Cannot delete segments as the path is too long: %"PRIu64" characters: %s%s\n",
1426 (uint64_t)(dirname_len + file_len), c->dirname, file);
1427 return AVERROR(ENAMETOOLONG);
1430 memcpy(filename + dirname_len, file, file_len + 1); // include the terminating zero
1431 dashenc_delete_file(s, filename);
1436 static inline void dashenc_delete_media_segments(AVFormatContext *s, OutputStream *os, int remove_count)
1438 for (int i = 0; i < remove_count; ++i) {
1439 dashenc_delete_segment_file(s, os->segments[i]->file);
1441 // Delete the segment regardless of whether the file was successfully deleted
1442 av_free(os->segments[i]);
1445 os->nb_segments -= remove_count;
1446 memmove(os->segments, os->segments + remove_count, os->nb_segments * sizeof(*os->segments));
1449 static int dash_flush(AVFormatContext *s, int final, int stream)
1451 DASHContext *c = s->priv_data;
1454 const char *proto = avio_find_protocol_name(s->url);
1455 int use_rename = proto && !strcmp(proto, "file");
1457 int cur_flush_segment_index = 0, next_exp_index = -1;
1459 cur_flush_segment_index = c->streams[stream].segment_index;
1461 //finding the next segment's expected index, based on the current pts value
1462 if (c->use_template && !c->use_timeline && c->index_correction &&
1463 c->streams[stream].last_pts != AV_NOPTS_VALUE &&
1464 c->streams[stream].first_pts != AV_NOPTS_VALUE) {
1465 int64_t pts_diff = av_rescale_q(c->streams[stream].last_pts -
1466 c->streams[stream].first_pts,
1467 s->streams[stream]->time_base,
1469 next_exp_index = (pts_diff / c->seg_duration) + 1;
1473 for (i = 0; i < s->nb_streams; i++) {
1474 OutputStream *os = &c->streams[i];
1475 AVStream *st = s->streams[i];
1476 int range_length, index_length = 0;
1478 if (!os->packets_written)
1481 // Flush the single stream that got a keyframe right now.
1482 // Flush all audio streams as well, in sync with video keyframes,
1483 // but not the other video streams.
1484 if (stream >= 0 && i != stream) {
1485 if (s->streams[i]->codecpar->codec_type != AVMEDIA_TYPE_AUDIO)
1487 // Make sure we don't flush audio streams multiple times, when
1488 // all video streams are flushed one at a time.
1489 if (c->has_video && os->segment_index > cur_flush_segment_index)
1493 if (!c->single_file) {
1494 if (os->segment_type == SEGMENT_TYPE_MP4 && !os->written_len)
1495 write_styp(os->ctx->pb);
1497 snprintf(os->full_path, sizeof(os->full_path), "%s%s", c->dirname, os->initfile);
1500 ret = flush_dynbuf(os, &range_length);
1503 os->packets_written = 0;
1505 if (c->single_file) {
1506 find_index_range(s, os->full_path, os->pos, &index_length);
1508 dashenc_io_close(s, &os->out, os->temp_path);
1511 ret = avpriv_io_move(os->temp_path, os->full_path);
1517 if (!os->muxer_overhead)
1518 os->muxer_overhead = ((int64_t) (range_length - os->total_pkt_size) *
1520 av_rescale_q(os->max_pts - os->start_pts,
1521 st->time_base, AV_TIME_BASE_Q);
1522 os->total_pkt_size = 0;
1524 if (!os->bit_rate) {
1525 // calculate average bitrate of first segment
1526 int64_t bitrate = (int64_t) range_length * 8 * AV_TIME_BASE / av_rescale_q(os->max_pts - os->start_pts,
1530 os->bit_rate = bitrate;
1532 add_segment(os, os->filename, os->start_pts, os->max_pts - os->start_pts, os->pos, range_length, index_length, next_exp_index);
1533 av_log(s, AV_LOG_VERBOSE, "Representation %d media segment %d written to: %s\n", i, os->segment_index, os->full_path);
1535 os->pos += range_length;
1538 if (c->window_size) {
1539 for (i = 0; i < s->nb_streams; i++) {
1540 OutputStream *os = &c->streams[i];
1541 int remove_count = os->nb_segments - c->window_size - c->extra_window_size;
1542 if (remove_count > 0)
1543 dashenc_delete_media_segments(s, os, remove_count);
1548 ret = write_manifest(s, final);
1552 static int dash_write_packet(AVFormatContext *s, AVPacket *pkt)
1554 DASHContext *c = s->priv_data;
1555 AVStream *st = s->streams[pkt->stream_index];
1556 OutputStream *os = &c->streams[pkt->stream_index];
1557 int64_t seg_end_duration, elapsed_duration;
1560 ret = update_stream_extradata(s, os, st->codecpar, &st->avg_frame_rate);
1564 // Fill in a heuristic guess of the packet duration, if none is available.
1565 // The mp4 muxer will do something similar (for the last packet in a fragment)
1566 // if nothing is set (setting it for the other packets doesn't hurt).
1567 // By setting a nonzero duration here, we can be sure that the mp4 muxer won't
1568 // invoke its heuristic (this doesn't have to be identical to that algorithm),
1569 // so that we know the exact timestamps of fragments.
1570 if (!pkt->duration && os->last_dts != AV_NOPTS_VALUE)
1571 pkt->duration = pkt->dts - os->last_dts;
1572 os->last_dts = pkt->dts;
1574 // If forcing the stream to start at 0, the mp4 muxer will set the start
1575 // timestamps to 0. Do the same here, to avoid mismatches in duration/timestamps.
1576 if (os->first_pts == AV_NOPTS_VALUE &&
1577 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
1578 pkt->pts -= pkt->dts;
1582 if (os->first_pts == AV_NOPTS_VALUE)
1583 os->first_pts = pkt->pts;
1584 os->last_pts = pkt->pts;
1586 if (!c->availability_start_time[0])
1587 format_date_now(c->availability_start_time,
1588 sizeof(c->availability_start_time));
1590 if (!os->availability_time_offset && pkt->duration) {
1591 int64_t frame_duration = av_rescale_q(pkt->duration, st->time_base,
1593 os->availability_time_offset = ((double) c->seg_duration -
1594 frame_duration) / AV_TIME_BASE;
1597 if (c->use_template && !c->use_timeline) {
1598 elapsed_duration = pkt->pts - os->first_pts;
1599 seg_end_duration = (int64_t) os->segment_index * c->seg_duration;
1601 elapsed_duration = pkt->pts - os->start_pts;
1602 seg_end_duration = c->seg_duration;
1605 if ((!c->has_video || st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) &&
1606 pkt->flags & AV_PKT_FLAG_KEY && os->packets_written &&
1607 av_compare_ts(elapsed_duration, st->time_base,
1608 seg_end_duration, AV_TIME_BASE_Q) >= 0) {
1609 int64_t prev_duration = c->last_duration;
1611 c->last_duration = av_rescale_q(pkt->pts - os->start_pts,
1614 c->total_duration = av_rescale_q(pkt->pts - os->first_pts,
1618 if ((!c->use_timeline || !c->use_template) && prev_duration) {
1619 if (c->last_duration < prev_duration*9/10 ||
1620 c->last_duration > prev_duration*11/10) {
1621 av_log(s, AV_LOG_WARNING,
1622 "Segment durations differ too much, enable use_timeline "
1623 "and use_template, or keep a stricter keyframe interval\n");
1627 if ((ret = dash_flush(s, 0, pkt->stream_index)) < 0)
1631 if (!os->packets_written) {
1632 // If we wrote a previous segment, adjust the start time of the segment
1633 // to the end of the previous one (which is the same as the mp4 muxer
1634 // does). This avoids gaps in the timeline.
1635 if (os->max_pts != AV_NOPTS_VALUE)
1636 os->start_pts = os->max_pts;
1638 os->start_pts = pkt->pts;
1640 if (os->max_pts == AV_NOPTS_VALUE)
1641 os->max_pts = pkt->pts + pkt->duration;
1643 os->max_pts = FFMAX(os->max_pts, pkt->pts + pkt->duration);
1644 os->packets_written++;
1645 os->total_pkt_size += pkt->size;
1646 if ((ret = ff_write_chained(os->ctx, 0, pkt, s, 0)) < 0)
1649 if (!os->init_range_length)
1650 flush_init_segment(s, os);
1652 //open the output context when the first frame of a segment is ready
1653 if (!c->single_file && os->packets_written == 1) {
1654 AVDictionary *opts = NULL;
1655 const char *proto = avio_find_protocol_name(s->url);
1656 int use_rename = proto && !strcmp(proto, "file");
1657 os->filename[0] = os->full_path[0] = os->temp_path[0] = '\0';
1658 ff_dash_fill_tmpl_params(os->filename, sizeof(os->filename),
1659 os->media_seg_name, pkt->stream_index,
1660 os->segment_index, os->bit_rate, os->start_pts);
1661 snprintf(os->full_path, sizeof(os->full_path), "%s%s", c->dirname,
1663 snprintf(os->temp_path, sizeof(os->temp_path),
1664 use_rename ? "%s.tmp" : "%s", os->full_path);
1665 set_http_options(&opts, c);
1666 ret = dashenc_io_open(s, &os->out, os->temp_path, &opts);
1667 av_dict_free(&opts);
1669 return handle_io_open_error(s, ret, os->temp_path);
1672 char *prefetch_url = use_rename ? NULL : os->filename;
1673 write_hls_media_playlist(os, s, pkt->stream_index, 0, prefetch_url);
1677 //write out the data immediately in streaming mode
1678 if (c->streaming && os->segment_type == SEGMENT_TYPE_MP4) {
1680 uint8_t *buf = NULL;
1681 if (!os->written_len)
1682 write_styp(os->ctx->pb);
1683 avio_flush(os->ctx->pb);
1684 len = avio_get_dyn_buf (os->ctx->pb, &buf);
1686 avio_write(os->out, buf + os->written_len, len - os->written_len);
1687 avio_flush(os->out);
1689 os->written_len = len;
1695 static int dash_write_trailer(AVFormatContext *s)
1697 DASHContext *c = s->priv_data;
1700 if (s->nb_streams > 0) {
1701 OutputStream *os = &c->streams[0];
1702 // If no segments have been written so far, try to do a crude
1703 // guess of the segment duration
1704 if (!c->last_duration)
1705 c->last_duration = av_rescale_q(os->max_pts - os->start_pts,
1706 s->streams[0]->time_base,
1708 c->total_duration = av_rescale_q(os->max_pts - os->first_pts,
1709 s->streams[0]->time_base,
1712 dash_flush(s, 1, -1);
1714 for (i = 0; i < s->nb_streams; ++i) {
1715 OutputStream *os = &c->streams[i];
1716 if (os->ctx && os->ctx_inited) {
1717 av_write_trailer(os->ctx);
1720 if (c->remove_at_exit) {
1721 dashenc_delete_media_segments(s, os, os->nb_segments);
1722 dashenc_delete_segment_file(s, os->initfile);
1726 if (c->remove_at_exit) {
1727 dashenc_delete_file(s, s->url);
1729 if (c->hls_playlist && c->master_playlist_created) {
1730 char filename[1024];
1731 for (i = 0; i < s->nb_streams; ++i) {
1732 OutputStream *os = &c->streams[i];
1733 if (os->segment_type == SEGMENT_TYPE_MP4) {
1734 get_hls_playlist_name(filename, sizeof(filename), c->dirname, i);
1735 dashenc_delete_file(s, filename);
1738 snprintf(filename, sizeof(filename), "%smaster.m3u8", c->dirname);
1739 dashenc_delete_file(s, filename);
1746 static int dash_check_bitstream(struct AVFormatContext *s, const AVPacket *avpkt)
1748 DASHContext *c = s->priv_data;
1749 OutputStream *os = &c->streams[avpkt->stream_index];
1750 AVFormatContext *oc = os->ctx;
1751 if (oc->oformat->check_bitstream) {
1753 AVPacket pkt = *avpkt;
1754 pkt.stream_index = 0;
1755 ret = oc->oformat->check_bitstream(oc, &pkt);
1757 AVStream *st = s->streams[avpkt->stream_index];
1758 AVStream *ost = oc->streams[0];
1759 st->internal->bsfcs = ost->internal->bsfcs;
1760 st->internal->nb_bsfcs = ost->internal->nb_bsfcs;
1761 ost->internal->bsfcs = NULL;
1762 ost->internal->nb_bsfcs = 0;
1769 #define OFFSET(x) offsetof(DASHContext, x)
1770 #define E AV_OPT_FLAG_ENCODING_PARAM
1771 static const AVOption options[] = {
1772 { "adaptation_sets", "Adaptation sets. Syntax: id=0,streams=0,1,2 id=1,streams=3,4 and so on", OFFSET(adaptation_sets), AV_OPT_TYPE_STRING, { 0 }, 0, 0, AV_OPT_FLAG_ENCODING_PARAM },
1773 { "window_size", "number of segments kept in the manifest", OFFSET(window_size), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, E },
1774 { "extra_window_size", "number of segments kept outside of the manifest before removing from disk", OFFSET(extra_window_size), AV_OPT_TYPE_INT, { .i64 = 5 }, 0, INT_MAX, E },
1775 #if FF_API_DASH_MIN_SEG_DURATION
1776 { "min_seg_duration", "minimum segment duration (in microseconds) (will be deprecated)", OFFSET(min_seg_duration), AV_OPT_TYPE_INT, { .i64 = 5000000 }, 0, INT_MAX, E },
1778 { "seg_duration", "segment duration (in seconds, fractional value can be set)", OFFSET(seg_duration), AV_OPT_TYPE_DURATION, { .i64 = 5000000 }, 0, INT_MAX, E },
1779 { "remove_at_exit", "remove all segments when finished", OFFSET(remove_at_exit), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
1780 { "use_template", "Use SegmentTemplate instead of SegmentList", OFFSET(use_template), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, E },
1781 { "use_timeline", "Use SegmentTimeline in SegmentTemplate", OFFSET(use_timeline), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, E },
1782 { "single_file", "Store all segments in one file, accessed using byte ranges", OFFSET(single_file), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
1783 { "single_file_name", "DASH-templated name to be used for baseURL. Implies storing all segments in one file, accessed using byte ranges", OFFSET(single_file_name), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, E },
1784 { "init_seg_name", "DASH-templated name to used for the initialization segment", OFFSET(init_seg_name), AV_OPT_TYPE_STRING, {.str = "init-stream$RepresentationID$.$ext$"}, 0, 0, E },
1785 { "media_seg_name", "DASH-templated name to used for the media segments", OFFSET(media_seg_name), AV_OPT_TYPE_STRING, {.str = "chunk-stream$RepresentationID$-$Number%05d$.$ext$"}, 0, 0, E },
1786 { "utc_timing_url", "URL of the page that will return the UTC timestamp in ISO format", OFFSET(utc_timing_url), AV_OPT_TYPE_STRING, { 0 }, 0, 0, E },
1787 { "method", "set the HTTP method", OFFSET(method), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
1788 { "http_user_agent", "override User-Agent field in HTTP header", OFFSET(user_agent), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
1789 { "http_persistent", "Use persistent HTTP connections", OFFSET(http_persistent), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, E },
1790 { "hls_playlist", "Generate HLS playlist files(master.m3u8, media_%d.m3u8)", OFFSET(hls_playlist), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
1791 { "streaming", "Enable/Disable streaming mode of output. Each frame will be moof fragment", OFFSET(streaming), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
1792 { "timeout", "set timeout for socket I/O operations", OFFSET(timeout), AV_OPT_TYPE_DURATION, { .i64 = -1 }, -1, INT_MAX, .flags = E },
1793 { "index_correction", "Enable/Disable segment index correction logic", OFFSET(index_correction), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
1794 { "format_options","set list of options for the container format (mp4/webm) used for dash", OFFSET(format_options_str), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
1795 { "dash_segment_type", "set dash segment files type", OFFSET(segment_type_option), AV_OPT_TYPE_INT, {.i64 = SEGMENT_TYPE_AUTO }, 0, SEGMENT_TYPE_NB - 1, E, "segment_type"},
1796 { "auto", "select segment file format based on codec", 0, AV_OPT_TYPE_CONST, {.i64 = SEGMENT_TYPE_AUTO }, 0, UINT_MAX, E, "segment_type"},
1797 { "mp4", "make segment file in ISOBMFF format", 0, AV_OPT_TYPE_CONST, {.i64 = SEGMENT_TYPE_MP4 }, 0, UINT_MAX, E, "segment_type"},
1798 { "webm", "make segment file in WebM format", 0, AV_OPT_TYPE_CONST, {.i64 = SEGMENT_TYPE_WEBM }, 0, UINT_MAX, E, "segment_type"},
1799 { "ignore_io_errors", "Ignore IO errors during open and write. Useful for long-duration runs with network output", OFFSET(ignore_io_errors), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
1800 { "lhls", "Enable Low-latency HLS(Experimental). Adds #EXT-X-PREFETCH tag with current segment's URI", OFFSET(lhls), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
1804 static const AVClass dash_class = {
1805 .class_name = "dash muxer",
1806 .item_name = av_default_item_name,
1808 .version = LIBAVUTIL_VERSION_INT,
1811 AVOutputFormat ff_dash_muxer = {
1813 .long_name = NULL_IF_CONFIG_SMALL("DASH Muxer"),
1814 .extensions = "mpd",
1815 .priv_data_size = sizeof(DASHContext),
1816 .audio_codec = AV_CODEC_ID_AAC,
1817 .video_codec = AV_CODEC_ID_H264,
1818 .flags = AVFMT_GLOBALHEADER | AVFMT_NOFILE | AVFMT_TS_NEGATIVE,
1820 .write_header = dash_write_header,
1821 .write_packet = dash_write_packet,
1822 .write_trailer = dash_write_trailer,
1823 .deinit = dash_free,
1824 .check_bitstream = dash_check_bitstream,
1825 .priv_class = &dash_class,