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;
59 typedef struct OutputStream {
61 int ctx_inited, as_idx;
66 int64_t init_start_pos;
67 int init_range_length;
68 int nb_segments, segments_size, segment_index;
70 int64_t first_pts, start_pts, max_pts;
73 char bandwidth_str[64];
78 typedef struct DASHContext {
79 const AVClass *class; /* Class for private options. */
80 char *adaptation_sets;
84 int extra_window_size;
90 OutputStream *streams;
92 int64_t last_duration;
93 int64_t total_duration;
94 char availability_start_time[100];
96 const char *single_file_name;
97 const char *init_seg_name;
98 const char *media_seg_name;
99 AVRational min_frame_rate, max_frame_rate;
100 int ambiguous_frame_rate;
101 const char *utc_timing_url;
104 static int dash_write(void *opaque, uint8_t *buf, int buf_size)
106 OutputStream *os = opaque;
108 avio_write(os->out, buf, buf_size);
113 static void set_codec_str(AVFormatContext *s, AVCodecParameters *par,
116 const AVCodecTag *tags[2] = { NULL, NULL };
118 if (par->codec_type == AVMEDIA_TYPE_VIDEO)
119 tags[0] = ff_codec_movvideo_tags;
120 else if (par->codec_type == AVMEDIA_TYPE_AUDIO)
121 tags[0] = ff_codec_movaudio_tags;
125 tag = av_codec_get_tag(tags, par->codec_id);
133 if (!strcmp(str, "mp4a") || !strcmp(str, "mp4v")) {
135 tags[0] = ff_mp4_obj_type;
136 oti = av_codec_get_tag(tags, par->codec_id);
138 av_strlcatf(str, size, ".%02"PRIx32, oti);
142 if (tag == MKTAG('m', 'p', '4', 'a')) {
143 if (par->extradata_size >= 2) {
144 int aot = par->extradata[0] >> 3;
146 aot = ((AV_RB16(par->extradata) >> 5) & 0x3f) + 32;
147 av_strlcatf(str, size, ".%d", aot);
149 } else if (tag == MKTAG('m', 'p', '4', 'v')) {
150 // Unimplemented, should output ProfileLevelIndication as a decimal number
151 av_log(s, AV_LOG_WARNING, "Incomplete RFC 6381 codec string for mp4v\n");
153 } else if (!strcmp(str, "avc1")) {
154 uint8_t *tmpbuf = NULL;
155 uint8_t *extradata = par->extradata;
156 int extradata_size = par->extradata_size;
159 if (extradata[0] != 1) {
161 if (avio_open_dyn_buf(&pb) < 0)
163 if (ff_isom_write_avcc(pb, extradata, extradata_size) < 0) {
164 ffio_free_dyn_buf(&pb);
167 extradata_size = avio_close_dyn_buf(pb, &extradata);
171 if (extradata_size >= 4)
172 av_strlcatf(str, size, ".%02x%02x%02x",
173 extradata[1], extradata[2], extradata[3]);
178 static void dash_free(AVFormatContext *s)
180 DASHContext *c = s->priv_data;
190 for (i = 0; i < s->nb_streams; i++) {
191 OutputStream *os = &c->streams[i];
192 if (os->ctx && os->ctx_inited)
193 av_write_trailer(os->ctx);
194 if (os->ctx && os->ctx->pb)
195 av_free(os->ctx->pb);
196 ff_format_io_close(s, &os->out);
198 avformat_free_context(os->ctx);
199 for (j = 0; j < os->nb_segments; j++)
200 av_free(os->segments[j]);
201 av_free(os->segments);
203 av_freep(&c->streams);
206 static void output_segment_list(OutputStream *os, AVIOContext *out, DASHContext *c)
208 int i, start_index = 0, start_number = 1;
209 if (c->window_size) {
210 start_index = FFMAX(os->nb_segments - c->window_size, 0);
211 start_number = FFMAX(os->segment_index - c->window_size, 1);
214 if (c->use_template) {
215 int timescale = c->use_timeline ? os->ctx->streams[0]->time_base.den : AV_TIME_BASE;
216 avio_printf(out, "\t\t\t\t<SegmentTemplate timescale=\"%d\" ", timescale);
217 if (!c->use_timeline)
218 avio_printf(out, "duration=\"%"PRId64"\" ", c->last_duration);
219 avio_printf(out, "initialization=\"%s\" media=\"%s\" startNumber=\"%d\">\n", c->init_seg_name, c->media_seg_name, c->use_timeline ? start_number : 1);
220 if (c->use_timeline) {
221 int64_t cur_time = 0;
222 avio_printf(out, "\t\t\t\t\t<SegmentTimeline>\n");
223 for (i = start_index; i < os->nb_segments; ) {
224 Segment *seg = os->segments[i];
226 avio_printf(out, "\t\t\t\t\t\t<S ");
227 if (i == start_index || seg->time != cur_time) {
228 cur_time = seg->time;
229 avio_printf(out, "t=\"%"PRId64"\" ", seg->time);
231 avio_printf(out, "d=\"%d\" ", seg->duration);
232 while (i + repeat + 1 < os->nb_segments &&
233 os->segments[i + repeat + 1]->duration == seg->duration &&
234 os->segments[i + repeat + 1]->time == os->segments[i + repeat]->time + os->segments[i + repeat]->duration)
237 avio_printf(out, "r=\"%d\" ", repeat);
238 avio_printf(out, "/>\n");
240 cur_time += (1 + repeat) * seg->duration;
242 avio_printf(out, "\t\t\t\t\t</SegmentTimeline>\n");
244 avio_printf(out, "\t\t\t\t</SegmentTemplate>\n");
245 } else if (c->single_file) {
246 avio_printf(out, "\t\t\t\t<BaseURL>%s</BaseURL>\n", os->initfile);
247 avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%"PRId64"\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);
248 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);
249 for (i = start_index; i < os->nb_segments; i++) {
250 Segment *seg = os->segments[i];
251 avio_printf(out, "\t\t\t\t\t<SegmentURL mediaRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->range_length - 1);
252 if (seg->index_length)
253 avio_printf(out, "indexRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->index_length - 1);
254 avio_printf(out, "/>\n");
256 avio_printf(out, "\t\t\t\t</SegmentList>\n");
258 avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%"PRId64"\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);
259 avio_printf(out, "\t\t\t\t\t<Initialization sourceURL=\"%s\" />\n", os->initfile);
260 for (i = start_index; i < os->nb_segments; i++) {
261 Segment *seg = os->segments[i];
262 avio_printf(out, "\t\t\t\t\t<SegmentURL media=\"%s\" />\n", seg->file);
264 avio_printf(out, "\t\t\t\t</SegmentList>\n");
268 static char *xmlescape(const char *str) {
269 int outlen = strlen(str)*3/2 + 6;
270 char *out = av_realloc(NULL, outlen + 1);
274 for (; *str; str++) {
275 if (pos + 6 > outlen) {
277 outlen = 2 * outlen + 6;
278 tmp = av_realloc(out, outlen + 1);
286 memcpy(&out[pos], "&", 5);
288 } else if (*str == '<') {
289 memcpy(&out[pos], "<", 4);
291 } else if (*str == '>') {
292 memcpy(&out[pos], ">", 4);
294 } else if (*str == '\'') {
295 memcpy(&out[pos], "'", 6);
297 } else if (*str == '\"') {
298 memcpy(&out[pos], """, 6);
308 static void write_time(AVIOContext *out, int64_t time)
310 int seconds = time / AV_TIME_BASE;
311 int fractions = time % AV_TIME_BASE;
312 int minutes = seconds / 60;
313 int hours = minutes / 60;
316 avio_printf(out, "PT");
318 avio_printf(out, "%dH", hours);
319 if (hours || minutes)
320 avio_printf(out, "%dM", minutes);
321 avio_printf(out, "%d.%dS", seconds, fractions / (AV_TIME_BASE / 10));
324 static void format_date_now(char *buf, int size)
326 time_t t = time(NULL);
327 struct tm *ptm, tmbuf;
328 ptm = gmtime_r(&t, &tmbuf);
330 if (!strftime(buf, size, "%Y-%m-%dT%H:%M:%SZ", ptm))
335 static int write_adaptation_set(AVFormatContext *s, AVIOContext *out, int as_index)
337 DASHContext *c = s->priv_data;
338 AdaptationSet *as = &c->as[as_index];
341 avio_printf(out, "\t\t<AdaptationSet id=\"%s\" contentType=\"%s\" segmentAlignment=\"true\" bitstreamSwitching=\"true\"",
342 as->id, as->media_type == AVMEDIA_TYPE_VIDEO ? "video" : "audio");
343 if (as->media_type == AVMEDIA_TYPE_VIDEO && c->max_frame_rate.num && !c->ambiguous_frame_rate)
344 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);
345 avio_printf(out, ">\n");
347 for (i = 0; i < s->nb_streams; i++) {
348 OutputStream *os = &c->streams[i];
350 if (os->as_idx - 1 != as_index)
353 if (as->media_type == AVMEDIA_TYPE_VIDEO) {
354 AVStream *st = s->streams[i];
355 avio_printf(out, "\t\t\t<Representation id=\"%d\" mimeType=\"video/mp4\" codecs=\"%s\"%s width=\"%d\" height=\"%d\"",
356 i, os->codec_str, os->bandwidth_str, s->streams[i]->codecpar->width, s->streams[i]->codecpar->height);
357 if (st->avg_frame_rate.num)
358 avio_printf(out, " frameRate=\"%d/%d\"", st->avg_frame_rate.num, st->avg_frame_rate.den);
359 avio_printf(out, ">\n");
361 avio_printf(out, "\t\t\t<Representation id=\"%d\" mimeType=\"audio/mp4\" codecs=\"%s\"%s audioSamplingRate=\"%d\">\n",
362 i, os->codec_str, os->bandwidth_str, s->streams[i]->codecpar->sample_rate);
363 avio_printf(out, "\t\t\t\t<AudioChannelConfiguration schemeIdUri=\"urn:mpeg:dash:23003:3:audio_channel_configuration:2011\" value=\"%d\" />\n",
364 s->streams[i]->codecpar->channels);
366 output_segment_list(os, out, c);
367 avio_printf(out, "\t\t\t</Representation>\n");
369 avio_printf(out, "\t\t</AdaptationSet>\n");
374 static int add_adaptation_set(AVFormatContext *s, AdaptationSet **as, enum AVMediaType type)
376 DASHContext *c = s->priv_data;
378 void *mem = av_realloc(c->as, sizeof(*c->as) * (c->nb_as + 1));
380 return AVERROR(ENOMEM);
384 *as = &c->as[c->nb_as - 1];
385 memset(*as, 0, sizeof(**as));
386 (*as)->media_type = type;
391 static int adaptation_set_add_stream(AVFormatContext *s, int as_idx, int i)
393 DASHContext *c = s->priv_data;
394 AdaptationSet *as = &c->as[as_idx - 1];
395 OutputStream *os = &c->streams[i];
397 if (as->media_type != s->streams[i]->codecpar->codec_type) {
398 av_log(s, AV_LOG_ERROR, "Codec type of stream %d doesn't match AdaptationSet's media type\n", i);
399 return AVERROR(EINVAL);
400 } else if (os->as_idx) {
401 av_log(s, AV_LOG_ERROR, "Stream %d is already assigned to an AdaptationSet\n", i);
402 return AVERROR(EINVAL);
409 static int parse_adaptation_sets(AVFormatContext *s)
411 DASHContext *c = s->priv_data;
412 const char *p = c->adaptation_sets;
413 enum { new_set, parse_id, parsing_streams } state;
417 // default: one AdaptationSet for each stream
419 for (i = 0; i < s->nb_streams; i++) {
420 if ((ret = add_adaptation_set(s, &as, s->streams[i]->codecpar->codec_type)) < 0)
422 snprintf(as->id, sizeof(as->id), "%d", i);
424 c->streams[i].as_idx = c->nb_as;
429 // syntax id=0,streams=0,1,2 id=1,streams=3,4 and so on
435 } else if (state == new_set && av_strstart(p, "id=", &p)) {
437 if ((ret = add_adaptation_set(s, &as, AVMEDIA_TYPE_UNKNOWN)) < 0)
441 snprintf(as->id, sizeof(as->id), "%.*s", n, p);
447 } else if (state == parse_id && av_strstart(p, "streams=", &p)) {
448 state = parsing_streams;
449 } else if (state == parsing_streams) {
450 AdaptationSet *as = &c->as[c->nb_as - 1];
451 char idx_str[8], *end_str;
453 n = strcspn(p, " ,");
454 snprintf(idx_str, sizeof(idx_str), "%.*s", n, p);
457 // if value is "a" or "v", map all streams of that type
458 if (as->media_type == AVMEDIA_TYPE_UNKNOWN && (idx_str[0] == 'v' || idx_str[0] == 'a')) {
459 enum AVMediaType type = (idx_str[0] == 'v') ? AVMEDIA_TYPE_VIDEO : AVMEDIA_TYPE_AUDIO;
460 av_log(s, AV_LOG_DEBUG, "Map all streams of type %s\n", idx_str);
462 for (i = 0; i < s->nb_streams; i++) {
463 if (s->streams[i]->codecpar->codec_type != type)
466 as->media_type = s->streams[i]->codecpar->codec_type;
468 if ((ret = adaptation_set_add_stream(s, c->nb_as, i)) < 0)
471 } else { // select single stream
472 i = strtol(idx_str, &end_str, 10);
473 if (idx_str == end_str || i < 0 || i >= s->nb_streams) {
474 av_log(s, AV_LOG_ERROR, "Selected stream \"%s\" not found!\n", idx_str);
475 return AVERROR(EINVAL);
477 av_log(s, AV_LOG_DEBUG, "Map stream %d\n", i);
479 if (as->media_type == AVMEDIA_TYPE_UNKNOWN) {
480 as->media_type = s->streams[i]->codecpar->codec_type;
483 if ((ret = adaptation_set_add_stream(s, c->nb_as, i)) < 0)
492 return AVERROR(EINVAL);
497 // check for unassigned streams
498 for (i = 0; i < s->nb_streams; i++) {
499 OutputStream *os = &c->streams[i];
501 av_log(s, AV_LOG_ERROR, "Stream %d is not mapped to an AdaptationSet\n", i);
502 return AVERROR(EINVAL);
508 static int write_manifest(AVFormatContext *s, int final)
510 DASHContext *c = s->priv_data;
512 char temp_filename[1024];
514 const char *proto = avio_find_protocol_name(s->filename);
515 int use_rename = proto && !strcmp(proto, "file");
516 static unsigned int warned_non_file = 0;
517 AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
519 if (!use_rename && !warned_non_file++)
520 av_log(s, AV_LOG_ERROR, "Cannot use rename on non file protocol, this may lead to races and temporary partial files\n");
522 snprintf(temp_filename, sizeof(temp_filename), use_rename ? "%s.tmp" : "%s", s->filename);
523 ret = s->io_open(s, &out, temp_filename, AVIO_FLAG_WRITE, NULL);
525 av_log(s, AV_LOG_ERROR, "Unable to open %s for writing\n", temp_filename);
528 avio_printf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
529 avio_printf(out, "<MPD xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
530 "\txmlns=\"urn:mpeg:dash:schema:mpd:2011\"\n"
531 "\txmlns:xlink=\"http://www.w3.org/1999/xlink\"\n"
532 "\txsi:schemaLocation=\"urn:mpeg:DASH:schema:MPD:2011 http://standards.iso.org/ittf/PubliclyAvailableStandards/MPEG-DASH_schema_files/DASH-MPD.xsd\"\n"
533 "\tprofiles=\"urn:mpeg:dash:profile:isoff-live:2011\"\n"
534 "\ttype=\"%s\"\n", final ? "static" : "dynamic");
536 avio_printf(out, "\tmediaPresentationDuration=\"");
537 write_time(out, c->total_duration);
538 avio_printf(out, "\"\n");
540 int64_t update_period = c->last_duration / AV_TIME_BASE;
542 if (c->use_template && !c->use_timeline)
544 avio_printf(out, "\tminimumUpdatePeriod=\"PT%"PRId64"S\"\n", update_period);
545 avio_printf(out, "\tsuggestedPresentationDelay=\"PT%"PRId64"S\"\n", c->last_duration / AV_TIME_BASE);
546 if (!c->availability_start_time[0] && s->nb_streams > 0 && c->streams[0].nb_segments > 0) {
547 format_date_now(c->availability_start_time, sizeof(c->availability_start_time));
549 if (c->availability_start_time[0])
550 avio_printf(out, "\tavailabilityStartTime=\"%s\"\n", c->availability_start_time);
551 format_date_now(now_str, sizeof(now_str));
553 avio_printf(out, "\tpublishTime=\"%s\"\n", now_str);
554 if (c->window_size && c->use_template) {
555 avio_printf(out, "\ttimeShiftBufferDepth=\"");
556 write_time(out, c->last_duration * c->window_size);
557 avio_printf(out, "\"\n");
560 avio_printf(out, "\tminBufferTime=\"");
561 write_time(out, c->last_duration * 2);
562 avio_printf(out, "\">\n");
563 avio_printf(out, "\t<ProgramInformation>\n");
565 char *escaped = xmlescape(title->value);
566 avio_printf(out, "\t\t<Title>%s</Title>\n", escaped);
569 avio_printf(out, "\t</ProgramInformation>\n");
570 if (c->utc_timing_url)
571 avio_printf(out, "\t<UTCTiming schemeIdUri=\"urn:mpeg:dash:utc:http-xsdate:2014\" value=\"%s\"/>\n", c->utc_timing_url);
573 if (c->window_size && s->nb_streams > 0 && c->streams[0].nb_segments > 0 && !c->use_template) {
574 OutputStream *os = &c->streams[0];
575 int start_index = FFMAX(os->nb_segments - c->window_size, 0);
576 int64_t start_time = av_rescale_q(os->segments[start_index]->time, s->streams[0]->time_base, AV_TIME_BASE_Q);
577 avio_printf(out, "\t<Period id=\"0\" start=\"");
578 write_time(out, start_time);
579 avio_printf(out, "\">\n");
581 avio_printf(out, "\t<Period id=\"0\" start=\"PT0.0S\">\n");
584 for (i = 0; i < c->nb_as; i++) {
585 if ((ret = write_adaptation_set(s, out, i)) < 0)
588 avio_printf(out, "\t</Period>\n");
589 avio_printf(out, "</MPD>\n");
591 ff_format_io_close(s, &out);
594 return avpriv_io_move(temp_filename, s->filename);
599 static int dash_init(AVFormatContext *s)
601 DASHContext *c = s->priv_data;
603 AVOutputFormat *oformat;
607 if (c->single_file_name)
611 c->ambiguous_frame_rate = 0;
613 av_strlcpy(c->dirname, s->filename, sizeof(c->dirname));
614 ptr = strrchr(c->dirname, '/');
616 av_strlcpy(basename, &ptr[1], sizeof(basename));
619 c->dirname[0] = '\0';
620 av_strlcpy(basename, s->filename, sizeof(basename));
623 ptr = strrchr(basename, '.');
627 oformat = av_guess_format("mp4", NULL, NULL);
629 return AVERROR_MUXER_NOT_FOUND;
631 c->streams = av_mallocz(sizeof(*c->streams) * s->nb_streams);
633 return AVERROR(ENOMEM);
635 if ((ret = parse_adaptation_sets(s)) < 0)
638 for (i = 0; i < s->nb_streams; i++) {
639 OutputStream *os = &c->streams[i];
640 AVFormatContext *ctx;
642 AVDictionary *opts = NULL;
645 os->bit_rate = s->streams[i]->codecpar->bit_rate;
647 snprintf(os->bandwidth_str, sizeof(os->bandwidth_str),
648 " bandwidth=\"%d\"", os->bit_rate);
650 int level = s->strict_std_compliance >= FF_COMPLIANCE_STRICT ?
651 AV_LOG_ERROR : AV_LOG_WARNING;
652 av_log(s, level, "No bit rate set for stream %d\n", i);
653 if (s->strict_std_compliance >= FF_COMPLIANCE_STRICT)
654 return AVERROR(EINVAL);
657 ctx = avformat_alloc_context();
659 return AVERROR(ENOMEM);
661 ctx->oformat = oformat;
662 ctx->interrupt_callback = s->interrupt_callback;
663 ctx->opaque = s->opaque;
664 ctx->io_close = s->io_close;
665 ctx->io_open = s->io_open;
667 if (!(st = avformat_new_stream(ctx, NULL)))
668 return AVERROR(ENOMEM);
669 avcodec_parameters_copy(st->codecpar, s->streams[i]->codecpar);
670 st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
671 st->time_base = s->streams[i]->time_base;
672 ctx->avoid_negative_ts = s->avoid_negative_ts;
673 ctx->flags = s->flags;
675 ctx->pb = avio_alloc_context(os->iobuf, sizeof(os->iobuf), AVIO_FLAG_WRITE, os, NULL, dash_write, NULL);
677 return AVERROR(ENOMEM);
679 if (c->single_file) {
680 if (c->single_file_name)
681 ff_dash_fill_tmpl_params(os->initfile, sizeof(os->initfile), c->single_file_name, i, 0, os->bit_rate, 0);
683 snprintf(os->initfile, sizeof(os->initfile), "%s-stream%d.m4s", basename, i);
685 ff_dash_fill_tmpl_params(os->initfile, sizeof(os->initfile), c->init_seg_name, i, 0, os->bit_rate, 0);
687 snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
688 ret = s->io_open(s, &os->out, filename, AVIO_FLAG_WRITE, NULL);
691 os->init_start_pos = 0;
693 av_dict_set(&opts, "movflags", "frag_custom+dash+delay_moov", 0);
694 if ((ret = avformat_init_output(ctx, &opts)) < 0)
700 av_log(s, AV_LOG_VERBOSE, "Representation %d init segment will be written to: %s\n", i, filename);
702 s->streams[i]->time_base = st->time_base;
703 // If the muxer wants to shift timestamps, request to have them shifted
704 // already before being handed to this muxer, so we don't have mismatches
705 // between the MPD and the actual segments.
706 s->avoid_negative_ts = ctx->avoid_negative_ts;
707 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
708 AVRational avg_frame_rate = s->streams[i]->avg_frame_rate;
709 if (avg_frame_rate.num > 0) {
710 if (av_cmp_q(avg_frame_rate, c->min_frame_rate) < 0)
711 c->min_frame_rate = avg_frame_rate;
712 if (av_cmp_q(c->max_frame_rate, avg_frame_rate) < 0)
713 c->max_frame_rate = avg_frame_rate;
715 c->ambiguous_frame_rate = 1;
720 set_codec_str(s, st->codecpar, os->codec_str, sizeof(os->codec_str));
721 os->first_pts = AV_NOPTS_VALUE;
722 os->max_pts = AV_NOPTS_VALUE;
723 os->last_dts = AV_NOPTS_VALUE;
724 os->segment_index = 1;
727 if (!c->has_video && c->min_seg_duration <= 0) {
728 av_log(s, AV_LOG_WARNING, "no video stream and no min seg duration set\n");
729 return AVERROR(EINVAL);
734 static int dash_write_header(AVFormatContext *s)
736 DASHContext *c = s->priv_data;
738 for (i = 0; i < s->nb_streams; i++) {
739 OutputStream *os = &c->streams[i];
740 if ((ret = avformat_write_header(os->ctx, NULL)) < 0) {
745 ret = write_manifest(s, 0);
747 av_log(s, AV_LOG_VERBOSE, "Manifest written to: %s\n", s->filename);
751 static int add_segment(OutputStream *os, const char *file,
752 int64_t time, int duration,
753 int64_t start_pos, int64_t range_length,
754 int64_t index_length)
758 if (os->nb_segments >= os->segments_size) {
759 os->segments_size = (os->segments_size + 1) * 2;
760 if ((err = av_reallocp(&os->segments, sizeof(*os->segments) *
761 os->segments_size)) < 0) {
762 os->segments_size = 0;
767 seg = av_mallocz(sizeof(*seg));
769 return AVERROR(ENOMEM);
770 av_strlcpy(seg->file, file, sizeof(seg->file));
772 seg->duration = duration;
773 if (seg->time < 0) { // If pts<0, it is expected to be cut away with an edit list
774 seg->duration += seg->time;
777 seg->start_pos = start_pos;
778 seg->range_length = range_length;
779 seg->index_length = index_length;
780 os->segments[os->nb_segments++] = seg;
785 static void write_styp(AVIOContext *pb)
788 ffio_wfourcc(pb, "styp");
789 ffio_wfourcc(pb, "msdh");
790 avio_wb32(pb, 0); /* minor */
791 ffio_wfourcc(pb, "msdh");
792 ffio_wfourcc(pb, "msix");
795 static void find_index_range(AVFormatContext *s, const char *full_path,
796 int64_t pos, int *index_length)
802 ret = s->io_open(s, &pb, full_path, AVIO_FLAG_READ, NULL);
805 if (avio_seek(pb, pos, SEEK_SET) != pos) {
806 ff_format_io_close(s, &pb);
809 ret = avio_read(pb, buf, 8);
810 ff_format_io_close(s, &pb);
813 if (AV_RL32(&buf[4]) != MKTAG('s', 'i', 'd', 'x'))
815 *index_length = AV_RB32(&buf[0]);
818 static int update_stream_extradata(AVFormatContext *s, OutputStream *os,
819 AVCodecParameters *par)
823 if (os->ctx->streams[0]->codecpar->extradata_size || !par->extradata_size)
826 extradata = av_malloc(par->extradata_size);
829 return AVERROR(ENOMEM);
831 memcpy(extradata, par->extradata, par->extradata_size);
833 os->ctx->streams[0]->codecpar->extradata = extradata;
834 os->ctx->streams[0]->codecpar->extradata_size = par->extradata_size;
836 set_codec_str(s, par, os->codec_str, sizeof(os->codec_str));
841 static int dash_flush(AVFormatContext *s, int final, int stream)
843 DASHContext *c = s->priv_data;
846 const char *proto = avio_find_protocol_name(s->filename);
847 int use_rename = proto && !strcmp(proto, "file");
849 int cur_flush_segment_index = 0;
851 cur_flush_segment_index = c->streams[stream].segment_index;
853 for (i = 0; i < s->nb_streams; i++) {
854 OutputStream *os = &c->streams[i];
855 char filename[1024] = "", full_path[1024], temp_path[1024];
857 int range_length, index_length = 0;
859 if (!os->packets_written)
862 // Flush the single stream that got a keyframe right now.
863 // Flush all audio streams as well, in sync with video keyframes,
864 // but not the other video streams.
865 if (stream >= 0 && i != stream) {
866 if (s->streams[i]->codecpar->codec_type != AVMEDIA_TYPE_AUDIO)
868 // Make sure we don't flush audio streams multiple times, when
869 // all video streams are flushed one at a time.
870 if (c->has_video && os->segment_index > cur_flush_segment_index)
874 if (!os->init_range_length) {
875 av_write_frame(os->ctx, NULL);
876 os->init_range_length = avio_tell(os->ctx->pb);
878 ff_format_io_close(s, &os->out);
881 start_pos = avio_tell(os->ctx->pb);
883 if (!c->single_file) {
884 ff_dash_fill_tmpl_params(filename, sizeof(filename), c->media_seg_name, i, os->segment_index, os->bit_rate, os->start_pts);
885 snprintf(full_path, sizeof(full_path), "%s%s", c->dirname, filename);
886 snprintf(temp_path, sizeof(temp_path), use_rename ? "%s.tmp" : "%s", full_path);
887 ret = s->io_open(s, &os->out, temp_path, AVIO_FLAG_WRITE, NULL);
890 write_styp(os->ctx->pb);
892 snprintf(full_path, sizeof(full_path), "%s%s", c->dirname, os->initfile);
895 av_write_frame(os->ctx, NULL);
896 avio_flush(os->ctx->pb);
897 os->packets_written = 0;
899 range_length = avio_tell(os->ctx->pb) - start_pos;
900 if (c->single_file) {
901 find_index_range(s, full_path, start_pos, &index_length);
903 ff_format_io_close(s, &os->out);
906 ret = avpriv_io_move(temp_path, full_path);
913 // calculate average bitrate of first segment
914 int64_t bitrate = (int64_t) range_length * 8 * AV_TIME_BASE / (os->max_pts - os->start_pts);
916 os->bit_rate = bitrate;
917 snprintf(os->bandwidth_str, sizeof(os->bandwidth_str),
918 " bandwidth=\"%d\"", os->bit_rate);
921 add_segment(os, filename, os->start_pts, os->max_pts - os->start_pts, start_pos, range_length, index_length);
922 av_log(s, AV_LOG_VERBOSE, "Representation %d media segment %d written to: %s\n", i, os->segment_index, full_path);
925 if (c->window_size || (final && c->remove_at_exit)) {
926 for (i = 0; i < s->nb_streams; i++) {
927 OutputStream *os = &c->streams[i];
929 int remove = os->nb_segments - c->window_size - c->extra_window_size;
930 if (final && c->remove_at_exit)
931 remove = os->nb_segments;
933 for (j = 0; j < remove; j++) {
935 snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->segments[j]->file);
937 av_free(os->segments[j]);
939 os->nb_segments -= remove;
940 memmove(os->segments, os->segments + remove, os->nb_segments * sizeof(*os->segments));
946 ret = write_manifest(s, final);
950 static int dash_write_packet(AVFormatContext *s, AVPacket *pkt)
952 DASHContext *c = s->priv_data;
953 AVStream *st = s->streams[pkt->stream_index];
954 OutputStream *os = &c->streams[pkt->stream_index];
957 ret = update_stream_extradata(s, os, st->codecpar);
961 // Fill in a heuristic guess of the packet duration, if none is available.
962 // The mp4 muxer will do something similar (for the last packet in a fragment)
963 // if nothing is set (setting it for the other packets doesn't hurt).
964 // By setting a nonzero duration here, we can be sure that the mp4 muxer won't
965 // invoke its heuristic (this doesn't have to be identical to that algorithm),
966 // so that we know the exact timestamps of fragments.
967 if (!pkt->duration && os->last_dts != AV_NOPTS_VALUE)
968 pkt->duration = pkt->dts - os->last_dts;
969 os->last_dts = pkt->dts;
971 // If forcing the stream to start at 0, the mp4 muxer will set the start
972 // timestamps to 0. Do the same here, to avoid mismatches in duration/timestamps.
973 if (os->first_pts == AV_NOPTS_VALUE &&
974 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
975 pkt->pts -= pkt->dts;
979 if (os->first_pts == AV_NOPTS_VALUE)
980 os->first_pts = pkt->pts;
982 if ((!c->has_video || st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) &&
983 pkt->flags & AV_PKT_FLAG_KEY && os->packets_written &&
984 av_compare_ts(pkt->pts - os->start_pts, st->time_base,
985 c->min_seg_duration, AV_TIME_BASE_Q) >= 0) {
986 int64_t prev_duration = c->last_duration;
988 c->last_duration = av_rescale_q(pkt->pts - os->start_pts,
991 c->total_duration = av_rescale_q(pkt->pts - os->first_pts,
995 if ((!c->use_timeline || !c->use_template) && prev_duration) {
996 if (c->last_duration < prev_duration*9/10 ||
997 c->last_duration > prev_duration*11/10) {
998 av_log(s, AV_LOG_WARNING,
999 "Segment durations differ too much, enable use_timeline "
1000 "and use_template, or keep a stricter keyframe interval\n");
1004 if ((ret = dash_flush(s, 0, pkt->stream_index)) < 0)
1008 if (!os->packets_written) {
1009 // If we wrote a previous segment, adjust the start time of the segment
1010 // to the end of the previous one (which is the same as the mp4 muxer
1011 // does). This avoids gaps in the timeline.
1012 if (os->max_pts != AV_NOPTS_VALUE)
1013 os->start_pts = os->max_pts;
1015 os->start_pts = pkt->pts;
1017 if (os->max_pts == AV_NOPTS_VALUE)
1018 os->max_pts = pkt->pts + pkt->duration;
1020 os->max_pts = FFMAX(os->max_pts, pkt->pts + pkt->duration);
1021 os->packets_written++;
1022 return ff_write_chained(os->ctx, 0, pkt, s, 0);
1025 static int dash_write_trailer(AVFormatContext *s)
1027 DASHContext *c = s->priv_data;
1029 if (s->nb_streams > 0) {
1030 OutputStream *os = &c->streams[0];
1031 // If no segments have been written so far, try to do a crude
1032 // guess of the segment duration
1033 if (!c->last_duration)
1034 c->last_duration = av_rescale_q(os->max_pts - os->start_pts,
1035 s->streams[0]->time_base,
1037 c->total_duration = av_rescale_q(os->max_pts - os->first_pts,
1038 s->streams[0]->time_base,
1041 dash_flush(s, 1, -1);
1043 if (c->remove_at_exit) {
1044 char filename[1024];
1046 for (i = 0; i < s->nb_streams; i++) {
1047 OutputStream *os = &c->streams[i];
1048 snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
1051 unlink(s->filename);
1057 static int dash_check_bitstream(struct AVFormatContext *s, const AVPacket *avpkt)
1059 DASHContext *c = s->priv_data;
1060 OutputStream *os = &c->streams[avpkt->stream_index];
1061 AVFormatContext *oc = os->ctx;
1062 if (oc->oformat->check_bitstream) {
1064 AVPacket pkt = *avpkt;
1065 pkt.stream_index = 0;
1066 ret = oc->oformat->check_bitstream(oc, &pkt);
1068 AVStream *st = s->streams[avpkt->stream_index];
1069 AVStream *ost = oc->streams[0];
1070 st->internal->bsfcs = ost->internal->bsfcs;
1071 st->internal->nb_bsfcs = ost->internal->nb_bsfcs;
1072 ost->internal->bsfcs = NULL;
1073 ost->internal->nb_bsfcs = 0;
1080 #define OFFSET(x) offsetof(DASHContext, x)
1081 #define E AV_OPT_FLAG_ENCODING_PARAM
1082 static const AVOption options[] = {
1083 { "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 },
1084 { "window_size", "number of segments kept in the manifest", OFFSET(window_size), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, E },
1085 { "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 },
1086 { "min_seg_duration", "minimum segment duration (in microseconds)", OFFSET(min_seg_duration), AV_OPT_TYPE_INT64, { .i64 = 5000000 }, 0, INT_MAX, E },
1087 { "remove_at_exit", "remove all segments when finished", OFFSET(remove_at_exit), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
1088 { "use_template", "Use SegmentTemplate instead of SegmentList", OFFSET(use_template), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, E },
1089 { "use_timeline", "Use SegmentTimeline in SegmentTemplate", OFFSET(use_timeline), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, E },
1090 { "single_file", "Store all segments in one file, accessed using byte ranges", OFFSET(single_file), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
1091 { "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 },
1092 { "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 },
1093 { "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 },
1094 { "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 },
1098 static const AVClass dash_class = {
1099 .class_name = "dash muxer",
1100 .item_name = av_default_item_name,
1102 .version = LIBAVUTIL_VERSION_INT,
1105 AVOutputFormat ff_dash_muxer = {
1107 .long_name = NULL_IF_CONFIG_SMALL("DASH Muxer"),
1108 .priv_data_size = sizeof(DASHContext),
1109 .audio_codec = AV_CODEC_ID_AAC,
1110 .video_codec = AV_CODEC_ID_H264,
1111 .flags = AVFMT_GLOBALHEADER | AVFMT_NOFILE | AVFMT_TS_NEGATIVE,
1113 .write_header = dash_write_header,
1114 .write_packet = dash_write_packet,
1115 .write_trailer = dash_write_trailer,
1116 .deinit = dash_free,
1117 .check_bitstream = dash_check_bitstream,
1118 .priv_class = &dash_class,