]> git.sesse.net Git - ffmpeg/blob - libavformat/dashenc.c
avformat/mpegts: reindent after last change
[ffmpeg] / libavformat / dashenc.c
1 /*
2  * MPEG-DASH ISO BMFF segmenter
3  * Copyright (c) 2014 Martin Storsjo
4  * Copyright (c) 2018 Akamai Technologies, Inc.
5  *
6  * This file is part of FFmpeg.
7  *
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.
12  *
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.
17  *
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
21  */
22
23 #include "config.h"
24 #if HAVE_UNISTD_H
25 #include <unistd.h>
26 #endif
27
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"
36
37 #include "avc.h"
38 #include "avformat.h"
39 #include "avio_internal.h"
40 #include "hlsplaylist.h"
41 #if CONFIG_HTTP_PROTOCOL
42 #include "http.h"
43 #endif
44 #include "internal.h"
45 #include "isom.h"
46 #include "os_support.h"
47 #include "url.h"
48 #include "vpcc.h"
49 #include "dash.h"
50
51 typedef struct Segment {
52     char file[1024];
53     int64_t start_pos;
54     int range_length, index_length;
55     int64_t time;
56     int duration;
57     int n;
58 } Segment;
59
60 typedef struct AdaptationSet {
61     char id[10];
62     enum AVMediaType media_type;
63     AVDictionary *metadata;
64     AVRational min_frame_rate, max_frame_rate;
65     int ambiguous_frame_rate;
66 } AdaptationSet;
67
68 typedef struct OutputStream {
69     AVFormatContext *ctx;
70     int ctx_inited, as_idx;
71     AVIOContext *out;
72     char format_name[8];
73     int packets_written;
74     char initfile[1024];
75     int64_t init_start_pos, pos;
76     int init_range_length;
77     int nb_segments, segments_size, segment_index;
78     Segment **segments;
79     int64_t first_pts, start_pts, max_pts;
80     int64_t last_dts, last_pts;
81     int bit_rate;
82
83     char codec_str[100];
84     int written_len;
85     char filename[1024];
86     char full_path[1024];
87     char temp_path[1024];
88     double availability_time_offset;
89     int total_pkt_size;
90     int muxer_overhead;
91 } OutputStream;
92
93 typedef struct DASHContext {
94     const AVClass *class;  /* Class for private options. */
95     char *adaptation_sets;
96     AdaptationSet *as;
97     int nb_as;
98     int window_size;
99     int extra_window_size;
100 #if FF_API_DASH_MIN_SEG_DURATION
101     int min_seg_duration;
102 #endif
103     int64_t seg_duration;
104     int remove_at_exit;
105     int use_template;
106     int use_timeline;
107     int single_file;
108     OutputStream *streams;
109     int has_video;
110     int64_t last_duration;
111     int64_t total_duration;
112     char availability_start_time[100];
113     char dirname[1024];
114     const char *single_file_name;
115     const char *init_seg_name;
116     const char *media_seg_name;
117     const char *utc_timing_url;
118     const char *method;
119     const char *user_agent;
120     int hls_playlist;
121     int http_persistent;
122     int master_playlist_created;
123     AVIOContext *mpd_out;
124     AVIOContext *m3u8_out;
125     int streaming;
126     int64_t timeout;
127     int index_correction;
128 } DASHContext;
129
130 static struct codec_string {
131     int id;
132     const char *str;
133 } codecs[] = {
134     { AV_CODEC_ID_VP8, "vp8" },
135     { AV_CODEC_ID_VP9, "vp9" },
136     { AV_CODEC_ID_VORBIS, "vorbis" },
137     { AV_CODEC_ID_OPUS, "opus" },
138     { 0, NULL }
139 };
140
141 static int dashenc_io_open(AVFormatContext *s, AVIOContext **pb, char *filename,
142                            AVDictionary **options) {
143     DASHContext *c = s->priv_data;
144     int http_base_proto = filename ? ff_is_http_proto(filename) : 0;
145     int err = AVERROR_MUXER_NOT_FOUND;
146     if (!*pb || !http_base_proto || !c->http_persistent) {
147         err = s->io_open(s, pb, filename, AVIO_FLAG_WRITE, options);
148 #if CONFIG_HTTP_PROTOCOL
149     } else {
150         URLContext *http_url_context = ffio_geturlcontext(*pb);
151         av_assert0(http_url_context);
152         err = ff_http_do_new_request(http_url_context, filename);
153 #endif
154     }
155     return err;
156 }
157
158 static void dashenc_io_close(AVFormatContext *s, AVIOContext **pb, char *filename) {
159     DASHContext *c = s->priv_data;
160     int http_base_proto = filename ? ff_is_http_proto(filename) : 0;
161
162     if (!http_base_proto || !c->http_persistent) {
163         ff_format_io_close(s, pb);
164 #if CONFIG_HTTP_PROTOCOL
165     } else {
166         URLContext *http_url_context = ffio_geturlcontext(*pb);
167         av_assert0(http_url_context);
168         avio_flush(*pb);
169         ffurl_shutdown(http_url_context, AVIO_FLAG_WRITE);
170 #endif
171     }
172 }
173
174 static void set_vp9_codec_str(AVFormatContext *s, AVCodecParameters *par,
175                               AVRational *frame_rate, char *str, int size) {
176     VPCC vpcc;
177     int ret = ff_isom_get_vpcc_features(s, par, frame_rate, &vpcc);
178     if (ret == 0) {
179         av_strlcatf(str, size, "vp09.%02x.%02x.%02x",
180                     vpcc.profile, vpcc.level, vpcc.bitdepth);
181     } else {
182         // Default to just vp9 in case of error while finding out profile or level
183         av_log(s, AV_LOG_WARNING, "Could not find VP9 profile and/or level\n");
184         av_strlcpy(str, "vp9", size);
185     }
186     return;
187 }
188
189 static void set_codec_str(AVFormatContext *s, AVCodecParameters *par,
190                           AVRational *frame_rate, char *str, int size)
191 {
192     const AVCodecTag *tags[2] = { NULL, NULL };
193     uint32_t tag;
194     int i;
195
196     // common Webm codecs are not part of RFC 6381
197     for (i = 0; codecs[i].id; i++)
198         if (codecs[i].id == par->codec_id) {
199             if (codecs[i].id == AV_CODEC_ID_VP9) {
200                 set_vp9_codec_str(s, par, frame_rate, str, size);
201             } else {
202                 av_strlcpy(str, codecs[i].str, size);
203             }
204             return;
205         }
206
207     // for codecs part of RFC 6381
208     if (par->codec_type == AVMEDIA_TYPE_VIDEO)
209         tags[0] = ff_codec_movvideo_tags;
210     else if (par->codec_type == AVMEDIA_TYPE_AUDIO)
211         tags[0] = ff_codec_movaudio_tags;
212     else
213         return;
214
215     tag = av_codec_get_tag(tags, par->codec_id);
216     if (!tag)
217         return;
218     if (size < 5)
219         return;
220
221     AV_WL32(str, tag);
222     str[4] = '\0';
223     if (!strcmp(str, "mp4a") || !strcmp(str, "mp4v")) {
224         uint32_t oti;
225         tags[0] = ff_mp4_obj_type;
226         oti = av_codec_get_tag(tags, par->codec_id);
227         if (oti)
228             av_strlcatf(str, size, ".%02"PRIx32, oti);
229         else
230             return;
231
232         if (tag == MKTAG('m', 'p', '4', 'a')) {
233             if (par->extradata_size >= 2) {
234                 int aot = par->extradata[0] >> 3;
235                 if (aot == 31)
236                     aot = ((AV_RB16(par->extradata) >> 5) & 0x3f) + 32;
237                 av_strlcatf(str, size, ".%d", aot);
238             }
239         } else if (tag == MKTAG('m', 'p', '4', 'v')) {
240             // Unimplemented, should output ProfileLevelIndication as a decimal number
241             av_log(s, AV_LOG_WARNING, "Incomplete RFC 6381 codec string for mp4v\n");
242         }
243     } else if (!strcmp(str, "avc1")) {
244         uint8_t *tmpbuf = NULL;
245         uint8_t *extradata = par->extradata;
246         int extradata_size = par->extradata_size;
247         if (!extradata_size)
248             return;
249         if (extradata[0] != 1) {
250             AVIOContext *pb;
251             if (avio_open_dyn_buf(&pb) < 0)
252                 return;
253             if (ff_isom_write_avcc(pb, extradata, extradata_size) < 0) {
254                 ffio_free_dyn_buf(&pb);
255                 return;
256             }
257             extradata_size = avio_close_dyn_buf(pb, &extradata);
258             tmpbuf = extradata;
259         }
260
261         if (extradata_size >= 4)
262             av_strlcatf(str, size, ".%02x%02x%02x",
263                         extradata[1], extradata[2], extradata[3]);
264         av_free(tmpbuf);
265     }
266 }
267
268 static int flush_dynbuf(OutputStream *os, int *range_length)
269 {
270     uint8_t *buffer;
271
272     if (!os->ctx->pb) {
273         return AVERROR(EINVAL);
274     }
275
276     // flush
277     av_write_frame(os->ctx, NULL);
278     avio_flush(os->ctx->pb);
279
280     // write out to file
281     *range_length = avio_close_dyn_buf(os->ctx->pb, &buffer);
282     os->ctx->pb = NULL;
283     avio_write(os->out, buffer + os->written_len, *range_length - os->written_len);
284     os->written_len = 0;
285     av_free(buffer);
286
287     // re-open buffer
288     return avio_open_dyn_buf(&os->ctx->pb);
289 }
290
291 static void set_http_options(AVDictionary **options, DASHContext *c)
292 {
293     if (c->method)
294         av_dict_set(options, "method", c->method, 0);
295     if (c->user_agent)
296         av_dict_set(options, "user_agent", c->user_agent, 0);
297     if (c->http_persistent)
298         av_dict_set_int(options, "multiple_requests", 1, 0);
299     if (c->timeout >= 0)
300         av_dict_set_int(options, "timeout", c->timeout, 0);
301 }
302
303 static void get_hls_playlist_name(char *playlist_name, int string_size,
304                                   const char *base_url, int id) {
305     if (base_url)
306         snprintf(playlist_name, string_size, "%smedia_%d.m3u8", base_url, id);
307     else
308         snprintf(playlist_name, string_size, "media_%d.m3u8", id);
309 }
310
311 static int flush_init_segment(AVFormatContext *s, OutputStream *os)
312 {
313     DASHContext *c = s->priv_data;
314     int ret, range_length;
315
316     ret = flush_dynbuf(os, &range_length);
317     if (ret < 0)
318         return ret;
319
320     os->pos = os->init_range_length = range_length;
321     if (!c->single_file)
322         ff_format_io_close(s, &os->out);
323     return 0;
324 }
325
326 static void dash_free(AVFormatContext *s)
327 {
328     DASHContext *c = s->priv_data;
329     int i, j;
330
331     if (c->as) {
332         for (i = 0; i < c->nb_as; i++)
333             av_dict_free(&c->as[i].metadata);
334         av_freep(&c->as);
335         c->nb_as = 0;
336     }
337
338     if (!c->streams)
339         return;
340     for (i = 0; i < s->nb_streams; i++) {
341         OutputStream *os = &c->streams[i];
342         if (os->ctx && os->ctx_inited)
343             av_write_trailer(os->ctx);
344         if (os->ctx && os->ctx->pb)
345             ffio_free_dyn_buf(&os->ctx->pb);
346         ff_format_io_close(s, &os->out);
347         if (os->ctx)
348             avformat_free_context(os->ctx);
349         for (j = 0; j < os->nb_segments; j++)
350             av_free(os->segments[j]);
351         av_free(os->segments);
352     }
353     av_freep(&c->streams);
354
355     ff_format_io_close(s, &c->mpd_out);
356     ff_format_io_close(s, &c->m3u8_out);
357 }
358
359 static void output_segment_list(OutputStream *os, AVIOContext *out, AVFormatContext *s,
360                                 int representation_id, int final)
361 {
362     DASHContext *c = s->priv_data;
363     int i, start_index = 0, start_number = 1;
364     if (c->window_size) {
365         start_index  = FFMAX(os->nb_segments   - c->window_size, 0);
366         start_number = FFMAX(os->segment_index - c->window_size, 1);
367     }
368
369     if (c->use_template) {
370         int timescale = c->use_timeline ? os->ctx->streams[0]->time_base.den : AV_TIME_BASE;
371         avio_printf(out, "\t\t\t\t<SegmentTemplate timescale=\"%d\" ", timescale);
372         if (!c->use_timeline) {
373             avio_printf(out, "duration=\"%"PRId64"\" ", c->seg_duration);
374             if (c->streaming && os->availability_time_offset)
375                 avio_printf(out, "availabilityTimeOffset=\"%.3f\" ",
376                             os->availability_time_offset);
377         }
378         avio_printf(out, "initialization=\"%s\" media=\"%s\" startNumber=\"%d\">\n", c->init_seg_name, c->media_seg_name, c->use_timeline ? start_number : 1);
379         if (c->use_timeline) {
380             int64_t cur_time = 0;
381             avio_printf(out, "\t\t\t\t\t<SegmentTimeline>\n");
382             for (i = start_index; i < os->nb_segments; ) {
383                 Segment *seg = os->segments[i];
384                 int repeat = 0;
385                 avio_printf(out, "\t\t\t\t\t\t<S ");
386                 if (i == start_index || seg->time != cur_time) {
387                     cur_time = seg->time;
388                     avio_printf(out, "t=\"%"PRId64"\" ", seg->time);
389                 }
390                 avio_printf(out, "d=\"%d\" ", seg->duration);
391                 while (i + repeat + 1 < os->nb_segments &&
392                        os->segments[i + repeat + 1]->duration == seg->duration &&
393                        os->segments[i + repeat + 1]->time == os->segments[i + repeat]->time + os->segments[i + repeat]->duration)
394                     repeat++;
395                 if (repeat > 0)
396                     avio_printf(out, "r=\"%d\" ", repeat);
397                 avio_printf(out, "/>\n");
398                 i += 1 + repeat;
399                 cur_time += (1 + repeat) * seg->duration;
400             }
401             avio_printf(out, "\t\t\t\t\t</SegmentTimeline>\n");
402         }
403         avio_printf(out, "\t\t\t\t</SegmentTemplate>\n");
404     } else if (c->single_file) {
405         avio_printf(out, "\t\t\t\t<BaseURL>%s</BaseURL>\n", os->initfile);
406         avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%"PRId64"\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);
407         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);
408         for (i = start_index; i < os->nb_segments; i++) {
409             Segment *seg = os->segments[i];
410             avio_printf(out, "\t\t\t\t\t<SegmentURL mediaRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->range_length - 1);
411             if (seg->index_length)
412                 avio_printf(out, "indexRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->index_length - 1);
413             avio_printf(out, "/>\n");
414         }
415         avio_printf(out, "\t\t\t\t</SegmentList>\n");
416     } else {
417         avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%"PRId64"\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);
418         avio_printf(out, "\t\t\t\t\t<Initialization sourceURL=\"%s\" />\n", os->initfile);
419         for (i = start_index; i < os->nb_segments; i++) {
420             Segment *seg = os->segments[i];
421             avio_printf(out, "\t\t\t\t\t<SegmentURL media=\"%s\" />\n", seg->file);
422         }
423         avio_printf(out, "\t\t\t\t</SegmentList>\n");
424     }
425     if (c->hls_playlist && start_index < os->nb_segments)
426     {
427         int timescale = os->ctx->streams[0]->time_base.den;
428         char temp_filename_hls[1024];
429         char filename_hls[1024];
430         AVDictionary *http_opts = NULL;
431         int target_duration = 0;
432         int ret = 0;
433         const char *proto = avio_find_protocol_name(c->dirname);
434         int use_rename = proto && !strcmp(proto, "file");
435
436         get_hls_playlist_name(filename_hls, sizeof(filename_hls),
437                               c->dirname, representation_id);
438
439         snprintf(temp_filename_hls, sizeof(temp_filename_hls), use_rename ? "%s.tmp" : "%s", filename_hls);
440
441         set_http_options(&http_opts, c);
442         dashenc_io_open(s, &c->m3u8_out, temp_filename_hls, &http_opts);
443         av_dict_free(&http_opts);
444         for (i = start_index; i < os->nb_segments; i++) {
445             Segment *seg = os->segments[i];
446             double duration = (double) seg->duration / timescale;
447             if (target_duration <= duration)
448                 target_duration = lrint(duration);
449         }
450
451         ff_hls_write_playlist_header(c->m3u8_out, 6, -1, target_duration,
452                                      start_number, PLAYLIST_TYPE_NONE);
453
454         ff_hls_write_init_file(c->m3u8_out, os->initfile, c->single_file,
455                                os->init_range_length, os->init_start_pos);
456
457         for (i = start_index; i < os->nb_segments; i++) {
458             Segment *seg = os->segments[i];
459             ret = ff_hls_write_file_entry(c->m3u8_out, 0, c->single_file,
460                                     (double) seg->duration / timescale, 0,
461                                     seg->range_length, seg->start_pos, NULL,
462                                     c->single_file ? os->initfile : seg->file,
463                                     NULL);
464             if (ret < 0) {
465                 av_log(os->ctx, AV_LOG_WARNING, "ff_hls_write_file_entry get error\n");
466             }
467         }
468
469         if (final)
470             ff_hls_write_end_list(c->m3u8_out);
471
472         dashenc_io_close(s, &c->m3u8_out, temp_filename_hls);
473
474         if (use_rename)
475             if (avpriv_io_move(temp_filename_hls, filename_hls) < 0) {
476                 av_log(os->ctx, AV_LOG_WARNING, "renaming file %s to %s failed\n\n", temp_filename_hls, filename_hls);
477             }
478     }
479
480 }
481
482 static char *xmlescape(const char *str) {
483     int outlen = strlen(str)*3/2 + 6;
484     char *out = av_realloc(NULL, outlen + 1);
485     int pos = 0;
486     if (!out)
487         return NULL;
488     for (; *str; str++) {
489         if (pos + 6 > outlen) {
490             char *tmp;
491             outlen = 2 * outlen + 6;
492             tmp = av_realloc(out, outlen + 1);
493             if (!tmp) {
494                 av_free(out);
495                 return NULL;
496             }
497             out = tmp;
498         }
499         if (*str == '&') {
500             memcpy(&out[pos], "&amp;", 5);
501             pos += 5;
502         } else if (*str == '<') {
503             memcpy(&out[pos], "&lt;", 4);
504             pos += 4;
505         } else if (*str == '>') {
506             memcpy(&out[pos], "&gt;", 4);
507             pos += 4;
508         } else if (*str == '\'') {
509             memcpy(&out[pos], "&apos;", 6);
510             pos += 6;
511         } else if (*str == '\"') {
512             memcpy(&out[pos], "&quot;", 6);
513             pos += 6;
514         } else {
515             out[pos++] = *str;
516         }
517     }
518     out[pos] = '\0';
519     return out;
520 }
521
522 static void write_time(AVIOContext *out, int64_t time)
523 {
524     int seconds = time / AV_TIME_BASE;
525     int fractions = time % AV_TIME_BASE;
526     int minutes = seconds / 60;
527     int hours = minutes / 60;
528     seconds %= 60;
529     minutes %= 60;
530     avio_printf(out, "PT");
531     if (hours)
532         avio_printf(out, "%dH", hours);
533     if (hours || minutes)
534         avio_printf(out, "%dM", minutes);
535     avio_printf(out, "%d.%dS", seconds, fractions / (AV_TIME_BASE / 10));
536 }
537
538 static void format_date_now(char *buf, int size)
539 {
540     time_t t = time(NULL);
541     struct tm *ptm, tmbuf;
542     ptm = gmtime_r(&t, &tmbuf);
543     if (ptm) {
544         if (!strftime(buf, size, "%Y-%m-%dT%H:%M:%SZ", ptm))
545             buf[0] = '\0';
546     }
547 }
548
549 static int write_adaptation_set(AVFormatContext *s, AVIOContext *out, int as_index,
550                                 int final)
551 {
552     DASHContext *c = s->priv_data;
553     AdaptationSet *as = &c->as[as_index];
554     AVDictionaryEntry *lang, *role;
555     int i;
556
557     avio_printf(out, "\t\t<AdaptationSet id=\"%s\" contentType=\"%s\" segmentAlignment=\"true\" bitstreamSwitching=\"true\"",
558                 as->id, as->media_type == AVMEDIA_TYPE_VIDEO ? "video" : "audio");
559     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)
560         avio_printf(out, " maxFrameRate=\"%d/%d\"", as->max_frame_rate.num, as->max_frame_rate.den);
561     lang = av_dict_get(as->metadata, "language", NULL, 0);
562     if (lang)
563         avio_printf(out, " lang=\"%s\"", lang->value);
564     avio_printf(out, ">\n");
565
566     role = av_dict_get(as->metadata, "role", NULL, 0);
567     if (role)
568         avio_printf(out, "\t\t\t<Role schemeIdUri=\"urn:mpeg:dash:role:2011\" value=\"%s\"/>\n", role->value);
569
570     for (i = 0; i < s->nb_streams; i++) {
571         OutputStream *os = &c->streams[i];
572         char bandwidth_str[64] = {'\0'};
573
574         if (os->as_idx - 1 != as_index)
575             continue;
576
577         if (os->bit_rate > 0)
578             snprintf(bandwidth_str, sizeof(bandwidth_str), " bandwidth=\"%d\"",
579                      os->bit_rate + os->muxer_overhead);
580
581         if (as->media_type == AVMEDIA_TYPE_VIDEO) {
582             AVStream *st = s->streams[i];
583             avio_printf(out, "\t\t\t<Representation id=\"%d\" mimeType=\"video/%s\" codecs=\"%s\"%s width=\"%d\" height=\"%d\"",
584                 i, os->format_name, os->codec_str, bandwidth_str, s->streams[i]->codecpar->width, s->streams[i]->codecpar->height);
585             if (st->avg_frame_rate.num)
586                 avio_printf(out, " frameRate=\"%d/%d\"", st->avg_frame_rate.num, st->avg_frame_rate.den);
587             avio_printf(out, ">\n");
588         } else {
589             avio_printf(out, "\t\t\t<Representation id=\"%d\" mimeType=\"audio/%s\" codecs=\"%s\"%s audioSamplingRate=\"%d\">\n",
590                 i, os->format_name, os->codec_str, bandwidth_str, s->streams[i]->codecpar->sample_rate);
591             avio_printf(out, "\t\t\t\t<AudioChannelConfiguration schemeIdUri=\"urn:mpeg:dash:23003:3:audio_channel_configuration:2011\" value=\"%d\" />\n",
592                 s->streams[i]->codecpar->channels);
593         }
594         output_segment_list(os, out, s, i, final);
595         avio_printf(out, "\t\t\t</Representation>\n");
596     }
597     avio_printf(out, "\t\t</AdaptationSet>\n");
598
599     return 0;
600 }
601
602 static int add_adaptation_set(AVFormatContext *s, AdaptationSet **as, enum AVMediaType type)
603 {
604     DASHContext *c = s->priv_data;
605
606     void *mem = av_realloc(c->as, sizeof(*c->as) * (c->nb_as + 1));
607     if (!mem)
608         return AVERROR(ENOMEM);
609     c->as = mem;
610     ++c->nb_as;
611
612     *as = &c->as[c->nb_as - 1];
613     memset(*as, 0, sizeof(**as));
614     (*as)->media_type = type;
615
616     return 0;
617 }
618
619 static int adaptation_set_add_stream(AVFormatContext *s, int as_idx, int i)
620 {
621     DASHContext *c = s->priv_data;
622     AdaptationSet *as = &c->as[as_idx - 1];
623     OutputStream *os = &c->streams[i];
624
625     if (as->media_type != s->streams[i]->codecpar->codec_type) {
626         av_log(s, AV_LOG_ERROR, "Codec type of stream %d doesn't match AdaptationSet's media type\n", i);
627         return AVERROR(EINVAL);
628     } else if (os->as_idx) {
629         av_log(s, AV_LOG_ERROR, "Stream %d is already assigned to an AdaptationSet\n", i);
630         return AVERROR(EINVAL);
631     }
632     os->as_idx = as_idx;
633
634     return 0;
635 }
636
637 static int parse_adaptation_sets(AVFormatContext *s)
638 {
639     DASHContext *c = s->priv_data;
640     const char *p = c->adaptation_sets;
641     enum { new_set, parse_id, parsing_streams } state;
642     AdaptationSet *as;
643     int i, n, ret;
644
645     // default: one AdaptationSet for each stream
646     if (!p) {
647         for (i = 0; i < s->nb_streams; i++) {
648             if ((ret = add_adaptation_set(s, &as, s->streams[i]->codecpar->codec_type)) < 0)
649                 return ret;
650             snprintf(as->id, sizeof(as->id), "%d", i);
651
652             c->streams[i].as_idx = c->nb_as;
653         }
654         goto end;
655     }
656
657     // syntax id=0,streams=0,1,2 id=1,streams=3,4 and so on
658     state = new_set;
659     while (*p) {
660         if (*p == ' ') {
661             p++;
662             continue;
663         } else if (state == new_set && av_strstart(p, "id=", &p)) {
664
665             if ((ret = add_adaptation_set(s, &as, AVMEDIA_TYPE_UNKNOWN)) < 0)
666                 return ret;
667
668             n = strcspn(p, ",");
669             snprintf(as->id, sizeof(as->id), "%.*s", n, p);
670
671             p += n;
672             if (*p)
673                 p++;
674             state = parse_id;
675         } else if (state == parse_id && av_strstart(p, "streams=", &p)) {
676             state = parsing_streams;
677         } else if (state == parsing_streams) {
678             AdaptationSet *as = &c->as[c->nb_as - 1];
679             char idx_str[8], *end_str;
680
681             n = strcspn(p, " ,");
682             snprintf(idx_str, sizeof(idx_str), "%.*s", n, p);
683             p += n;
684
685             // if value is "a" or "v", map all streams of that type
686             if (as->media_type == AVMEDIA_TYPE_UNKNOWN && (idx_str[0] == 'v' || idx_str[0] == 'a')) {
687                 enum AVMediaType type = (idx_str[0] == 'v') ? AVMEDIA_TYPE_VIDEO : AVMEDIA_TYPE_AUDIO;
688                 av_log(s, AV_LOG_DEBUG, "Map all streams of type %s\n", idx_str);
689
690                 for (i = 0; i < s->nb_streams; i++) {
691                     if (s->streams[i]->codecpar->codec_type != type)
692                         continue;
693
694                     as->media_type = s->streams[i]->codecpar->codec_type;
695
696                     if ((ret = adaptation_set_add_stream(s, c->nb_as, i)) < 0)
697                         return ret;
698                 }
699             } else { // select single stream
700                 i = strtol(idx_str, &end_str, 10);
701                 if (idx_str == end_str || i < 0 || i >= s->nb_streams) {
702                     av_log(s, AV_LOG_ERROR, "Selected stream \"%s\" not found!\n", idx_str);
703                     return AVERROR(EINVAL);
704                 }
705                 av_log(s, AV_LOG_DEBUG, "Map stream %d\n", i);
706
707                 if (as->media_type == AVMEDIA_TYPE_UNKNOWN) {
708                     as->media_type = s->streams[i]->codecpar->codec_type;
709                 }
710
711                 if ((ret = adaptation_set_add_stream(s, c->nb_as, i)) < 0)
712                     return ret;
713             }
714
715             if (*p == ' ')
716                 state = new_set;
717             if (*p)
718                 p++;
719         } else {
720             return AVERROR(EINVAL);
721         }
722     }
723
724 end:
725     // check for unassigned streams
726     for (i = 0; i < s->nb_streams; i++) {
727         OutputStream *os = &c->streams[i];
728         if (!os->as_idx) {
729             av_log(s, AV_LOG_ERROR, "Stream %d is not mapped to an AdaptationSet\n", i);
730             return AVERROR(EINVAL);
731         }
732     }
733     return 0;
734 }
735
736 static int write_manifest(AVFormatContext *s, int final)
737 {
738     DASHContext *c = s->priv_data;
739     AVIOContext *out;
740     char temp_filename[1024];
741     int ret, i;
742     const char *proto = avio_find_protocol_name(s->url);
743     int use_rename = proto && !strcmp(proto, "file");
744     static unsigned int warned_non_file = 0;
745     AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
746     AVDictionary *opts = NULL;
747
748     if (!use_rename && !warned_non_file++)
749         av_log(s, AV_LOG_ERROR, "Cannot use rename on non file protocol, this may lead to races and temporary partial files\n");
750
751     snprintf(temp_filename, sizeof(temp_filename), use_rename ? "%s.tmp" : "%s", s->url);
752     set_http_options(&opts, c);
753     ret = dashenc_io_open(s, &c->mpd_out, temp_filename, &opts);
754     if (ret < 0) {
755         av_log(s, AV_LOG_ERROR, "Unable to open %s for writing\n", temp_filename);
756         return ret;
757     }
758     out = c->mpd_out;
759     av_dict_free(&opts);
760     avio_printf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
761     avio_printf(out, "<MPD xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
762                 "\txmlns=\"urn:mpeg:dash:schema:mpd:2011\"\n"
763                 "\txmlns:xlink=\"http://www.w3.org/1999/xlink\"\n"
764                 "\txsi:schemaLocation=\"urn:mpeg:DASH:schema:MPD:2011 http://standards.iso.org/ittf/PubliclyAvailableStandards/MPEG-DASH_schema_files/DASH-MPD.xsd\"\n"
765                 "\tprofiles=\"urn:mpeg:dash:profile:isoff-live:2011\"\n"
766                 "\ttype=\"%s\"\n", final ? "static" : "dynamic");
767     if (final) {
768         avio_printf(out, "\tmediaPresentationDuration=\"");
769         write_time(out, c->total_duration);
770         avio_printf(out, "\"\n");
771     } else {
772         int64_t update_period = c->last_duration / AV_TIME_BASE;
773         char now_str[100];
774         if (c->use_template && !c->use_timeline)
775             update_period = 500;
776         avio_printf(out, "\tminimumUpdatePeriod=\"PT%"PRId64"S\"\n", update_period);
777         avio_printf(out, "\tsuggestedPresentationDelay=\"PT%"PRId64"S\"\n", c->last_duration / AV_TIME_BASE);
778         if (c->availability_start_time[0])
779             avio_printf(out, "\tavailabilityStartTime=\"%s\"\n", c->availability_start_time);
780         format_date_now(now_str, sizeof(now_str));
781         if (now_str[0])
782             avio_printf(out, "\tpublishTime=\"%s\"\n", now_str);
783         if (c->window_size && c->use_template) {
784             avio_printf(out, "\ttimeShiftBufferDepth=\"");
785             write_time(out, c->last_duration * c->window_size);
786             avio_printf(out, "\"\n");
787         }
788     }
789     avio_printf(out, "\tminBufferTime=\"");
790     write_time(out, c->last_duration * 2);
791     avio_printf(out, "\">\n");
792     avio_printf(out, "\t<ProgramInformation>\n");
793     if (title) {
794         char *escaped = xmlescape(title->value);
795         avio_printf(out, "\t\t<Title>%s</Title>\n", escaped);
796         av_free(escaped);
797     }
798     avio_printf(out, "\t</ProgramInformation>\n");
799
800     if (c->window_size && s->nb_streams > 0 && c->streams[0].nb_segments > 0 && !c->use_template) {
801         OutputStream *os = &c->streams[0];
802         int start_index = FFMAX(os->nb_segments - c->window_size, 0);
803         int64_t start_time = av_rescale_q(os->segments[start_index]->time, s->streams[0]->time_base, AV_TIME_BASE_Q);
804         avio_printf(out, "\t<Period id=\"0\" start=\"");
805         write_time(out, start_time);
806         avio_printf(out, "\">\n");
807     } else {
808         avio_printf(out, "\t<Period id=\"0\" start=\"PT0.0S\">\n");
809     }
810
811     for (i = 0; i < c->nb_as; i++) {
812         if ((ret = write_adaptation_set(s, out, i, final)) < 0)
813             return ret;
814     }
815     avio_printf(out, "\t</Period>\n");
816
817     if (c->utc_timing_url)
818         avio_printf(out, "\t<UTCTiming schemeIdUri=\"urn:mpeg:dash:utc:http-xsdate:2014\" value=\"%s\"/>\n", c->utc_timing_url);
819
820     avio_printf(out, "</MPD>\n");
821     avio_flush(out);
822     dashenc_io_close(s, &c->mpd_out, temp_filename);
823
824     if (use_rename) {
825         if ((ret = avpriv_io_move(temp_filename, s->url)) < 0)
826             return ret;
827     }
828
829     if (c->hls_playlist && !c->master_playlist_created) {
830         char filename_hls[1024];
831         const char *audio_group = "A1";
832         int is_default = 1;
833         int max_audio_bitrate = 0;
834
835         if (*c->dirname)
836             snprintf(filename_hls, sizeof(filename_hls), "%s/master.m3u8", c->dirname);
837         else
838             snprintf(filename_hls, sizeof(filename_hls), "master.m3u8");
839
840         snprintf(temp_filename, sizeof(temp_filename), use_rename ? "%s.tmp" : "%s", filename_hls);
841
842         set_http_options(&opts, c);
843         ret = avio_open2(&out, temp_filename, AVIO_FLAG_WRITE, NULL, &opts);
844         if (ret < 0) {
845             av_log(s, AV_LOG_ERROR, "Unable to open %s for writing\n", temp_filename);
846             return ret;
847         }
848         av_dict_free(&opts);
849
850         ff_hls_write_playlist_version(out, 7);
851
852         for (i = 0; i < s->nb_streams; i++) {
853             char playlist_file[64];
854             AVStream *st = s->streams[i];
855             OutputStream *os = &c->streams[i];
856             if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO)
857                 continue;
858             get_hls_playlist_name(playlist_file, sizeof(playlist_file), NULL, i);
859             ff_hls_write_audio_rendition(out, (char *)audio_group,
860                                          playlist_file, i, is_default);
861             max_audio_bitrate = FFMAX(st->codecpar->bit_rate +
862                                       os->muxer_overhead, max_audio_bitrate);
863             is_default = 0;
864         }
865
866         for (i = 0; i < s->nb_streams; i++) {
867             char playlist_file[64];
868             AVStream *st = s->streams[i];
869             OutputStream *os = &c->streams[i];
870             char *agroup = NULL;
871             int stream_bitrate = st->codecpar->bit_rate + os->muxer_overhead;
872             if ((st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) && max_audio_bitrate) {
873                 agroup = (char *)audio_group;
874                 stream_bitrate += max_audio_bitrate;
875             }
876             get_hls_playlist_name(playlist_file, sizeof(playlist_file), NULL, i);
877             ff_hls_write_stream_info(st, out, stream_bitrate, playlist_file, agroup, NULL, NULL);
878         }
879         avio_close(out);
880         if (use_rename)
881             if ((ret = avpriv_io_move(temp_filename, filename_hls)) < 0)
882                 return ret;
883         c->master_playlist_created = 1;
884     }
885
886     return 0;
887 }
888
889 static int dict_copy_entry(AVDictionary **dst, const AVDictionary *src, const char *key)
890 {
891     AVDictionaryEntry *entry = av_dict_get(src, key, NULL, 0);
892     if (entry)
893         av_dict_set(dst, key, entry->value, AV_DICT_DONT_OVERWRITE);
894     return 0;
895 }
896
897 static int dash_init(AVFormatContext *s)
898 {
899     DASHContext *c = s->priv_data;
900     int ret = 0, i;
901     char *ptr;
902     char basename[1024];
903
904     if (c->single_file_name)
905         c->single_file = 1;
906     if (c->single_file)
907         c->use_template = 0;
908
909 #if FF_API_DASH_MIN_SEG_DURATION
910     if (c->min_seg_duration != 5000000) {
911         av_log(s, AV_LOG_WARNING, "The min_seg_duration option is deprecated and will be removed. Please use the -seg_duration\n");
912         c->seg_duration = c->min_seg_duration;
913     }
914 #endif
915
916     av_strlcpy(c->dirname, s->url, sizeof(c->dirname));
917     ptr = strrchr(c->dirname, '/');
918     if (ptr) {
919         av_strlcpy(basename, &ptr[1], sizeof(basename));
920         ptr[1] = '\0';
921     } else {
922         c->dirname[0] = '\0';
923         av_strlcpy(basename, s->url, sizeof(basename));
924     }
925
926     ptr = strrchr(basename, '.');
927     if (ptr)
928         *ptr = '\0';
929
930     c->streams = av_mallocz(sizeof(*c->streams) * s->nb_streams);
931     if (!c->streams)
932         return AVERROR(ENOMEM);
933
934     if ((ret = parse_adaptation_sets(s)) < 0)
935         return ret;
936
937     for (i = 0; i < s->nb_streams; i++) {
938         OutputStream *os = &c->streams[i];
939         AdaptationSet *as = &c->as[os->as_idx - 1];
940         AVFormatContext *ctx;
941         AVStream *st;
942         AVDictionary *opts = NULL;
943         char filename[1024];
944
945         os->bit_rate = s->streams[i]->codecpar->bit_rate;
946         if (!os->bit_rate) {
947             int level = s->strict_std_compliance >= FF_COMPLIANCE_STRICT ?
948                         AV_LOG_ERROR : AV_LOG_WARNING;
949             av_log(s, level, "No bit rate set for stream %d\n", i);
950             if (s->strict_std_compliance >= FF_COMPLIANCE_STRICT)
951                 return AVERROR(EINVAL);
952         }
953
954         // copy AdaptationSet language and role from stream metadata
955         dict_copy_entry(&as->metadata, s->streams[i]->metadata, "language");
956         dict_copy_entry(&as->metadata, s->streams[i]->metadata, "role");
957
958         ctx = avformat_alloc_context();
959         if (!ctx)
960             return AVERROR(ENOMEM);
961
962         // choose muxer based on codec: webm for VP8 and opus, mp4 otherwise
963         // note: os->format_name is also used as part of the mimetype of the
964         //       representation, e.g. video/<format_name>
965         if (s->streams[i]->codecpar->codec_id == AV_CODEC_ID_VP8 ||
966             s->streams[i]->codecpar->codec_id == AV_CODEC_ID_OPUS ||
967             s->streams[i]->codecpar->codec_id == AV_CODEC_ID_VORBIS) {
968             snprintf(os->format_name, sizeof(os->format_name), "webm");
969
970             if (s->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
971                 av_log(s, AV_LOG_ERROR,
972                        "WebM support in dashenc is experimental and has not "
973                        "been validated. For testing purposes, make sure "
974                        "to add -strict experimental and override "
975                        "-init_seg_name and -media_seg_name to end with "
976                        "the extension 'webm'.\n");
977                 return AVERROR(EINVAL);
978             }
979         } else {
980             snprintf(os->format_name, sizeof(os->format_name), "mp4");
981         }
982         ctx->oformat = av_guess_format(os->format_name, NULL, NULL);
983         if (!ctx->oformat)
984             return AVERROR_MUXER_NOT_FOUND;
985         os->ctx = ctx;
986         ctx->interrupt_callback    = s->interrupt_callback;
987         ctx->opaque                = s->opaque;
988         ctx->io_close              = s->io_close;
989         ctx->io_open               = s->io_open;
990         ctx->strict_std_compliance = s->strict_std_compliance;
991
992         if (!(st = avformat_new_stream(ctx, NULL)))
993             return AVERROR(ENOMEM);
994         avcodec_parameters_copy(st->codecpar, s->streams[i]->codecpar);
995         st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
996         st->time_base = s->streams[i]->time_base;
997         st->avg_frame_rate = s->streams[i]->avg_frame_rate;
998         ctx->avoid_negative_ts = s->avoid_negative_ts;
999         ctx->flags = s->flags;
1000
1001         if ((ret = avio_open_dyn_buf(&ctx->pb)) < 0)
1002             return ret;
1003
1004         if (c->single_file) {
1005             if (c->single_file_name)
1006                 ff_dash_fill_tmpl_params(os->initfile, sizeof(os->initfile), c->single_file_name, i, 0, os->bit_rate, 0);
1007             else
1008                 snprintf(os->initfile, sizeof(os->initfile), "%s-stream%d.m4s", basename, i);
1009         } else {
1010             ff_dash_fill_tmpl_params(os->initfile, sizeof(os->initfile), c->init_seg_name, i, 0, os->bit_rate, 0);
1011         }
1012         snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
1013         set_http_options(&opts, c);
1014         ret = s->io_open(s, &os->out, filename, AVIO_FLAG_WRITE, &opts);
1015         if (ret < 0)
1016             return ret;
1017         av_dict_free(&opts);
1018         os->init_start_pos = 0;
1019
1020         if (!strcmp(os->format_name, "mp4")) {
1021             if (c->streaming)
1022                 av_dict_set(&opts, "movflags", "frag_every_frame+dash+delay_moov", 0);
1023             else
1024                 av_dict_set(&opts, "movflags", "frag_custom+dash+delay_moov", 0);
1025         } else {
1026             av_dict_set_int(&opts, "cluster_time_limit", c->seg_duration / 1000, 0);
1027             av_dict_set_int(&opts, "cluster_size_limit", 5 * 1024 * 1024, 0); // set a large cluster size limit
1028             av_dict_set_int(&opts, "dash", 1, 0);
1029             av_dict_set_int(&opts, "dash_track_number", i + 1, 0);
1030             av_dict_set_int(&opts, "live", 1, 0);
1031         }
1032         if ((ret = avformat_init_output(ctx, &opts)) < 0)
1033             return ret;
1034         os->ctx_inited = 1;
1035         avio_flush(ctx->pb);
1036         av_dict_free(&opts);
1037
1038         av_log(s, AV_LOG_VERBOSE, "Representation %d init segment will be written to: %s\n", i, filename);
1039
1040         s->streams[i]->time_base = st->time_base;
1041         // If the muxer wants to shift timestamps, request to have them shifted
1042         // already before being handed to this muxer, so we don't have mismatches
1043         // between the MPD and the actual segments.
1044         s->avoid_negative_ts = ctx->avoid_negative_ts;
1045         if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
1046             AVRational avg_frame_rate = s->streams[i]->avg_frame_rate;
1047             if (avg_frame_rate.num > 0) {
1048                 if (av_cmp_q(avg_frame_rate, as->min_frame_rate) < 0)
1049                     as->min_frame_rate = avg_frame_rate;
1050                 if (av_cmp_q(as->max_frame_rate, avg_frame_rate) < 0)
1051                     as->max_frame_rate = avg_frame_rate;
1052             } else {
1053                 as->ambiguous_frame_rate = 1;
1054             }
1055             c->has_video = 1;
1056         }
1057
1058         set_codec_str(s, st->codecpar, &st->avg_frame_rate, os->codec_str,
1059                       sizeof(os->codec_str));
1060         os->first_pts = AV_NOPTS_VALUE;
1061         os->max_pts = AV_NOPTS_VALUE;
1062         os->last_dts = AV_NOPTS_VALUE;
1063         os->segment_index = 1;
1064     }
1065
1066     if (!c->has_video && c->seg_duration <= 0) {
1067         av_log(s, AV_LOG_WARNING, "no video stream and no seg duration set\n");
1068         return AVERROR(EINVAL);
1069     }
1070     return 0;
1071 }
1072
1073 static int dash_write_header(AVFormatContext *s)
1074 {
1075     DASHContext *c = s->priv_data;
1076     int i, ret;
1077     for (i = 0; i < s->nb_streams; i++) {
1078         OutputStream *os = &c->streams[i];
1079         if ((ret = avformat_write_header(os->ctx, NULL)) < 0)
1080             return ret;
1081
1082         // Flush init segment
1083         // Only for WebM segment, since for mp4 delay_moov is set and
1084         // the init segment is thus flushed after the first packets.
1085         if (strcmp(os->format_name, "mp4") &&
1086             (ret = flush_init_segment(s, os)) < 0)
1087             return ret;
1088     }
1089     return ret;
1090 }
1091
1092 static int add_segment(OutputStream *os, const char *file,
1093                        int64_t time, int duration,
1094                        int64_t start_pos, int64_t range_length,
1095                        int64_t index_length, int next_exp_index)
1096 {
1097     int err;
1098     Segment *seg;
1099     if (os->nb_segments >= os->segments_size) {
1100         os->segments_size = (os->segments_size + 1) * 2;
1101         if ((err = av_reallocp(&os->segments, sizeof(*os->segments) *
1102                                os->segments_size)) < 0) {
1103             os->segments_size = 0;
1104             os->nb_segments = 0;
1105             return err;
1106         }
1107     }
1108     seg = av_mallocz(sizeof(*seg));
1109     if (!seg)
1110         return AVERROR(ENOMEM);
1111     av_strlcpy(seg->file, file, sizeof(seg->file));
1112     seg->time = time;
1113     seg->duration = duration;
1114     if (seg->time < 0) { // If pts<0, it is expected to be cut away with an edit list
1115         seg->duration += seg->time;
1116         seg->time = 0;
1117     }
1118     seg->start_pos = start_pos;
1119     seg->range_length = range_length;
1120     seg->index_length = index_length;
1121     os->segments[os->nb_segments++] = seg;
1122     os->segment_index++;
1123     //correcting the segment index if it has fallen behind the expected value
1124     if (os->segment_index < next_exp_index) {
1125         av_log(NULL, AV_LOG_WARNING, "Correcting the segment index after file %s: current=%d corrected=%d\n",
1126                file, os->segment_index, next_exp_index);
1127         os->segment_index = next_exp_index;
1128     }
1129     return 0;
1130 }
1131
1132 static void write_styp(AVIOContext *pb)
1133 {
1134     avio_wb32(pb, 24);
1135     ffio_wfourcc(pb, "styp");
1136     ffio_wfourcc(pb, "msdh");
1137     avio_wb32(pb, 0); /* minor */
1138     ffio_wfourcc(pb, "msdh");
1139     ffio_wfourcc(pb, "msix");
1140 }
1141
1142 static void find_index_range(AVFormatContext *s, const char *full_path,
1143                              int64_t pos, int *index_length)
1144 {
1145     uint8_t buf[8];
1146     AVIOContext *pb;
1147     int ret;
1148
1149     ret = s->io_open(s, &pb, full_path, AVIO_FLAG_READ, NULL);
1150     if (ret < 0)
1151         return;
1152     if (avio_seek(pb, pos, SEEK_SET) != pos) {
1153         ff_format_io_close(s, &pb);
1154         return;
1155     }
1156     ret = avio_read(pb, buf, 8);
1157     ff_format_io_close(s, &pb);
1158     if (ret < 8)
1159         return;
1160     if (AV_RL32(&buf[4]) != MKTAG('s', 'i', 'd', 'x'))
1161         return;
1162     *index_length = AV_RB32(&buf[0]);
1163 }
1164
1165 static int update_stream_extradata(AVFormatContext *s, OutputStream *os,
1166                                    AVCodecParameters *par,
1167                                    AVRational *frame_rate)
1168 {
1169     uint8_t *extradata;
1170
1171     if (os->ctx->streams[0]->codecpar->extradata_size || !par->extradata_size)
1172         return 0;
1173
1174     extradata = av_malloc(par->extradata_size);
1175
1176     if (!extradata)
1177         return AVERROR(ENOMEM);
1178
1179     memcpy(extradata, par->extradata, par->extradata_size);
1180
1181     os->ctx->streams[0]->codecpar->extradata = extradata;
1182     os->ctx->streams[0]->codecpar->extradata_size = par->extradata_size;
1183
1184     set_codec_str(s, par, frame_rate, os->codec_str, sizeof(os->codec_str));
1185
1186     return 0;
1187 }
1188
1189 static void dashenc_delete_file(AVFormatContext *s, char *filename) {
1190     DASHContext *c = s->priv_data;
1191     int http_base_proto = ff_is_http_proto(filename);
1192
1193     if (http_base_proto) {
1194         AVIOContext *out = NULL;
1195         AVDictionary *http_opts = NULL;
1196
1197         set_http_options(&http_opts, c);
1198         av_dict_set(&http_opts, "method", "DELETE", 0);
1199
1200         if (dashenc_io_open(s, &out, filename, &http_opts) < 0) {
1201             av_log(s, AV_LOG_ERROR, "failed to delete %s\n", filename);
1202         }
1203
1204         av_dict_free(&http_opts);
1205         dashenc_io_close(s, &out, filename);
1206     } else if (unlink(filename) < 0) {
1207         av_log(s, AV_LOG_ERROR, "failed to delete %s: %s\n", filename, strerror(errno));
1208     }
1209 }
1210
1211 static int dash_flush(AVFormatContext *s, int final, int stream)
1212 {
1213     DASHContext *c = s->priv_data;
1214     int i, ret = 0;
1215
1216     const char *proto = avio_find_protocol_name(s->url);
1217     int use_rename = proto && !strcmp(proto, "file");
1218
1219     int cur_flush_segment_index = 0, next_exp_index = -1;
1220     if (stream >= 0) {
1221         cur_flush_segment_index = c->streams[stream].segment_index;
1222
1223         //finding the next segment's expected index, based on the current pts value
1224         if (c->use_template && !c->use_timeline && c->index_correction &&
1225             c->streams[stream].last_pts != AV_NOPTS_VALUE &&
1226             c->streams[stream].first_pts != AV_NOPTS_VALUE) {
1227             int64_t pts_diff = av_rescale_q(c->streams[stream].last_pts -
1228                                             c->streams[stream].first_pts,
1229                                             s->streams[stream]->time_base,
1230                                             AV_TIME_BASE_Q);
1231             next_exp_index = (pts_diff / c->seg_duration) + 1;
1232         }
1233     }
1234
1235     for (i = 0; i < s->nb_streams; i++) {
1236         OutputStream *os = &c->streams[i];
1237         AVStream *st = s->streams[i];
1238         int range_length, index_length = 0;
1239
1240         if (!os->packets_written)
1241             continue;
1242
1243         // Flush the single stream that got a keyframe right now.
1244         // Flush all audio streams as well, in sync with video keyframes,
1245         // but not the other video streams.
1246         if (stream >= 0 && i != stream) {
1247             if (s->streams[i]->codecpar->codec_type != AVMEDIA_TYPE_AUDIO)
1248                 continue;
1249             // Make sure we don't flush audio streams multiple times, when
1250             // all video streams are flushed one at a time.
1251             if (c->has_video && os->segment_index > cur_flush_segment_index)
1252                 continue;
1253         }
1254
1255         if (!c->single_file) {
1256             if (!strcmp(os->format_name, "mp4") && !os->written_len)
1257                 write_styp(os->ctx->pb);
1258         } else {
1259             snprintf(os->full_path, sizeof(os->full_path), "%s%s", c->dirname, os->initfile);
1260         }
1261
1262         ret = flush_dynbuf(os, &range_length);
1263         if (ret < 0)
1264             break;
1265         os->packets_written = 0;
1266
1267         if (c->single_file) {
1268             find_index_range(s, os->full_path, os->pos, &index_length);
1269         } else {
1270             dashenc_io_close(s, &os->out, os->temp_path);
1271
1272             if (use_rename) {
1273                 ret = avpriv_io_move(os->temp_path, os->full_path);
1274                 if (ret < 0)
1275                     break;
1276             }
1277         }
1278
1279         if (!os->muxer_overhead)
1280             os->muxer_overhead = ((int64_t) (range_length - os->total_pkt_size) *
1281                                   8 * AV_TIME_BASE) /
1282                                  av_rescale_q(os->max_pts - os->start_pts,
1283                                               st->time_base, AV_TIME_BASE_Q);
1284         os->total_pkt_size = 0;
1285
1286         if (!os->bit_rate) {
1287             // calculate average bitrate of first segment
1288             int64_t bitrate = (int64_t) range_length * 8 * AV_TIME_BASE / av_rescale_q(os->max_pts - os->start_pts,
1289                                                                                        st->time_base,
1290                                                                                        AV_TIME_BASE_Q);
1291             if (bitrate >= 0)
1292                 os->bit_rate = bitrate;
1293         }
1294         add_segment(os, os->filename, os->start_pts, os->max_pts - os->start_pts, os->pos, range_length, index_length, next_exp_index);
1295         av_log(s, AV_LOG_VERBOSE, "Representation %d media segment %d written to: %s\n", i, os->segment_index, os->full_path);
1296
1297         os->pos += range_length;
1298     }
1299
1300     if (c->window_size || (final && c->remove_at_exit)) {
1301         for (i = 0; i < s->nb_streams; i++) {
1302             OutputStream *os = &c->streams[i];
1303             int j;
1304             int remove = os->nb_segments - c->window_size - c->extra_window_size;
1305             if (final && c->remove_at_exit)
1306                 remove = os->nb_segments;
1307             if (remove > 0) {
1308                 for (j = 0; j < remove; j++) {
1309                     char filename[1024];
1310                     snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->segments[j]->file);
1311                     dashenc_delete_file(s, filename);
1312                     av_free(os->segments[j]);
1313                 }
1314                 os->nb_segments -= remove;
1315                 memmove(os->segments, os->segments + remove, os->nb_segments * sizeof(*os->segments));
1316             }
1317         }
1318     }
1319
1320     if (ret >= 0)
1321         ret = write_manifest(s, final);
1322     return ret;
1323 }
1324
1325 static int dash_write_packet(AVFormatContext *s, AVPacket *pkt)
1326 {
1327     DASHContext *c = s->priv_data;
1328     AVStream *st = s->streams[pkt->stream_index];
1329     OutputStream *os = &c->streams[pkt->stream_index];
1330     int64_t seg_end_duration, elapsed_duration;
1331     int ret;
1332
1333     ret = update_stream_extradata(s, os, st->codecpar, &st->avg_frame_rate);
1334     if (ret < 0)
1335         return ret;
1336
1337     // Fill in a heuristic guess of the packet duration, if none is available.
1338     // The mp4 muxer will do something similar (for the last packet in a fragment)
1339     // if nothing is set (setting it for the other packets doesn't hurt).
1340     // By setting a nonzero duration here, we can be sure that the mp4 muxer won't
1341     // invoke its heuristic (this doesn't have to be identical to that algorithm),
1342     // so that we know the exact timestamps of fragments.
1343     if (!pkt->duration && os->last_dts != AV_NOPTS_VALUE)
1344         pkt->duration = pkt->dts - os->last_dts;
1345     os->last_dts = pkt->dts;
1346
1347     // If forcing the stream to start at 0, the mp4 muxer will set the start
1348     // timestamps to 0. Do the same here, to avoid mismatches in duration/timestamps.
1349     if (os->first_pts == AV_NOPTS_VALUE &&
1350         s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
1351         pkt->pts -= pkt->dts;
1352         pkt->dts  = 0;
1353     }
1354
1355     if (os->first_pts == AV_NOPTS_VALUE)
1356         os->first_pts = pkt->pts;
1357     os->last_pts = pkt->pts;
1358
1359     if (!c->availability_start_time[0])
1360         format_date_now(c->availability_start_time,
1361                         sizeof(c->availability_start_time));
1362
1363     if (!os->availability_time_offset && pkt->duration) {
1364         int64_t frame_duration = av_rescale_q(pkt->duration, st->time_base,
1365                                               AV_TIME_BASE_Q);
1366          os->availability_time_offset = ((double) c->seg_duration -
1367                                          frame_duration) / AV_TIME_BASE;
1368     }
1369
1370     if (c->use_template && !c->use_timeline) {
1371         elapsed_duration = pkt->pts - os->first_pts;
1372         seg_end_duration = (int64_t) os->segment_index * c->seg_duration;
1373     } else {
1374         elapsed_duration = pkt->pts - os->start_pts;
1375         seg_end_duration = c->seg_duration;
1376     }
1377
1378     if ((!c->has_video || st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) &&
1379         pkt->flags & AV_PKT_FLAG_KEY && os->packets_written &&
1380         av_compare_ts(elapsed_duration, st->time_base,
1381                       seg_end_duration, AV_TIME_BASE_Q) >= 0) {
1382         int64_t prev_duration = c->last_duration;
1383
1384         c->last_duration = av_rescale_q(pkt->pts - os->start_pts,
1385                                         st->time_base,
1386                                         AV_TIME_BASE_Q);
1387         c->total_duration = av_rescale_q(pkt->pts - os->first_pts,
1388                                          st->time_base,
1389                                          AV_TIME_BASE_Q);
1390
1391         if ((!c->use_timeline || !c->use_template) && prev_duration) {
1392             if (c->last_duration < prev_duration*9/10 ||
1393                 c->last_duration > prev_duration*11/10) {
1394                 av_log(s, AV_LOG_WARNING,
1395                        "Segment durations differ too much, enable use_timeline "
1396                        "and use_template, or keep a stricter keyframe interval\n");
1397             }
1398         }
1399
1400         if ((ret = dash_flush(s, 0, pkt->stream_index)) < 0)
1401             return ret;
1402     }
1403
1404     if (!os->packets_written) {
1405         // If we wrote a previous segment, adjust the start time of the segment
1406         // to the end of the previous one (which is the same as the mp4 muxer
1407         // does). This avoids gaps in the timeline.
1408         if (os->max_pts != AV_NOPTS_VALUE)
1409             os->start_pts = os->max_pts;
1410         else
1411             os->start_pts = pkt->pts;
1412     }
1413     if (os->max_pts == AV_NOPTS_VALUE)
1414         os->max_pts = pkt->pts + pkt->duration;
1415     else
1416         os->max_pts = FFMAX(os->max_pts, pkt->pts + pkt->duration);
1417     os->packets_written++;
1418     os->total_pkt_size += pkt->size;
1419     if ((ret = ff_write_chained(os->ctx, 0, pkt, s, 0)) < 0)
1420         return ret;
1421
1422     if (!os->init_range_length)
1423         flush_init_segment(s, os);
1424
1425     //open the output context when the first frame of a segment is ready
1426     if (!c->single_file && os->packets_written == 1) {
1427         AVDictionary *opts = NULL;
1428         const char *proto = avio_find_protocol_name(s->url);
1429         int use_rename = proto && !strcmp(proto, "file");
1430         os->filename[0] = os->full_path[0] = os->temp_path[0] = '\0';
1431         ff_dash_fill_tmpl_params(os->filename, sizeof(os->filename),
1432                                  c->media_seg_name, pkt->stream_index,
1433                                  os->segment_index, os->bit_rate, os->start_pts);
1434         snprintf(os->full_path, sizeof(os->full_path), "%s%s", c->dirname,
1435                  os->filename);
1436         snprintf(os->temp_path, sizeof(os->temp_path),
1437                  use_rename ? "%s.tmp" : "%s", os->full_path);
1438         set_http_options(&opts, c);
1439         ret = dashenc_io_open(s, &os->out, os->temp_path, &opts);
1440         if (ret < 0)
1441             return ret;
1442         av_dict_free(&opts);
1443     }
1444
1445     //write out the data immediately in streaming mode
1446     if (c->streaming && !strcmp(os->format_name, "mp4")) {
1447         int len = 0;
1448         uint8_t *buf = NULL;
1449         if (!os->written_len)
1450             write_styp(os->ctx->pb);
1451         avio_flush(os->ctx->pb);
1452         len = avio_get_dyn_buf (os->ctx->pb, &buf);
1453         avio_write(os->out, buf + os->written_len, len - os->written_len);
1454         os->written_len = len;
1455         avio_flush(os->out);
1456     }
1457
1458     return ret;
1459 }
1460
1461 static int dash_write_trailer(AVFormatContext *s)
1462 {
1463     DASHContext *c = s->priv_data;
1464
1465     if (s->nb_streams > 0) {
1466         OutputStream *os = &c->streams[0];
1467         // If no segments have been written so far, try to do a crude
1468         // guess of the segment duration
1469         if (!c->last_duration)
1470             c->last_duration = av_rescale_q(os->max_pts - os->start_pts,
1471                                             s->streams[0]->time_base,
1472                                             AV_TIME_BASE_Q);
1473         c->total_duration = av_rescale_q(os->max_pts - os->first_pts,
1474                                          s->streams[0]->time_base,
1475                                          AV_TIME_BASE_Q);
1476     }
1477     dash_flush(s, 1, -1);
1478
1479     if (c->remove_at_exit) {
1480         char filename[1024];
1481         int i;
1482         for (i = 0; i < s->nb_streams; i++) {
1483             OutputStream *os = &c->streams[i];
1484             snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
1485             dashenc_delete_file(s, filename);
1486         }
1487         dashenc_delete_file(s, s->url);
1488     }
1489
1490     return 0;
1491 }
1492
1493 static int dash_check_bitstream(struct AVFormatContext *s, const AVPacket *avpkt)
1494 {
1495     DASHContext *c = s->priv_data;
1496     OutputStream *os = &c->streams[avpkt->stream_index];
1497     AVFormatContext *oc = os->ctx;
1498     if (oc->oformat->check_bitstream) {
1499         int ret;
1500         AVPacket pkt = *avpkt;
1501         pkt.stream_index = 0;
1502         ret = oc->oformat->check_bitstream(oc, &pkt);
1503         if (ret == 1) {
1504             AVStream *st = s->streams[avpkt->stream_index];
1505             AVStream *ost = oc->streams[0];
1506             st->internal->bsfcs = ost->internal->bsfcs;
1507             st->internal->nb_bsfcs = ost->internal->nb_bsfcs;
1508             ost->internal->bsfcs = NULL;
1509             ost->internal->nb_bsfcs = 0;
1510         }
1511         return ret;
1512     }
1513     return 1;
1514 }
1515
1516 #define OFFSET(x) offsetof(DASHContext, x)
1517 #define E AV_OPT_FLAG_ENCODING_PARAM
1518 static const AVOption options[] = {
1519     { "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 },
1520     { "window_size", "number of segments kept in the manifest", OFFSET(window_size), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, E },
1521     { "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 },
1522 #if FF_API_DASH_MIN_SEG_DURATION
1523     { "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 },
1524 #endif
1525     { "seg_duration", "segment duration (in seconds, fractional value can be set)", OFFSET(seg_duration), AV_OPT_TYPE_DURATION, { .i64 = 5000000 }, 0, INT_MAX, E },
1526     { "remove_at_exit", "remove all segments when finished", OFFSET(remove_at_exit), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
1527     { "use_template", "Use SegmentTemplate instead of SegmentList", OFFSET(use_template), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, E },
1528     { "use_timeline", "Use SegmentTimeline in SegmentTemplate", OFFSET(use_timeline), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, E },
1529     { "single_file", "Store all segments in one file, accessed using byte ranges", OFFSET(single_file), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
1530     { "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 },
1531     { "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 },
1532     { "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 },
1533     { "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 },
1534     { "method", "set the HTTP method", OFFSET(method), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
1535     { "http_user_agent", "override User-Agent field in HTTP header", OFFSET(user_agent), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
1536     { "http_persistent", "Use persistent HTTP connections", OFFSET(http_persistent), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, E },
1537     { "hls_playlist", "Generate HLS playlist files(master.m3u8, media_%d.m3u8)", OFFSET(hls_playlist), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
1538     { "streaming", "Enable/Disable streaming mode of output. Each frame will be moof fragment", OFFSET(streaming), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
1539     { "timeout", "set timeout for socket I/O operations", OFFSET(timeout), AV_OPT_TYPE_DURATION, { .i64 = -1 }, -1, INT_MAX, .flags = E },
1540     { "index_correction", "Enable/Disable segment index correction logic", OFFSET(index_correction), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
1541     { NULL },
1542 };
1543
1544 static const AVClass dash_class = {
1545     .class_name = "dash muxer",
1546     .item_name  = av_default_item_name,
1547     .option     = options,
1548     .version    = LIBAVUTIL_VERSION_INT,
1549 };
1550
1551 AVOutputFormat ff_dash_muxer = {
1552     .name           = "dash",
1553     .long_name      = NULL_IF_CONFIG_SMALL("DASH Muxer"),
1554     .extensions     = "mpd",
1555     .priv_data_size = sizeof(DASHContext),
1556     .audio_codec    = AV_CODEC_ID_AAC,
1557     .video_codec    = AV_CODEC_ID_H264,
1558     .flags          = AVFMT_GLOBALHEADER | AVFMT_NOFILE | AVFMT_TS_NEGATIVE,
1559     .init           = dash_init,
1560     .write_header   = dash_write_header,
1561     .write_packet   = dash_write_packet,
1562     .write_trailer  = dash_write_trailer,
1563     .deinit         = dash_free,
1564     .check_bitstream = dash_check_bitstream,
1565     .priv_class     = &dash_class,
1566 };