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"
44 typedef struct Segment {
47 int range_length, index_length;
53 typedef struct OutputStream {
60 int64_t init_start_pos;
61 int init_range_length;
62 int nb_segments, segments_size, segment_index;
64 int64_t first_pts, start_pts, max_pts;
67 char bandwidth_str[64];
72 typedef struct DASHContext {
73 const AVClass *class; /* Class for private options. */
75 int extra_window_size;
81 OutputStream *streams;
82 int has_video, has_audio;
83 int64_t last_duration;
84 int64_t total_duration;
85 char availability_start_time[100];
87 const char *single_file_name;
88 const char *init_seg_name;
89 const char *media_seg_name;
90 AVRational min_frame_rate, max_frame_rate;
91 int ambiguous_frame_rate;
92 const char *utc_timing_url;
95 static int dash_write(void *opaque, uint8_t *buf, int buf_size)
97 OutputStream *os = opaque;
99 avio_write(os->out, buf, buf_size);
104 static void set_codec_str(AVFormatContext *s, AVCodecParameters *par,
107 const AVCodecTag *tags[2] = { NULL, NULL };
109 if (par->codec_type == AVMEDIA_TYPE_VIDEO)
110 tags[0] = ff_codec_movvideo_tags;
111 else if (par->codec_type == AVMEDIA_TYPE_AUDIO)
112 tags[0] = ff_codec_movaudio_tags;
116 tag = av_codec_get_tag(tags, par->codec_id);
124 if (!strcmp(str, "mp4a") || !strcmp(str, "mp4v")) {
126 tags[0] = ff_mp4_obj_type;
127 oti = av_codec_get_tag(tags, par->codec_id);
129 av_strlcatf(str, size, ".%02"PRIx32, oti);
133 if (tag == MKTAG('m', 'p', '4', 'a')) {
134 if (par->extradata_size >= 2) {
135 int aot = par->extradata[0] >> 3;
137 aot = ((AV_RB16(par->extradata) >> 5) & 0x3f) + 32;
138 av_strlcatf(str, size, ".%d", aot);
140 } else if (tag == MKTAG('m', 'p', '4', 'v')) {
141 // Unimplemented, should output ProfileLevelIndication as a decimal number
142 av_log(s, AV_LOG_WARNING, "Incomplete RFC 6381 codec string for mp4v\n");
144 } else if (!strcmp(str, "avc1")) {
145 uint8_t *tmpbuf = NULL;
146 uint8_t *extradata = par->extradata;
147 int extradata_size = par->extradata_size;
150 if (extradata[0] != 1) {
152 if (avio_open_dyn_buf(&pb) < 0)
154 if (ff_isom_write_avcc(pb, extradata, extradata_size) < 0) {
155 ffio_free_dyn_buf(&pb);
158 extradata_size = avio_close_dyn_buf(pb, &extradata);
162 if (extradata_size >= 4)
163 av_strlcatf(str, size, ".%02x%02x%02x",
164 extradata[1], extradata[2], extradata[3]);
169 static void dash_free(AVFormatContext *s)
171 DASHContext *c = s->priv_data;
175 for (i = 0; i < s->nb_streams; i++) {
176 OutputStream *os = &c->streams[i];
177 if (os->ctx && os->ctx_inited)
178 av_write_trailer(os->ctx);
179 if (os->ctx && os->ctx->pb)
180 av_free(os->ctx->pb);
181 ff_format_io_close(s, &os->out);
183 avformat_free_context(os->ctx);
184 for (j = 0; j < os->nb_segments; j++)
185 av_free(os->segments[j]);
186 av_free(os->segments);
188 av_freep(&c->streams);
191 static void output_segment_list(OutputStream *os, AVIOContext *out, DASHContext *c)
193 int i, start_index = 0, start_number = 1;
194 if (c->window_size) {
195 start_index = FFMAX(os->nb_segments - c->window_size, 0);
196 start_number = FFMAX(os->segment_index - c->window_size, 1);
199 if (c->use_template) {
200 int timescale = c->use_timeline ? os->ctx->streams[0]->time_base.den : AV_TIME_BASE;
201 avio_printf(out, "\t\t\t\t<SegmentTemplate timescale=\"%d\" ", timescale);
202 if (!c->use_timeline)
203 avio_printf(out, "duration=\"%"PRId64"\" ", c->last_duration);
204 avio_printf(out, "initialization=\"%s\" media=\"%s\" startNumber=\"%d\">\n", c->init_seg_name, c->media_seg_name, c->use_timeline ? start_number : 1);
205 if (c->use_timeline) {
206 int64_t cur_time = 0;
207 avio_printf(out, "\t\t\t\t\t<SegmentTimeline>\n");
208 for (i = start_index; i < os->nb_segments; ) {
209 Segment *seg = os->segments[i];
211 avio_printf(out, "\t\t\t\t\t\t<S ");
212 if (i == start_index || seg->time != cur_time) {
213 cur_time = seg->time;
214 avio_printf(out, "t=\"%"PRId64"\" ", seg->time);
216 avio_printf(out, "d=\"%d\" ", seg->duration);
217 while (i + repeat + 1 < os->nb_segments &&
218 os->segments[i + repeat + 1]->duration == seg->duration &&
219 os->segments[i + repeat + 1]->time == os->segments[i + repeat]->time + os->segments[i + repeat]->duration)
222 avio_printf(out, "r=\"%d\" ", repeat);
223 avio_printf(out, "/>\n");
225 cur_time += (1 + repeat) * seg->duration;
227 avio_printf(out, "\t\t\t\t\t</SegmentTimeline>\n");
229 avio_printf(out, "\t\t\t\t</SegmentTemplate>\n");
230 } else if (c->single_file) {
231 avio_printf(out, "\t\t\t\t<BaseURL>%s</BaseURL>\n", os->initfile);
232 avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%"PRId64"\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);
233 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);
234 for (i = start_index; i < os->nb_segments; i++) {
235 Segment *seg = os->segments[i];
236 avio_printf(out, "\t\t\t\t\t<SegmentURL mediaRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->range_length - 1);
237 if (seg->index_length)
238 avio_printf(out, "indexRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->index_length - 1);
239 avio_printf(out, "/>\n");
241 avio_printf(out, "\t\t\t\t</SegmentList>\n");
243 avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%"PRId64"\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);
244 avio_printf(out, "\t\t\t\t\t<Initialization sourceURL=\"%s\" />\n", os->initfile);
245 for (i = start_index; i < os->nb_segments; i++) {
246 Segment *seg = os->segments[i];
247 avio_printf(out, "\t\t\t\t\t<SegmentURL media=\"%s\" />\n", seg->file);
249 avio_printf(out, "\t\t\t\t</SegmentList>\n");
253 static char *xmlescape(const char *str) {
254 int outlen = strlen(str)*3/2 + 6;
255 char *out = av_realloc(NULL, outlen + 1);
259 for (; *str; str++) {
260 if (pos + 6 > outlen) {
262 outlen = 2 * outlen + 6;
263 tmp = av_realloc(out, outlen + 1);
271 memcpy(&out[pos], "&", 5);
273 } else if (*str == '<') {
274 memcpy(&out[pos], "<", 4);
276 } else if (*str == '>') {
277 memcpy(&out[pos], ">", 4);
279 } else if (*str == '\'') {
280 memcpy(&out[pos], "'", 6);
282 } else if (*str == '\"') {
283 memcpy(&out[pos], """, 6);
293 static void write_time(AVIOContext *out, int64_t time)
295 int seconds = time / AV_TIME_BASE;
296 int fractions = time % AV_TIME_BASE;
297 int minutes = seconds / 60;
298 int hours = minutes / 60;
301 avio_printf(out, "PT");
303 avio_printf(out, "%dH", hours);
304 if (hours || minutes)
305 avio_printf(out, "%dM", minutes);
306 avio_printf(out, "%d.%dS", seconds, fractions / (AV_TIME_BASE / 10));
309 static void format_date_now(char *buf, int size)
311 time_t t = time(NULL);
312 struct tm *ptm, tmbuf;
313 ptm = gmtime_r(&t, &tmbuf);
315 if (!strftime(buf, size, "%Y-%m-%dT%H:%M:%SZ", ptm))
320 static int write_manifest(AVFormatContext *s, int final)
322 DASHContext *c = s->priv_data;
324 char temp_filename[1024];
325 int ret, i, as_id = 0;
326 const char *proto = avio_find_protocol_name(s->filename);
327 int use_rename = proto && !strcmp(proto, "file");
328 static unsigned int warned_non_file = 0;
329 AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
331 if (!use_rename && !warned_non_file++)
332 av_log(s, AV_LOG_ERROR, "Cannot use rename on non file protocol, this may lead to races and temporary partial files\n");
334 snprintf(temp_filename, sizeof(temp_filename), use_rename ? "%s.tmp" : "%s", s->filename);
335 ret = s->io_open(s, &out, temp_filename, AVIO_FLAG_WRITE, NULL);
337 av_log(s, AV_LOG_ERROR, "Unable to open %s for writing\n", temp_filename);
340 avio_printf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
341 avio_printf(out, "<MPD xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
342 "\txmlns=\"urn:mpeg:dash:schema:mpd:2011\"\n"
343 "\txmlns:xlink=\"http://www.w3.org/1999/xlink\"\n"
344 "\txsi:schemaLocation=\"urn:mpeg:DASH:schema:MPD:2011 http://standards.iso.org/ittf/PubliclyAvailableStandards/MPEG-DASH_schema_files/DASH-MPD.xsd\"\n"
345 "\tprofiles=\"urn:mpeg:dash:profile:isoff-live:2011\"\n"
346 "\ttype=\"%s\"\n", final ? "static" : "dynamic");
348 avio_printf(out, "\tmediaPresentationDuration=\"");
349 write_time(out, c->total_duration);
350 avio_printf(out, "\"\n");
352 int64_t update_period = c->last_duration / AV_TIME_BASE;
354 if (c->use_template && !c->use_timeline)
356 avio_printf(out, "\tminimumUpdatePeriod=\"PT%"PRId64"S\"\n", update_period);
357 avio_printf(out, "\tsuggestedPresentationDelay=\"PT%"PRId64"S\"\n", c->last_duration / AV_TIME_BASE);
358 if (!c->availability_start_time[0] && s->nb_streams > 0 && c->streams[0].nb_segments > 0) {
359 format_date_now(c->availability_start_time, sizeof(c->availability_start_time));
361 if (c->availability_start_time[0])
362 avio_printf(out, "\tavailabilityStartTime=\"%s\"\n", c->availability_start_time);
363 format_date_now(now_str, sizeof(now_str));
365 avio_printf(out, "\tpublishTime=\"%s\"\n", now_str);
366 if (c->window_size && c->use_template) {
367 avio_printf(out, "\ttimeShiftBufferDepth=\"");
368 write_time(out, c->last_duration * c->window_size);
369 avio_printf(out, "\"\n");
372 avio_printf(out, "\tminBufferTime=\"");
373 write_time(out, c->last_duration * 2);
374 avio_printf(out, "\">\n");
375 avio_printf(out, "\t<ProgramInformation>\n");
377 char *escaped = xmlescape(title->value);
378 avio_printf(out, "\t\t<Title>%s</Title>\n", escaped);
381 avio_printf(out, "\t</ProgramInformation>\n");
382 if (c->utc_timing_url)
383 avio_printf(out, "\t<UTCTiming schemeIdUri=\"urn:mpeg:dash:utc:http-xsdate:2014\" value=\"%s\"/>\n", c->utc_timing_url);
385 if (c->window_size && s->nb_streams > 0 && c->streams[0].nb_segments > 0 && !c->use_template) {
386 OutputStream *os = &c->streams[0];
387 int start_index = FFMAX(os->nb_segments - c->window_size, 0);
388 int64_t start_time = av_rescale_q(os->segments[start_index]->time, s->streams[0]->time_base, AV_TIME_BASE_Q);
389 avio_printf(out, "\t<Period id=\"0\" start=\"");
390 write_time(out, start_time);
391 avio_printf(out, "\">\n");
393 avio_printf(out, "\t<Period id=\"0\" start=\"PT0.0S\">\n");
397 avio_printf(out, "\t\t<AdaptationSet id=\"%d\" contentType=\"video\" segmentAlignment=\"true\" bitstreamSwitching=\"true\"", as_id++);
398 if (c->max_frame_rate.num && !c->ambiguous_frame_rate)
399 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);
400 avio_printf(out, ">\n");
402 for (i = 0; i < s->nb_streams; i++) {
403 AVStream *st = s->streams[i];
404 OutputStream *os = &c->streams[i];
406 if (st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO)
409 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->codecpar->width, st->codecpar->height);
410 if (st->avg_frame_rate.num)
411 avio_printf(out, " frameRate=\"%d/%d\"", st->avg_frame_rate.num, st->avg_frame_rate.den);
412 avio_printf(out, ">\n");
414 output_segment_list(&c->streams[i], out, c);
415 avio_printf(out, "\t\t\t</Representation>\n");
417 avio_printf(out, "\t\t</AdaptationSet>\n");
420 avio_printf(out, "\t\t<AdaptationSet id=\"%d\" contentType=\"audio\" segmentAlignment=\"true\" bitstreamSwitching=\"true\">\n", as_id++);
421 for (i = 0; i < s->nb_streams; i++) {
422 AVStream *st = s->streams[i];
423 OutputStream *os = &c->streams[i];
425 if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO)
428 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->codecpar->sample_rate);
429 avio_printf(out, "\t\t\t\t<AudioChannelConfiguration schemeIdUri=\"urn:mpeg:dash:23003:3:audio_channel_configuration:2011\" value=\"%d\" />\n", st->codecpar->channels);
430 output_segment_list(&c->streams[i], out, c);
431 avio_printf(out, "\t\t\t</Representation>\n");
433 avio_printf(out, "\t\t</AdaptationSet>\n");
435 avio_printf(out, "\t</Period>\n");
436 avio_printf(out, "</MPD>\n");
438 ff_format_io_close(s, &out);
441 return avpriv_io_move(temp_filename, s->filename);
446 static int set_bitrate(AVFormatContext *s)
448 DASHContext *c = s->priv_data;
451 for (i = 0; i < s->nb_streams; i++) {
452 OutputStream *os = &c->streams[i];
454 os->bit_rate = s->streams[i]->codecpar->bit_rate;
456 snprintf(os->bandwidth_str, sizeof(os->bandwidth_str),
457 " bandwidth=\"%d\"", os->bit_rate);
459 int level = s->strict_std_compliance >= FF_COMPLIANCE_STRICT ?
460 AV_LOG_ERROR : AV_LOG_WARNING;
461 av_log(s, level, "No bit rate set for stream %d\n", i);
462 if (s->strict_std_compliance >= FF_COMPLIANCE_STRICT)
463 return AVERROR(EINVAL);
470 static int dash_init(AVFormatContext *s)
472 DASHContext *c = s->priv_data;
474 AVOutputFormat *oformat;
478 if (c->single_file_name)
482 c->ambiguous_frame_rate = 0;
484 av_strlcpy(c->dirname, s->filename, sizeof(c->dirname));
485 ptr = strrchr(c->dirname, '/');
487 av_strlcpy(basename, &ptr[1], sizeof(basename));
490 c->dirname[0] = '\0';
491 av_strlcpy(basename, s->filename, sizeof(basename));
494 ptr = strrchr(basename, '.');
498 oformat = av_guess_format("mp4", NULL, NULL);
500 return AVERROR_MUXER_NOT_FOUND;
502 c->streams = av_mallocz(sizeof(*c->streams) * s->nb_streams);
504 return AVERROR(ENOMEM);
506 ret = set_bitrate(s);
510 for (i = 0; i < s->nb_streams; i++) {
511 OutputStream *os = &c->streams[i];
512 AVFormatContext *ctx;
514 AVDictionary *opts = NULL;
517 ctx = avformat_alloc_context();
519 return AVERROR(ENOMEM);
521 ctx->oformat = oformat;
522 ctx->interrupt_callback = s->interrupt_callback;
523 ctx->opaque = s->opaque;
524 ctx->io_close = s->io_close;
525 ctx->io_open = s->io_open;
527 if (!(st = avformat_new_stream(ctx, NULL)))
528 return AVERROR(ENOMEM);
529 avcodec_parameters_copy(st->codecpar, s->streams[i]->codecpar);
530 st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
531 st->time_base = s->streams[i]->time_base;
532 ctx->avoid_negative_ts = s->avoid_negative_ts;
533 ctx->flags = s->flags;
535 ctx->pb = avio_alloc_context(os->iobuf, sizeof(os->iobuf), AVIO_FLAG_WRITE, os, NULL, dash_write, NULL);
537 return AVERROR(ENOMEM);
539 if (c->single_file) {
540 if (c->single_file_name)
541 ff_dash_fill_tmpl_params(os->initfile, sizeof(os->initfile), c->single_file_name, i, 0, os->bit_rate, 0);
543 snprintf(os->initfile, sizeof(os->initfile), "%s-stream%d.m4s", basename, i);
545 ff_dash_fill_tmpl_params(os->initfile, sizeof(os->initfile), c->init_seg_name, i, 0, os->bit_rate, 0);
547 snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
548 ret = s->io_open(s, &os->out, filename, AVIO_FLAG_WRITE, NULL);
551 os->init_start_pos = 0;
553 av_dict_set(&opts, "movflags", "frag_custom+dash+delay_moov", 0);
554 if ((ret = avformat_init_output(ctx, &opts)) < 0)
560 av_log(s, AV_LOG_VERBOSE, "Representation %d init segment will be written to: %s\n", i, filename);
562 s->streams[i]->time_base = st->time_base;
563 // If the muxer wants to shift timestamps, request to have them shifted
564 // already before being handed to this muxer, so we don't have mismatches
565 // between the MPD and the actual segments.
566 s->avoid_negative_ts = ctx->avoid_negative_ts;
567 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
568 AVRational avg_frame_rate = s->streams[i]->avg_frame_rate;
569 if (avg_frame_rate.num > 0) {
570 if (av_cmp_q(avg_frame_rate, c->min_frame_rate) < 0)
571 c->min_frame_rate = avg_frame_rate;
572 if (av_cmp_q(c->max_frame_rate, avg_frame_rate) < 0)
573 c->max_frame_rate = avg_frame_rate;
575 c->ambiguous_frame_rate = 1;
578 } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
582 set_codec_str(s, st->codecpar, os->codec_str, sizeof(os->codec_str));
583 os->first_pts = AV_NOPTS_VALUE;
584 os->max_pts = AV_NOPTS_VALUE;
585 os->last_dts = AV_NOPTS_VALUE;
586 os->segment_index = 1;
589 if (!c->has_video && c->min_seg_duration <= 0) {
590 av_log(s, AV_LOG_WARNING, "no video stream and no min seg duration set\n");
591 return AVERROR(EINVAL);
596 static int dash_write_header(AVFormatContext *s)
598 DASHContext *c = s->priv_data;
600 for (i = 0; i < s->nb_streams; i++) {
601 OutputStream *os = &c->streams[i];
602 if ((ret = avformat_write_header(os->ctx, NULL)) < 0) {
607 ret = write_manifest(s, 0);
609 av_log(s, AV_LOG_VERBOSE, "Manifest written to: %s\n", s->filename);
613 static int add_segment(OutputStream *os, const char *file,
614 int64_t time, int duration,
615 int64_t start_pos, int64_t range_length,
616 int64_t index_length)
620 if (os->nb_segments >= os->segments_size) {
621 os->segments_size = (os->segments_size + 1) * 2;
622 if ((err = av_reallocp(&os->segments, sizeof(*os->segments) *
623 os->segments_size)) < 0) {
624 os->segments_size = 0;
629 seg = av_mallocz(sizeof(*seg));
631 return AVERROR(ENOMEM);
632 av_strlcpy(seg->file, file, sizeof(seg->file));
634 seg->duration = duration;
635 if (seg->time < 0) { // If pts<0, it is expected to be cut away with an edit list
636 seg->duration += seg->time;
639 seg->start_pos = start_pos;
640 seg->range_length = range_length;
641 seg->index_length = index_length;
642 os->segments[os->nb_segments++] = seg;
647 static void write_styp(AVIOContext *pb)
650 ffio_wfourcc(pb, "styp");
651 ffio_wfourcc(pb, "msdh");
652 avio_wb32(pb, 0); /* minor */
653 ffio_wfourcc(pb, "msdh");
654 ffio_wfourcc(pb, "msix");
657 static void find_index_range(AVFormatContext *s, const char *full_path,
658 int64_t pos, int *index_length)
664 ret = s->io_open(s, &pb, full_path, AVIO_FLAG_READ, NULL);
667 if (avio_seek(pb, pos, SEEK_SET) != pos) {
668 ff_format_io_close(s, &pb);
671 ret = avio_read(pb, buf, 8);
672 ff_format_io_close(s, &pb);
675 if (AV_RL32(&buf[4]) != MKTAG('s', 'i', 'd', 'x'))
677 *index_length = AV_RB32(&buf[0]);
680 static int update_stream_extradata(AVFormatContext *s, OutputStream *os,
681 AVCodecParameters *par)
685 if (os->ctx->streams[0]->codecpar->extradata_size || !par->extradata_size)
688 extradata = av_malloc(par->extradata_size);
691 return AVERROR(ENOMEM);
693 memcpy(extradata, par->extradata, par->extradata_size);
695 os->ctx->streams[0]->codecpar->extradata = extradata;
696 os->ctx->streams[0]->codecpar->extradata_size = par->extradata_size;
698 set_codec_str(s, par, os->codec_str, sizeof(os->codec_str));
703 static int dash_flush(AVFormatContext *s, int final, int stream)
705 DASHContext *c = s->priv_data;
708 const char *proto = avio_find_protocol_name(s->filename);
709 int use_rename = proto && !strcmp(proto, "file");
711 int cur_flush_segment_index = 0;
713 cur_flush_segment_index = c->streams[stream].segment_index;
715 for (i = 0; i < s->nb_streams; i++) {
716 OutputStream *os = &c->streams[i];
717 char filename[1024] = "", full_path[1024], temp_path[1024];
719 int range_length, index_length = 0;
721 if (!os->packets_written)
724 // Flush the single stream that got a keyframe right now.
725 // Flush all audio streams as well, in sync with video keyframes,
726 // but not the other video streams.
727 if (stream >= 0 && i != stream) {
728 if (s->streams[i]->codecpar->codec_type != AVMEDIA_TYPE_AUDIO)
730 // Make sure we don't flush audio streams multiple times, when
731 // all video streams are flushed one at a time.
732 if (c->has_video && os->segment_index > cur_flush_segment_index)
736 if (!os->init_range_length) {
737 av_write_frame(os->ctx, NULL);
738 os->init_range_length = avio_tell(os->ctx->pb);
740 ff_format_io_close(s, &os->out);
743 start_pos = avio_tell(os->ctx->pb);
745 if (!c->single_file) {
746 ff_dash_fill_tmpl_params(filename, sizeof(filename), c->media_seg_name, i, os->segment_index, os->bit_rate, os->start_pts);
747 snprintf(full_path, sizeof(full_path), "%s%s", c->dirname, filename);
748 snprintf(temp_path, sizeof(temp_path), use_rename ? "%s.tmp" : "%s", full_path);
749 ret = s->io_open(s, &os->out, temp_path, AVIO_FLAG_WRITE, NULL);
752 write_styp(os->ctx->pb);
754 snprintf(full_path, sizeof(full_path), "%s%s", c->dirname, os->initfile);
757 av_write_frame(os->ctx, NULL);
758 avio_flush(os->ctx->pb);
759 os->packets_written = 0;
761 range_length = avio_tell(os->ctx->pb) - start_pos;
762 if (c->single_file) {
763 find_index_range(s, full_path, start_pos, &index_length);
765 ff_format_io_close(s, &os->out);
768 ret = avpriv_io_move(temp_path, full_path);
773 add_segment(os, filename, os->start_pts, os->max_pts - os->start_pts, start_pos, range_length, index_length);
774 av_log(s, AV_LOG_VERBOSE, "Representation %d media segment %d written to: %s\n", i, os->segment_index, full_path);
777 if (c->window_size || (final && c->remove_at_exit)) {
778 for (i = 0; i < s->nb_streams; i++) {
779 OutputStream *os = &c->streams[i];
781 int remove = os->nb_segments - c->window_size - c->extra_window_size;
782 if (final && c->remove_at_exit)
783 remove = os->nb_segments;
785 for (j = 0; j < remove; j++) {
787 snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->segments[j]->file);
789 av_free(os->segments[j]);
791 os->nb_segments -= remove;
792 memmove(os->segments, os->segments + remove, os->nb_segments * sizeof(*os->segments));
798 ret = write_manifest(s, final);
802 static int dash_write_packet(AVFormatContext *s, AVPacket *pkt)
804 DASHContext *c = s->priv_data;
805 AVStream *st = s->streams[pkt->stream_index];
806 OutputStream *os = &c->streams[pkt->stream_index];
809 ret = update_stream_extradata(s, os, st->codecpar);
813 // Fill in a heuristic guess of the packet duration, if none is available.
814 // The mp4 muxer will do something similar (for the last packet in a fragment)
815 // if nothing is set (setting it for the other packets doesn't hurt).
816 // By setting a nonzero duration here, we can be sure that the mp4 muxer won't
817 // invoke its heuristic (this doesn't have to be identical to that algorithm),
818 // so that we know the exact timestamps of fragments.
819 if (!pkt->duration && os->last_dts != AV_NOPTS_VALUE)
820 pkt->duration = pkt->dts - os->last_dts;
821 os->last_dts = pkt->dts;
823 // If forcing the stream to start at 0, the mp4 muxer will set the start
824 // timestamps to 0. Do the same here, to avoid mismatches in duration/timestamps.
825 if (os->first_pts == AV_NOPTS_VALUE &&
826 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
827 pkt->pts -= pkt->dts;
831 if (os->first_pts == AV_NOPTS_VALUE)
832 os->first_pts = pkt->pts;
834 if ((!c->has_video || st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) &&
835 pkt->flags & AV_PKT_FLAG_KEY && os->packets_written &&
836 av_compare_ts(pkt->pts - os->start_pts, st->time_base,
837 c->min_seg_duration, AV_TIME_BASE_Q) >= 0) {
838 int64_t prev_duration = c->last_duration;
840 c->last_duration = av_rescale_q(pkt->pts - os->start_pts,
843 c->total_duration = av_rescale_q(pkt->pts - os->first_pts,
847 if ((!c->use_timeline || !c->use_template) && prev_duration) {
848 if (c->last_duration < prev_duration*9/10 ||
849 c->last_duration > prev_duration*11/10) {
850 av_log(s, AV_LOG_WARNING,
851 "Segment durations differ too much, enable use_timeline "
852 "and use_template, or keep a stricter keyframe interval\n");
856 if ((ret = dash_flush(s, 0, pkt->stream_index)) < 0)
860 if (!os->packets_written) {
861 // If we wrote a previous segment, adjust the start time of the segment
862 // to the end of the previous one (which is the same as the mp4 muxer
863 // does). This avoids gaps in the timeline.
864 if (os->max_pts != AV_NOPTS_VALUE)
865 os->start_pts = os->max_pts;
867 os->start_pts = pkt->pts;
869 if (os->max_pts == AV_NOPTS_VALUE)
870 os->max_pts = pkt->pts + pkt->duration;
872 os->max_pts = FFMAX(os->max_pts, pkt->pts + pkt->duration);
873 os->packets_written++;
874 return ff_write_chained(os->ctx, 0, pkt, s, 0);
877 static int dash_write_trailer(AVFormatContext *s)
879 DASHContext *c = s->priv_data;
883 if (s->nb_streams > 0) {
884 OutputStream *os = &c->streams[0];
885 // If no segments have been written so far, try to do a crude
886 // guess of the segment duration
887 if (!c->last_duration)
888 c->last_duration = av_rescale_q(os->max_pts - os->start_pts,
889 s->streams[0]->time_base,
891 c->total_duration = av_rescale_q(os->max_pts - os->first_pts,
892 s->streams[0]->time_base,
895 dash_flush(s, 1, -1);
897 if (c->remove_at_exit) {
900 for (i = 0; i < s->nb_streams; i++) {
901 OutputStream *os = &c->streams[i];
902 snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
911 static int dash_check_bitstream(struct AVFormatContext *s, const AVPacket *avpkt)
913 DASHContext *c = s->priv_data;
914 OutputStream *os = &c->streams[avpkt->stream_index];
915 AVFormatContext *oc = os->ctx;
916 if (oc->oformat->check_bitstream) {
918 AVPacket pkt = *avpkt;
919 pkt.stream_index = 0;
920 ret = oc->oformat->check_bitstream(oc, &pkt);
922 AVStream *st = s->streams[avpkt->stream_index];
923 AVStream *ost = oc->streams[0];
924 st->internal->bsfcs = ost->internal->bsfcs;
925 st->internal->nb_bsfcs = ost->internal->nb_bsfcs;
926 ost->internal->bsfcs = NULL;
927 ost->internal->nb_bsfcs = 0;
934 #define OFFSET(x) offsetof(DASHContext, x)
935 #define E AV_OPT_FLAG_ENCODING_PARAM
936 static const AVOption options[] = {
937 { "window_size", "number of segments kept in the manifest", OFFSET(window_size), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, E },
938 { "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 },
939 { "min_seg_duration", "minimum segment duration (in microseconds)", OFFSET(min_seg_duration), AV_OPT_TYPE_INT64, { .i64 = 5000000 }, 0, INT_MAX, E },
940 { "remove_at_exit", "remove all segments when finished", OFFSET(remove_at_exit), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
941 { "use_template", "Use SegmentTemplate instead of SegmentList", OFFSET(use_template), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, E },
942 { "use_timeline", "Use SegmentTimeline in SegmentTemplate", OFFSET(use_timeline), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, E },
943 { "single_file", "Store all segments in one file, accessed using byte ranges", OFFSET(single_file), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
944 { "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 },
945 { "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 },
946 { "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 },
947 { "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 },
951 static const AVClass dash_class = {
952 .class_name = "dash muxer",
953 .item_name = av_default_item_name,
955 .version = LIBAVUTIL_VERSION_INT,
958 AVOutputFormat ff_dash_muxer = {
960 .long_name = NULL_IF_CONFIG_SMALL("DASH Muxer"),
961 .priv_data_size = sizeof(DASHContext),
962 .audio_codec = AV_CODEC_ID_AAC,
963 .video_codec = AV_CODEC_ID_H264,
964 .flags = AVFMT_GLOBALHEADER | AVFMT_NOFILE | AVFMT_TS_NEGATIVE,
966 .write_header = dash_write_header,
967 .write_packet = dash_write_packet,
968 .write_trailer = dash_write_trailer,
970 .check_bitstream = dash_check_bitstream,
971 .priv_class = &dash_class,