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/avstring.h"
29 #include "libavutil/intreadwrite.h"
30 #include "libavutil/mathematics.h"
31 #include "libavutil/opt.h"
32 #include "libavutil/rational.h"
33 #include "libavutil/time_internal.h"
37 #include "avio_internal.h"
40 #include "os_support.h"
43 // See ISO/IEC 23009-1:2014 5.3.9.4.4
45 DASH_TMPL_ID_UNDEFINED = -1,
49 DASH_TMPL_ID_BANDWIDTH,
53 typedef struct Segment {
56 int range_length, index_length;
62 typedef struct OutputStream {
69 int64_t init_start_pos;
70 int init_range_length;
71 int nb_segments, segments_size, segment_index;
73 int64_t first_pts, start_pts, max_pts;
76 char bandwidth_str[64];
81 typedef struct DASHContext {
82 const AVClass *class; /* Class for private options. */
84 int extra_window_size;
90 OutputStream *streams;
91 int has_video, has_audio;
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;
103 static int dash_write(void *opaque, uint8_t *buf, int buf_size)
105 OutputStream *os = opaque;
107 ffurl_write(os->out, buf, buf_size);
112 static void set_codec_str(AVFormatContext *s, AVCodecContext *codec,
115 const AVCodecTag *tags[2] = { NULL, NULL };
117 if (codec->codec_type == AVMEDIA_TYPE_VIDEO)
118 tags[0] = ff_codec_movvideo_tags;
119 else if (codec->codec_type == AVMEDIA_TYPE_AUDIO)
120 tags[0] = ff_codec_movaudio_tags;
124 tag = av_codec_get_tag(tags, codec->codec_id);
132 if (!strcmp(str, "mp4a") || !strcmp(str, "mp4v")) {
134 tags[0] = ff_mp4_obj_type;
135 oti = av_codec_get_tag(tags, codec->codec_id);
137 av_strlcatf(str, size, ".%02x", oti);
141 if (tag == MKTAG('m', 'p', '4', 'a')) {
142 if (codec->extradata_size >= 2) {
143 int aot = codec->extradata[0] >> 3;
145 aot = ((AV_RB16(codec->extradata) >> 5) & 0x3f) + 32;
146 av_strlcatf(str, size, ".%d", aot);
148 } else if (tag == MKTAG('m', 'p', '4', 'v')) {
149 // Unimplemented, should output ProfileLevelIndication as a decimal number
150 av_log(s, AV_LOG_WARNING, "Incomplete RFC 6381 codec string for mp4v\n");
152 } else if (!strcmp(str, "avc1")) {
153 uint8_t *tmpbuf = NULL;
154 uint8_t *extradata = codec->extradata;
155 int extradata_size = codec->extradata_size;
158 if (extradata[0] != 1) {
160 if (avio_open_dyn_buf(&pb) < 0)
162 if (ff_isom_write_avcc(pb, extradata, extradata_size) < 0) {
163 ffio_free_dyn_buf(&pb);
166 extradata_size = avio_close_dyn_buf(pb, &extradata);
170 if (extradata_size >= 4)
171 av_strlcatf(str, size, ".%02x%02x%02x",
172 extradata[1], extradata[2], extradata[3]);
177 static void dash_free(AVFormatContext *s)
179 DASHContext *c = s->priv_data;
183 for (i = 0; i < s->nb_streams; i++) {
184 OutputStream *os = &c->streams[i];
185 if (os->ctx && os->ctx_inited)
186 av_write_trailer(os->ctx);
187 if (os->ctx && os->ctx->pb)
188 av_free(os->ctx->pb);
189 ffurl_close(os->out);
192 avformat_free_context(os->ctx);
193 for (j = 0; j < os->nb_segments; j++)
194 av_free(os->segments[j]);
195 av_free(os->segments);
197 av_freep(&c->streams);
200 static void output_segment_list(OutputStream *os, AVIOContext *out, DASHContext *c)
202 int i, start_index = 0, start_number = 1;
203 if (c->window_size) {
204 start_index = FFMAX(os->nb_segments - c->window_size, 0);
205 start_number = FFMAX(os->segment_index - c->window_size, 1);
208 if (c->use_template) {
209 int timescale = c->use_timeline ? os->ctx->streams[0]->time_base.den : AV_TIME_BASE;
210 avio_printf(out, "\t\t\t\t<SegmentTemplate timescale=\"%d\" ", timescale);
211 if (!c->use_timeline)
212 avio_printf(out, "duration=\"%"PRId64"\" ", c->last_duration);
213 avio_printf(out, "initialization=\"%s\" media=\"%s\" startNumber=\"%d\">\n", c->init_seg_name, c->media_seg_name, c->use_timeline ? start_number : 1);
214 if (c->use_timeline) {
215 int64_t cur_time = 0;
216 avio_printf(out, "\t\t\t\t\t<SegmentTimeline>\n");
217 for (i = start_index; i < os->nb_segments; ) {
218 Segment *seg = os->segments[i];
220 avio_printf(out, "\t\t\t\t\t\t<S ");
221 if (i == start_index || seg->time != cur_time) {
222 cur_time = seg->time;
223 avio_printf(out, "t=\"%"PRId64"\" ", seg->time);
225 avio_printf(out, "d=\"%d\" ", seg->duration);
226 while (i + repeat + 1 < os->nb_segments &&
227 os->segments[i + repeat + 1]->duration == seg->duration &&
228 os->segments[i + repeat + 1]->time == os->segments[i + repeat]->time + os->segments[i + repeat]->duration)
231 avio_printf(out, "r=\"%d\" ", repeat);
232 avio_printf(out, "/>\n");
234 cur_time += (1 + repeat) * seg->duration;
236 avio_printf(out, "\t\t\t\t\t</SegmentTimeline>\n");
238 avio_printf(out, "\t\t\t\t</SegmentTemplate>\n");
239 } else if (c->single_file) {
240 avio_printf(out, "\t\t\t\t<BaseURL>%s</BaseURL>\n", os->initfile);
241 avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%"PRId64"\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);
242 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);
243 for (i = start_index; i < os->nb_segments; i++) {
244 Segment *seg = os->segments[i];
245 avio_printf(out, "\t\t\t\t\t<SegmentURL mediaRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->range_length - 1);
246 if (seg->index_length)
247 avio_printf(out, "indexRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->index_length - 1);
248 avio_printf(out, "/>\n");
250 avio_printf(out, "\t\t\t\t</SegmentList>\n");
252 avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%"PRId64"\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);
253 avio_printf(out, "\t\t\t\t\t<Initialization sourceURL=\"%s\" />\n", os->initfile);
254 for (i = start_index; i < os->nb_segments; i++) {
255 Segment *seg = os->segments[i];
256 avio_printf(out, "\t\t\t\t\t<SegmentURL media=\"%s\" />\n", seg->file);
258 avio_printf(out, "\t\t\t\t</SegmentList>\n");
262 static DASHTmplId dash_read_tmpl_id(const char *identifier, char *format_tag,
263 size_t format_tag_size, const char **ptr) {
264 const char *next_ptr;
265 DASHTmplId id_type = DASH_TMPL_ID_UNDEFINED;
267 if (av_strstart(identifier, "$$", &next_ptr)) {
268 id_type = DASH_TMPL_ID_ESCAPE;
270 } else if (av_strstart(identifier, "$RepresentationID$", &next_ptr)) {
271 id_type = DASH_TMPL_ID_REP_ID;
272 // default to basic format, as $RepresentationID$ identifiers
273 // are not allowed to have custom format-tags.
274 av_strlcpy(format_tag, "%d", format_tag_size);
276 } else { // the following identifiers may have an explicit format_tag
277 if (av_strstart(identifier, "$Number", &next_ptr))
278 id_type = DASH_TMPL_ID_NUMBER;
279 else if (av_strstart(identifier, "$Bandwidth", &next_ptr))
280 id_type = DASH_TMPL_ID_BANDWIDTH;
281 else if (av_strstart(identifier, "$Time", &next_ptr))
282 id_type = DASH_TMPL_ID_TIME;
284 id_type = DASH_TMPL_ID_UNDEFINED;
286 // next parse the dash format-tag and generate a c-string format tag
287 // (next_ptr now points at the first '%' at the beginning of the format-tag)
288 if (id_type != DASH_TMPL_ID_UNDEFINED) {
289 const char *number_format = (id_type == DASH_TMPL_ID_TIME) ? PRId64 : "d";
290 if (next_ptr[0] == '$') { // no dash format-tag
291 snprintf(format_tag, format_tag_size, "%%%s", number_format);
294 const char *width_ptr;
295 // only tolerate single-digit width-field (i.e. up to 9-digit width)
296 if (av_strstart(next_ptr, "%0", &width_ptr) &&
297 av_isdigit(width_ptr[0]) &&
298 av_strstart(&width_ptr[1], "d$", &next_ptr)) {
299 // yes, we're using a format tag to build format_tag.
300 snprintf(format_tag, format_tag_size, "%s%c%s", "%0", width_ptr[0], number_format);
303 av_log(NULL, AV_LOG_WARNING, "Failed to parse format-tag beginning with %s. Expected either a "
304 "closing '$' character or a format-string like '%%0[width]d', "
305 "where width must be a single digit\n", next_ptr);
306 id_type = DASH_TMPL_ID_UNDEFINED;
314 static void dash_fill_tmpl_params(char *dst, size_t buffer_size,
315 const char *template, int rep_id,
316 int number, int bit_rate,
319 const char *t_cur = template;
320 while (dst_pos < buffer_size - 1 && *t_cur) {
321 char format_tag[7]; // May be "%d", "%0Xd", or "%0Xlld" (for $Time$), where X is in [0-9]
324 const char *t_next = strchr(t_cur, '$'); // copy over everything up to the first '$' character
326 int num_copy_bytes = FFMIN(t_next - t_cur, buffer_size - dst_pos - 1);
327 av_strlcpy(&dst[dst_pos], t_cur, num_copy_bytes + 1);
329 dst_pos += num_copy_bytes;
331 } else { // no more DASH identifiers to substitute - just copy the rest over and break
332 av_strlcpy(&dst[dst_pos], t_cur, buffer_size - dst_pos);
336 if (dst_pos >= buffer_size - 1 || !*t_cur)
339 // t_cur is now pointing to a '$' character
340 id_type = dash_read_tmpl_id(t_cur, format_tag, sizeof(format_tag), &t_next);
342 case DASH_TMPL_ID_ESCAPE:
343 av_strlcpy(&dst[dst_pos], "$", 2);
346 case DASH_TMPL_ID_REP_ID:
347 n = snprintf(&dst[dst_pos], buffer_size - dst_pos, format_tag, rep_id);
349 case DASH_TMPL_ID_NUMBER:
350 n = snprintf(&dst[dst_pos], buffer_size - dst_pos, format_tag, number);
352 case DASH_TMPL_ID_BANDWIDTH:
353 n = snprintf(&dst[dst_pos], buffer_size - dst_pos, format_tag, bit_rate);
355 case DASH_TMPL_ID_TIME:
356 n = snprintf(&dst[dst_pos], buffer_size - dst_pos, format_tag, time);
358 case DASH_TMPL_ID_UNDEFINED:
359 // copy over one byte and advance
360 av_strlcpy(&dst[dst_pos], t_cur, 2);
365 // t_next points just past the processed identifier
366 // n is the number of bytes that were attempted to be written to dst
367 // (may have failed to write all because buffer_size).
370 dst_pos += FFMIN(n, buffer_size - dst_pos - 1);
375 static char *xmlescape(const char *str) {
376 int outlen = strlen(str)*3/2 + 6;
377 char *out = av_realloc(NULL, outlen + 1);
381 for (; *str; str++) {
382 if (pos + 6 > outlen) {
384 outlen = 2 * outlen + 6;
385 tmp = av_realloc(out, outlen + 1);
393 memcpy(&out[pos], "&", 5);
395 } else if (*str == '<') {
396 memcpy(&out[pos], "<", 4);
398 } else if (*str == '>') {
399 memcpy(&out[pos], ">", 4);
401 } else if (*str == '\'') {
402 memcpy(&out[pos], "'", 6);
404 } else if (*str == '\"') {
405 memcpy(&out[pos], """, 6);
415 static void write_time(AVIOContext *out, int64_t time)
417 int seconds = time / AV_TIME_BASE;
418 int fractions = time % AV_TIME_BASE;
419 int minutes = seconds / 60;
420 int hours = minutes / 60;
423 avio_printf(out, "PT");
425 avio_printf(out, "%dH", hours);
426 if (hours || minutes)
427 avio_printf(out, "%dM", minutes);
428 avio_printf(out, "%d.%dS", seconds, fractions / (AV_TIME_BASE / 10));
431 static void format_date_now(char *buf, int size)
433 time_t t = time(NULL);
434 struct tm *ptm, tmbuf;
435 ptm = gmtime_r(&t, &tmbuf);
437 if (!strftime(buf, size, "%Y-%m-%dT%H:%M:%S", ptm))
442 static int write_manifest(AVFormatContext *s, int final)
444 DASHContext *c = s->priv_data;
446 char temp_filename[1024];
448 AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
450 snprintf(temp_filename, sizeof(temp_filename), "%s.tmp", s->filename);
451 ret = avio_open2(&out, temp_filename, AVIO_FLAG_WRITE, &s->interrupt_callback, NULL);
453 av_log(s, AV_LOG_ERROR, "Unable to open %s for writing\n", temp_filename);
456 avio_printf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
457 avio_printf(out, "<MPD xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
458 "\txmlns=\"urn:mpeg:dash:schema:mpd:2011\"\n"
459 "\txmlns:xlink=\"http://www.w3.org/1999/xlink\"\n"
460 "\txsi:schemaLocation=\"urn:mpeg:DASH:schema:MPD:2011 http://standards.iso.org/ittf/PubliclyAvailableStandards/MPEG-DASH_schema_files/DASH-MPD.xsd\"\n"
461 "\tprofiles=\"urn:mpeg:dash:profile:isoff-live:2011\"\n"
462 "\ttype=\"%s\"\n", final ? "static" : "dynamic");
464 avio_printf(out, "\tmediaPresentationDuration=\"");
465 write_time(out, c->total_duration);
466 avio_printf(out, "\"\n");
468 int64_t update_period = c->last_duration / AV_TIME_BASE;
470 if (c->use_template && !c->use_timeline)
472 avio_printf(out, "\tminimumUpdatePeriod=\"PT%"PRId64"S\"\n", update_period);
473 avio_printf(out, "\tsuggestedPresentationDelay=\"PT%"PRId64"S\"\n", c->last_duration / AV_TIME_BASE);
474 if (!c->availability_start_time[0] && s->nb_streams > 0 && c->streams[0].nb_segments > 0) {
475 format_date_now(c->availability_start_time, sizeof(c->availability_start_time));
477 if (c->availability_start_time[0])
478 avio_printf(out, "\tavailabilityStartTime=\"%s\"\n", c->availability_start_time);
479 format_date_now(now_str, sizeof(now_str));
481 avio_printf(out, "\tpublishTime=\"%s\"\n", now_str);
482 if (c->window_size && c->use_template) {
483 avio_printf(out, "\ttimeShiftBufferDepth=\"");
484 write_time(out, c->last_duration * c->window_size);
485 avio_printf(out, "\"\n");
488 avio_printf(out, "\tminBufferTime=\"");
489 write_time(out, c->last_duration);
490 avio_printf(out, "\">\n");
491 avio_printf(out, "\t<ProgramInformation>\n");
493 char *escaped = xmlescape(title->value);
494 avio_printf(out, "\t\t<Title>%s</Title>\n", escaped);
497 avio_printf(out, "\t</ProgramInformation>\n");
498 if (c->window_size && s->nb_streams > 0 && c->streams[0].nb_segments > 0 && !c->use_template) {
499 OutputStream *os = &c->streams[0];
500 int start_index = FFMAX(os->nb_segments - c->window_size, 0);
501 int64_t start_time = av_rescale_q(os->segments[start_index]->time, s->streams[0]->time_base, AV_TIME_BASE_Q);
502 avio_printf(out, "\t<Period start=\"");
503 write_time(out, start_time);
504 avio_printf(out, "\">\n");
506 avio_printf(out, "\t<Period start=\"PT0.0S\">\n");
510 avio_printf(out, "\t\t<AdaptationSet contentType=\"video\" segmentAlignment=\"true\" bitstreamSwitching=\"true\"");
511 if (c->max_frame_rate.num && !c->ambiguous_frame_rate)
512 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);
513 avio_printf(out, ">\n");
515 for (i = 0; i < s->nb_streams; i++) {
516 AVStream *st = s->streams[i];
517 OutputStream *os = &c->streams[i];
519 if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO)
522 avio_printf(out, "\t\t\t<Representation id=\"%d\" mimeType=\"video/mp4\" codecs=\"%s\"%s width=\"%d\" height=\"%d\"", i, os->codec_str, os->bandwidth_str, st->codec->width, st->codec->height);
523 if (st->avg_frame_rate.num)
524 avio_printf(out, " frameRate=\"%d/%d\"", st->avg_frame_rate.num, st->avg_frame_rate.den);
525 avio_printf(out, ">\n");
527 output_segment_list(&c->streams[i], out, c);
528 avio_printf(out, "\t\t\t</Representation>\n");
530 avio_printf(out, "\t\t</AdaptationSet>\n");
533 avio_printf(out, "\t\t<AdaptationSet contentType=\"audio\" segmentAlignment=\"true\" bitstreamSwitching=\"true\">\n");
534 for (i = 0; i < s->nb_streams; i++) {
535 AVStream *st = s->streams[i];
536 OutputStream *os = &c->streams[i];
538 if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO)
541 avio_printf(out, "\t\t\t<Representation id=\"%d\" mimeType=\"audio/mp4\" codecs=\"%s\"%s audioSamplingRate=\"%d\">\n", i, os->codec_str, os->bandwidth_str, st->codec->sample_rate);
542 avio_printf(out, "\t\t\t\t<AudioChannelConfiguration schemeIdUri=\"urn:mpeg:dash:23003:3:audio_channel_configuration:2011\" value=\"%d\" />\n", st->codec->channels);
543 output_segment_list(&c->streams[i], out, c);
544 avio_printf(out, "\t\t\t</Representation>\n");
546 avio_printf(out, "\t\t</AdaptationSet>\n");
548 avio_printf(out, "\t</Period>\n");
549 avio_printf(out, "</MPD>\n");
552 return ff_rename(temp_filename, s->filename, s);
555 static int dash_write_header(AVFormatContext *s)
557 DASHContext *c = s->priv_data;
559 AVOutputFormat *oformat;
563 if (c->single_file_name)
567 c->ambiguous_frame_rate = 0;
569 av_strlcpy(c->dirname, s->filename, sizeof(c->dirname));
570 ptr = strrchr(c->dirname, '/');
572 av_strlcpy(basename, &ptr[1], sizeof(basename));
575 c->dirname[0] = '\0';
576 av_strlcpy(basename, s->filename, sizeof(basename));
579 ptr = strrchr(basename, '.');
583 oformat = av_guess_format("mp4", NULL, NULL);
585 ret = AVERROR_MUXER_NOT_FOUND;
589 c->streams = av_mallocz(sizeof(*c->streams) * s->nb_streams);
591 ret = AVERROR(ENOMEM);
595 for (i = 0; i < s->nb_streams; i++) {
596 OutputStream *os = &c->streams[i];
597 AVFormatContext *ctx;
599 AVDictionary *opts = NULL;
602 os->bit_rate = s->streams[i]->codec->bit_rate ?
603 s->streams[i]->codec->bit_rate :
604 s->streams[i]->codec->rc_max_rate;
606 snprintf(os->bandwidth_str, sizeof(os->bandwidth_str),
607 " bandwidth=\"%d\"", os->bit_rate);
609 int level = s->strict_std_compliance >= FF_COMPLIANCE_STRICT ?
610 AV_LOG_ERROR : AV_LOG_WARNING;
611 av_log(s, level, "No bit rate set for stream %d\n", i);
612 if (s->strict_std_compliance >= FF_COMPLIANCE_STRICT) {
613 ret = AVERROR(EINVAL);
618 ctx = avformat_alloc_context();
620 ret = AVERROR(ENOMEM);
624 ctx->oformat = oformat;
625 ctx->interrupt_callback = s->interrupt_callback;
627 if (!(st = avformat_new_stream(ctx, NULL))) {
628 ret = AVERROR(ENOMEM);
631 avcodec_copy_context(st->codec, s->streams[i]->codec);
632 st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
633 st->time_base = s->streams[i]->time_base;
634 ctx->avoid_negative_ts = s->avoid_negative_ts;
636 ctx->pb = avio_alloc_context(os->iobuf, sizeof(os->iobuf), AVIO_FLAG_WRITE, os, NULL, dash_write, NULL);
638 ret = AVERROR(ENOMEM);
642 if (c->single_file) {
643 if (c->single_file_name)
644 dash_fill_tmpl_params(os->initfile, sizeof(os->initfile), c->single_file_name, i, 0, os->bit_rate, 0);
646 snprintf(os->initfile, sizeof(os->initfile), "%s-stream%d.m4s", basename, i);
648 dash_fill_tmpl_params(os->initfile, sizeof(os->initfile), c->init_seg_name, i, 0, os->bit_rate, 0);
650 snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
651 ret = ffurl_open(&os->out, filename, AVIO_FLAG_WRITE, &s->interrupt_callback, NULL);
654 os->init_start_pos = 0;
656 av_dict_set(&opts, "movflags", "frag_custom+dash+delay_moov", 0);
657 if ((ret = avformat_write_header(ctx, &opts)) < 0) {
664 av_log(s, AV_LOG_VERBOSE, "Representation %d init segment will be written to: %s\n", i, filename);
666 s->streams[i]->time_base = st->time_base;
667 // If the muxer wants to shift timestamps, request to have them shifted
668 // already before being handed to this muxer, so we don't have mismatches
669 // between the MPD and the actual segments.
670 s->avoid_negative_ts = ctx->avoid_negative_ts;
671 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
672 AVRational avg_frame_rate = s->streams[i]->avg_frame_rate;
673 if (avg_frame_rate.num > 0) {
674 if (av_cmp_q(avg_frame_rate, c->min_frame_rate) < 0)
675 c->min_frame_rate = avg_frame_rate;
676 if (av_cmp_q(c->max_frame_rate, avg_frame_rate) < 0)
677 c->max_frame_rate = avg_frame_rate;
679 c->ambiguous_frame_rate = 1;
682 } else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
686 set_codec_str(s, st->codec, os->codec_str, sizeof(os->codec_str));
687 os->first_pts = AV_NOPTS_VALUE;
688 os->max_pts = AV_NOPTS_VALUE;
689 os->last_dts = AV_NOPTS_VALUE;
690 os->segment_index = 1;
693 if (!c->has_video && c->min_seg_duration <= 0) {
694 av_log(s, AV_LOG_WARNING, "no video stream and no min seg duration set\n");
695 ret = AVERROR(EINVAL);
697 ret = write_manifest(s, 0);
699 av_log(s, AV_LOG_VERBOSE, "Manifest written to: %s\n", s->filename);
707 static int add_segment(OutputStream *os, const char *file,
708 int64_t time, int duration,
709 int64_t start_pos, int64_t range_length,
710 int64_t index_length)
714 if (os->nb_segments >= os->segments_size) {
715 os->segments_size = (os->segments_size + 1) * 2;
716 if ((err = av_reallocp(&os->segments, sizeof(*os->segments) *
717 os->segments_size)) < 0) {
718 os->segments_size = 0;
723 seg = av_mallocz(sizeof(*seg));
725 return AVERROR(ENOMEM);
726 av_strlcpy(seg->file, file, sizeof(seg->file));
728 seg->duration = duration;
729 if (seg->time < 0) { // If pts<0, it is expected to be cut away with an edit list
730 seg->duration += seg->time;
733 seg->start_pos = start_pos;
734 seg->range_length = range_length;
735 seg->index_length = index_length;
736 os->segments[os->nb_segments++] = seg;
741 static void write_styp(AVIOContext *pb)
744 ffio_wfourcc(pb, "styp");
745 ffio_wfourcc(pb, "msdh");
746 avio_wb32(pb, 0); /* minor */
747 ffio_wfourcc(pb, "msdh");
748 ffio_wfourcc(pb, "msix");
751 static void find_index_range(AVFormatContext *s, const char *full_path,
752 int64_t pos, int *index_length)
758 ret = ffurl_open(&fd, full_path, AVIO_FLAG_READ, &s->interrupt_callback, NULL);
761 if (ffurl_seek(fd, pos, SEEK_SET) != pos) {
765 ret = ffurl_read(fd, buf, 8);
769 if (AV_RL32(&buf[4]) != MKTAG('s', 'i', 'd', 'x'))
771 *index_length = AV_RB32(&buf[0]);
774 static int update_stream_extradata(AVFormatContext *s, OutputStream *os,
775 AVCodecContext *codec)
779 if (os->ctx->streams[0]->codec->extradata_size || !codec->extradata_size)
782 extradata = av_malloc(codec->extradata_size);
785 return AVERROR(ENOMEM);
787 memcpy(extradata, codec->extradata, codec->extradata_size);
789 os->ctx->streams[0]->codec->extradata = extradata;
790 os->ctx->streams[0]->codec->extradata_size = codec->extradata_size;
792 set_codec_str(s, codec, os->codec_str, sizeof(os->codec_str));
797 static int dash_flush(AVFormatContext *s, int final, int stream)
799 DASHContext *c = s->priv_data;
801 int cur_flush_segment_index = 0;
803 cur_flush_segment_index = c->streams[stream].segment_index;
805 for (i = 0; i < s->nb_streams; i++) {
806 OutputStream *os = &c->streams[i];
807 char filename[1024] = "", full_path[1024], temp_path[1024];
809 int range_length, index_length = 0;
811 if (!os->packets_written)
814 // Flush the single stream that got a keyframe right now.
815 // Flush all audio streams as well, in sync with video keyframes,
816 // but not the other video streams.
817 if (stream >= 0 && i != stream) {
818 if (s->streams[i]->codec->codec_type != AVMEDIA_TYPE_AUDIO)
820 // Make sure we don't flush audio streams multiple times, when
821 // all video streams are flushed one at a time.
822 if (c->has_video && os->segment_index > cur_flush_segment_index)
826 if (!os->init_range_length) {
827 av_write_frame(os->ctx, NULL);
828 os->init_range_length = avio_tell(os->ctx->pb);
829 if (!c->single_file) {
830 ffurl_close(os->out);
835 start_pos = avio_tell(os->ctx->pb);
837 if (!c->single_file) {
838 dash_fill_tmpl_params(filename, sizeof(filename), c->media_seg_name, i, os->segment_index, os->bit_rate, os->start_pts);
839 snprintf(full_path, sizeof(full_path), "%s%s", c->dirname, filename);
840 snprintf(temp_path, sizeof(temp_path), "%s.tmp", full_path);
841 ret = ffurl_open(&os->out, temp_path, AVIO_FLAG_WRITE, &s->interrupt_callback, NULL);
844 write_styp(os->ctx->pb);
846 snprintf(full_path, sizeof(full_path), "%s%s", c->dirname, os->initfile);
849 av_write_frame(os->ctx, NULL);
850 avio_flush(os->ctx->pb);
851 os->packets_written = 0;
853 range_length = avio_tell(os->ctx->pb) - start_pos;
854 if (c->single_file) {
855 find_index_range(s, full_path, start_pos, &index_length);
857 ffurl_close(os->out);
859 ret = ff_rename(temp_path, full_path, s);
863 add_segment(os, filename, os->start_pts, os->max_pts - os->start_pts, start_pos, range_length, index_length);
864 av_log(s, AV_LOG_VERBOSE, "Representation %d media segment %d written to: %s\n", i, os->segment_index, full_path);
867 if (c->window_size || (final && c->remove_at_exit)) {
868 for (i = 0; i < s->nb_streams; i++) {
869 OutputStream *os = &c->streams[i];
871 int remove = os->nb_segments - c->window_size - c->extra_window_size;
872 if (final && c->remove_at_exit)
873 remove = os->nb_segments;
875 for (j = 0; j < remove; j++) {
877 snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->segments[j]->file);
879 av_free(os->segments[j]);
881 os->nb_segments -= remove;
882 memmove(os->segments, os->segments + remove, os->nb_segments * sizeof(*os->segments));
888 ret = write_manifest(s, final);
892 static int dash_write_packet(AVFormatContext *s, AVPacket *pkt)
894 DASHContext *c = s->priv_data;
895 AVStream *st = s->streams[pkt->stream_index];
896 OutputStream *os = &c->streams[pkt->stream_index];
897 int64_t seg_end_duration = (os->segment_index) * (int64_t) c->min_seg_duration;
900 ret = update_stream_extradata(s, os, st->codec);
904 // Fill in a heuristic guess of the packet duration, if none is available.
905 // The mp4 muxer will do something similar (for the last packet in a fragment)
906 // if nothing is set (setting it for the other packets doesn't hurt).
907 // By setting a nonzero duration here, we can be sure that the mp4 muxer won't
908 // invoke its heuristic (this doesn't have to be identical to that algorithm),
909 // so that we know the exact timestamps of fragments.
910 if (!pkt->duration && os->last_dts != AV_NOPTS_VALUE)
911 pkt->duration = pkt->dts - os->last_dts;
912 os->last_dts = pkt->dts;
914 // If forcing the stream to start at 0, the mp4 muxer will set the start
915 // timestamps to 0. Do the same here, to avoid mismatches in duration/timestamps.
916 if (os->first_pts == AV_NOPTS_VALUE &&
917 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
918 pkt->pts -= pkt->dts;
922 if (os->first_pts == AV_NOPTS_VALUE)
923 os->first_pts = pkt->pts;
925 if ((!c->has_video || st->codec->codec_type == AVMEDIA_TYPE_VIDEO) &&
926 pkt->flags & AV_PKT_FLAG_KEY && os->packets_written &&
927 av_compare_ts(pkt->pts - os->first_pts, st->time_base,
928 seg_end_duration, AV_TIME_BASE_Q) >= 0) {
929 int64_t prev_duration = c->last_duration;
931 c->last_duration = av_rescale_q(pkt->pts - os->start_pts,
934 c->total_duration = av_rescale_q(pkt->pts - os->first_pts,
938 if ((!c->use_timeline || !c->use_template) && prev_duration) {
939 if (c->last_duration < prev_duration*9/10 ||
940 c->last_duration > prev_duration*11/10) {
941 av_log(s, AV_LOG_WARNING,
942 "Segment durations differ too much, enable use_timeline "
943 "and use_template, or keep a stricter keyframe interval\n");
947 if ((ret = dash_flush(s, 0, pkt->stream_index)) < 0)
951 if (!os->packets_written) {
952 // If we wrote a previous segment, adjust the start time of the segment
953 // to the end of the previous one (which is the same as the mp4 muxer
954 // does). This avoids gaps in the timeline.
955 if (os->max_pts != AV_NOPTS_VALUE)
956 os->start_pts = os->max_pts;
958 os->start_pts = pkt->pts;
960 if (os->max_pts == AV_NOPTS_VALUE)
961 os->max_pts = pkt->pts + pkt->duration;
963 os->max_pts = FFMAX(os->max_pts, pkt->pts + pkt->duration);
964 os->packets_written++;
965 return ff_write_chained(os->ctx, 0, pkt, s, 0);
968 static int dash_write_trailer(AVFormatContext *s)
970 DASHContext *c = s->priv_data;
972 if (s->nb_streams > 0) {
973 OutputStream *os = &c->streams[0];
974 // If no segments have been written so far, try to do a crude
975 // guess of the segment duration
976 if (!c->last_duration)
977 c->last_duration = av_rescale_q(os->max_pts - os->start_pts,
978 s->streams[0]->time_base,
980 c->total_duration = av_rescale_q(os->max_pts - os->first_pts,
981 s->streams[0]->time_base,
984 dash_flush(s, 1, -1);
986 if (c->remove_at_exit) {
989 for (i = 0; i < s->nb_streams; i++) {
990 OutputStream *os = &c->streams[i];
991 snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
1001 #define OFFSET(x) offsetof(DASHContext, x)
1002 #define E AV_OPT_FLAG_ENCODING_PARAM
1003 static const AVOption options[] = {
1004 { "window_size", "number of segments kept in the manifest", OFFSET(window_size), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, E },
1005 { "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 },
1006 { "min_seg_duration", "minimum segment duration (in microseconds)", OFFSET(min_seg_duration), AV_OPT_TYPE_INT64, { .i64 = 5000000 }, 0, INT_MAX, E },
1007 { "remove_at_exit", "remove all segments when finished", OFFSET(remove_at_exit), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
1008 { "use_template", "Use SegmentTemplate instead of SegmentList", OFFSET(use_template), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, E },
1009 { "use_timeline", "Use SegmentTimeline in SegmentTemplate", OFFSET(use_timeline), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, E },
1010 { "single_file", "Store all segments in one file, accessed using byte ranges", OFFSET(single_file), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
1011 { "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 },
1012 { "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 },
1013 { "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 },
1017 static const AVClass dash_class = {
1018 .class_name = "dash muxer",
1019 .item_name = av_default_item_name,
1021 .version = LIBAVUTIL_VERSION_INT,
1024 AVOutputFormat ff_dash_muxer = {
1026 .long_name = NULL_IF_CONFIG_SMALL("DASH Muxer"),
1027 .priv_data_size = sizeof(DASHContext),
1028 .audio_codec = AV_CODEC_ID_AAC,
1029 .video_codec = AV_CODEC_ID_H264,
1030 .flags = AVFMT_GLOBALHEADER | AVFMT_NOFILE | AVFMT_TS_NEGATIVE,
1031 .write_header = dash_write_header,
1032 .write_packet = dash_write_packet,
1033 .write_trailer = dash_write_trailer,
1034 .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
1035 .priv_class = &dash_class,