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"
50 typedef struct Segment {
53 int range_length, index_length;
59 typedef struct AdaptationSet {
61 enum AVMediaType media_type;
62 AVDictionary *metadata;
63 AVRational min_frame_rate, max_frame_rate;
64 int ambiguous_frame_rate;
67 typedef struct OutputStream {
69 int ctx_inited, as_idx;
74 int64_t init_start_pos, pos;
75 int init_range_length;
76 int nb_segments, segments_size, segment_index;
78 int64_t first_pts, start_pts, max_pts;
81 char bandwidth_str[64];
88 double availability_time_offset;
91 typedef struct DASHContext {
92 const AVClass *class; /* Class for private options. */
93 char *adaptation_sets;
97 int extra_window_size;
98 #if FF_API_DASH_MIN_SEG_DURATION
101 int64_t seg_duration;
106 OutputStream *streams;
108 int64_t last_duration;
109 int64_t total_duration;
110 char availability_start_time[100];
112 const char *single_file_name;
113 const char *init_seg_name;
114 const char *media_seg_name;
115 const char *utc_timing_url;
117 const char *user_agent;
120 int master_playlist_created;
121 AVIOContext *mpd_out;
122 AVIOContext *m3u8_out;
127 static struct codec_string {
131 { AV_CODEC_ID_VP8, "vp8" },
132 { AV_CODEC_ID_VP9, "vp9" },
133 { AV_CODEC_ID_VORBIS, "vorbis" },
134 { AV_CODEC_ID_OPUS, "opus" },
138 static int dashenc_io_open(AVFormatContext *s, AVIOContext **pb, char *filename,
139 AVDictionary **options) {
140 DASHContext *c = s->priv_data;
141 int http_base_proto = filename ? ff_is_http_proto(filename) : 0;
142 int err = AVERROR_MUXER_NOT_FOUND;
143 if (!*pb || !http_base_proto || !c->http_persistent) {
144 err = s->io_open(s, pb, filename, AVIO_FLAG_WRITE, options);
145 #if CONFIG_HTTP_PROTOCOL
147 URLContext *http_url_context = ffio_geturlcontext(*pb);
148 av_assert0(http_url_context);
149 err = ff_http_do_new_request(http_url_context, filename);
155 static void dashenc_io_close(AVFormatContext *s, AVIOContext **pb, char *filename) {
156 DASHContext *c = s->priv_data;
157 int http_base_proto = filename ? ff_is_http_proto(filename) : 0;
159 if (!http_base_proto || !c->http_persistent) {
160 ff_format_io_close(s, pb);
161 #if CONFIG_HTTP_PROTOCOL
163 URLContext *http_url_context = ffio_geturlcontext(*pb);
164 av_assert0(http_url_context);
166 ffurl_shutdown(http_url_context, AVIO_FLAG_WRITE);
171 static void set_codec_str(AVFormatContext *s, AVCodecParameters *par,
174 const AVCodecTag *tags[2] = { NULL, NULL };
178 // common Webm codecs are not part of RFC 6381
179 for (i = 0; codecs[i].id; i++)
180 if (codecs[i].id == par->codec_id) {
181 av_strlcpy(str, codecs[i].str, size);
185 // for codecs part of RFC 6381
186 if (par->codec_type == AVMEDIA_TYPE_VIDEO)
187 tags[0] = ff_codec_movvideo_tags;
188 else if (par->codec_type == AVMEDIA_TYPE_AUDIO)
189 tags[0] = ff_codec_movaudio_tags;
193 tag = av_codec_get_tag(tags, par->codec_id);
201 if (!strcmp(str, "mp4a") || !strcmp(str, "mp4v")) {
203 tags[0] = ff_mp4_obj_type;
204 oti = av_codec_get_tag(tags, par->codec_id);
206 av_strlcatf(str, size, ".%02"PRIx32, oti);
210 if (tag == MKTAG('m', 'p', '4', 'a')) {
211 if (par->extradata_size >= 2) {
212 int aot = par->extradata[0] >> 3;
214 aot = ((AV_RB16(par->extradata) >> 5) & 0x3f) + 32;
215 av_strlcatf(str, size, ".%d", aot);
217 } else if (tag == MKTAG('m', 'p', '4', 'v')) {
218 // Unimplemented, should output ProfileLevelIndication as a decimal number
219 av_log(s, AV_LOG_WARNING, "Incomplete RFC 6381 codec string for mp4v\n");
221 } else if (!strcmp(str, "avc1")) {
222 uint8_t *tmpbuf = NULL;
223 uint8_t *extradata = par->extradata;
224 int extradata_size = par->extradata_size;
227 if (extradata[0] != 1) {
229 if (avio_open_dyn_buf(&pb) < 0)
231 if (ff_isom_write_avcc(pb, extradata, extradata_size) < 0) {
232 ffio_free_dyn_buf(&pb);
235 extradata_size = avio_close_dyn_buf(pb, &extradata);
239 if (extradata_size >= 4)
240 av_strlcatf(str, size, ".%02x%02x%02x",
241 extradata[1], extradata[2], extradata[3]);
246 static int flush_dynbuf(OutputStream *os, int *range_length)
251 return AVERROR(EINVAL);
255 av_write_frame(os->ctx, NULL);
256 avio_flush(os->ctx->pb);
259 *range_length = avio_close_dyn_buf(os->ctx->pb, &buffer);
261 avio_write(os->out, buffer + os->written_len, *range_length - os->written_len);
266 return avio_open_dyn_buf(&os->ctx->pb);
269 static void set_http_options(AVDictionary **options, DASHContext *c)
272 av_dict_set(options, "method", c->method, 0);
274 av_dict_set(options, "user_agent", c->user_agent, 0);
275 if (c->http_persistent)
276 av_dict_set_int(options, "multiple_requests", 1, 0);
278 av_dict_set_int(options, "timeout", c->timeout, 0);
281 static void get_hls_playlist_name(char *playlist_name, int string_size,
282 const char *base_url, int id) {
284 snprintf(playlist_name, string_size, "%smedia_%d.m3u8", base_url, id);
286 snprintf(playlist_name, string_size, "media_%d.m3u8", id);
289 static int flush_init_segment(AVFormatContext *s, OutputStream *os)
291 DASHContext *c = s->priv_data;
292 int ret, range_length;
294 ret = flush_dynbuf(os, &range_length);
298 os->pos = os->init_range_length = range_length;
300 ff_format_io_close(s, &os->out);
304 static void dash_free(AVFormatContext *s)
306 DASHContext *c = s->priv_data;
310 for (i = 0; i < c->nb_as; i++)
311 av_dict_free(&c->as[i].metadata);
318 for (i = 0; i < s->nb_streams; i++) {
319 OutputStream *os = &c->streams[i];
320 if (os->ctx && os->ctx_inited)
321 av_write_trailer(os->ctx);
322 if (os->ctx && os->ctx->pb)
323 ffio_free_dyn_buf(&os->ctx->pb);
324 ff_format_io_close(s, &os->out);
326 avformat_free_context(os->ctx);
327 for (j = 0; j < os->nb_segments; j++)
328 av_free(os->segments[j]);
329 av_free(os->segments);
331 av_freep(&c->streams);
333 ff_format_io_close(s, &c->mpd_out);
334 ff_format_io_close(s, &c->m3u8_out);
337 static void output_segment_list(OutputStream *os, AVIOContext *out, AVFormatContext *s,
338 int representation_id, int final)
340 DASHContext *c = s->priv_data;
341 int i, start_index = 0, start_number = 1;
342 if (c->window_size) {
343 start_index = FFMAX(os->nb_segments - c->window_size, 0);
344 start_number = FFMAX(os->segment_index - c->window_size, 1);
347 if (c->use_template) {
348 int timescale = c->use_timeline ? os->ctx->streams[0]->time_base.den : AV_TIME_BASE;
349 avio_printf(out, "\t\t\t\t<SegmentTemplate timescale=\"%d\" ", timescale);
350 if (!c->use_timeline) {
351 avio_printf(out, "duration=\"%"PRId64"\" ", c->seg_duration);
352 if (c->streaming && os->availability_time_offset)
353 avio_printf(out, "availabilityTimeOffset=\"%.3f\" ",
354 os->availability_time_offset);
356 avio_printf(out, "initialization=\"%s\" media=\"%s\" startNumber=\"%d\">\n", c->init_seg_name, c->media_seg_name, c->use_timeline ? start_number : 1);
357 if (c->use_timeline) {
358 int64_t cur_time = 0;
359 avio_printf(out, "\t\t\t\t\t<SegmentTimeline>\n");
360 for (i = start_index; i < os->nb_segments; ) {
361 Segment *seg = os->segments[i];
363 avio_printf(out, "\t\t\t\t\t\t<S ");
364 if (i == start_index || seg->time != cur_time) {
365 cur_time = seg->time;
366 avio_printf(out, "t=\"%"PRId64"\" ", seg->time);
368 avio_printf(out, "d=\"%d\" ", seg->duration);
369 while (i + repeat + 1 < os->nb_segments &&
370 os->segments[i + repeat + 1]->duration == seg->duration &&
371 os->segments[i + repeat + 1]->time == os->segments[i + repeat]->time + os->segments[i + repeat]->duration)
374 avio_printf(out, "r=\"%d\" ", repeat);
375 avio_printf(out, "/>\n");
377 cur_time += (1 + repeat) * seg->duration;
379 avio_printf(out, "\t\t\t\t\t</SegmentTimeline>\n");
381 avio_printf(out, "\t\t\t\t</SegmentTemplate>\n");
382 } else if (c->single_file) {
383 avio_printf(out, "\t\t\t\t<BaseURL>%s</BaseURL>\n", os->initfile);
384 avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%"PRId64"\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);
385 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);
386 for (i = start_index; i < os->nb_segments; i++) {
387 Segment *seg = os->segments[i];
388 avio_printf(out, "\t\t\t\t\t<SegmentURL mediaRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->range_length - 1);
389 if (seg->index_length)
390 avio_printf(out, "indexRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->index_length - 1);
391 avio_printf(out, "/>\n");
393 avio_printf(out, "\t\t\t\t</SegmentList>\n");
395 avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%"PRId64"\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);
396 avio_printf(out, "\t\t\t\t\t<Initialization sourceURL=\"%s\" />\n", os->initfile);
397 for (i = start_index; i < os->nb_segments; i++) {
398 Segment *seg = os->segments[i];
399 avio_printf(out, "\t\t\t\t\t<SegmentURL media=\"%s\" />\n", seg->file);
401 avio_printf(out, "\t\t\t\t</SegmentList>\n");
403 if (c->hls_playlist && start_index < os->nb_segments)
405 int timescale = os->ctx->streams[0]->time_base.den;
406 char temp_filename_hls[1024];
407 char filename_hls[1024];
408 AVDictionary *http_opts = NULL;
409 int target_duration = 0;
411 const char *proto = avio_find_protocol_name(c->dirname);
412 int use_rename = proto && !strcmp(proto, "file");
414 get_hls_playlist_name(filename_hls, sizeof(filename_hls),
415 c->dirname, representation_id);
417 snprintf(temp_filename_hls, sizeof(temp_filename_hls), use_rename ? "%s.tmp" : "%s", filename_hls);
419 set_http_options(&http_opts, c);
420 dashenc_io_open(s, &c->m3u8_out, temp_filename_hls, &http_opts);
421 av_dict_free(&http_opts);
422 for (i = start_index; i < os->nb_segments; i++) {
423 Segment *seg = os->segments[i];
424 double duration = (double) seg->duration / timescale;
425 if (target_duration <= duration)
426 target_duration = lrint(duration);
429 ff_hls_write_playlist_header(c->m3u8_out, 6, -1, target_duration,
430 start_number, PLAYLIST_TYPE_NONE);
432 ff_hls_write_init_file(c->m3u8_out, os->initfile, c->single_file,
433 os->init_range_length, os->init_start_pos);
435 for (i = start_index; i < os->nb_segments; i++) {
436 Segment *seg = os->segments[i];
437 ret = ff_hls_write_file_entry(c->m3u8_out, 0, c->single_file,
438 (double) seg->duration / timescale, 0,
439 seg->range_length, seg->start_pos, NULL,
440 c->single_file ? os->initfile : seg->file,
443 av_log(os->ctx, AV_LOG_WARNING, "ff_hls_write_file_entry get error\n");
448 ff_hls_write_end_list(c->m3u8_out);
450 dashenc_io_close(s, &c->m3u8_out, temp_filename_hls);
453 if (avpriv_io_move(temp_filename_hls, filename_hls) < 0) {
454 av_log(os->ctx, AV_LOG_WARNING, "renaming file %s to %s failed\n\n", temp_filename_hls, filename_hls);
460 static char *xmlescape(const char *str) {
461 int outlen = strlen(str)*3/2 + 6;
462 char *out = av_realloc(NULL, outlen + 1);
466 for (; *str; str++) {
467 if (pos + 6 > outlen) {
469 outlen = 2 * outlen + 6;
470 tmp = av_realloc(out, outlen + 1);
478 memcpy(&out[pos], "&", 5);
480 } else if (*str == '<') {
481 memcpy(&out[pos], "<", 4);
483 } else if (*str == '>') {
484 memcpy(&out[pos], ">", 4);
486 } else if (*str == '\'') {
487 memcpy(&out[pos], "'", 6);
489 } else if (*str == '\"') {
490 memcpy(&out[pos], """, 6);
500 static void write_time(AVIOContext *out, int64_t time)
502 int seconds = time / AV_TIME_BASE;
503 int fractions = time % AV_TIME_BASE;
504 int minutes = seconds / 60;
505 int hours = minutes / 60;
508 avio_printf(out, "PT");
510 avio_printf(out, "%dH", hours);
511 if (hours || minutes)
512 avio_printf(out, "%dM", minutes);
513 avio_printf(out, "%d.%dS", seconds, fractions / (AV_TIME_BASE / 10));
516 static void format_date_now(char *buf, int size)
518 time_t t = time(NULL);
519 struct tm *ptm, tmbuf;
520 ptm = gmtime_r(&t, &tmbuf);
522 if (!strftime(buf, size, "%Y-%m-%dT%H:%M:%SZ", ptm))
527 static int write_adaptation_set(AVFormatContext *s, AVIOContext *out, int as_index,
530 DASHContext *c = s->priv_data;
531 AdaptationSet *as = &c->as[as_index];
532 AVDictionaryEntry *lang, *role;
535 avio_printf(out, "\t\t<AdaptationSet id=\"%s\" contentType=\"%s\" segmentAlignment=\"true\" bitstreamSwitching=\"true\"",
536 as->id, as->media_type == AVMEDIA_TYPE_VIDEO ? "video" : "audio");
537 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)
538 avio_printf(out, " maxFrameRate=\"%d/%d\"", as->max_frame_rate.num, as->max_frame_rate.den);
539 lang = av_dict_get(as->metadata, "language", NULL, 0);
541 avio_printf(out, " lang=\"%s\"", lang->value);
542 avio_printf(out, ">\n");
544 role = av_dict_get(as->metadata, "role", NULL, 0);
546 avio_printf(out, "\t\t\t<Role schemeIdUri=\"urn:mpeg:dash:role:2011\" value=\"%s\"/>\n", role->value);
548 for (i = 0; i < s->nb_streams; i++) {
549 OutputStream *os = &c->streams[i];
551 if (os->as_idx - 1 != as_index)
554 if (as->media_type == AVMEDIA_TYPE_VIDEO) {
555 AVStream *st = s->streams[i];
556 avio_printf(out, "\t\t\t<Representation id=\"%d\" mimeType=\"video/%s\" codecs=\"%s\"%s width=\"%d\" height=\"%d\"",
557 i, os->format_name, os->codec_str, os->bandwidth_str, s->streams[i]->codecpar->width, s->streams[i]->codecpar->height);
558 if (st->avg_frame_rate.num)
559 avio_printf(out, " frameRate=\"%d/%d\"", st->avg_frame_rate.num, st->avg_frame_rate.den);
560 avio_printf(out, ">\n");
562 avio_printf(out, "\t\t\t<Representation id=\"%d\" mimeType=\"audio/%s\" codecs=\"%s\"%s audioSamplingRate=\"%d\">\n",
563 i, os->format_name, os->codec_str, os->bandwidth_str, s->streams[i]->codecpar->sample_rate);
564 avio_printf(out, "\t\t\t\t<AudioChannelConfiguration schemeIdUri=\"urn:mpeg:dash:23003:3:audio_channel_configuration:2011\" value=\"%d\" />\n",
565 s->streams[i]->codecpar->channels);
567 output_segment_list(os, out, s, i, final);
568 avio_printf(out, "\t\t\t</Representation>\n");
570 avio_printf(out, "\t\t</AdaptationSet>\n");
575 static int add_adaptation_set(AVFormatContext *s, AdaptationSet **as, enum AVMediaType type)
577 DASHContext *c = s->priv_data;
579 void *mem = av_realloc(c->as, sizeof(*c->as) * (c->nb_as + 1));
581 return AVERROR(ENOMEM);
585 *as = &c->as[c->nb_as - 1];
586 memset(*as, 0, sizeof(**as));
587 (*as)->media_type = type;
592 static int adaptation_set_add_stream(AVFormatContext *s, int as_idx, int i)
594 DASHContext *c = s->priv_data;
595 AdaptationSet *as = &c->as[as_idx - 1];
596 OutputStream *os = &c->streams[i];
598 if (as->media_type != s->streams[i]->codecpar->codec_type) {
599 av_log(s, AV_LOG_ERROR, "Codec type of stream %d doesn't match AdaptationSet's media type\n", i);
600 return AVERROR(EINVAL);
601 } else if (os->as_idx) {
602 av_log(s, AV_LOG_ERROR, "Stream %d is already assigned to an AdaptationSet\n", i);
603 return AVERROR(EINVAL);
610 static int parse_adaptation_sets(AVFormatContext *s)
612 DASHContext *c = s->priv_data;
613 const char *p = c->adaptation_sets;
614 enum { new_set, parse_id, parsing_streams } state;
618 // default: one AdaptationSet for each stream
620 for (i = 0; i < s->nb_streams; i++) {
621 if ((ret = add_adaptation_set(s, &as, s->streams[i]->codecpar->codec_type)) < 0)
623 snprintf(as->id, sizeof(as->id), "%d", i);
625 c->streams[i].as_idx = c->nb_as;
630 // syntax id=0,streams=0,1,2 id=1,streams=3,4 and so on
636 } else if (state == new_set && av_strstart(p, "id=", &p)) {
638 if ((ret = add_adaptation_set(s, &as, AVMEDIA_TYPE_UNKNOWN)) < 0)
642 snprintf(as->id, sizeof(as->id), "%.*s", n, p);
648 } else if (state == parse_id && av_strstart(p, "streams=", &p)) {
649 state = parsing_streams;
650 } else if (state == parsing_streams) {
651 AdaptationSet *as = &c->as[c->nb_as - 1];
652 char idx_str[8], *end_str;
654 n = strcspn(p, " ,");
655 snprintf(idx_str, sizeof(idx_str), "%.*s", n, p);
658 // if value is "a" or "v", map all streams of that type
659 if (as->media_type == AVMEDIA_TYPE_UNKNOWN && (idx_str[0] == 'v' || idx_str[0] == 'a')) {
660 enum AVMediaType type = (idx_str[0] == 'v') ? AVMEDIA_TYPE_VIDEO : AVMEDIA_TYPE_AUDIO;
661 av_log(s, AV_LOG_DEBUG, "Map all streams of type %s\n", idx_str);
663 for (i = 0; i < s->nb_streams; i++) {
664 if (s->streams[i]->codecpar->codec_type != type)
667 as->media_type = s->streams[i]->codecpar->codec_type;
669 if ((ret = adaptation_set_add_stream(s, c->nb_as, i)) < 0)
672 } else { // select single stream
673 i = strtol(idx_str, &end_str, 10);
674 if (idx_str == end_str || i < 0 || i >= s->nb_streams) {
675 av_log(s, AV_LOG_ERROR, "Selected stream \"%s\" not found!\n", idx_str);
676 return AVERROR(EINVAL);
678 av_log(s, AV_LOG_DEBUG, "Map stream %d\n", i);
680 if (as->media_type == AVMEDIA_TYPE_UNKNOWN) {
681 as->media_type = s->streams[i]->codecpar->codec_type;
684 if ((ret = adaptation_set_add_stream(s, c->nb_as, i)) < 0)
693 return AVERROR(EINVAL);
698 // check for unassigned streams
699 for (i = 0; i < s->nb_streams; i++) {
700 OutputStream *os = &c->streams[i];
702 av_log(s, AV_LOG_ERROR, "Stream %d is not mapped to an AdaptationSet\n", i);
703 return AVERROR(EINVAL);
709 static int write_manifest(AVFormatContext *s, int final)
711 DASHContext *c = s->priv_data;
713 char temp_filename[1024];
715 const char *proto = avio_find_protocol_name(s->url);
716 int use_rename = proto && !strcmp(proto, "file");
717 static unsigned int warned_non_file = 0;
718 AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
719 AVDictionary *opts = NULL;
721 if (!use_rename && !warned_non_file++)
722 av_log(s, AV_LOG_ERROR, "Cannot use rename on non file protocol, this may lead to races and temporary partial files\n");
724 snprintf(temp_filename, sizeof(temp_filename), use_rename ? "%s.tmp" : "%s", s->url);
725 set_http_options(&opts, c);
726 ret = dashenc_io_open(s, &c->mpd_out, temp_filename, &opts);
728 av_log(s, AV_LOG_ERROR, "Unable to open %s for writing\n", temp_filename);
733 avio_printf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
734 avio_printf(out, "<MPD xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
735 "\txmlns=\"urn:mpeg:dash:schema:mpd:2011\"\n"
736 "\txmlns:xlink=\"http://www.w3.org/1999/xlink\"\n"
737 "\txsi:schemaLocation=\"urn:mpeg:DASH:schema:MPD:2011 http://standards.iso.org/ittf/PubliclyAvailableStandards/MPEG-DASH_schema_files/DASH-MPD.xsd\"\n"
738 "\tprofiles=\"urn:mpeg:dash:profile:isoff-live:2011\"\n"
739 "\ttype=\"%s\"\n", final ? "static" : "dynamic");
741 avio_printf(out, "\tmediaPresentationDuration=\"");
742 write_time(out, c->total_duration);
743 avio_printf(out, "\"\n");
745 int64_t update_period = c->last_duration / AV_TIME_BASE;
747 if (c->use_template && !c->use_timeline)
749 avio_printf(out, "\tminimumUpdatePeriod=\"PT%"PRId64"S\"\n", update_period);
750 avio_printf(out, "\tsuggestedPresentationDelay=\"PT%"PRId64"S\"\n", c->last_duration / AV_TIME_BASE);
751 if (c->availability_start_time[0])
752 avio_printf(out, "\tavailabilityStartTime=\"%s\"\n", c->availability_start_time);
753 format_date_now(now_str, sizeof(now_str));
755 avio_printf(out, "\tpublishTime=\"%s\"\n", now_str);
756 if (c->window_size && c->use_template) {
757 avio_printf(out, "\ttimeShiftBufferDepth=\"");
758 write_time(out, c->last_duration * c->window_size);
759 avio_printf(out, "\"\n");
762 avio_printf(out, "\tminBufferTime=\"");
763 write_time(out, c->last_duration * 2);
764 avio_printf(out, "\">\n");
765 avio_printf(out, "\t<ProgramInformation>\n");
767 char *escaped = xmlescape(title->value);
768 avio_printf(out, "\t\t<Title>%s</Title>\n", escaped);
771 avio_printf(out, "\t</ProgramInformation>\n");
773 if (c->window_size && s->nb_streams > 0 && c->streams[0].nb_segments > 0 && !c->use_template) {
774 OutputStream *os = &c->streams[0];
775 int start_index = FFMAX(os->nb_segments - c->window_size, 0);
776 int64_t start_time = av_rescale_q(os->segments[start_index]->time, s->streams[0]->time_base, AV_TIME_BASE_Q);
777 avio_printf(out, "\t<Period id=\"0\" start=\"");
778 write_time(out, start_time);
779 avio_printf(out, "\">\n");
781 avio_printf(out, "\t<Period id=\"0\" start=\"PT0.0S\">\n");
784 for (i = 0; i < c->nb_as; i++) {
785 if ((ret = write_adaptation_set(s, out, i, final)) < 0)
788 avio_printf(out, "\t</Period>\n");
790 if (c->utc_timing_url)
791 avio_printf(out, "\t<UTCTiming schemeIdUri=\"urn:mpeg:dash:utc:http-xsdate:2014\" value=\"%s\"/>\n", c->utc_timing_url);
793 avio_printf(out, "</MPD>\n");
795 dashenc_io_close(s, &c->mpd_out, temp_filename);
798 if ((ret = avpriv_io_move(temp_filename, s->url)) < 0)
802 if (c->hls_playlist && !c->master_playlist_created) {
803 char filename_hls[1024];
804 const char *audio_group = "A1";
806 int max_audio_bitrate = 0;
809 snprintf(filename_hls, sizeof(filename_hls), "%s/master.m3u8", c->dirname);
811 snprintf(filename_hls, sizeof(filename_hls), "master.m3u8");
813 snprintf(temp_filename, sizeof(temp_filename), use_rename ? "%s.tmp" : "%s", filename_hls);
815 set_http_options(&opts, c);
816 ret = avio_open2(&out, temp_filename, AVIO_FLAG_WRITE, NULL, &opts);
818 av_log(s, AV_LOG_ERROR, "Unable to open %s for writing\n", temp_filename);
823 ff_hls_write_playlist_version(out, 6);
825 for (i = 0; i < s->nb_streams; i++) {
826 char playlist_file[64];
827 AVStream *st = s->streams[i];
828 if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO)
830 get_hls_playlist_name(playlist_file, sizeof(playlist_file), NULL, i);
831 ff_hls_write_audio_rendition(out, (char *)audio_group,
832 playlist_file, i, is_default);
833 max_audio_bitrate = FFMAX(st->codecpar->bit_rate, max_audio_bitrate);
837 for (i = 0; i < s->nb_streams; i++) {
838 char playlist_file[64];
839 AVStream *st = s->streams[i];
841 int stream_bitrate = st->codecpar->bit_rate;
842 if ((st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) && max_audio_bitrate) {
843 agroup = (char *)audio_group;
844 stream_bitrate += max_audio_bitrate;
846 get_hls_playlist_name(playlist_file, sizeof(playlist_file), NULL, i);
847 ff_hls_write_stream_info(st, out, stream_bitrate, playlist_file, agroup, NULL, NULL);
851 if ((ret = avpriv_io_move(temp_filename, filename_hls)) < 0)
853 c->master_playlist_created = 1;
859 static int dict_copy_entry(AVDictionary **dst, const AVDictionary *src, const char *key)
861 AVDictionaryEntry *entry = av_dict_get(src, key, NULL, 0);
863 av_dict_set(dst, key, entry->value, AV_DICT_DONT_OVERWRITE);
867 static int dash_init(AVFormatContext *s)
869 DASHContext *c = s->priv_data;
874 if (c->single_file_name)
879 #if FF_API_DASH_MIN_SEG_DURATION
880 if (c->min_seg_duration != 5000000) {
881 av_log(s, AV_LOG_WARNING, "The min_seg_duration option is deprecated and will be removed. Please use the -seg_duration\n");
882 c->seg_duration = c->min_seg_duration;
886 av_strlcpy(c->dirname, s->url, sizeof(c->dirname));
887 ptr = strrchr(c->dirname, '/');
889 av_strlcpy(basename, &ptr[1], sizeof(basename));
892 c->dirname[0] = '\0';
893 av_strlcpy(basename, s->url, sizeof(basename));
896 ptr = strrchr(basename, '.');
900 c->streams = av_mallocz(sizeof(*c->streams) * s->nb_streams);
902 return AVERROR(ENOMEM);
904 if ((ret = parse_adaptation_sets(s)) < 0)
907 for (i = 0; i < s->nb_streams; i++) {
908 OutputStream *os = &c->streams[i];
909 AdaptationSet *as = &c->as[os->as_idx - 1];
910 AVFormatContext *ctx;
912 AVDictionary *opts = NULL;
915 os->bit_rate = s->streams[i]->codecpar->bit_rate;
917 snprintf(os->bandwidth_str, sizeof(os->bandwidth_str),
918 " bandwidth=\"%d\"", os->bit_rate);
920 int level = s->strict_std_compliance >= FF_COMPLIANCE_STRICT ?
921 AV_LOG_ERROR : AV_LOG_WARNING;
922 av_log(s, level, "No bit rate set for stream %d\n", i);
923 if (s->strict_std_compliance >= FF_COMPLIANCE_STRICT)
924 return AVERROR(EINVAL);
927 // copy AdaptationSet language and role from stream metadata
928 dict_copy_entry(&as->metadata, s->streams[i]->metadata, "language");
929 dict_copy_entry(&as->metadata, s->streams[i]->metadata, "role");
931 ctx = avformat_alloc_context();
933 return AVERROR(ENOMEM);
935 // choose muxer based on codec: webm for VP8/9 and opus, mp4 otherwise
936 // note: os->format_name is also used as part of the mimetype of the
937 // representation, e.g. video/<format_name>
938 if (s->streams[i]->codecpar->codec_id == AV_CODEC_ID_VP8 ||
939 s->streams[i]->codecpar->codec_id == AV_CODEC_ID_VP9 ||
940 s->streams[i]->codecpar->codec_id == AV_CODEC_ID_OPUS ||
941 s->streams[i]->codecpar->codec_id == AV_CODEC_ID_VORBIS) {
942 snprintf(os->format_name, sizeof(os->format_name), "webm");
944 snprintf(os->format_name, sizeof(os->format_name), "mp4");
946 ctx->oformat = av_guess_format(os->format_name, NULL, NULL);
948 return AVERROR_MUXER_NOT_FOUND;
950 ctx->interrupt_callback = s->interrupt_callback;
951 ctx->opaque = s->opaque;
952 ctx->io_close = s->io_close;
953 ctx->io_open = s->io_open;
955 if (!(st = avformat_new_stream(ctx, NULL)))
956 return AVERROR(ENOMEM);
957 avcodec_parameters_copy(st->codecpar, s->streams[i]->codecpar);
958 st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
959 st->time_base = s->streams[i]->time_base;
960 st->avg_frame_rate = s->streams[i]->avg_frame_rate;
961 ctx->avoid_negative_ts = s->avoid_negative_ts;
962 ctx->flags = s->flags;
964 if ((ret = avio_open_dyn_buf(&ctx->pb)) < 0)
967 if (c->single_file) {
968 if (c->single_file_name)
969 ff_dash_fill_tmpl_params(os->initfile, sizeof(os->initfile), c->single_file_name, i, 0, os->bit_rate, 0);
971 snprintf(os->initfile, sizeof(os->initfile), "%s-stream%d.m4s", basename, i);
973 ff_dash_fill_tmpl_params(os->initfile, sizeof(os->initfile), c->init_seg_name, i, 0, os->bit_rate, 0);
975 snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
976 set_http_options(&opts, c);
977 ret = s->io_open(s, &os->out, filename, AVIO_FLAG_WRITE, &opts);
981 os->init_start_pos = 0;
983 if (!strcmp(os->format_name, "mp4")) {
985 av_dict_set(&opts, "movflags", "frag_every_frame+dash+delay_moov", 0);
987 av_dict_set(&opts, "movflags", "frag_custom+dash+delay_moov", 0);
989 av_dict_set_int(&opts, "cluster_time_limit", c->seg_duration / 1000, 0);
990 av_dict_set_int(&opts, "cluster_size_limit", 5 * 1024 * 1024, 0); // set a large cluster size limit
991 av_dict_set_int(&opts, "dash", 1, 0);
992 av_dict_set_int(&opts, "dash_track_number", i + 1, 0);
993 av_dict_set_int(&opts, "live", 1, 0);
995 if ((ret = avformat_init_output(ctx, &opts)) < 0)
1001 av_log(s, AV_LOG_VERBOSE, "Representation %d init segment will be written to: %s\n", i, filename);
1003 // Flush init segment
1004 // except for mp4, since delay_moov is set and the init segment
1005 // is then flushed after the first packets
1006 if (strcmp(os->format_name, "mp4")) {
1007 flush_init_segment(s, os);
1010 s->streams[i]->time_base = st->time_base;
1011 // If the muxer wants to shift timestamps, request to have them shifted
1012 // already before being handed to this muxer, so we don't have mismatches
1013 // between the MPD and the actual segments.
1014 s->avoid_negative_ts = ctx->avoid_negative_ts;
1015 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
1016 AVRational avg_frame_rate = s->streams[i]->avg_frame_rate;
1017 if (avg_frame_rate.num > 0) {
1018 if (av_cmp_q(avg_frame_rate, as->min_frame_rate) < 0)
1019 as->min_frame_rate = avg_frame_rate;
1020 if (av_cmp_q(as->max_frame_rate, avg_frame_rate) < 0)
1021 as->max_frame_rate = avg_frame_rate;
1023 as->ambiguous_frame_rate = 1;
1028 set_codec_str(s, st->codecpar, os->codec_str, sizeof(os->codec_str));
1029 os->first_pts = AV_NOPTS_VALUE;
1030 os->max_pts = AV_NOPTS_VALUE;
1031 os->last_dts = AV_NOPTS_VALUE;
1032 os->segment_index = 1;
1035 if (!c->has_video && c->seg_duration <= 0) {
1036 av_log(s, AV_LOG_WARNING, "no video stream and no seg duration set\n");
1037 return AVERROR(EINVAL);
1042 static int dash_write_header(AVFormatContext *s)
1044 DASHContext *c = s->priv_data;
1046 for (i = 0; i < s->nb_streams; i++) {
1047 OutputStream *os = &c->streams[i];
1048 if ((ret = avformat_write_header(os->ctx, NULL)) < 0)
1054 static int add_segment(OutputStream *os, const char *file,
1055 int64_t time, int duration,
1056 int64_t start_pos, int64_t range_length,
1057 int64_t index_length)
1061 if (os->nb_segments >= os->segments_size) {
1062 os->segments_size = (os->segments_size + 1) * 2;
1063 if ((err = av_reallocp(&os->segments, sizeof(*os->segments) *
1064 os->segments_size)) < 0) {
1065 os->segments_size = 0;
1066 os->nb_segments = 0;
1070 seg = av_mallocz(sizeof(*seg));
1072 return AVERROR(ENOMEM);
1073 av_strlcpy(seg->file, file, sizeof(seg->file));
1075 seg->duration = duration;
1076 if (seg->time < 0) { // If pts<0, it is expected to be cut away with an edit list
1077 seg->duration += seg->time;
1080 seg->start_pos = start_pos;
1081 seg->range_length = range_length;
1082 seg->index_length = index_length;
1083 os->segments[os->nb_segments++] = seg;
1084 os->segment_index++;
1088 static void write_styp(AVIOContext *pb)
1091 ffio_wfourcc(pb, "styp");
1092 ffio_wfourcc(pb, "msdh");
1093 avio_wb32(pb, 0); /* minor */
1094 ffio_wfourcc(pb, "msdh");
1095 ffio_wfourcc(pb, "msix");
1098 static void find_index_range(AVFormatContext *s, const char *full_path,
1099 int64_t pos, int *index_length)
1105 ret = s->io_open(s, &pb, full_path, AVIO_FLAG_READ, NULL);
1108 if (avio_seek(pb, pos, SEEK_SET) != pos) {
1109 ff_format_io_close(s, &pb);
1112 ret = avio_read(pb, buf, 8);
1113 ff_format_io_close(s, &pb);
1116 if (AV_RL32(&buf[4]) != MKTAG('s', 'i', 'd', 'x'))
1118 *index_length = AV_RB32(&buf[0]);
1121 static int update_stream_extradata(AVFormatContext *s, OutputStream *os,
1122 AVCodecParameters *par)
1126 if (os->ctx->streams[0]->codecpar->extradata_size || !par->extradata_size)
1129 extradata = av_malloc(par->extradata_size);
1132 return AVERROR(ENOMEM);
1134 memcpy(extradata, par->extradata, par->extradata_size);
1136 os->ctx->streams[0]->codecpar->extradata = extradata;
1137 os->ctx->streams[0]->codecpar->extradata_size = par->extradata_size;
1139 set_codec_str(s, par, os->codec_str, sizeof(os->codec_str));
1144 static void dashenc_delete_file(AVFormatContext *s, char *filename) {
1145 DASHContext *c = s->priv_data;
1146 int http_base_proto = ff_is_http_proto(filename);
1148 if (http_base_proto) {
1149 AVIOContext *out = NULL;
1150 AVDictionary *http_opts = NULL;
1152 set_http_options(&http_opts, c);
1153 av_dict_set(&http_opts, "method", "DELETE", 0);
1155 if (dashenc_io_open(s, &out, filename, &http_opts) < 0) {
1156 av_log(s, AV_LOG_ERROR, "failed to delete %s\n", filename);
1159 av_dict_free(&http_opts);
1160 dashenc_io_close(s, &out, filename);
1161 } else if (unlink(filename) < 0) {
1162 av_log(s, AV_LOG_ERROR, "failed to delete %s: %s\n", filename, strerror(errno));
1166 static int dash_flush(AVFormatContext *s, int final, int stream)
1168 DASHContext *c = s->priv_data;
1171 const char *proto = avio_find_protocol_name(s->url);
1172 int use_rename = proto && !strcmp(proto, "file");
1174 int cur_flush_segment_index = 0;
1176 cur_flush_segment_index = c->streams[stream].segment_index;
1178 for (i = 0; i < s->nb_streams; i++) {
1179 OutputStream *os = &c->streams[i];
1180 AVStream *st = s->streams[i];
1181 int range_length, index_length = 0;
1183 if (!os->packets_written)
1186 // Flush the single stream that got a keyframe right now.
1187 // Flush all audio streams as well, in sync with video keyframes,
1188 // but not the other video streams.
1189 if (stream >= 0 && i != stream) {
1190 if (s->streams[i]->codecpar->codec_type != AVMEDIA_TYPE_AUDIO)
1192 // Make sure we don't flush audio streams multiple times, when
1193 // all video streams are flushed one at a time.
1194 if (c->has_video && os->segment_index > cur_flush_segment_index)
1198 if (!c->single_file) {
1199 if (!strcmp(os->format_name, "mp4") && !os->written_len)
1200 write_styp(os->ctx->pb);
1202 snprintf(os->full_path, sizeof(os->full_path), "%s%s", c->dirname, os->initfile);
1205 ret = flush_dynbuf(os, &range_length);
1208 os->packets_written = 0;
1210 if (c->single_file) {
1211 find_index_range(s, os->full_path, os->pos, &index_length);
1213 dashenc_io_close(s, &os->out, os->temp_path);
1216 ret = avpriv_io_move(os->temp_path, os->full_path);
1222 if (!os->bit_rate) {
1223 // calculate average bitrate of first segment
1224 int64_t bitrate = (int64_t) range_length * 8 * AV_TIME_BASE / av_rescale_q(os->max_pts - os->start_pts,
1228 os->bit_rate = bitrate;
1229 snprintf(os->bandwidth_str, sizeof(os->bandwidth_str),
1230 " bandwidth=\"%d\"", os->bit_rate);
1233 add_segment(os, os->filename, os->start_pts, os->max_pts - os->start_pts, os->pos, range_length, index_length);
1234 av_log(s, AV_LOG_VERBOSE, "Representation %d media segment %d written to: %s\n", i, os->segment_index, os->full_path);
1236 os->pos += range_length;
1239 if (c->window_size || (final && c->remove_at_exit)) {
1240 for (i = 0; i < s->nb_streams; i++) {
1241 OutputStream *os = &c->streams[i];
1243 int remove = os->nb_segments - c->window_size - c->extra_window_size;
1244 if (final && c->remove_at_exit)
1245 remove = os->nb_segments;
1247 for (j = 0; j < remove; j++) {
1248 char filename[1024];
1249 snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->segments[j]->file);
1250 dashenc_delete_file(s, filename);
1251 av_free(os->segments[j]);
1253 os->nb_segments -= remove;
1254 memmove(os->segments, os->segments + remove, os->nb_segments * sizeof(*os->segments));
1260 ret = write_manifest(s, final);
1264 static int dash_write_packet(AVFormatContext *s, AVPacket *pkt)
1266 DASHContext *c = s->priv_data;
1267 AVStream *st = s->streams[pkt->stream_index];
1268 OutputStream *os = &c->streams[pkt->stream_index];
1269 int64_t seg_end_duration, elapsed_duration;
1272 ret = update_stream_extradata(s, os, st->codecpar);
1276 // Fill in a heuristic guess of the packet duration, if none is available.
1277 // The mp4 muxer will do something similar (for the last packet in a fragment)
1278 // if nothing is set (setting it for the other packets doesn't hurt).
1279 // By setting a nonzero duration here, we can be sure that the mp4 muxer won't
1280 // invoke its heuristic (this doesn't have to be identical to that algorithm),
1281 // so that we know the exact timestamps of fragments.
1282 if (!pkt->duration && os->last_dts != AV_NOPTS_VALUE)
1283 pkt->duration = pkt->dts - os->last_dts;
1284 os->last_dts = pkt->dts;
1286 // If forcing the stream to start at 0, the mp4 muxer will set the start
1287 // timestamps to 0. Do the same here, to avoid mismatches in duration/timestamps.
1288 if (os->first_pts == AV_NOPTS_VALUE &&
1289 s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
1290 pkt->pts -= pkt->dts;
1294 if (os->first_pts == AV_NOPTS_VALUE)
1295 os->first_pts = pkt->pts;
1297 if (!c->availability_start_time[0])
1298 format_date_now(c->availability_start_time,
1299 sizeof(c->availability_start_time));
1301 if (!os->availability_time_offset && pkt->duration) {
1302 int64_t frame_duration = av_rescale_q(pkt->duration, st->time_base,
1304 os->availability_time_offset = ((double) c->seg_duration -
1305 frame_duration) / AV_TIME_BASE;
1308 if (c->use_template && !c->use_timeline) {
1309 elapsed_duration = pkt->pts - os->first_pts;
1310 seg_end_duration = (int64_t) os->segment_index * c->seg_duration;
1312 elapsed_duration = pkt->pts - os->start_pts;
1313 seg_end_duration = c->seg_duration;
1316 if ((!c->has_video || st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) &&
1317 pkt->flags & AV_PKT_FLAG_KEY && os->packets_written &&
1318 av_compare_ts(elapsed_duration, st->time_base,
1319 seg_end_duration, AV_TIME_BASE_Q) >= 0) {
1320 int64_t prev_duration = c->last_duration;
1322 c->last_duration = av_rescale_q(pkt->pts - os->start_pts,
1325 c->total_duration = av_rescale_q(pkt->pts - os->first_pts,
1329 if ((!c->use_timeline || !c->use_template) && prev_duration) {
1330 if (c->last_duration < prev_duration*9/10 ||
1331 c->last_duration > prev_duration*11/10) {
1332 av_log(s, AV_LOG_WARNING,
1333 "Segment durations differ too much, enable use_timeline "
1334 "and use_template, or keep a stricter keyframe interval\n");
1338 if ((ret = dash_flush(s, 0, pkt->stream_index)) < 0)
1342 if (!os->packets_written) {
1343 // If we wrote a previous segment, adjust the start time of the segment
1344 // to the end of the previous one (which is the same as the mp4 muxer
1345 // does). This avoids gaps in the timeline.
1346 if (os->max_pts != AV_NOPTS_VALUE)
1347 os->start_pts = os->max_pts;
1349 os->start_pts = pkt->pts;
1351 if (os->max_pts == AV_NOPTS_VALUE)
1352 os->max_pts = pkt->pts + pkt->duration;
1354 os->max_pts = FFMAX(os->max_pts, pkt->pts + pkt->duration);
1355 os->packets_written++;
1356 if ((ret = ff_write_chained(os->ctx, 0, pkt, s, 0)) < 0)
1359 if (!os->init_range_length)
1360 flush_init_segment(s, os);
1362 //open the output context when the first frame of a segment is ready
1363 if (!c->single_file && os->packets_written == 1) {
1364 AVDictionary *opts = NULL;
1365 const char *proto = avio_find_protocol_name(s->url);
1366 int use_rename = proto && !strcmp(proto, "file");
1367 os->filename[0] = os->full_path[0] = os->temp_path[0] = '\0';
1368 ff_dash_fill_tmpl_params(os->filename, sizeof(os->filename),
1369 c->media_seg_name, pkt->stream_index,
1370 os->segment_index, os->bit_rate, os->start_pts);
1371 snprintf(os->full_path, sizeof(os->full_path), "%s%s", c->dirname,
1373 snprintf(os->temp_path, sizeof(os->temp_path),
1374 use_rename ? "%s.tmp" : "%s", os->full_path);
1375 set_http_options(&opts, c);
1376 ret = dashenc_io_open(s, &os->out, os->temp_path, &opts);
1379 av_dict_free(&opts);
1382 //write out the data immediately in streaming mode
1383 if (c->streaming && !strcmp(os->format_name, "mp4")) {
1385 uint8_t *buf = NULL;
1386 if (!os->written_len)
1387 write_styp(os->ctx->pb);
1388 avio_flush(os->ctx->pb);
1389 len = avio_get_dyn_buf (os->ctx->pb, &buf);
1390 avio_write(os->out, buf + os->written_len, len - os->written_len);
1391 os->written_len = len;
1392 avio_flush(os->out);
1398 static int dash_write_trailer(AVFormatContext *s)
1400 DASHContext *c = s->priv_data;
1402 if (s->nb_streams > 0) {
1403 OutputStream *os = &c->streams[0];
1404 // If no segments have been written so far, try to do a crude
1405 // guess of the segment duration
1406 if (!c->last_duration)
1407 c->last_duration = av_rescale_q(os->max_pts - os->start_pts,
1408 s->streams[0]->time_base,
1410 c->total_duration = av_rescale_q(os->max_pts - os->first_pts,
1411 s->streams[0]->time_base,
1414 dash_flush(s, 1, -1);
1416 if (c->remove_at_exit) {
1417 char filename[1024];
1419 for (i = 0; i < s->nb_streams; i++) {
1420 OutputStream *os = &c->streams[i];
1421 snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
1422 dashenc_delete_file(s, filename);
1424 dashenc_delete_file(s, s->url);
1430 static int dash_check_bitstream(struct AVFormatContext *s, const AVPacket *avpkt)
1432 DASHContext *c = s->priv_data;
1433 OutputStream *os = &c->streams[avpkt->stream_index];
1434 AVFormatContext *oc = os->ctx;
1435 if (oc->oformat->check_bitstream) {
1437 AVPacket pkt = *avpkt;
1438 pkt.stream_index = 0;
1439 ret = oc->oformat->check_bitstream(oc, &pkt);
1441 AVStream *st = s->streams[avpkt->stream_index];
1442 AVStream *ost = oc->streams[0];
1443 st->internal->bsfcs = ost->internal->bsfcs;
1444 st->internal->nb_bsfcs = ost->internal->nb_bsfcs;
1445 ost->internal->bsfcs = NULL;
1446 ost->internal->nb_bsfcs = 0;
1453 #define OFFSET(x) offsetof(DASHContext, x)
1454 #define E AV_OPT_FLAG_ENCODING_PARAM
1455 static const AVOption options[] = {
1456 { "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 },
1457 { "window_size", "number of segments kept in the manifest", OFFSET(window_size), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, E },
1458 { "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 },
1459 #if FF_API_DASH_MIN_SEG_DURATION
1460 { "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 },
1462 { "seg_duration", "segment duration (in seconds, fractional value can be set)", OFFSET(seg_duration), AV_OPT_TYPE_DURATION, { .i64 = 5000000 }, 0, INT_MAX, E },
1463 { "remove_at_exit", "remove all segments when finished", OFFSET(remove_at_exit), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
1464 { "use_template", "Use SegmentTemplate instead of SegmentList", OFFSET(use_template), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, E },
1465 { "use_timeline", "Use SegmentTimeline in SegmentTemplate", OFFSET(use_timeline), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, E },
1466 { "single_file", "Store all segments in one file, accessed using byte ranges", OFFSET(single_file), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
1467 { "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 },
1468 { "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 },
1469 { "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 },
1470 { "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 },
1471 { "method", "set the HTTP method", OFFSET(method), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
1472 { "http_user_agent", "override User-Agent field in HTTP header", OFFSET(user_agent), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
1473 { "http_persistent", "Use persistent HTTP connections", OFFSET(http_persistent), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, E },
1474 { "hls_playlist", "Generate HLS playlist files(master.m3u8, media_%d.m3u8)", OFFSET(hls_playlist), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
1475 { "streaming", "Enable/Disable streaming mode of output. Each frame will be moof fragment", OFFSET(streaming), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
1476 { "timeout", "set timeout for socket I/O operations", OFFSET(timeout), AV_OPT_TYPE_DURATION, { .i64 = -1 }, -1, INT_MAX, .flags = E },
1480 static const AVClass dash_class = {
1481 .class_name = "dash muxer",
1482 .item_name = av_default_item_name,
1484 .version = LIBAVUTIL_VERSION_INT,
1487 AVOutputFormat ff_dash_muxer = {
1489 .long_name = NULL_IF_CONFIG_SMALL("DASH Muxer"),
1490 .extensions = "mpd",
1491 .priv_data_size = sizeof(DASHContext),
1492 .audio_codec = AV_CODEC_ID_AAC,
1493 .video_codec = AV_CODEC_ID_H264,
1494 .flags = AVFMT_GLOBALHEADER | AVFMT_NOFILE | AVFMT_TS_NEGATIVE,
1496 .write_header = dash_write_header,
1497 .write_packet = dash_write_packet,
1498 .write_trailer = dash_write_trailer,
1499 .deinit = dash_free,
1500 .check_bitstream = dash_check_bitstream,
1501 .priv_class = &dash_class,