2 * MPEG-DASH ISO BMFF segmenter
3 * Copyright (c) 2014 Martin Storsjo
5 * This file is part of FFmpeg.
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
27 #include "libavutil/avassert.h"
28 #include "libavutil/avutil.h"
29 #include "libavutil/avstring.h"
30 #include "libavutil/intreadwrite.h"
31 #include "libavutil/mathematics.h"
32 #include "libavutil/opt.h"
33 #include "libavutil/rational.h"
34 #include "libavutil/time_internal.h"
38 #include "avio_internal.h"
41 #include "os_support.h"
45 typedef struct Segment {
48 int range_length, index_length;
54 typedef struct AdaptationSet {
56 enum AVMediaType media_type;
57 AVDictionary *metadata;
60 typedef struct OutputStream {
62 int ctx_inited, as_idx;
67 int64_t init_start_pos, pos;
68 int init_range_length;
69 int nb_segments, segments_size, segment_index;
71 int64_t first_pts, start_pts, max_pts;
74 char bandwidth_str[64];
79 typedef struct DASHContext {
80 const AVClass *class; /* Class for private options. */
81 char *adaptation_sets;
85 int extra_window_size;
91 OutputStream *streams;
93 int64_t last_duration;
94 int64_t total_duration;
95 char availability_start_time[100];
97 const char *single_file_name;
98 const char *init_seg_name;
99 const char *media_seg_name;
100 AVRational min_frame_rate, max_frame_rate;
101 int ambiguous_frame_rate;
102 const char *utc_timing_url;
105 static struct codec_string {
109 { AV_CODEC_ID_VP8, "vp8" },
110 { AV_CODEC_ID_VP9, "vp9" },
111 { AV_CODEC_ID_VORBIS, "vorbis" },
112 { AV_CODEC_ID_OPUS, "opus" },
116 static void set_codec_str(AVFormatContext *s, AVCodecParameters *par,
119 const AVCodecTag *tags[2] = { NULL, NULL };
123 // common Webm codecs are not part of RFC 6381
124 for (i = 0; codecs[i].id; i++)
125 if (codecs[i].id == par->codec_id) {
126 av_strlcpy(str, codecs[i].str, size);
130 // for codecs part of RFC 6381
131 if (par->codec_type == AVMEDIA_TYPE_VIDEO)
132 tags[0] = ff_codec_movvideo_tags;
133 else if (par->codec_type == AVMEDIA_TYPE_AUDIO)
134 tags[0] = ff_codec_movaudio_tags;
138 tag = av_codec_get_tag(tags, par->codec_id);
146 if (!strcmp(str, "mp4a") || !strcmp(str, "mp4v")) {
148 tags[0] = ff_mp4_obj_type;
149 oti = av_codec_get_tag(tags, par->codec_id);
151 av_strlcatf(str, size, ".%02"PRIx32, oti);
155 if (tag == MKTAG('m', 'p', '4', 'a')) {
156 if (par->extradata_size >= 2) {
157 int aot = par->extradata[0] >> 3;
159 aot = ((AV_RB16(par->extradata) >> 5) & 0x3f) + 32;
160 av_strlcatf(str, size, ".%d", aot);
162 } else if (tag == MKTAG('m', 'p', '4', 'v')) {
163 // Unimplemented, should output ProfileLevelIndication as a decimal number
164 av_log(s, AV_LOG_WARNING, "Incomplete RFC 6381 codec string for mp4v\n");
166 } else if (!strcmp(str, "avc1")) {
167 uint8_t *tmpbuf = NULL;
168 uint8_t *extradata = par->extradata;
169 int extradata_size = par->extradata_size;
172 if (extradata[0] != 1) {
174 if (avio_open_dyn_buf(&pb) < 0)
176 if (ff_isom_write_avcc(pb, extradata, extradata_size) < 0) {
177 ffio_free_dyn_buf(&pb);
180 extradata_size = avio_close_dyn_buf(pb, &extradata);
184 if (extradata_size >= 4)
185 av_strlcatf(str, size, ".%02x%02x%02x",
186 extradata[1], extradata[2], extradata[3]);
191 static int flush_dynbuf(OutputStream *os, int *range_length)
196 return AVERROR(EINVAL);
200 av_write_frame(os->ctx, NULL);
201 avio_flush(os->ctx->pb);
204 *range_length = avio_close_dyn_buf(os->ctx->pb, &buffer);
206 avio_write(os->out, buffer, *range_length);
210 return avio_open_dyn_buf(&os->ctx->pb);
213 static int flush_init_segment(AVFormatContext *s, OutputStream *os)
215 DASHContext *c = s->priv_data;
216 int ret, range_length;
218 ret = flush_dynbuf(os, &range_length);
222 os->pos = os->init_range_length = range_length;
224 ff_format_io_close(s, &os->out);
228 static void dash_free(AVFormatContext *s)
230 DASHContext *c = s->priv_data;
234 for (i = 0; i < c->nb_as; i++)
235 av_dict_free(&c->as[i].metadata);
242 for (i = 0; i < s->nb_streams; i++) {
243 OutputStream *os = &c->streams[i];
244 if (os->ctx && os->ctx_inited)
245 av_write_trailer(os->ctx);
246 if (os->ctx && os->ctx->pb)
247 ffio_free_dyn_buf(&os->ctx->pb);
248 ff_format_io_close(s, &os->out);
250 avformat_free_context(os->ctx);
251 for (j = 0; j < os->nb_segments; j++)
252 av_free(os->segments[j]);
253 av_free(os->segments);
255 av_freep(&c->streams);
258 static void output_segment_list(OutputStream *os, AVIOContext *out, DASHContext *c)
260 int i, start_index = 0, start_number = 1;
261 if (c->window_size) {
262 start_index = FFMAX(os->nb_segments - c->window_size, 0);
263 start_number = FFMAX(os->segment_index - c->window_size, 1);
266 if (c->use_template) {
267 int timescale = c->use_timeline ? os->ctx->streams[0]->time_base.den : AV_TIME_BASE;
268 avio_printf(out, "\t\t\t\t<SegmentTemplate timescale=\"%d\" ", timescale);
269 if (!c->use_timeline)
270 avio_printf(out, "duration=\"%"PRId64"\" ", c->last_duration);
271 avio_printf(out, "initialization=\"%s\" media=\"%s\" startNumber=\"%d\">\n", c->init_seg_name, c->media_seg_name, c->use_timeline ? start_number : 1);
272 if (c->use_timeline) {
273 int64_t cur_time = 0;
274 avio_printf(out, "\t\t\t\t\t<SegmentTimeline>\n");
275 for (i = start_index; i < os->nb_segments; ) {
276 Segment *seg = os->segments[i];
278 avio_printf(out, "\t\t\t\t\t\t<S ");
279 if (i == start_index || seg->time != cur_time) {
280 cur_time = seg->time;
281 avio_printf(out, "t=\"%"PRId64"\" ", seg->time);
283 avio_printf(out, "d=\"%d\" ", seg->duration);
284 while (i + repeat + 1 < os->nb_segments &&
285 os->segments[i + repeat + 1]->duration == seg->duration &&
286 os->segments[i + repeat + 1]->time == os->segments[i + repeat]->time + os->segments[i + repeat]->duration)
289 avio_printf(out, "r=\"%d\" ", repeat);
290 avio_printf(out, "/>\n");
292 cur_time += (1 + repeat) * seg->duration;
294 avio_printf(out, "\t\t\t\t\t</SegmentTimeline>\n");
296 avio_printf(out, "\t\t\t\t</SegmentTemplate>\n");
297 } else if (c->single_file) {
298 avio_printf(out, "\t\t\t\t<BaseURL>%s</BaseURL>\n", os->initfile);
299 avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%"PRId64"\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);
300 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);
301 for (i = start_index; i < os->nb_segments; i++) {
302 Segment *seg = os->segments[i];
303 avio_printf(out, "\t\t\t\t\t<SegmentURL mediaRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->range_length - 1);
304 if (seg->index_length)
305 avio_printf(out, "indexRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->index_length - 1);
306 avio_printf(out, "/>\n");
308 avio_printf(out, "\t\t\t\t</SegmentList>\n");
310 avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%"PRId64"\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);
311 avio_printf(out, "\t\t\t\t\t<Initialization sourceURL=\"%s\" />\n", os->initfile);
312 for (i = start_index; i < os->nb_segments; i++) {
313 Segment *seg = os->segments[i];
314 avio_printf(out, "\t\t\t\t\t<SegmentURL media=\"%s\" />\n", seg->file);
316 avio_printf(out, "\t\t\t\t</SegmentList>\n");
320 static char *xmlescape(const char *str) {
321 int outlen = strlen(str)*3/2 + 6;
322 char *out = av_realloc(NULL, outlen + 1);
326 for (; *str; str++) {
327 if (pos + 6 > outlen) {
329 outlen = 2 * outlen + 6;
330 tmp = av_realloc(out, outlen + 1);
338 memcpy(&out[pos], "&", 5);
340 } else if (*str == '<') {
341 memcpy(&out[pos], "<", 4);
343 } else if (*str == '>') {
344 memcpy(&out[pos], ">", 4);
346 } else if (*str == '\'') {
347 memcpy(&out[pos], "'", 6);
349 } else if (*str == '\"') {
350 memcpy(&out[pos], """, 6);
360 static void write_time(AVIOContext *out, int64_t time)
362 int seconds = time / AV_TIME_BASE;
363 int fractions = time % AV_TIME_BASE;
364 int minutes = seconds / 60;
365 int hours = minutes / 60;
368 avio_printf(out, "PT");
370 avio_printf(out, "%dH", hours);
371 if (hours || minutes)
372 avio_printf(out, "%dM", minutes);
373 avio_printf(out, "%d.%dS", seconds, fractions / (AV_TIME_BASE / 10));
376 static void format_date_now(char *buf, int size)
378 time_t t = time(NULL);
379 struct tm *ptm, tmbuf;
380 ptm = gmtime_r(&t, &tmbuf);
382 if (!strftime(buf, size, "%Y-%m-%dT%H:%M:%SZ", ptm))
387 static int write_adaptation_set(AVFormatContext *s, AVIOContext *out, int as_index)
389 DASHContext *c = s->priv_data;
390 AdaptationSet *as = &c->as[as_index];
391 AVDictionaryEntry *lang, *role;
394 avio_printf(out, "\t\t<AdaptationSet id=\"%s\" contentType=\"%s\" segmentAlignment=\"true\" bitstreamSwitching=\"true\"",
395 as->id, as->media_type == AVMEDIA_TYPE_VIDEO ? "video" : "audio");
396 if (as->media_type == AVMEDIA_TYPE_VIDEO && c->max_frame_rate.num && !c->ambiguous_frame_rate)
397 avio_printf(out, " %s=\"%d/%d\"", (av_cmp_q(c->min_frame_rate, c->max_frame_rate) < 0) ? "maxFrameRate" : "frameRate", c->max_frame_rate.num, c->max_frame_rate.den);
398 lang = av_dict_get(as->metadata, "language", NULL, 0);
400 avio_printf(out, " lang=\"%s\"", lang->value);
401 avio_printf(out, ">\n");
403 role = av_dict_get(as->metadata, "role", NULL, 0);
405 avio_printf(out, "\t\t\t<Role schemeIdUri=\"urn:mpeg:dash:role:2011\" value=\"%s\"/>\n", role->value);
407 for (i = 0; i < s->nb_streams; i++) {
408 OutputStream *os = &c->streams[i];
410 if (os->as_idx - 1 != as_index)
413 if (as->media_type == AVMEDIA_TYPE_VIDEO) {
414 AVStream *st = s->streams[i];
415 avio_printf(out, "\t\t\t<Representation id=\"%d\" mimeType=\"video/%s\" codecs=\"%s\"%s width=\"%d\" height=\"%d\"",
416 i, os->format_name, os->codec_str, os->bandwidth_str, s->streams[i]->codecpar->width, s->streams[i]->codecpar->height);
417 if (st->avg_frame_rate.num)
418 avio_printf(out, " frameRate=\"%d/%d\"", st->avg_frame_rate.num, st->avg_frame_rate.den);
419 avio_printf(out, ">\n");
421 avio_printf(out, "\t\t\t<Representation id=\"%d\" mimeType=\"audio/%s\" codecs=\"%s\"%s audioSamplingRate=\"%d\">\n",
422 i, os->format_name, os->codec_str, os->bandwidth_str, s->streams[i]->codecpar->sample_rate);
423 avio_printf(out, "\t\t\t\t<AudioChannelConfiguration schemeIdUri=\"urn:mpeg:dash:23003:3:audio_channel_configuration:2011\" value=\"%d\" />\n",
424 s->streams[i]->codecpar->channels);
426 output_segment_list(os, out, c);
427 avio_printf(out, "\t\t\t</Representation>\n");
429 avio_printf(out, "\t\t</AdaptationSet>\n");
434 static int add_adaptation_set(AVFormatContext *s, AdaptationSet **as, enum AVMediaType type)
436 DASHContext *c = s->priv_data;
438 void *mem = av_realloc(c->as, sizeof(*c->as) * (c->nb_as + 1));
440 return AVERROR(ENOMEM);
444 *as = &c->as[c->nb_as - 1];
445 memset(*as, 0, sizeof(**as));
446 (*as)->media_type = type;
451 static int adaptation_set_add_stream(AVFormatContext *s, int as_idx, int i)
453 DASHContext *c = s->priv_data;
454 AdaptationSet *as = &c->as[as_idx - 1];
455 OutputStream *os = &c->streams[i];
457 if (as->media_type != s->streams[i]->codecpar->codec_type) {
458 av_log(s, AV_LOG_ERROR, "Codec type of stream %d doesn't match AdaptationSet's media type\n", i);
459 return AVERROR(EINVAL);
460 } else if (os->as_idx) {
461 av_log(s, AV_LOG_ERROR, "Stream %d is already assigned to an AdaptationSet\n", i);
462 return AVERROR(EINVAL);
469 static int parse_adaptation_sets(AVFormatContext *s)
471 DASHContext *c = s->priv_data;
472 const char *p = c->adaptation_sets;
473 enum { new_set, parse_id, parsing_streams } state;
477 // default: one AdaptationSet for each stream
479 for (i = 0; i < s->nb_streams; i++) {
480 if ((ret = add_adaptation_set(s, &as, s->streams[i]->codecpar->codec_type)) < 0)
482 snprintf(as->id, sizeof(as->id), "%d", i);
484 c->streams[i].as_idx = c->nb_as;
489 // syntax id=0,streams=0,1,2 id=1,streams=3,4 and so on
495 } else if (state == new_set && av_strstart(p, "id=", &p)) {
497 if ((ret = add_adaptation_set(s, &as, AVMEDIA_TYPE_UNKNOWN)) < 0)
501 snprintf(as->id, sizeof(as->id), "%.*s", n, p);
507 } else if (state == parse_id && av_strstart(p, "streams=", &p)) {
508 state = parsing_streams;
509 } else if (state == parsing_streams) {
510 AdaptationSet *as = &c->as[c->nb_as - 1];
511 char idx_str[8], *end_str;
513 n = strcspn(p, " ,");
514 snprintf(idx_str, sizeof(idx_str), "%.*s", n, p);
517 // if value is "a" or "v", map all streams of that type
518 if (as->media_type == AVMEDIA_TYPE_UNKNOWN && (idx_str[0] == 'v' || idx_str[0] == 'a')) {
519 enum AVMediaType type = (idx_str[0] == 'v') ? AVMEDIA_TYPE_VIDEO : AVMEDIA_TYPE_AUDIO;
520 av_log(s, AV_LOG_DEBUG, "Map all streams of type %s\n", idx_str);
522 for (i = 0; i < s->nb_streams; i++) {
523 if (s->streams[i]->codecpar->codec_type != type)
526 as->media_type = s->streams[i]->codecpar->codec_type;
528 if ((ret = adaptation_set_add_stream(s, c->nb_as, i)) < 0)
531 } else { // select single stream
532 i = strtol(idx_str, &end_str, 10);
533 if (idx_str == end_str || i < 0 || i >= s->nb_streams) {
534 av_log(s, AV_LOG_ERROR, "Selected stream \"%s\" not found!\n", idx_str);
535 return AVERROR(EINVAL);
537 av_log(s, AV_LOG_DEBUG, "Map stream %d\n", i);
539 if (as->media_type == AVMEDIA_TYPE_UNKNOWN) {
540 as->media_type = s->streams[i]->codecpar->codec_type;
543 if ((ret = adaptation_set_add_stream(s, c->nb_as, i)) < 0)
552 return AVERROR(EINVAL);
557 // check for unassigned streams
558 for (i = 0; i < s->nb_streams; i++) {
559 OutputStream *os = &c->streams[i];
561 av_log(s, AV_LOG_ERROR, "Stream %d is not mapped to an AdaptationSet\n", i);
562 return AVERROR(EINVAL);
568 static int write_manifest(AVFormatContext *s, int final)
570 DASHContext *c = s->priv_data;
572 char temp_filename[1024];
574 const char *proto = avio_find_protocol_name(s->filename);
575 int use_rename = proto && !strcmp(proto, "file");
576 static unsigned int warned_non_file = 0;
577 AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
579 if (!use_rename && !warned_non_file++)
580 av_log(s, AV_LOG_ERROR, "Cannot use rename on non file protocol, this may lead to races and temporary partial files\n");
582 snprintf(temp_filename, sizeof(temp_filename), use_rename ? "%s.tmp" : "%s", s->filename);
583 ret = s->io_open(s, &out, temp_filename, AVIO_FLAG_WRITE, NULL);
585 av_log(s, AV_LOG_ERROR, "Unable to open %s for writing\n", temp_filename);
588 avio_printf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
589 avio_printf(out, "<MPD xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
590 "\txmlns=\"urn:mpeg:dash:schema:mpd:2011\"\n"
591 "\txmlns:xlink=\"http://www.w3.org/1999/xlink\"\n"
592 "\txsi:schemaLocation=\"urn:mpeg:DASH:schema:MPD:2011 http://standards.iso.org/ittf/PubliclyAvailableStandards/MPEG-DASH_schema_files/DASH-MPD.xsd\"\n"
593 "\tprofiles=\"urn:mpeg:dash:profile:isoff-live:2011\"\n"
594 "\ttype=\"%s\"\n", final ? "static" : "dynamic");
596 avio_printf(out, "\tmediaPresentationDuration=\"");
597 write_time(out, c->total_duration);
598 avio_printf(out, "\"\n");
600 int64_t update_period = c->last_duration / AV_TIME_BASE;
602 if (c->use_template && !c->use_timeline)
604 avio_printf(out, "\tminimumUpdatePeriod=\"PT%"PRId64"S\"\n", update_period);
605 avio_printf(out, "\tsuggestedPresentationDelay=\"PT%"PRId64"S\"\n", c->last_duration / AV_TIME_BASE);
606 if (!c->availability_start_time[0] && s->nb_streams > 0 && c->streams[0].nb_segments > 0) {
607 format_date_now(c->availability_start_time, sizeof(c->availability_start_time));
609 if (c->availability_start_time[0])
610 avio_printf(out, "\tavailabilityStartTime=\"%s\"\n", c->availability_start_time);
611 format_date_now(now_str, sizeof(now_str));
613 avio_printf(out, "\tpublishTime=\"%s\"\n", now_str);
614 if (c->window_size && c->use_template) {
615 avio_printf(out, "\ttimeShiftBufferDepth=\"");
616 write_time(out, c->last_duration * c->window_size);
617 avio_printf(out, "\"\n");
620 avio_printf(out, "\tminBufferTime=\"");
621 write_time(out, c->last_duration * 2);
622 avio_printf(out, "\">\n");
623 avio_printf(out, "\t<ProgramInformation>\n");
625 char *escaped = xmlescape(title->value);
626 avio_printf(out, "\t\t<Title>%s</Title>\n", escaped);
629 avio_printf(out, "\t</ProgramInformation>\n");
630 if (c->utc_timing_url)
631 avio_printf(out, "\t<UTCTiming schemeIdUri=\"urn:mpeg:dash:utc:http-xsdate:2014\" value=\"%s\"/>\n", c->utc_timing_url);
633 if (c->window_size && s->nb_streams > 0 && c->streams[0].nb_segments > 0 && !c->use_template) {
634 OutputStream *os = &c->streams[0];
635 int start_index = FFMAX(os->nb_segments - c->window_size, 0);
636 int64_t start_time = av_rescale_q(os->segments[start_index]->time, s->streams[0]->time_base, AV_TIME_BASE_Q);
637 avio_printf(out, "\t<Period id=\"0\" start=\"");
638 write_time(out, start_time);
639 avio_printf(out, "\">\n");
641 avio_printf(out, "\t<Period id=\"0\" start=\"PT0.0S\">\n");
644 for (i = 0; i < c->nb_as; i++) {
645 if ((ret = write_adaptation_set(s, out, i)) < 0)
648 avio_printf(out, "\t</Period>\n");
649 avio_printf(out, "</MPD>\n");
651 ff_format_io_close(s, &out);
654 return avpriv_io_move(temp_filename, s->filename);
659 static int dict_copy_entry(AVDictionary **dst, const AVDictionary *src, const char *key)
661 AVDictionaryEntry *entry = av_dict_get(src, key, NULL, 0);
663 av_dict_set(dst, key, entry->value, AV_DICT_DONT_OVERWRITE);
667 static int dict_set_int(AVDictionary **pm, const char *key, int64_t value, int flags)
670 snprintf(valuestr, sizeof(valuestr), "%"PRId64, value);
671 flags &= ~AV_DICT_DONT_STRDUP_VAL;
672 return av_dict_set(pm, key, valuestr, flags);
675 static int dash_init(AVFormatContext *s)
677 DASHContext *c = s->priv_data;
682 if (c->single_file_name)
686 c->ambiguous_frame_rate = 0;
688 av_strlcpy(c->dirname, s->filename, sizeof(c->dirname));
689 ptr = strrchr(c->dirname, '/');
691 av_strlcpy(basename, &ptr[1], sizeof(basename));
694 c->dirname[0] = '\0';
695 av_strlcpy(basename, s->filename, sizeof(basename));
698 ptr = strrchr(basename, '.');
702 c->streams = av_mallocz(sizeof(*c->streams) * s->nb_streams);
704 return AVERROR(ENOMEM);
706 if ((ret = parse_adaptation_sets(s)) < 0)
709 for (i = 0; i < s->nb_streams; i++) {
710 OutputStream *os = &c->streams[i];
711 AdaptationSet *as = &c->as[os->as_idx - 1];
712 AVFormatContext *ctx;
714 AVDictionary *opts = NULL;
717 os->bit_rate = s->streams[i]->codecpar->bit_rate;
719 snprintf(os->bandwidth_str, sizeof(os->bandwidth_str),
720 " bandwidth=\"%d\"", os->bit_rate);
722 int level = s->strict_std_compliance >= FF_COMPLIANCE_STRICT ?
723 AV_LOG_ERROR : AV_LOG_WARNING;
724 av_log(s, level, "No bit rate set for stream %d\n", i);
725 if (s->strict_std_compliance >= FF_COMPLIANCE_STRICT)
726 return AVERROR(EINVAL);
729 // copy AdaptationSet language and role from stream metadata
730 dict_copy_entry(&as->metadata, s->streams[i]->metadata, "language");
731 dict_copy_entry(&as->metadata, s->streams[i]->metadata, "role");
733 ctx = avformat_alloc_context();
735 return AVERROR(ENOMEM);
737 // choose muxer based on codec: webm for VP8/9 and opus, mp4 otherwise
738 // note: os->format_name is also used as part of the mimetype of the
739 // representation, e.g. video/<format_name>
740 if (s->streams[i]->codecpar->codec_id == AV_CODEC_ID_VP8 ||
741 s->streams[i]->codecpar->codec_id == AV_CODEC_ID_VP9 ||
742 s->streams[i]->codecpar->codec_id == AV_CODEC_ID_OPUS ||
743 s->streams[i]->codecpar->codec_id == AV_CODEC_ID_VORBIS) {
744 snprintf(os->format_name, sizeof(os->format_name), "webm");
746 snprintf(os->format_name, sizeof(os->format_name), "mp4");
748 ctx->oformat = av_guess_format(os->format_name, NULL, NULL);
750 return AVERROR_MUXER_NOT_FOUND;
752 ctx->interrupt_callback = s->interrupt_callback;
753 ctx->opaque = s->opaque;
754 ctx->io_close = s->io_close;
755 ctx->io_open = s->io_open;
757 if (!(st = avformat_new_stream(ctx, NULL)))
758 return AVERROR(ENOMEM);
759 avcodec_parameters_copy(st->codecpar, s->streams[i]->codecpar);
760 st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
761 st->time_base = s->streams[i]->time_base;
762 ctx->avoid_negative_ts = s->avoid_negative_ts;
763 ctx->flags = s->flags;
765 if ((ret = avio_open_dyn_buf(&ctx->pb)) < 0)
768 if (c->single_file) {
769 if (c->single_file_name)
770 ff_dash_fill_tmpl_params(os->initfile, sizeof(os->initfile), c->single_file_name, i, 0, os->bit_rate, 0);
772 snprintf(os->initfile, sizeof(os->initfile), "%s-stream%d.m4s", basename, i);
774 ff_dash_fill_tmpl_params(os->initfile, sizeof(os->initfile), c->init_seg_name, i, 0, os->bit_rate, 0);
776 snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
777 ret = s->io_open(s, &os->out, filename, AVIO_FLAG_WRITE, NULL);
780 os->init_start_pos = 0;
782 if (!strcmp(os->format_name, "mp4")) {
783 av_dict_set(&opts, "movflags", "frag_custom+dash+delay_moov", 0);
785 dict_set_int(&opts, "cluster_time_limit", c->min_seg_duration / 1000, 0);
786 dict_set_int(&opts, "cluster_size_limit", 5 * 1024 * 1024, 0); // set a large cluster size limit
788 if ((ret = avformat_write_header(ctx, &opts)) < 0)
794 av_log(s, AV_LOG_VERBOSE, "Representation %d init segment will be written to: %s\n", i, filename);
796 // Flush init segment
797 // except for mp4, since delay_moov is set and the init segment
798 // is then flushed after the first packets
799 if (strcmp(os->format_name, "mp4")) {
800 flush_init_segment(s, os);
803 s->streams[i]->time_base = st->time_base;
804 // If the muxer wants to shift timestamps, request to have them shifted
805 // already before being handed to this muxer, so we don't have mismatches
806 // between the MPD and the actual segments.
807 s->avoid_negative_ts = ctx->avoid_negative_ts;
808 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
809 AVRational avg_frame_rate = s->streams[i]->avg_frame_rate;
810 if (avg_frame_rate.num > 0) {
811 if (av_cmp_q(avg_frame_rate, c->min_frame_rate) < 0)
812 c->min_frame_rate = avg_frame_rate;
813 if (av_cmp_q(c->max_frame_rate, avg_frame_rate) < 0)
814 c->max_frame_rate = avg_frame_rate;
816 c->ambiguous_frame_rate = 1;
821 set_codec_str(s, st->codecpar, os->codec_str, sizeof(os->codec_str));
822 os->first_pts = AV_NOPTS_VALUE;
823 os->max_pts = AV_NOPTS_VALUE;
824 os->last_dts = AV_NOPTS_VALUE;
825 os->segment_index = 1;
828 if (!c->has_video && c->min_seg_duration <= 0) {
829 av_log(s, AV_LOG_WARNING, "no video stream and no min seg duration set\n");
830 return AVERROR(EINVAL);
835 static int dash_write_header(AVFormatContext *s)
837 DASHContext *c = s->priv_data;
839 for (i = 0; i < s->nb_streams; i++) {
840 OutputStream *os = &c->streams[i];
841 if ((ret = avformat_write_header(os->ctx, NULL)) < 0) {
846 ret = write_manifest(s, 0);
848 av_log(s, AV_LOG_VERBOSE, "Manifest written to: %s\n", s->filename);
852 static int add_segment(OutputStream *os, const char *file,
853 int64_t time, int duration,
854 int64_t start_pos, int64_t range_length,
855 int64_t index_length)
859 if (os->nb_segments >= os->segments_size) {
860 os->segments_size = (os->segments_size + 1) * 2;
861 if ((err = av_reallocp(&os->segments, sizeof(*os->segments) *
862 os->segments_size)) < 0) {
863 os->segments_size = 0;
868 seg = av_mallocz(sizeof(*seg));
870 return AVERROR(ENOMEM);
871 av_strlcpy(seg->file, file, sizeof(seg->file));
873 seg->duration = duration;
874 if (seg->time < 0) { // If pts<0, it is expected to be cut away with an edit list
875 seg->duration += seg->time;
878 seg->start_pos = start_pos;
879 seg->range_length = range_length;
880 seg->index_length = index_length;
881 os->segments[os->nb_segments++] = seg;
886 static void write_styp(AVIOContext *pb)
889 ffio_wfourcc(pb, "styp");
890 ffio_wfourcc(pb, "msdh");
891 avio_wb32(pb, 0); /* minor */
892 ffio_wfourcc(pb, "msdh");
893 ffio_wfourcc(pb, "msix");
896 static void find_index_range(AVFormatContext *s, const char *full_path,
897 int64_t pos, int *index_length)
903 ret = s->io_open(s, &pb, full_path, AVIO_FLAG_READ, NULL);
906 if (avio_seek(pb, pos, SEEK_SET) != pos) {
907 ff_format_io_close(s, &pb);
910 ret = avio_read(pb, buf, 8);
911 ff_format_io_close(s, &pb);
914 if (AV_RL32(&buf[4]) != MKTAG('s', 'i', 'd', 'x'))
916 *index_length = AV_RB32(&buf[0]);
919 static int update_stream_extradata(AVFormatContext *s, OutputStream *os,
920 AVCodecParameters *par)
924 if (os->ctx->streams[0]->codecpar->extradata_size || !par->extradata_size)
927 extradata = av_malloc(par->extradata_size);
930 return AVERROR(ENOMEM);
932 memcpy(extradata, par->extradata, par->extradata_size);
934 os->ctx->streams[0]->codecpar->extradata = extradata;
935 os->ctx->streams[0]->codecpar->extradata_size = par->extradata_size;
937 set_codec_str(s, par, os->codec_str, sizeof(os->codec_str));
942 static int dash_flush(AVFormatContext *s, int final, int stream)
944 DASHContext *c = s->priv_data;
947 const char *proto = avio_find_protocol_name(s->filename);
948 int use_rename = proto && !strcmp(proto, "file");
950 int cur_flush_segment_index = 0;
952 cur_flush_segment_index = c->streams[stream].segment_index;
954 for (i = 0; i < s->nb_streams; i++) {
955 OutputStream *os = &c->streams[i];
956 char filename[1024] = "", full_path[1024], temp_path[1024];
957 int range_length, index_length = 0;
959 if (!os->packets_written)
962 // Flush the single stream that got a keyframe right now.
963 // Flush all audio streams as well, in sync with video keyframes,
964 // but not the other video streams.
965 if (stream >= 0 && i != stream) {
966 if (s->streams[i]->codecpar->codec_type != AVMEDIA_TYPE_AUDIO)
968 // Make sure we don't flush audio streams multiple times, when
969 // all video streams are flushed one at a time.
970 if (c->has_video && os->segment_index > cur_flush_segment_index)
974 if (!os->init_range_length) {
975 flush_init_segment(s, os);
978 if (!c->single_file) {
979 ff_dash_fill_tmpl_params(filename, sizeof(filename), c->media_seg_name, i, os->segment_index, os->bit_rate, os->start_pts);
980 snprintf(full_path, sizeof(full_path), "%s%s", c->dirname, filename);
981 snprintf(temp_path, sizeof(temp_path), use_rename ? "%s.tmp" : "%s", full_path);
982 ret = s->io_open(s, &os->out, temp_path, AVIO_FLAG_WRITE, NULL);
985 if (!strcmp(os->format_name, "mp4"))
986 write_styp(os->ctx->pb);
988 snprintf(full_path, sizeof(full_path), "%s%s", c->dirname, os->initfile);
991 ret = flush_dynbuf(os, &range_length);
994 os->packets_written = 0;
996 if (c->single_file) {
997 find_index_range(s, full_path, os->pos, &index_length);
999 ff_format_io_close(s, &os->out);
1002 ret = avpriv_io_move(temp_path, full_path);
1008 if (!os->bit_rate) {
1009 // calculate average bitrate of first segment
1010 int64_t bitrate = (int64_t) range_length * 8 * AV_TIME_BASE / (os->max_pts - os->start_pts);
1012 os->bit_rate = bitrate;
1013 snprintf(os->bandwidth_str, sizeof(os->bandwidth_str),
1014 " bandwidth=\"%d\"", os->bit_rate);
1017 add_segment(os, filename, os->start_pts, os->max_pts - os->start_pts, os->pos, range_length, index_length);
1018 av_log(s, AV_LOG_VERBOSE, "Representation %d media segment %d written to: %s\n", i, os->segment_index, full_path);
1020 os->pos += range_length;
1023 if (c->window_size || (final && c->remove_at_exit)) {
1024 for (i = 0; i < s->nb_streams; i++) {
1025 OutputStream *os = &c->streams[i];
1027 int remove = os->nb_segments - c->window_size - c->extra_window_size;
1028 if (final && c->remove_at_exit)
1029 remove = os->nb_segments;
1031 for (j = 0; j < remove; j++) {
1032 char filename[1024];
1033 snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->segments[j]->file);
1035 av_free(os->segments[j]);
1037 os->nb_segments -= remove;
1038 memmove(os->segments, os->segments + remove, os->nb_segments * sizeof(*os->segments));
1044 ret = write_manifest(s, final);
1048 static int dash_write_packet(AVFormatContext *s, AVPacket *pkt)
1050 DASHContext *c = s->priv_data;
1051 AVStream *st = s->streams[pkt->stream_index];
1052 OutputStream *os = &c->streams[pkt->stream_index];
1055 ret = update_stream_extradata(s, os, st->codecpar);
1059 // Fill in a heuristic guess of the packet duration, if none is available.
1060 // The mp4 muxer will do something similar (for the last packet in a fragment)
1061 // if nothing is set (setting it for the other packets doesn't hurt).
1062 // By setting a nonzero duration here, we can be sure that the mp4 muxer won't
1063 // invoke its heuristic (this doesn't have to be identical to that algorithm),
1064 // so that we know the exact timestamps of fragments.
1065 if (!pkt->duration && os->last_dts != AV_NOPTS_VALUE)
1066 pkt->duration = pkt->dts - os->last_dts;
1067 os->last_dts = pkt->dts;
1069 // If forcing the stream to start at 0, the mp4 muxer will set the start
1070 // timestamps to 0. Do the same here, to avoid mismatches in duration/timestamps.
1071 if (os->first_pts == AV_NOPTS_VALUE &&
1072 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
1073 pkt->pts -= pkt->dts;
1077 if (os->first_pts == AV_NOPTS_VALUE)
1078 os->first_pts = pkt->pts;
1080 if ((!c->has_video || st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) &&
1081 pkt->flags & AV_PKT_FLAG_KEY && os->packets_written &&
1082 av_compare_ts(pkt->pts - os->start_pts, st->time_base,
1083 c->min_seg_duration, AV_TIME_BASE_Q) >= 0) {
1084 int64_t prev_duration = c->last_duration;
1086 c->last_duration = av_rescale_q(pkt->pts - os->start_pts,
1089 c->total_duration = av_rescale_q(pkt->pts - os->first_pts,
1093 if ((!c->use_timeline || !c->use_template) && prev_duration) {
1094 if (c->last_duration < prev_duration*9/10 ||
1095 c->last_duration > prev_duration*11/10) {
1096 av_log(s, AV_LOG_WARNING,
1097 "Segment durations differ too much, enable use_timeline "
1098 "and use_template, or keep a stricter keyframe interval\n");
1102 if ((ret = dash_flush(s, 0, pkt->stream_index)) < 0)
1106 if (!os->packets_written) {
1107 // If we wrote a previous segment, adjust the start time of the segment
1108 // to the end of the previous one (which is the same as the mp4 muxer
1109 // does). This avoids gaps in the timeline.
1110 if (os->max_pts != AV_NOPTS_VALUE)
1111 os->start_pts = os->max_pts;
1113 os->start_pts = pkt->pts;
1115 if (os->max_pts == AV_NOPTS_VALUE)
1116 os->max_pts = pkt->pts + pkt->duration;
1118 os->max_pts = FFMAX(os->max_pts, pkt->pts + pkt->duration);
1119 os->packets_written++;
1120 return ff_write_chained(os->ctx, 0, pkt, s, 0);
1123 static int dash_write_trailer(AVFormatContext *s)
1125 DASHContext *c = s->priv_data;
1127 if (s->nb_streams > 0) {
1128 OutputStream *os = &c->streams[0];
1129 // If no segments have been written so far, try to do a crude
1130 // guess of the segment duration
1131 if (!c->last_duration)
1132 c->last_duration = av_rescale_q(os->max_pts - os->start_pts,
1133 s->streams[0]->time_base,
1135 c->total_duration = av_rescale_q(os->max_pts - os->first_pts,
1136 s->streams[0]->time_base,
1139 dash_flush(s, 1, -1);
1141 if (c->remove_at_exit) {
1142 char filename[1024];
1144 for (i = 0; i < s->nb_streams; i++) {
1145 OutputStream *os = &c->streams[i];
1146 snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
1149 unlink(s->filename);
1155 static int dash_check_bitstream(struct AVFormatContext *s, const AVPacket *avpkt)
1157 DASHContext *c = s->priv_data;
1158 OutputStream *os = &c->streams[avpkt->stream_index];
1159 AVFormatContext *oc = os->ctx;
1160 if (oc->oformat->check_bitstream) {
1162 AVPacket pkt = *avpkt;
1163 pkt.stream_index = 0;
1164 ret = oc->oformat->check_bitstream(oc, &pkt);
1166 AVStream *st = s->streams[avpkt->stream_index];
1167 AVStream *ost = oc->streams[0];
1168 st->internal->bsfcs = ost->internal->bsfcs;
1169 st->internal->nb_bsfcs = ost->internal->nb_bsfcs;
1170 ost->internal->bsfcs = NULL;
1171 ost->internal->nb_bsfcs = 0;
1178 #define OFFSET(x) offsetof(DASHContext, x)
1179 #define E AV_OPT_FLAG_ENCODING_PARAM
1180 static const AVOption options[] = {
1181 { "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 },
1182 { "window_size", "number of segments kept in the manifest", OFFSET(window_size), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, E },
1183 { "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 },
1184 { "min_seg_duration", "minimum segment duration (in microseconds)", OFFSET(min_seg_duration), AV_OPT_TYPE_INT64, { .i64 = 5000000 }, 0, INT_MAX, E },
1185 { "remove_at_exit", "remove all segments when finished", OFFSET(remove_at_exit), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
1186 { "use_template", "Use SegmentTemplate instead of SegmentList", OFFSET(use_template), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, E },
1187 { "use_timeline", "Use SegmentTimeline in SegmentTemplate", OFFSET(use_timeline), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, E },
1188 { "single_file", "Store all segments in one file, accessed using byte ranges", OFFSET(single_file), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
1189 { "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 },
1190 { "init_seg_name", "DASH-templated name to used for the initialization segment", OFFSET(init_seg_name), AV_OPT_TYPE_STRING, {.str = "init-stream$RepresentationID$.m4s"}, 0, 0, E },
1191 { "media_seg_name", "DASH-templated name to used for the media segments", OFFSET(media_seg_name), AV_OPT_TYPE_STRING, {.str = "chunk-stream$RepresentationID$-$Number%05d$.m4s"}, 0, 0, E },
1192 { "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 },
1196 static const AVClass dash_class = {
1197 .class_name = "dash muxer",
1198 .item_name = av_default_item_name,
1200 .version = LIBAVUTIL_VERSION_INT,
1203 AVOutputFormat ff_dash_muxer = {
1205 .long_name = NULL_IF_CONFIG_SMALL("DASH Muxer"),
1206 .priv_data_size = sizeof(DASHContext),
1207 .audio_codec = AV_CODEC_ID_AAC,
1208 .video_codec = AV_CODEC_ID_H264,
1209 .flags = AVFMT_GLOBALHEADER | AVFMT_NOFILE | AVFMT_TS_NEGATIVE,
1211 .write_header = dash_write_header,
1212 .write_packet = dash_write_packet,
1213 .write_trailer = dash_write_trailer,
1214 .deinit = dash_free,
1215 .check_bitstream = dash_check_bitstream,
1216 .priv_class = &dash_class,