2 * MPEG-DASH ISO BMFF segmenter
3 * Copyright (c) 2014 Martin Storsjo
4 * Copyright (c) 2018 Akamai Technologies, Inc.
6 * This file is part of FFmpeg.
8 * FFmpeg is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * FFmpeg is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with FFmpeg; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
28 #include "libavutil/avassert.h"
29 #include "libavutil/avutil.h"
30 #include "libavutil/avstring.h"
31 #include "libavutil/intreadwrite.h"
32 #include "libavutil/mathematics.h"
33 #include "libavutil/opt.h"
34 #include "libavutil/rational.h"
35 #include "libavutil/time_internal.h"
39 #include "avio_internal.h"
40 #include "hlsplaylist.h"
41 #if CONFIG_HTTP_PROTOCOL
46 #include "os_support.h"
51 typedef struct Segment {
54 int range_length, index_length;
60 typedef struct AdaptationSet {
62 enum AVMediaType media_type;
63 AVDictionary *metadata;
64 AVRational min_frame_rate, max_frame_rate;
65 int ambiguous_frame_rate;
68 typedef struct OutputStream {
70 int ctx_inited, as_idx;
75 int64_t init_start_pos, pos;
76 int init_range_length;
77 int nb_segments, segments_size, segment_index;
79 int64_t first_pts, start_pts, max_pts;
80 int64_t last_dts, last_pts;
88 double availability_time_offset;
93 typedef struct DASHContext {
94 const AVClass *class; /* Class for private options. */
95 char *adaptation_sets;
99 int extra_window_size;
100 #if FF_API_DASH_MIN_SEG_DURATION
101 int min_seg_duration;
103 int64_t seg_duration;
108 OutputStream *streams;
110 int64_t last_duration;
111 int64_t total_duration;
112 char availability_start_time[100];
114 const char *single_file_name;
115 const char *init_seg_name;
116 const char *media_seg_name;
117 const char *utc_timing_url;
119 const char *user_agent;
122 int master_playlist_created;
123 AVIOContext *mpd_out;
124 AVIOContext *m3u8_out;
127 int index_correction;
128 char *format_options_str;
131 static struct codec_string {
135 { AV_CODEC_ID_VP8, "vp8" },
136 { AV_CODEC_ID_VP9, "vp9" },
137 { AV_CODEC_ID_VORBIS, "vorbis" },
138 { AV_CODEC_ID_OPUS, "opus" },
142 static int dashenc_io_open(AVFormatContext *s, AVIOContext **pb, char *filename,
143 AVDictionary **options) {
144 DASHContext *c = s->priv_data;
145 int http_base_proto = filename ? ff_is_http_proto(filename) : 0;
146 int err = AVERROR_MUXER_NOT_FOUND;
147 if (!*pb || !http_base_proto || !c->http_persistent) {
148 err = s->io_open(s, pb, filename, AVIO_FLAG_WRITE, options);
149 #if CONFIG_HTTP_PROTOCOL
151 URLContext *http_url_context = ffio_geturlcontext(*pb);
152 av_assert0(http_url_context);
153 err = ff_http_do_new_request(http_url_context, filename);
159 static void dashenc_io_close(AVFormatContext *s, AVIOContext **pb, char *filename) {
160 DASHContext *c = s->priv_data;
161 int http_base_proto = filename ? ff_is_http_proto(filename) : 0;
163 if (!http_base_proto || !c->http_persistent) {
164 ff_format_io_close(s, pb);
165 #if CONFIG_HTTP_PROTOCOL
167 URLContext *http_url_context = ffio_geturlcontext(*pb);
168 av_assert0(http_url_context);
170 ffurl_shutdown(http_url_context, AVIO_FLAG_WRITE);
175 static void set_vp9_codec_str(AVFormatContext *s, AVCodecParameters *par,
176 AVRational *frame_rate, char *str, int size) {
178 int ret = ff_isom_get_vpcc_features(s, par, frame_rate, &vpcc);
180 av_strlcatf(str, size, "vp09.%02x.%02x.%02x",
181 vpcc.profile, vpcc.level, vpcc.bitdepth);
183 // Default to just vp9 in case of error while finding out profile or level
184 av_log(s, AV_LOG_WARNING, "Could not find VP9 profile and/or level\n");
185 av_strlcpy(str, "vp9", size);
190 static void set_codec_str(AVFormatContext *s, AVCodecParameters *par,
191 AVRational *frame_rate, char *str, int size)
193 const AVCodecTag *tags[2] = { NULL, NULL };
197 // common Webm codecs are not part of RFC 6381
198 for (i = 0; codecs[i].id; i++)
199 if (codecs[i].id == par->codec_id) {
200 if (codecs[i].id == AV_CODEC_ID_VP9) {
201 set_vp9_codec_str(s, par, frame_rate, str, size);
203 av_strlcpy(str, codecs[i].str, size);
208 // for codecs part of RFC 6381
209 if (par->codec_type == AVMEDIA_TYPE_VIDEO)
210 tags[0] = ff_codec_movvideo_tags;
211 else if (par->codec_type == AVMEDIA_TYPE_AUDIO)
212 tags[0] = ff_codec_movaudio_tags;
216 tag = av_codec_get_tag(tags, par->codec_id);
224 if (!strcmp(str, "mp4a") || !strcmp(str, "mp4v")) {
226 tags[0] = ff_mp4_obj_type;
227 oti = av_codec_get_tag(tags, par->codec_id);
229 av_strlcatf(str, size, ".%02"PRIx32, oti);
233 if (tag == MKTAG('m', 'p', '4', 'a')) {
234 if (par->extradata_size >= 2) {
235 int aot = par->extradata[0] >> 3;
237 aot = ((AV_RB16(par->extradata) >> 5) & 0x3f) + 32;
238 av_strlcatf(str, size, ".%d", aot);
240 } else if (tag == MKTAG('m', 'p', '4', 'v')) {
241 // Unimplemented, should output ProfileLevelIndication as a decimal number
242 av_log(s, AV_LOG_WARNING, "Incomplete RFC 6381 codec string for mp4v\n");
244 } else if (!strcmp(str, "avc1")) {
245 uint8_t *tmpbuf = NULL;
246 uint8_t *extradata = par->extradata;
247 int extradata_size = par->extradata_size;
250 if (extradata[0] != 1) {
252 if (avio_open_dyn_buf(&pb) < 0)
254 if (ff_isom_write_avcc(pb, extradata, extradata_size) < 0) {
255 ffio_free_dyn_buf(&pb);
258 extradata_size = avio_close_dyn_buf(pb, &extradata);
262 if (extradata_size >= 4)
263 av_strlcatf(str, size, ".%02x%02x%02x",
264 extradata[1], extradata[2], extradata[3]);
269 static int flush_dynbuf(OutputStream *os, int *range_length)
274 return AVERROR(EINVAL);
278 av_write_frame(os->ctx, NULL);
279 avio_flush(os->ctx->pb);
282 *range_length = avio_close_dyn_buf(os->ctx->pb, &buffer);
284 avio_write(os->out, buffer + os->written_len, *range_length - os->written_len);
289 return avio_open_dyn_buf(&os->ctx->pb);
292 static void set_http_options(AVDictionary **options, DASHContext *c)
295 av_dict_set(options, "method", c->method, 0);
297 av_dict_set(options, "user_agent", c->user_agent, 0);
298 if (c->http_persistent)
299 av_dict_set_int(options, "multiple_requests", 1, 0);
301 av_dict_set_int(options, "timeout", c->timeout, 0);
304 static void get_hls_playlist_name(char *playlist_name, int string_size,
305 const char *base_url, int id) {
307 snprintf(playlist_name, string_size, "%smedia_%d.m3u8", base_url, id);
309 snprintf(playlist_name, string_size, "media_%d.m3u8", id);
312 static int flush_init_segment(AVFormatContext *s, OutputStream *os)
314 DASHContext *c = s->priv_data;
315 int ret, range_length;
317 ret = flush_dynbuf(os, &range_length);
321 os->pos = os->init_range_length = range_length;
323 ff_format_io_close(s, &os->out);
327 static void dash_free(AVFormatContext *s)
329 DASHContext *c = s->priv_data;
333 for (i = 0; i < c->nb_as; i++)
334 av_dict_free(&c->as[i].metadata);
341 for (i = 0; i < s->nb_streams; i++) {
342 OutputStream *os = &c->streams[i];
343 if (os->ctx && os->ctx_inited)
344 av_write_trailer(os->ctx);
345 if (os->ctx && os->ctx->pb)
346 ffio_free_dyn_buf(&os->ctx->pb);
347 ff_format_io_close(s, &os->out);
349 avformat_free_context(os->ctx);
350 for (j = 0; j < os->nb_segments; j++)
351 av_free(os->segments[j]);
352 av_free(os->segments);
354 av_freep(&c->streams);
356 ff_format_io_close(s, &c->mpd_out);
357 ff_format_io_close(s, &c->m3u8_out);
360 static void output_segment_list(OutputStream *os, AVIOContext *out, AVFormatContext *s,
361 int representation_id, int final)
363 DASHContext *c = s->priv_data;
364 int i, start_index = 0, start_number = 1;
365 if (c->window_size) {
366 start_index = FFMAX(os->nb_segments - c->window_size, 0);
367 start_number = FFMAX(os->segment_index - c->window_size, 1);
370 if (c->use_template) {
371 int timescale = c->use_timeline ? os->ctx->streams[0]->time_base.den : AV_TIME_BASE;
372 avio_printf(out, "\t\t\t\t<SegmentTemplate timescale=\"%d\" ", timescale);
373 if (!c->use_timeline) {
374 avio_printf(out, "duration=\"%"PRId64"\" ", c->seg_duration);
375 if (c->streaming && os->availability_time_offset)
376 avio_printf(out, "availabilityTimeOffset=\"%.3f\" ",
377 os->availability_time_offset);
379 avio_printf(out, "initialization=\"%s\" media=\"%s\" startNumber=\"%d\">\n", c->init_seg_name, c->media_seg_name, c->use_timeline ? start_number : 1);
380 if (c->use_timeline) {
381 int64_t cur_time = 0;
382 avio_printf(out, "\t\t\t\t\t<SegmentTimeline>\n");
383 for (i = start_index; i < os->nb_segments; ) {
384 Segment *seg = os->segments[i];
386 avio_printf(out, "\t\t\t\t\t\t<S ");
387 if (i == start_index || seg->time != cur_time) {
388 cur_time = seg->time;
389 avio_printf(out, "t=\"%"PRId64"\" ", seg->time);
391 avio_printf(out, "d=\"%d\" ", seg->duration);
392 while (i + repeat + 1 < os->nb_segments &&
393 os->segments[i + repeat + 1]->duration == seg->duration &&
394 os->segments[i + repeat + 1]->time == os->segments[i + repeat]->time + os->segments[i + repeat]->duration)
397 avio_printf(out, "r=\"%d\" ", repeat);
398 avio_printf(out, "/>\n");
400 cur_time += (1 + repeat) * seg->duration;
402 avio_printf(out, "\t\t\t\t\t</SegmentTimeline>\n");
404 avio_printf(out, "\t\t\t\t</SegmentTemplate>\n");
405 } else if (c->single_file) {
406 avio_printf(out, "\t\t\t\t<BaseURL>%s</BaseURL>\n", os->initfile);
407 avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%"PRId64"\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);
408 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);
409 for (i = start_index; i < os->nb_segments; i++) {
410 Segment *seg = os->segments[i];
411 avio_printf(out, "\t\t\t\t\t<SegmentURL mediaRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->range_length - 1);
412 if (seg->index_length)
413 avio_printf(out, "indexRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->index_length - 1);
414 avio_printf(out, "/>\n");
416 avio_printf(out, "\t\t\t\t</SegmentList>\n");
418 avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%"PRId64"\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);
419 avio_printf(out, "\t\t\t\t\t<Initialization sourceURL=\"%s\" />\n", os->initfile);
420 for (i = start_index; i < os->nb_segments; i++) {
421 Segment *seg = os->segments[i];
422 avio_printf(out, "\t\t\t\t\t<SegmentURL media=\"%s\" />\n", seg->file);
424 avio_printf(out, "\t\t\t\t</SegmentList>\n");
426 if (c->hls_playlist && start_index < os->nb_segments)
428 int timescale = os->ctx->streams[0]->time_base.den;
429 char temp_filename_hls[1024];
430 char filename_hls[1024];
431 AVDictionary *http_opts = NULL;
432 int target_duration = 0;
434 const char *proto = avio_find_protocol_name(c->dirname);
435 int use_rename = proto && !strcmp(proto, "file");
437 get_hls_playlist_name(filename_hls, sizeof(filename_hls),
438 c->dirname, representation_id);
440 snprintf(temp_filename_hls, sizeof(temp_filename_hls), use_rename ? "%s.tmp" : "%s", filename_hls);
442 set_http_options(&http_opts, c);
443 dashenc_io_open(s, &c->m3u8_out, temp_filename_hls, &http_opts);
444 av_dict_free(&http_opts);
445 for (i = start_index; i < os->nb_segments; i++) {
446 Segment *seg = os->segments[i];
447 double duration = (double) seg->duration / timescale;
448 if (target_duration <= duration)
449 target_duration = lrint(duration);
452 ff_hls_write_playlist_header(c->m3u8_out, 6, -1, target_duration,
453 start_number, PLAYLIST_TYPE_NONE);
455 ff_hls_write_init_file(c->m3u8_out, os->initfile, c->single_file,
456 os->init_range_length, os->init_start_pos);
458 for (i = start_index; i < os->nb_segments; i++) {
459 Segment *seg = os->segments[i];
460 ret = ff_hls_write_file_entry(c->m3u8_out, 0, c->single_file,
461 (double) seg->duration / timescale, 0,
462 seg->range_length, seg->start_pos, NULL,
463 c->single_file ? os->initfile : seg->file,
466 av_log(os->ctx, AV_LOG_WARNING, "ff_hls_write_file_entry get error\n");
471 ff_hls_write_end_list(c->m3u8_out);
473 dashenc_io_close(s, &c->m3u8_out, temp_filename_hls);
476 if (avpriv_io_move(temp_filename_hls, filename_hls) < 0) {
477 av_log(os->ctx, AV_LOG_WARNING, "renaming file %s to %s failed\n\n", temp_filename_hls, filename_hls);
483 static char *xmlescape(const char *str) {
484 int outlen = strlen(str)*3/2 + 6;
485 char *out = av_realloc(NULL, outlen + 1);
489 for (; *str; str++) {
490 if (pos + 6 > outlen) {
492 outlen = 2 * outlen + 6;
493 tmp = av_realloc(out, outlen + 1);
501 memcpy(&out[pos], "&", 5);
503 } else if (*str == '<') {
504 memcpy(&out[pos], "<", 4);
506 } else if (*str == '>') {
507 memcpy(&out[pos], ">", 4);
509 } else if (*str == '\'') {
510 memcpy(&out[pos], "'", 6);
512 } else if (*str == '\"') {
513 memcpy(&out[pos], """, 6);
523 static void write_time(AVIOContext *out, int64_t time)
525 int seconds = time / AV_TIME_BASE;
526 int fractions = time % AV_TIME_BASE;
527 int minutes = seconds / 60;
528 int hours = minutes / 60;
531 avio_printf(out, "PT");
533 avio_printf(out, "%dH", hours);
534 if (hours || minutes)
535 avio_printf(out, "%dM", minutes);
536 avio_printf(out, "%d.%dS", seconds, fractions / (AV_TIME_BASE / 10));
539 static void format_date_now(char *buf, int size)
541 time_t t = time(NULL);
542 struct tm *ptm, tmbuf;
543 ptm = gmtime_r(&t, &tmbuf);
545 if (!strftime(buf, size, "%Y-%m-%dT%H:%M:%SZ", ptm))
550 static int write_adaptation_set(AVFormatContext *s, AVIOContext *out, int as_index,
553 DASHContext *c = s->priv_data;
554 AdaptationSet *as = &c->as[as_index];
555 AVDictionaryEntry *lang, *role;
558 avio_printf(out, "\t\t<AdaptationSet id=\"%s\" contentType=\"%s\" segmentAlignment=\"true\" bitstreamSwitching=\"true\"",
559 as->id, as->media_type == AVMEDIA_TYPE_VIDEO ? "video" : "audio");
560 if (as->media_type == AVMEDIA_TYPE_VIDEO && as->max_frame_rate.num && !as->ambiguous_frame_rate && av_cmp_q(as->min_frame_rate, as->max_frame_rate) < 0)
561 avio_printf(out, " maxFrameRate=\"%d/%d\"", as->max_frame_rate.num, as->max_frame_rate.den);
562 lang = av_dict_get(as->metadata, "language", NULL, 0);
564 avio_printf(out, " lang=\"%s\"", lang->value);
565 avio_printf(out, ">\n");
567 role = av_dict_get(as->metadata, "role", NULL, 0);
569 avio_printf(out, "\t\t\t<Role schemeIdUri=\"urn:mpeg:dash:role:2011\" value=\"%s\"/>\n", role->value);
571 for (i = 0; i < s->nb_streams; i++) {
572 OutputStream *os = &c->streams[i];
573 char bandwidth_str[64] = {'\0'};
575 if (os->as_idx - 1 != as_index)
578 if (os->bit_rate > 0)
579 snprintf(bandwidth_str, sizeof(bandwidth_str), " bandwidth=\"%d\"",
580 os->bit_rate + os->muxer_overhead);
582 if (as->media_type == AVMEDIA_TYPE_VIDEO) {
583 AVStream *st = s->streams[i];
584 avio_printf(out, "\t\t\t<Representation id=\"%d\" mimeType=\"video/%s\" codecs=\"%s\"%s width=\"%d\" height=\"%d\"",
585 i, os->format_name, os->codec_str, bandwidth_str, s->streams[i]->codecpar->width, s->streams[i]->codecpar->height);
586 if (st->avg_frame_rate.num)
587 avio_printf(out, " frameRate=\"%d/%d\"", st->avg_frame_rate.num, st->avg_frame_rate.den);
588 avio_printf(out, ">\n");
590 avio_printf(out, "\t\t\t<Representation id=\"%d\" mimeType=\"audio/%s\" codecs=\"%s\"%s audioSamplingRate=\"%d\">\n",
591 i, os->format_name, os->codec_str, bandwidth_str, s->streams[i]->codecpar->sample_rate);
592 avio_printf(out, "\t\t\t\t<AudioChannelConfiguration schemeIdUri=\"urn:mpeg:dash:23003:3:audio_channel_configuration:2011\" value=\"%d\" />\n",
593 s->streams[i]->codecpar->channels);
595 output_segment_list(os, out, s, i, final);
596 avio_printf(out, "\t\t\t</Representation>\n");
598 avio_printf(out, "\t\t</AdaptationSet>\n");
603 static int add_adaptation_set(AVFormatContext *s, AdaptationSet **as, enum AVMediaType type)
605 DASHContext *c = s->priv_data;
607 void *mem = av_realloc(c->as, sizeof(*c->as) * (c->nb_as + 1));
609 return AVERROR(ENOMEM);
613 *as = &c->as[c->nb_as - 1];
614 memset(*as, 0, sizeof(**as));
615 (*as)->media_type = type;
620 static int adaptation_set_add_stream(AVFormatContext *s, int as_idx, int i)
622 DASHContext *c = s->priv_data;
623 AdaptationSet *as = &c->as[as_idx - 1];
624 OutputStream *os = &c->streams[i];
626 if (as->media_type != s->streams[i]->codecpar->codec_type) {
627 av_log(s, AV_LOG_ERROR, "Codec type of stream %d doesn't match AdaptationSet's media type\n", i);
628 return AVERROR(EINVAL);
629 } else if (os->as_idx) {
630 av_log(s, AV_LOG_ERROR, "Stream %d is already assigned to an AdaptationSet\n", i);
631 return AVERROR(EINVAL);
638 static int parse_adaptation_sets(AVFormatContext *s)
640 DASHContext *c = s->priv_data;
641 const char *p = c->adaptation_sets;
642 enum { new_set, parse_id, parsing_streams } state;
646 // default: one AdaptationSet for each stream
648 for (i = 0; i < s->nb_streams; i++) {
649 if ((ret = add_adaptation_set(s, &as, s->streams[i]->codecpar->codec_type)) < 0)
651 snprintf(as->id, sizeof(as->id), "%d", i);
653 c->streams[i].as_idx = c->nb_as;
658 // syntax id=0,streams=0,1,2 id=1,streams=3,4 and so on
664 } else if (state == new_set && av_strstart(p, "id=", &p)) {
666 if ((ret = add_adaptation_set(s, &as, AVMEDIA_TYPE_UNKNOWN)) < 0)
670 snprintf(as->id, sizeof(as->id), "%.*s", n, p);
676 } else if (state == parse_id && av_strstart(p, "streams=", &p)) {
677 state = parsing_streams;
678 } else if (state == parsing_streams) {
679 AdaptationSet *as = &c->as[c->nb_as - 1];
680 char idx_str[8], *end_str;
682 n = strcspn(p, " ,");
683 snprintf(idx_str, sizeof(idx_str), "%.*s", n, p);
686 // if value is "a" or "v", map all streams of that type
687 if (as->media_type == AVMEDIA_TYPE_UNKNOWN && (idx_str[0] == 'v' || idx_str[0] == 'a')) {
688 enum AVMediaType type = (idx_str[0] == 'v') ? AVMEDIA_TYPE_VIDEO : AVMEDIA_TYPE_AUDIO;
689 av_log(s, AV_LOG_DEBUG, "Map all streams of type %s\n", idx_str);
691 for (i = 0; i < s->nb_streams; i++) {
692 if (s->streams[i]->codecpar->codec_type != type)
695 as->media_type = s->streams[i]->codecpar->codec_type;
697 if ((ret = adaptation_set_add_stream(s, c->nb_as, i)) < 0)
700 } else { // select single stream
701 i = strtol(idx_str, &end_str, 10);
702 if (idx_str == end_str || i < 0 || i >= s->nb_streams) {
703 av_log(s, AV_LOG_ERROR, "Selected stream \"%s\" not found!\n", idx_str);
704 return AVERROR(EINVAL);
706 av_log(s, AV_LOG_DEBUG, "Map stream %d\n", i);
708 if (as->media_type == AVMEDIA_TYPE_UNKNOWN) {
709 as->media_type = s->streams[i]->codecpar->codec_type;
712 if ((ret = adaptation_set_add_stream(s, c->nb_as, i)) < 0)
721 return AVERROR(EINVAL);
726 // check for unassigned streams
727 for (i = 0; i < s->nb_streams; i++) {
728 OutputStream *os = &c->streams[i];
730 av_log(s, AV_LOG_ERROR, "Stream %d is not mapped to an AdaptationSet\n", i);
731 return AVERROR(EINVAL);
737 static int write_manifest(AVFormatContext *s, int final)
739 DASHContext *c = s->priv_data;
741 char temp_filename[1024];
743 const char *proto = avio_find_protocol_name(s->url);
744 int use_rename = proto && !strcmp(proto, "file");
745 static unsigned int warned_non_file = 0;
746 AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
747 AVDictionary *opts = NULL;
749 if (!use_rename && !warned_non_file++)
750 av_log(s, AV_LOG_ERROR, "Cannot use rename on non file protocol, this may lead to races and temporary partial files\n");
752 snprintf(temp_filename, sizeof(temp_filename), use_rename ? "%s.tmp" : "%s", s->url);
753 set_http_options(&opts, c);
754 ret = dashenc_io_open(s, &c->mpd_out, temp_filename, &opts);
756 av_log(s, AV_LOG_ERROR, "Unable to open %s for writing\n", temp_filename);
761 avio_printf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
762 avio_printf(out, "<MPD xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
763 "\txmlns=\"urn:mpeg:dash:schema:mpd:2011\"\n"
764 "\txmlns:xlink=\"http://www.w3.org/1999/xlink\"\n"
765 "\txsi:schemaLocation=\"urn:mpeg:DASH:schema:MPD:2011 http://standards.iso.org/ittf/PubliclyAvailableStandards/MPEG-DASH_schema_files/DASH-MPD.xsd\"\n"
766 "\tprofiles=\"urn:mpeg:dash:profile:isoff-live:2011\"\n"
767 "\ttype=\"%s\"\n", final ? "static" : "dynamic");
769 avio_printf(out, "\tmediaPresentationDuration=\"");
770 write_time(out, c->total_duration);
771 avio_printf(out, "\"\n");
773 int64_t update_period = c->last_duration / AV_TIME_BASE;
775 if (c->use_template && !c->use_timeline)
777 avio_printf(out, "\tminimumUpdatePeriod=\"PT%"PRId64"S\"\n", update_period);
778 avio_printf(out, "\tsuggestedPresentationDelay=\"PT%"PRId64"S\"\n", c->last_duration / AV_TIME_BASE);
779 if (c->availability_start_time[0])
780 avio_printf(out, "\tavailabilityStartTime=\"%s\"\n", c->availability_start_time);
781 format_date_now(now_str, sizeof(now_str));
783 avio_printf(out, "\tpublishTime=\"%s\"\n", now_str);
784 if (c->window_size && c->use_template) {
785 avio_printf(out, "\ttimeShiftBufferDepth=\"");
786 write_time(out, c->last_duration * c->window_size);
787 avio_printf(out, "\"\n");
790 avio_printf(out, "\tminBufferTime=\"");
791 write_time(out, c->last_duration * 2);
792 avio_printf(out, "\">\n");
793 avio_printf(out, "\t<ProgramInformation>\n");
795 char *escaped = xmlescape(title->value);
796 avio_printf(out, "\t\t<Title>%s</Title>\n", escaped);
799 avio_printf(out, "\t</ProgramInformation>\n");
801 if (c->window_size && s->nb_streams > 0 && c->streams[0].nb_segments > 0 && !c->use_template) {
802 OutputStream *os = &c->streams[0];
803 int start_index = FFMAX(os->nb_segments - c->window_size, 0);
804 int64_t start_time = av_rescale_q(os->segments[start_index]->time, s->streams[0]->time_base, AV_TIME_BASE_Q);
805 avio_printf(out, "\t<Period id=\"0\" start=\"");
806 write_time(out, start_time);
807 avio_printf(out, "\">\n");
809 avio_printf(out, "\t<Period id=\"0\" start=\"PT0.0S\">\n");
812 for (i = 0; i < c->nb_as; i++) {
813 if ((ret = write_adaptation_set(s, out, i, final)) < 0)
816 avio_printf(out, "\t</Period>\n");
818 if (c->utc_timing_url)
819 avio_printf(out, "\t<UTCTiming schemeIdUri=\"urn:mpeg:dash:utc:http-xsdate:2014\" value=\"%s\"/>\n", c->utc_timing_url);
821 avio_printf(out, "</MPD>\n");
823 dashenc_io_close(s, &c->mpd_out, temp_filename);
826 if ((ret = avpriv_io_move(temp_filename, s->url)) < 0)
830 if (c->hls_playlist && !c->master_playlist_created) {
831 char filename_hls[1024];
832 const char *audio_group = "A1";
834 int max_audio_bitrate = 0;
837 snprintf(filename_hls, sizeof(filename_hls), "%s/master.m3u8", c->dirname);
839 snprintf(filename_hls, sizeof(filename_hls), "master.m3u8");
841 snprintf(temp_filename, sizeof(temp_filename), use_rename ? "%s.tmp" : "%s", filename_hls);
843 set_http_options(&opts, c);
844 ret = avio_open2(&out, temp_filename, AVIO_FLAG_WRITE, NULL, &opts);
846 av_log(s, AV_LOG_ERROR, "Unable to open %s for writing\n", temp_filename);
851 ff_hls_write_playlist_version(out, 7);
853 for (i = 0; i < s->nb_streams; i++) {
854 char playlist_file[64];
855 AVStream *st = s->streams[i];
856 OutputStream *os = &c->streams[i];
857 if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO)
859 get_hls_playlist_name(playlist_file, sizeof(playlist_file), NULL, i);
860 ff_hls_write_audio_rendition(out, (char *)audio_group,
861 playlist_file, i, is_default);
862 max_audio_bitrate = FFMAX(st->codecpar->bit_rate +
863 os->muxer_overhead, max_audio_bitrate);
867 for (i = 0; i < s->nb_streams; i++) {
868 char playlist_file[64];
869 AVStream *st = s->streams[i];
870 OutputStream *os = &c->streams[i];
872 int stream_bitrate = st->codecpar->bit_rate + os->muxer_overhead;
873 if ((st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) && max_audio_bitrate) {
874 agroup = (char *)audio_group;
875 stream_bitrate += max_audio_bitrate;
877 get_hls_playlist_name(playlist_file, sizeof(playlist_file), NULL, i);
878 ff_hls_write_stream_info(st, out, stream_bitrate, playlist_file, agroup, NULL, NULL);
882 if ((ret = avpriv_io_move(temp_filename, filename_hls)) < 0)
884 c->master_playlist_created = 1;
890 static int dict_copy_entry(AVDictionary **dst, const AVDictionary *src, const char *key)
892 AVDictionaryEntry *entry = av_dict_get(src, key, NULL, 0);
894 av_dict_set(dst, key, entry->value, AV_DICT_DONT_OVERWRITE);
898 static int dash_init(AVFormatContext *s)
900 DASHContext *c = s->priv_data;
905 if (c->single_file_name)
910 #if FF_API_DASH_MIN_SEG_DURATION
911 if (c->min_seg_duration != 5000000) {
912 av_log(s, AV_LOG_WARNING, "The min_seg_duration option is deprecated and will be removed. Please use the -seg_duration\n");
913 c->seg_duration = c->min_seg_duration;
917 av_strlcpy(c->dirname, s->url, sizeof(c->dirname));
918 ptr = strrchr(c->dirname, '/');
920 av_strlcpy(basename, &ptr[1], sizeof(basename));
923 c->dirname[0] = '\0';
924 av_strlcpy(basename, s->url, sizeof(basename));
927 ptr = strrchr(basename, '.');
931 c->streams = av_mallocz(sizeof(*c->streams) * s->nb_streams);
933 return AVERROR(ENOMEM);
935 if ((ret = parse_adaptation_sets(s)) < 0)
938 for (i = 0; i < s->nb_streams; i++) {
939 OutputStream *os = &c->streams[i];
940 AdaptationSet *as = &c->as[os->as_idx - 1];
941 AVFormatContext *ctx;
943 AVDictionary *opts = NULL;
946 os->bit_rate = s->streams[i]->codecpar->bit_rate;
948 int level = s->strict_std_compliance >= FF_COMPLIANCE_STRICT ?
949 AV_LOG_ERROR : AV_LOG_WARNING;
950 av_log(s, level, "No bit rate set for stream %d\n", i);
951 if (s->strict_std_compliance >= FF_COMPLIANCE_STRICT)
952 return AVERROR(EINVAL);
955 // copy AdaptationSet language and role from stream metadata
956 dict_copy_entry(&as->metadata, s->streams[i]->metadata, "language");
957 dict_copy_entry(&as->metadata, s->streams[i]->metadata, "role");
959 ctx = avformat_alloc_context();
961 return AVERROR(ENOMEM);
963 // choose muxer based on codec: webm for VP8 and opus, mp4 otherwise
964 // note: os->format_name is also used as part of the mimetype of the
965 // representation, e.g. video/<format_name>
966 if (s->streams[i]->codecpar->codec_id == AV_CODEC_ID_VP8 ||
967 s->streams[i]->codecpar->codec_id == AV_CODEC_ID_OPUS ||
968 s->streams[i]->codecpar->codec_id == AV_CODEC_ID_VORBIS) {
969 snprintf(os->format_name, sizeof(os->format_name), "webm");
971 if (s->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
972 av_log(s, AV_LOG_ERROR,
973 "WebM support in dashenc is experimental and has not "
974 "been validated. For testing purposes, make sure "
975 "to add -strict experimental and override "
976 "-init_seg_name and -media_seg_name to end with "
977 "the extension 'webm'.\n");
978 return AVERROR(EINVAL);
981 snprintf(os->format_name, sizeof(os->format_name), "mp4");
983 ctx->oformat = av_guess_format(os->format_name, NULL, NULL);
985 return AVERROR_MUXER_NOT_FOUND;
987 ctx->interrupt_callback = s->interrupt_callback;
988 ctx->opaque = s->opaque;
989 ctx->io_close = s->io_close;
990 ctx->io_open = s->io_open;
991 ctx->strict_std_compliance = s->strict_std_compliance;
993 if (!(st = avformat_new_stream(ctx, NULL)))
994 return AVERROR(ENOMEM);
995 avcodec_parameters_copy(st->codecpar, s->streams[i]->codecpar);
996 st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
997 st->time_base = s->streams[i]->time_base;
998 st->avg_frame_rate = s->streams[i]->avg_frame_rate;
999 ctx->avoid_negative_ts = s->avoid_negative_ts;
1000 ctx->flags = s->flags;
1002 if ((ret = avio_open_dyn_buf(&ctx->pb)) < 0)
1005 if (c->single_file) {
1006 if (c->single_file_name)
1007 ff_dash_fill_tmpl_params(os->initfile, sizeof(os->initfile), c->single_file_name, i, 0, os->bit_rate, 0);
1009 snprintf(os->initfile, sizeof(os->initfile), "%s-stream%d.m4s", basename, i);
1011 ff_dash_fill_tmpl_params(os->initfile, sizeof(os->initfile), c->init_seg_name, i, 0, os->bit_rate, 0);
1013 snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
1014 set_http_options(&opts, c);
1015 ret = s->io_open(s, &os->out, filename, AVIO_FLAG_WRITE, &opts);
1018 av_dict_free(&opts);
1019 os->init_start_pos = 0;
1021 if (c->format_options_str) {
1022 ret = av_dict_parse_string(&opts, c->format_options_str, "=", ":", 0);
1026 if (!strcmp(os->format_name, "mp4")) {
1028 av_dict_set(&opts, "movflags", "frag_every_frame+dash+delay_moov", 0);
1030 av_dict_set(&opts, "movflags", "frag_custom+dash+delay_moov", 0);
1032 av_dict_set_int(&opts, "cluster_time_limit", c->seg_duration / 1000, 0);
1033 av_dict_set_int(&opts, "cluster_size_limit", 5 * 1024 * 1024, 0); // set a large cluster size limit
1034 av_dict_set_int(&opts, "dash", 1, 0);
1035 av_dict_set_int(&opts, "dash_track_number", i + 1, 0);
1036 av_dict_set_int(&opts, "live", 1, 0);
1038 if ((ret = avformat_init_output(ctx, &opts)) < 0)
1041 avio_flush(ctx->pb);
1042 av_dict_free(&opts);
1044 av_log(s, AV_LOG_VERBOSE, "Representation %d init segment will be written to: %s\n", i, filename);
1046 s->streams[i]->time_base = st->time_base;
1047 // If the muxer wants to shift timestamps, request to have them shifted
1048 // already before being handed to this muxer, so we don't have mismatches
1049 // between the MPD and the actual segments.
1050 s->avoid_negative_ts = ctx->avoid_negative_ts;
1051 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
1052 AVRational avg_frame_rate = s->streams[i]->avg_frame_rate;
1053 if (avg_frame_rate.num > 0) {
1054 if (av_cmp_q(avg_frame_rate, as->min_frame_rate) < 0)
1055 as->min_frame_rate = avg_frame_rate;
1056 if (av_cmp_q(as->max_frame_rate, avg_frame_rate) < 0)
1057 as->max_frame_rate = avg_frame_rate;
1059 as->ambiguous_frame_rate = 1;
1064 set_codec_str(s, st->codecpar, &st->avg_frame_rate, os->codec_str,
1065 sizeof(os->codec_str));
1066 os->first_pts = AV_NOPTS_VALUE;
1067 os->max_pts = AV_NOPTS_VALUE;
1068 os->last_dts = AV_NOPTS_VALUE;
1069 os->segment_index = 1;
1072 if (!c->has_video && c->seg_duration <= 0) {
1073 av_log(s, AV_LOG_WARNING, "no video stream and no seg duration set\n");
1074 return AVERROR(EINVAL);
1079 static int dash_write_header(AVFormatContext *s)
1081 DASHContext *c = s->priv_data;
1083 for (i = 0; i < s->nb_streams; i++) {
1084 OutputStream *os = &c->streams[i];
1085 if ((ret = avformat_write_header(os->ctx, NULL)) < 0)
1088 // Flush init segment
1089 // Only for WebM segment, since for mp4 delay_moov is set and
1090 // the init segment is thus flushed after the first packets.
1091 if (strcmp(os->format_name, "mp4") &&
1092 (ret = flush_init_segment(s, os)) < 0)
1098 static int add_segment(OutputStream *os, const char *file,
1099 int64_t time, int duration,
1100 int64_t start_pos, int64_t range_length,
1101 int64_t index_length, int next_exp_index)
1105 if (os->nb_segments >= os->segments_size) {
1106 os->segments_size = (os->segments_size + 1) * 2;
1107 if ((err = av_reallocp(&os->segments, sizeof(*os->segments) *
1108 os->segments_size)) < 0) {
1109 os->segments_size = 0;
1110 os->nb_segments = 0;
1114 seg = av_mallocz(sizeof(*seg));
1116 return AVERROR(ENOMEM);
1117 av_strlcpy(seg->file, file, sizeof(seg->file));
1119 seg->duration = duration;
1120 if (seg->time < 0) { // If pts<0, it is expected to be cut away with an edit list
1121 seg->duration += seg->time;
1124 seg->start_pos = start_pos;
1125 seg->range_length = range_length;
1126 seg->index_length = index_length;
1127 os->segments[os->nb_segments++] = seg;
1128 os->segment_index++;
1129 //correcting the segment index if it has fallen behind the expected value
1130 if (os->segment_index < next_exp_index) {
1131 av_log(NULL, AV_LOG_WARNING, "Correcting the segment index after file %s: current=%d corrected=%d\n",
1132 file, os->segment_index, next_exp_index);
1133 os->segment_index = next_exp_index;
1138 static void write_styp(AVIOContext *pb)
1141 ffio_wfourcc(pb, "styp");
1142 ffio_wfourcc(pb, "msdh");
1143 avio_wb32(pb, 0); /* minor */
1144 ffio_wfourcc(pb, "msdh");
1145 ffio_wfourcc(pb, "msix");
1148 static void find_index_range(AVFormatContext *s, const char *full_path,
1149 int64_t pos, int *index_length)
1155 ret = s->io_open(s, &pb, full_path, AVIO_FLAG_READ, NULL);
1158 if (avio_seek(pb, pos, SEEK_SET) != pos) {
1159 ff_format_io_close(s, &pb);
1162 ret = avio_read(pb, buf, 8);
1163 ff_format_io_close(s, &pb);
1166 if (AV_RL32(&buf[4]) != MKTAG('s', 'i', 'd', 'x'))
1168 *index_length = AV_RB32(&buf[0]);
1171 static int update_stream_extradata(AVFormatContext *s, OutputStream *os,
1172 AVCodecParameters *par,
1173 AVRational *frame_rate)
1177 if (os->ctx->streams[0]->codecpar->extradata_size || !par->extradata_size)
1180 extradata = av_malloc(par->extradata_size);
1183 return AVERROR(ENOMEM);
1185 memcpy(extradata, par->extradata, par->extradata_size);
1187 os->ctx->streams[0]->codecpar->extradata = extradata;
1188 os->ctx->streams[0]->codecpar->extradata_size = par->extradata_size;
1190 set_codec_str(s, par, frame_rate, os->codec_str, sizeof(os->codec_str));
1195 static void dashenc_delete_file(AVFormatContext *s, char *filename) {
1196 DASHContext *c = s->priv_data;
1197 int http_base_proto = ff_is_http_proto(filename);
1199 if (http_base_proto) {
1200 AVIOContext *out = NULL;
1201 AVDictionary *http_opts = NULL;
1203 set_http_options(&http_opts, c);
1204 av_dict_set(&http_opts, "method", "DELETE", 0);
1206 if (dashenc_io_open(s, &out, filename, &http_opts) < 0) {
1207 av_log(s, AV_LOG_ERROR, "failed to delete %s\n", filename);
1210 av_dict_free(&http_opts);
1211 dashenc_io_close(s, &out, filename);
1212 } else if (unlink(filename) < 0) {
1213 av_log(s, AV_LOG_ERROR, "failed to delete %s: %s\n", filename, strerror(errno));
1217 static int dash_flush(AVFormatContext *s, int final, int stream)
1219 DASHContext *c = s->priv_data;
1222 const char *proto = avio_find_protocol_name(s->url);
1223 int use_rename = proto && !strcmp(proto, "file");
1225 int cur_flush_segment_index = 0, next_exp_index = -1;
1227 cur_flush_segment_index = c->streams[stream].segment_index;
1229 //finding the next segment's expected index, based on the current pts value
1230 if (c->use_template && !c->use_timeline && c->index_correction &&
1231 c->streams[stream].last_pts != AV_NOPTS_VALUE &&
1232 c->streams[stream].first_pts != AV_NOPTS_VALUE) {
1233 int64_t pts_diff = av_rescale_q(c->streams[stream].last_pts -
1234 c->streams[stream].first_pts,
1235 s->streams[stream]->time_base,
1237 next_exp_index = (pts_diff / c->seg_duration) + 1;
1241 for (i = 0; i < s->nb_streams; i++) {
1242 OutputStream *os = &c->streams[i];
1243 AVStream *st = s->streams[i];
1244 int range_length, index_length = 0;
1246 if (!os->packets_written)
1249 // Flush the single stream that got a keyframe right now.
1250 // Flush all audio streams as well, in sync with video keyframes,
1251 // but not the other video streams.
1252 if (stream >= 0 && i != stream) {
1253 if (s->streams[i]->codecpar->codec_type != AVMEDIA_TYPE_AUDIO)
1255 // Make sure we don't flush audio streams multiple times, when
1256 // all video streams are flushed one at a time.
1257 if (c->has_video && os->segment_index > cur_flush_segment_index)
1261 if (!c->single_file) {
1262 if (!strcmp(os->format_name, "mp4") && !os->written_len)
1263 write_styp(os->ctx->pb);
1265 snprintf(os->full_path, sizeof(os->full_path), "%s%s", c->dirname, os->initfile);
1268 ret = flush_dynbuf(os, &range_length);
1271 os->packets_written = 0;
1273 if (c->single_file) {
1274 find_index_range(s, os->full_path, os->pos, &index_length);
1276 dashenc_io_close(s, &os->out, os->temp_path);
1279 ret = avpriv_io_move(os->temp_path, os->full_path);
1285 if (!os->muxer_overhead)
1286 os->muxer_overhead = ((int64_t) (range_length - os->total_pkt_size) *
1288 av_rescale_q(os->max_pts - os->start_pts,
1289 st->time_base, AV_TIME_BASE_Q);
1290 os->total_pkt_size = 0;
1292 if (!os->bit_rate) {
1293 // calculate average bitrate of first segment
1294 int64_t bitrate = (int64_t) range_length * 8 * AV_TIME_BASE / av_rescale_q(os->max_pts - os->start_pts,
1298 os->bit_rate = bitrate;
1300 add_segment(os, os->filename, os->start_pts, os->max_pts - os->start_pts, os->pos, range_length, index_length, next_exp_index);
1301 av_log(s, AV_LOG_VERBOSE, "Representation %d media segment %d written to: %s\n", i, os->segment_index, os->full_path);
1303 os->pos += range_length;
1306 if (c->window_size || (final && c->remove_at_exit)) {
1307 for (i = 0; i < s->nb_streams; i++) {
1308 OutputStream *os = &c->streams[i];
1310 int remove = os->nb_segments - c->window_size - c->extra_window_size;
1311 if (final && c->remove_at_exit)
1312 remove = os->nb_segments;
1314 for (j = 0; j < remove; j++) {
1315 char filename[1024];
1316 snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->segments[j]->file);
1317 dashenc_delete_file(s, filename);
1318 av_free(os->segments[j]);
1320 os->nb_segments -= remove;
1321 memmove(os->segments, os->segments + remove, os->nb_segments * sizeof(*os->segments));
1327 ret = write_manifest(s, final);
1331 static int dash_write_packet(AVFormatContext *s, AVPacket *pkt)
1333 DASHContext *c = s->priv_data;
1334 AVStream *st = s->streams[pkt->stream_index];
1335 OutputStream *os = &c->streams[pkt->stream_index];
1336 int64_t seg_end_duration, elapsed_duration;
1339 ret = update_stream_extradata(s, os, st->codecpar, &st->avg_frame_rate);
1343 // Fill in a heuristic guess of the packet duration, if none is available.
1344 // The mp4 muxer will do something similar (for the last packet in a fragment)
1345 // if nothing is set (setting it for the other packets doesn't hurt).
1346 // By setting a nonzero duration here, we can be sure that the mp4 muxer won't
1347 // invoke its heuristic (this doesn't have to be identical to that algorithm),
1348 // so that we know the exact timestamps of fragments.
1349 if (!pkt->duration && os->last_dts != AV_NOPTS_VALUE)
1350 pkt->duration = pkt->dts - os->last_dts;
1351 os->last_dts = pkt->dts;
1353 // If forcing the stream to start at 0, the mp4 muxer will set the start
1354 // timestamps to 0. Do the same here, to avoid mismatches in duration/timestamps.
1355 if (os->first_pts == AV_NOPTS_VALUE &&
1356 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
1357 pkt->pts -= pkt->dts;
1361 if (os->first_pts == AV_NOPTS_VALUE)
1362 os->first_pts = pkt->pts;
1363 os->last_pts = pkt->pts;
1365 if (!c->availability_start_time[0])
1366 format_date_now(c->availability_start_time,
1367 sizeof(c->availability_start_time));
1369 if (!os->availability_time_offset && pkt->duration) {
1370 int64_t frame_duration = av_rescale_q(pkt->duration, st->time_base,
1372 os->availability_time_offset = ((double) c->seg_duration -
1373 frame_duration) / AV_TIME_BASE;
1376 if (c->use_template && !c->use_timeline) {
1377 elapsed_duration = pkt->pts - os->first_pts;
1378 seg_end_duration = (int64_t) os->segment_index * c->seg_duration;
1380 elapsed_duration = pkt->pts - os->start_pts;
1381 seg_end_duration = c->seg_duration;
1384 if ((!c->has_video || st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) &&
1385 pkt->flags & AV_PKT_FLAG_KEY && os->packets_written &&
1386 av_compare_ts(elapsed_duration, st->time_base,
1387 seg_end_duration, AV_TIME_BASE_Q) >= 0) {
1388 int64_t prev_duration = c->last_duration;
1390 c->last_duration = av_rescale_q(pkt->pts - os->start_pts,
1393 c->total_duration = av_rescale_q(pkt->pts - os->first_pts,
1397 if ((!c->use_timeline || !c->use_template) && prev_duration) {
1398 if (c->last_duration < prev_duration*9/10 ||
1399 c->last_duration > prev_duration*11/10) {
1400 av_log(s, AV_LOG_WARNING,
1401 "Segment durations differ too much, enable use_timeline "
1402 "and use_template, or keep a stricter keyframe interval\n");
1406 if ((ret = dash_flush(s, 0, pkt->stream_index)) < 0)
1410 if (!os->packets_written) {
1411 // If we wrote a previous segment, adjust the start time of the segment
1412 // to the end of the previous one (which is the same as the mp4 muxer
1413 // does). This avoids gaps in the timeline.
1414 if (os->max_pts != AV_NOPTS_VALUE)
1415 os->start_pts = os->max_pts;
1417 os->start_pts = pkt->pts;
1419 if (os->max_pts == AV_NOPTS_VALUE)
1420 os->max_pts = pkt->pts + pkt->duration;
1422 os->max_pts = FFMAX(os->max_pts, pkt->pts + pkt->duration);
1423 os->packets_written++;
1424 os->total_pkt_size += pkt->size;
1425 if ((ret = ff_write_chained(os->ctx, 0, pkt, s, 0)) < 0)
1428 if (!os->init_range_length)
1429 flush_init_segment(s, os);
1431 //open the output context when the first frame of a segment is ready
1432 if (!c->single_file && os->packets_written == 1) {
1433 AVDictionary *opts = NULL;
1434 const char *proto = avio_find_protocol_name(s->url);
1435 int use_rename = proto && !strcmp(proto, "file");
1436 os->filename[0] = os->full_path[0] = os->temp_path[0] = '\0';
1437 ff_dash_fill_tmpl_params(os->filename, sizeof(os->filename),
1438 c->media_seg_name, pkt->stream_index,
1439 os->segment_index, os->bit_rate, os->start_pts);
1440 snprintf(os->full_path, sizeof(os->full_path), "%s%s", c->dirname,
1442 snprintf(os->temp_path, sizeof(os->temp_path),
1443 use_rename ? "%s.tmp" : "%s", os->full_path);
1444 set_http_options(&opts, c);
1445 ret = dashenc_io_open(s, &os->out, os->temp_path, &opts);
1448 av_dict_free(&opts);
1451 //write out the data immediately in streaming mode
1452 if (c->streaming && !strcmp(os->format_name, "mp4")) {
1454 uint8_t *buf = NULL;
1455 if (!os->written_len)
1456 write_styp(os->ctx->pb);
1457 avio_flush(os->ctx->pb);
1458 len = avio_get_dyn_buf (os->ctx->pb, &buf);
1459 avio_write(os->out, buf + os->written_len, len - os->written_len);
1460 os->written_len = len;
1461 avio_flush(os->out);
1467 static int dash_write_trailer(AVFormatContext *s)
1469 DASHContext *c = s->priv_data;
1471 if (s->nb_streams > 0) {
1472 OutputStream *os = &c->streams[0];
1473 // If no segments have been written so far, try to do a crude
1474 // guess of the segment duration
1475 if (!c->last_duration)
1476 c->last_duration = av_rescale_q(os->max_pts - os->start_pts,
1477 s->streams[0]->time_base,
1479 c->total_duration = av_rescale_q(os->max_pts - os->first_pts,
1480 s->streams[0]->time_base,
1483 dash_flush(s, 1, -1);
1485 if (c->remove_at_exit) {
1486 char filename[1024];
1488 for (i = 0; i < s->nb_streams; i++) {
1489 OutputStream *os = &c->streams[i];
1490 snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
1491 dashenc_delete_file(s, filename);
1493 dashenc_delete_file(s, s->url);
1499 static int dash_check_bitstream(struct AVFormatContext *s, const AVPacket *avpkt)
1501 DASHContext *c = s->priv_data;
1502 OutputStream *os = &c->streams[avpkt->stream_index];
1503 AVFormatContext *oc = os->ctx;
1504 if (oc->oformat->check_bitstream) {
1506 AVPacket pkt = *avpkt;
1507 pkt.stream_index = 0;
1508 ret = oc->oformat->check_bitstream(oc, &pkt);
1510 AVStream *st = s->streams[avpkt->stream_index];
1511 AVStream *ost = oc->streams[0];
1512 st->internal->bsfcs = ost->internal->bsfcs;
1513 st->internal->nb_bsfcs = ost->internal->nb_bsfcs;
1514 ost->internal->bsfcs = NULL;
1515 ost->internal->nb_bsfcs = 0;
1522 #define OFFSET(x) offsetof(DASHContext, x)
1523 #define E AV_OPT_FLAG_ENCODING_PARAM
1524 static const AVOption options[] = {
1525 { "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 },
1526 { "window_size", "number of segments kept in the manifest", OFFSET(window_size), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, E },
1527 { "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 },
1528 #if FF_API_DASH_MIN_SEG_DURATION
1529 { "min_seg_duration", "minimum segment duration (in microseconds) (will be deprecated)", OFFSET(min_seg_duration), AV_OPT_TYPE_INT, { .i64 = 5000000 }, 0, INT_MAX, E },
1531 { "seg_duration", "segment duration (in seconds, fractional value can be set)", OFFSET(seg_duration), AV_OPT_TYPE_DURATION, { .i64 = 5000000 }, 0, INT_MAX, E },
1532 { "remove_at_exit", "remove all segments when finished", OFFSET(remove_at_exit), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
1533 { "use_template", "Use SegmentTemplate instead of SegmentList", OFFSET(use_template), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, E },
1534 { "use_timeline", "Use SegmentTimeline in SegmentTemplate", OFFSET(use_timeline), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, E },
1535 { "single_file", "Store all segments in one file, accessed using byte ranges", OFFSET(single_file), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
1536 { "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 },
1537 { "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 },
1538 { "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 },
1539 { "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 },
1540 { "method", "set the HTTP method", OFFSET(method), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
1541 { "http_user_agent", "override User-Agent field in HTTP header", OFFSET(user_agent), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
1542 { "http_persistent", "Use persistent HTTP connections", OFFSET(http_persistent), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, E },
1543 { "hls_playlist", "Generate HLS playlist files(master.m3u8, media_%d.m3u8)", OFFSET(hls_playlist), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
1544 { "streaming", "Enable/Disable streaming mode of output. Each frame will be moof fragment", OFFSET(streaming), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
1545 { "timeout", "set timeout for socket I/O operations", OFFSET(timeout), AV_OPT_TYPE_DURATION, { .i64 = -1 }, -1, INT_MAX, .flags = E },
1546 { "index_correction", "Enable/Disable segment index correction logic", OFFSET(index_correction), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
1547 { "format_options","set list of options for the container format (mp4/webm) used for dash", OFFSET(format_options_str), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
1551 static const AVClass dash_class = {
1552 .class_name = "dash muxer",
1553 .item_name = av_default_item_name,
1555 .version = LIBAVUTIL_VERSION_INT,
1558 AVOutputFormat ff_dash_muxer = {
1560 .long_name = NULL_IF_CONFIG_SMALL("DASH Muxer"),
1561 .extensions = "mpd",
1562 .priv_data_size = sizeof(DASHContext),
1563 .audio_codec = AV_CODEC_ID_AAC,
1564 .video_codec = AV_CODEC_ID_H264,
1565 .flags = AVFMT_GLOBALHEADER | AVFMT_NOFILE | AVFMT_TS_NEGATIVE,
1567 .write_header = dash_write_header,
1568 .write_packet = dash_write_packet,
1569 .write_trailer = dash_write_trailer,
1570 .deinit = dash_free,
1571 .check_bitstream = dash_check_bitstream,
1572 .priv_class = &dash_class,