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/avstring.h"
28 #include "libavutil/intreadwrite.h"
29 #include "libavutil/mathematics.h"
30 #include "libavutil/opt.h"
31 #include "libavutil/time_internal.h"
35 #include "avio_internal.h"
38 #include "os_support.h"
41 typedef struct Segment {
44 int range_length, index_length;
50 typedef struct OutputStream {
57 int64_t init_start_pos;
58 int init_range_length;
59 int nb_segments, segments_size, segment_index;
61 int64_t first_dts, start_dts, end_dts;
62 char bandwidth_str[64];
67 typedef struct DASHContext {
68 const AVClass *class; /* Class for private options. */
70 int extra_window_size;
76 OutputStream *streams;
77 int has_video, has_audio;
80 char availability_start_time[100];
84 static int dash_write(void *opaque, uint8_t *buf, int buf_size)
86 OutputStream *os = opaque;
88 ffurl_write(os->out, buf, buf_size);
93 static void set_codec_str(AVFormatContext *s, AVCodecContext *codec,
96 const AVCodecTag *tags[2] = { NULL, NULL };
98 if (codec->codec_type == AVMEDIA_TYPE_VIDEO)
99 tags[0] = ff_codec_movvideo_tags;
100 else if (codec->codec_type == AVMEDIA_TYPE_AUDIO)
101 tags[0] = ff_codec_movaudio_tags;
105 tag = av_codec_get_tag(tags, codec->codec_id);
113 if (!strcmp(str, "mp4a") || !strcmp(str, "mp4v")) {
115 tags[0] = ff_mp4_obj_type;
116 oti = av_codec_get_tag(tags, codec->codec_id);
118 av_strlcatf(str, size, ".%02x", oti);
122 if (tag == MKTAG('m', 'p', '4', 'a')) {
123 if (codec->extradata_size >= 2) {
124 int aot = codec->extradata[0] >> 3;
126 aot = ((AV_RB16(codec->extradata) >> 5) & 0x3f) + 32;
127 av_strlcatf(str, size, ".%d", aot);
129 } else if (tag == MKTAG('m', 'p', '4', 'v')) {
130 // Unimplemented, should output ProfileLevelIndication as a decimal number
131 av_log(s, AV_LOG_WARNING, "Incomplete RFC 6381 codec string for mp4v\n");
133 } else if (!strcmp(str, "avc1")) {
134 uint8_t *tmpbuf = NULL;
135 uint8_t *extradata = codec->extradata;
136 int extradata_size = codec->extradata_size;
139 if (extradata[0] != 1) {
141 if (avio_open_dyn_buf(&pb) < 0)
143 if (ff_isom_write_avcc(pb, extradata, extradata_size) < 0) {
144 avio_close_dyn_buf(pb, &tmpbuf);
148 extradata_size = avio_close_dyn_buf(pb, &extradata);
152 if (extradata_size >= 4)
153 av_strlcatf(str, size, ".%02x%02x%02x",
154 extradata[1], extradata[2], extradata[3]);
159 static void dash_free(AVFormatContext *s)
161 DASHContext *c = s->priv_data;
165 for (i = 0; i < s->nb_streams; i++) {
166 OutputStream *os = &c->streams[i];
167 if (os->ctx && os->ctx_inited)
168 av_write_trailer(os->ctx);
169 if (os->ctx && os->ctx->pb)
170 av_free(os->ctx->pb);
171 ffurl_close(os->out);
174 avformat_free_context(os->ctx);
175 for (j = 0; j < os->nb_segments; j++)
176 av_free(os->segments[j]);
177 av_free(os->segments);
179 av_freep(&c->streams);
182 static void output_segment_list(OutputStream *os, AVIOContext *out, DASHContext *c)
184 int i, start_index = 0, start_number = 1;
185 if (c->window_size) {
186 start_index = FFMAX(os->nb_segments - c->window_size, 0);
187 start_number = FFMAX(os->segment_index - c->window_size, 1);
190 if (c->use_template) {
191 int timescale = c->use_timeline ? os->ctx->streams[0]->time_base.den : AV_TIME_BASE;
192 avio_printf(out, "\t\t\t\t<SegmentTemplate timescale=\"%d\" ", timescale);
193 if (!c->use_timeline)
194 avio_printf(out, "duration=\"%d\" ", c->last_duration);
195 avio_printf(out, "initialization=\"init-stream$RepresentationID$.m4s\" media=\"chunk-stream$RepresentationID$-$Number%%05d$.m4s\" startNumber=\"%d\">\n", c->use_timeline ? start_number : 1);
196 if (c->use_timeline) {
197 avio_printf(out, "\t\t\t\t\t<SegmentTimeline>\n");
198 for (i = start_index; i < os->nb_segments; ) {
199 Segment *seg = os->segments[i];
201 avio_printf(out, "\t\t\t\t\t\t<S ");
202 if (i == start_index)
203 avio_printf(out, "t=\"%"PRId64"\" ", seg->time);
204 avio_printf(out, "d=\"%d\" ", seg->duration);
205 while (i + repeat + 1 < os->nb_segments && os->segments[i + repeat + 1]->duration == seg->duration)
208 avio_printf(out, "r=\"%d\" ", repeat);
209 avio_printf(out, "/>\n");
212 avio_printf(out, "\t\t\t\t\t</SegmentTimeline>\n");
214 avio_printf(out, "\t\t\t\t</SegmentTemplate>\n");
215 } else if (c->single_file) {
216 avio_printf(out, "\t\t\t\t<BaseURL>%s</BaseURL>\n", os->initfile);
217 avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%d\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);
218 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);
219 for (i = start_index; i < os->nb_segments; i++) {
220 Segment *seg = os->segments[i];
221 avio_printf(out, "\t\t\t\t\t<SegmentURL mediaRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->range_length - 1);
222 if (seg->index_length)
223 avio_printf(out, "indexRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->index_length - 1);
224 avio_printf(out, "/>\n");
226 avio_printf(out, "\t\t\t\t</SegmentList>\n");
228 avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%d\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);
229 avio_printf(out, "\t\t\t\t\t<Initialization sourceURL=\"%s\" />\n", os->initfile);
230 for (i = start_index; i < os->nb_segments; i++) {
231 Segment *seg = os->segments[i];
232 avio_printf(out, "\t\t\t\t\t<SegmentURL media=\"%s\" />\n", seg->file);
234 avio_printf(out, "\t\t\t\t</SegmentList>\n");
238 static char *xmlescape(const char *str) {
239 int outlen = strlen(str)*3/2 + 6;
240 char *out = av_realloc(NULL, outlen + 1);
244 for (; *str; str++) {
245 if (pos + 6 > outlen) {
247 outlen = 2 * outlen + 6;
248 tmp = av_realloc(out, outlen + 1);
256 memcpy(&out[pos], "&", 5);
258 } else if (*str == '<') {
259 memcpy(&out[pos], "<", 4);
261 } else if (*str == '>') {
262 memcpy(&out[pos], ">", 4);
264 } else if (*str == '\'') {
265 memcpy(&out[pos], "'", 6);
267 } else if (*str == '\"') {
268 memcpy(&out[pos], """, 6);
278 static void write_time(AVIOContext *out, int64_t time)
280 int seconds = time / AV_TIME_BASE;
281 int fractions = time % AV_TIME_BASE;
282 int minutes = seconds / 60;
283 int hours = minutes / 60;
286 avio_printf(out, "PT");
288 avio_printf(out, "%dH", hours);
289 if (hours || minutes)
290 avio_printf(out, "%dM", minutes);
291 avio_printf(out, "%d.%dS", seconds, fractions / (AV_TIME_BASE / 10));
294 static int write_manifest(AVFormatContext *s, int final)
296 DASHContext *c = s->priv_data;
298 char temp_filename[1024];
299 const char *write_filename;
301 AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
303 snprintf(temp_filename, sizeof(temp_filename), "%s.tmp", s->filename);
304 write_filename = USE_RENAME_REPLACE ? temp_filename : s->filename;
305 ret = avio_open2(&out, write_filename, AVIO_FLAG_WRITE, &s->interrupt_callback, NULL);
307 av_log(s, AV_LOG_ERROR, "Unable to open %s for writing\n", write_filename);
310 avio_printf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
311 avio_printf(out, "<MPD xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
312 "\txmlns=\"urn:mpeg:dash:schema:mpd:2011\"\n"
313 "\txmlns:xlink=\"http://www.w3.org/1999/xlink\"\n"
314 "\txsi:schemaLocation=\"urn:mpeg:DASH:schema:MPD:2011 http://standards.iso.org/ittf/PubliclyAvailableStandards/MPEG-DASH_schema_files/DASH-MPD.xsd\"\n"
315 "\tprofiles=\"urn:mpeg:dash:profile:isoff-live:2011\"\n"
316 "\ttype=\"%s\"\n", final ? "static" : "dynamic");
318 avio_printf(out, "\tmediaPresentationDuration=\"");
319 write_time(out, c->total_duration);
320 avio_printf(out, "\"\n");
322 int update_period = c->last_duration / AV_TIME_BASE;
323 if (c->use_template && !c->use_timeline)
325 avio_printf(out, "\tminimumUpdatePeriod=\"PT%dS\"\n", update_period);
326 avio_printf(out, "\tsuggestedPresentationDelay=\"PT%dS\"\n", c->last_duration / AV_TIME_BASE);
327 if (!c->availability_start_time[0] && s->nb_streams > 0 && c->streams[0].nb_segments > 0) {
328 time_t t = time(NULL);
329 struct tm *ptm, tmbuf;
330 ptm = gmtime_r(&t, &tmbuf);
332 if (!strftime(c->availability_start_time, sizeof(c->availability_start_time),
333 "%Y-%m-%dT%H:%M:%S", ptm))
334 c->availability_start_time[0] = '\0';
337 if (c->availability_start_time[0])
338 avio_printf(out, "\tavailabilityStartTime=\"%s\"\n", c->availability_start_time);
339 if (c->window_size && c->use_template) {
340 avio_printf(out, "\ttimeShiftBufferDepth=\"");
341 write_time(out, c->last_duration * c->window_size);
342 avio_printf(out, "\"\n");
345 avio_printf(out, "\tminBufferTime=\"");
346 write_time(out, c->last_duration);
347 avio_printf(out, "\">\n");
348 avio_printf(out, "\t<ProgramInformation>\n");
350 char *escaped = xmlescape(title->value);
351 avio_printf(out, "\t\t<Title>%s</Title>\n", escaped);
354 avio_printf(out, "\t</ProgramInformation>\n");
355 if (c->window_size && s->nb_streams > 0 && c->streams[0].nb_segments > 0 && !c->use_template) {
356 OutputStream *os = &c->streams[0];
357 int start_index = FFMAX(os->nb_segments - c->window_size, 0);
358 int64_t start_time = av_rescale_q(os->segments[start_index]->time, s->streams[0]->time_base, AV_TIME_BASE_Q);
359 avio_printf(out, "\t<Period start=\"");
360 write_time(out, start_time);
361 avio_printf(out, "\">\n");
363 avio_printf(out, "\t<Period start=\"PT0.0S\">\n");
367 avio_printf(out, "\t\t<AdaptationSet id=\"video\" segmentAlignment=\"true\" bitstreamSwitching=\"true\">\n");
368 for (i = 0; i < s->nb_streams; i++) {
369 AVStream *st = s->streams[i];
370 OutputStream *os = &c->streams[i];
371 if (s->streams[i]->codec->codec_type != AVMEDIA_TYPE_VIDEO)
373 avio_printf(out, "\t\t\t<Representation id=\"%d\" mimeType=\"video/mp4\" codecs=\"%s\"%s width=\"%d\" height=\"%d\">\n", i, os->codec_str, os->bandwidth_str, st->codec->width, st->codec->height);
374 output_segment_list(&c->streams[i], out, c);
375 avio_printf(out, "\t\t\t</Representation>\n");
377 avio_printf(out, "\t\t</AdaptationSet>\n");
380 avio_printf(out, "\t\t<AdaptationSet id=\"audio\" segmentAlignment=\"true\" bitstreamSwitching=\"true\">\n");
381 for (i = 0; i < s->nb_streams; i++) {
382 AVStream *st = s->streams[i];
383 OutputStream *os = &c->streams[i];
384 if (s->streams[i]->codec->codec_type != AVMEDIA_TYPE_AUDIO)
386 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);
387 avio_printf(out, "\t\t\t\t<AudioChannelConfiguration schemeIdUri=\"urn:mpeg:dash:23003:3:audio_channel_configuration:2011\" value=\"%d\" />\n", st->codec->channels);
388 output_segment_list(&c->streams[i], out, c);
389 avio_printf(out, "\t\t\t</Representation>\n");
391 avio_printf(out, "\t\t</AdaptationSet>\n");
393 avio_printf(out, "\t</Period>\n");
394 avio_printf(out, "</MPD>\n");
397 return USE_RENAME_REPLACE ? ff_rename(temp_filename, s->filename, s) : 0;
400 static int dash_write_header(AVFormatContext *s)
402 DASHContext *c = s->priv_data;
404 AVOutputFormat *oformat;
411 av_strlcpy(c->dirname, s->filename, sizeof(c->dirname));
412 ptr = strrchr(c->dirname, '/');
414 av_strlcpy(basename, &ptr[1], sizeof(basename));
417 c->dirname[0] = '\0';
418 av_strlcpy(basename, s->filename, sizeof(basename));
421 ptr = strrchr(basename, '.');
425 oformat = av_guess_format("mp4", NULL, NULL);
427 ret = AVERROR_MUXER_NOT_FOUND;
431 c->streams = av_mallocz(sizeof(*c->streams) * s->nb_streams);
433 ret = AVERROR(ENOMEM);
437 for (i = 0; i < s->nb_streams; i++) {
438 OutputStream *os = &c->streams[i];
439 AVFormatContext *ctx;
441 AVDictionary *opts = NULL;
444 int bit_rate = s->streams[i]->codec->bit_rate ?
445 s->streams[i]->codec->bit_rate :
446 s->streams[i]->codec->rc_max_rate;
448 snprintf(os->bandwidth_str, sizeof(os->bandwidth_str),
449 " bandwidth=\"%d\"", bit_rate);
451 int level = s->strict_std_compliance >= FF_COMPLIANCE_STRICT ?
452 AV_LOG_ERROR : AV_LOG_WARNING;
453 av_log(s, level, "No bit rate set for stream %d\n", i);
454 if (s->strict_std_compliance >= FF_COMPLIANCE_STRICT) {
455 ret = AVERROR(EINVAL);
460 ctx = avformat_alloc_context();
462 ret = AVERROR(ENOMEM);
466 ctx->oformat = oformat;
467 ctx->interrupt_callback = s->interrupt_callback;
469 if (!(st = avformat_new_stream(ctx, NULL))) {
470 ret = AVERROR(ENOMEM);
473 avcodec_copy_context(st->codec, s->streams[i]->codec);
474 st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
475 st->time_base = s->streams[i]->time_base;
476 ctx->avoid_negative_ts = s->avoid_negative_ts;
478 ctx->pb = avio_alloc_context(os->iobuf, sizeof(os->iobuf), AVIO_FLAG_WRITE, os, NULL, dash_write, NULL);
480 ret = AVERROR(ENOMEM);
485 snprintf(os->initfile, sizeof(os->initfile), "%s-stream%d.m4s", basename, i);
487 snprintf(os->initfile, sizeof(os->initfile), "init-stream%d.m4s", i);
488 snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
489 ret = ffurl_open(&os->out, filename, AVIO_FLAG_WRITE, &s->interrupt_callback, NULL);
492 os->init_start_pos = 0;
494 av_dict_set(&opts, "movflags", "frag_custom+dash", 0);
495 if ((ret = avformat_write_header(ctx, &opts)) < 0) {
502 if (c->single_file) {
503 os->init_range_length = avio_tell(ctx->pb);
505 ffurl_close(os->out);
509 s->streams[i]->time_base = st->time_base;
510 // If the muxer wants to shift timestamps, request to have them shifted
511 // already before being handed to this muxer, so we don't have mismatches
512 // between the MPD and the actual segments.
513 s->avoid_negative_ts = ctx->avoid_negative_ts;
514 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
516 else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
519 set_codec_str(s, os->ctx->streams[0]->codec, os->codec_str, sizeof(os->codec_str));
520 os->first_dts = AV_NOPTS_VALUE;
521 os->segment_index = 1;
524 if (!c->has_video && c->min_seg_duration <= 0) {
525 av_log(s, AV_LOG_WARNING, "no video stream and no min seg duration set\n");
526 ret = AVERROR(EINVAL);
528 ret = write_manifest(s, 0);
536 static int add_segment(OutputStream *os, const char *file,
537 int64_t time, int duration,
538 int64_t start_pos, int64_t range_length,
539 int64_t index_length)
543 if (os->nb_segments >= os->segments_size) {
544 os->segments_size = (os->segments_size + 1) * 2;
545 if ((err = av_reallocp(&os->segments, sizeof(*os->segments) *
546 os->segments_size)) < 0) {
547 os->segments_size = 0;
552 seg = av_mallocz(sizeof(*seg));
554 return AVERROR(ENOMEM);
555 av_strlcpy(seg->file, file, sizeof(seg->file));
557 seg->duration = duration;
558 seg->start_pos = start_pos;
559 seg->range_length = range_length;
560 seg->index_length = index_length;
561 os->segments[os->nb_segments++] = seg;
566 static void write_styp(AVIOContext *pb)
569 ffio_wfourcc(pb, "styp");
570 ffio_wfourcc(pb, "msdh");
571 avio_wb32(pb, 0); /* minor */
572 ffio_wfourcc(pb, "msdh");
573 ffio_wfourcc(pb, "msix");
576 static void find_index_range(AVFormatContext *s, const char *dirname,
577 const char *filename, int64_t pos,
580 char full_path[1024];
585 snprintf(full_path, sizeof(full_path), "%s%s", dirname, filename);
586 ret = ffurl_open(&fd, full_path, AVIO_FLAG_READ, &s->interrupt_callback, NULL);
589 if (ffurl_seek(fd, pos, SEEK_SET) != pos) {
593 ret = ffurl_read(fd, buf, 8);
597 if (AV_RL32(&buf[4]) != MKTAG('s', 'i', 'd', 'x'))
599 *index_length = AV_RB32(&buf[0]);
602 static int dash_flush(AVFormatContext *s, int final, int stream)
604 DASHContext *c = s->priv_data;
606 int cur_flush_segment_index = 0;
608 cur_flush_segment_index = c->streams[stream].segment_index;
610 for (i = 0; i < s->nb_streams; i++) {
611 OutputStream *os = &c->streams[i];
612 char filename[1024] = "", full_path[1024], temp_path[1024];
613 const char *write_path;
614 int64_t start_pos = avio_tell(os->ctx->pb);
615 int range_length, index_length = 0;
617 if (!os->packets_written)
620 // Flush the single stream that got a keyframe right now.
621 // Flush all audio streams as well, in sync with video keyframes,
622 // but not the other video streams.
623 if (stream >= 0 && i != stream) {
624 if (s->streams[i]->codec->codec_type != AVMEDIA_TYPE_AUDIO)
626 // Make sure we don't flush audio streams multiple times, when
627 // all video streams are flushed one at a time.
628 if (c->has_video && os->segment_index > cur_flush_segment_index)
632 if (!c->single_file) {
633 snprintf(filename, sizeof(filename), "chunk-stream%d-%05d.m4s", i, os->segment_index);
634 snprintf(full_path, sizeof(full_path), "%s%s", c->dirname, filename);
635 snprintf(temp_path, sizeof(temp_path), "%s.tmp", full_path);
636 write_path = USE_RENAME_REPLACE ? temp_path : full_path;
637 ret = ffurl_open(&os->out, write_path, AVIO_FLAG_WRITE, &s->interrupt_callback, NULL);
640 write_styp(os->ctx->pb);
642 av_write_frame(os->ctx, NULL);
643 avio_flush(os->ctx->pb);
644 os->packets_written = 0;
646 range_length = avio_tell(os->ctx->pb) - start_pos;
647 if (c->single_file) {
648 find_index_range(s, c->dirname, os->initfile, start_pos, &index_length);
650 ffurl_close(os->out);
652 ret = USE_RENAME_REPLACE ? ff_rename(temp_path, full_path, s) : 0;
656 add_segment(os, filename, os->start_dts, os->end_dts - os->start_dts, start_pos, range_length, index_length);
659 if (c->window_size || (final && c->remove_at_exit)) {
660 for (i = 0; i < s->nb_streams; i++) {
661 OutputStream *os = &c->streams[i];
663 int remove = os->nb_segments - c->window_size - c->extra_window_size;
664 if (final && c->remove_at_exit)
665 remove = os->nb_segments;
667 for (j = 0; j < remove; j++) {
669 snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->segments[j]->file);
671 av_free(os->segments[j]);
673 os->nb_segments -= remove;
674 memmove(os->segments, os->segments + remove, os->nb_segments * sizeof(*os->segments));
680 ret = write_manifest(s, final);
684 static int dash_write_packet(AVFormatContext *s, AVPacket *pkt)
686 DASHContext *c = s->priv_data;
687 AVStream *st = s->streams[pkt->stream_index];
688 OutputStream *os = &c->streams[pkt->stream_index];
689 int64_t seg_end_duration = (os->segment_index) * (int64_t) c->min_seg_duration;
692 // If forcing the stream to start at 0, the mp4 muxer will set the start
693 // timestamps to 0. Do the same here, to avoid mismatches in duration/timestamps.
694 if (os->first_dts == AV_NOPTS_VALUE &&
695 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
696 pkt->pts -= pkt->dts;
700 if (os->first_dts == AV_NOPTS_VALUE)
701 os->first_dts = pkt->dts;
703 if ((!c->has_video || st->codec->codec_type == AVMEDIA_TYPE_VIDEO) &&
704 pkt->flags & AV_PKT_FLAG_KEY && os->packets_written &&
705 av_compare_ts(pkt->dts - os->first_dts, st->time_base,
706 seg_end_duration, AV_TIME_BASE_Q) >= 0) {
707 int64_t prev_duration = c->last_duration;
709 c->last_duration = av_rescale_q(pkt->dts - os->start_dts,
712 c->total_duration = av_rescale_q(pkt->dts - os->first_dts,
716 if ((!c->use_timeline || !c->use_template) && prev_duration) {
717 if (c->last_duration < prev_duration*9/10 ||
718 c->last_duration > prev_duration*11/10) {
719 av_log(s, AV_LOG_WARNING,
720 "Segment durations differ too much, enable use_timeline "
721 "and use_template, or keep a stricter keyframe interval\n");
725 if ((ret = dash_flush(s, 0, pkt->stream_index)) < 0)
729 if (!os->packets_written)
730 os->start_dts = pkt->dts;
731 os->end_dts = pkt->dts + pkt->duration;
732 os->packets_written++;
733 return ff_write_chained(os->ctx, 0, pkt, s, 0);
736 static int dash_write_trailer(AVFormatContext *s)
738 DASHContext *c = s->priv_data;
740 if (s->nb_streams > 0) {
741 OutputStream *os = &c->streams[0];
742 // If no segments have been written so far, try to do a crude
743 // guess of the segment duration
744 if (!c->last_duration)
745 c->last_duration = av_rescale_q(os->end_dts - os->start_dts,
746 s->streams[0]->time_base,
748 c->total_duration = av_rescale_q(os->end_dts - os->first_dts,
749 s->streams[0]->time_base,
752 dash_flush(s, 1, -1);
754 if (c->remove_at_exit) {
757 for (i = 0; i < s->nb_streams; i++) {
758 OutputStream *os = &c->streams[i];
759 snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
769 #define OFFSET(x) offsetof(DASHContext, x)
770 #define E AV_OPT_FLAG_ENCODING_PARAM
771 static const AVOption options[] = {
772 { "window_size", "number of segments kept in the manifest", OFFSET(window_size), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, E },
773 { "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 },
774 { "min_seg_duration", "minimum segment duration (in microseconds)", OFFSET(min_seg_duration), AV_OPT_TYPE_INT64, { .i64 = 5000000 }, 0, INT_MAX, E },
775 { "remove_at_exit", "remove all segments when finished", OFFSET(remove_at_exit), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, E },
776 { "use_template", "Use SegmentTemplate instead of SegmentList", OFFSET(use_template), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, E },
777 { "use_timeline", "Use SegmentTimeline in SegmentTemplate", OFFSET(use_timeline), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, E },
778 { "single_file", "Store all segments in one file, accessed using byte ranges", OFFSET(single_file), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, E },
782 static const AVClass dash_class = {
783 .class_name = "dash muxer",
784 .item_name = av_default_item_name,
786 .version = LIBAVUTIL_VERSION_INT,
789 AVOutputFormat ff_dash_muxer = {
791 .long_name = NULL_IF_CONFIG_SMALL("DASH Muxer"),
792 .priv_data_size = sizeof(DASHContext),
793 .audio_codec = AV_CODEC_ID_AAC,
794 .video_codec = AV_CODEC_ID_H264,
795 .flags = AVFMT_GLOBALHEADER | AVFMT_NOFILE | AVFMT_TS_NEGATIVE,
796 .write_header = dash_write_header,
797 .write_packet = dash_write_packet,
798 .write_trailer = dash_write_trailer,
799 .codec_tag = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
800 .priv_class = &dash_class,