]> git.sesse.net Git - ffmpeg/blob - libavformat/dashenc.c
avformat/dashdec: add dash demuxer base version
[ffmpeg] / libavformat / dashenc.c
1 /*
2  * MPEG-DASH ISO BMFF segmenter
3  * Copyright (c) 2014 Martin Storsjo
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 #include "config.h"
23 #if HAVE_UNISTD_H
24 #include <unistd.h>
25 #endif
26
27 #include "libavutil/avassert.h"
28 #include "libavutil/avstring.h"
29 #include "libavutil/intreadwrite.h"
30 #include "libavutil/mathematics.h"
31 #include "libavutil/opt.h"
32 #include "libavutil/rational.h"
33 #include "libavutil/time_internal.h"
34
35 #include "avc.h"
36 #include "avformat.h"
37 #include "avio_internal.h"
38 #include "internal.h"
39 #include "isom.h"
40 #include "os_support.h"
41 #include "url.h"
42 #include "dash.h"
43
44 typedef struct Segment {
45     char file[1024];
46     int64_t start_pos;
47     int range_length, index_length;
48     int64_t time;
49     int duration;
50     int n;
51 } Segment;
52
53 typedef struct OutputStream {
54     AVFormatContext *ctx;
55     int ctx_inited;
56     uint8_t iobuf[32768];
57     AVIOContext *out;
58     int packets_written;
59     char initfile[1024];
60     int64_t init_start_pos;
61     int init_range_length;
62     int nb_segments, segments_size, segment_index;
63     Segment **segments;
64     int64_t first_pts, start_pts, max_pts;
65     int64_t last_dts;
66     int bit_rate;
67     char bandwidth_str[64];
68
69     char codec_str[100];
70 } OutputStream;
71
72 typedef struct DASHContext {
73     const AVClass *class;  /* Class for private options. */
74     int window_size;
75     int extra_window_size;
76     int min_seg_duration;
77     int remove_at_exit;
78     int use_template;
79     int use_timeline;
80     int single_file;
81     OutputStream *streams;
82     int has_video, has_audio;
83     int64_t last_duration;
84     int64_t total_duration;
85     char availability_start_time[100];
86     char dirname[1024];
87     const char *single_file_name;
88     const char *init_seg_name;
89     const char *media_seg_name;
90     AVRational min_frame_rate, max_frame_rate;
91     int ambiguous_frame_rate;
92     const char *utc_timing_url;
93 } DASHContext;
94
95 static int dash_write(void *opaque, uint8_t *buf, int buf_size)
96 {
97     OutputStream *os = opaque;
98     if (os->out)
99         avio_write(os->out, buf, buf_size);
100     return buf_size;
101 }
102
103 // RFC 6381
104 static void set_codec_str(AVFormatContext *s, AVCodecParameters *par,
105                           char *str, int size)
106 {
107     const AVCodecTag *tags[2] = { NULL, NULL };
108     uint32_t tag;
109     if (par->codec_type == AVMEDIA_TYPE_VIDEO)
110         tags[0] = ff_codec_movvideo_tags;
111     else if (par->codec_type == AVMEDIA_TYPE_AUDIO)
112         tags[0] = ff_codec_movaudio_tags;
113     else
114         return;
115
116     tag = av_codec_get_tag(tags, par->codec_id);
117     if (!tag)
118         return;
119     if (size < 5)
120         return;
121
122     AV_WL32(str, tag);
123     str[4] = '\0';
124     if (!strcmp(str, "mp4a") || !strcmp(str, "mp4v")) {
125         uint32_t oti;
126         tags[0] = ff_mp4_obj_type;
127         oti = av_codec_get_tag(tags, par->codec_id);
128         if (oti)
129             av_strlcatf(str, size, ".%02"PRIx32, oti);
130         else
131             return;
132
133         if (tag == MKTAG('m', 'p', '4', 'a')) {
134             if (par->extradata_size >= 2) {
135                 int aot = par->extradata[0] >> 3;
136                 if (aot == 31)
137                     aot = ((AV_RB16(par->extradata) >> 5) & 0x3f) + 32;
138                 av_strlcatf(str, size, ".%d", aot);
139             }
140         } else if (tag == MKTAG('m', 'p', '4', 'v')) {
141             // Unimplemented, should output ProfileLevelIndication as a decimal number
142             av_log(s, AV_LOG_WARNING, "Incomplete RFC 6381 codec string for mp4v\n");
143         }
144     } else if (!strcmp(str, "avc1")) {
145         uint8_t *tmpbuf = NULL;
146         uint8_t *extradata = par->extradata;
147         int extradata_size = par->extradata_size;
148         if (!extradata_size)
149             return;
150         if (extradata[0] != 1) {
151             AVIOContext *pb;
152             if (avio_open_dyn_buf(&pb) < 0)
153                 return;
154             if (ff_isom_write_avcc(pb, extradata, extradata_size) < 0) {
155                 ffio_free_dyn_buf(&pb);
156                 return;
157             }
158             extradata_size = avio_close_dyn_buf(pb, &extradata);
159             tmpbuf = extradata;
160         }
161
162         if (extradata_size >= 4)
163             av_strlcatf(str, size, ".%02x%02x%02x",
164                         extradata[1], extradata[2], extradata[3]);
165         av_free(tmpbuf);
166     }
167 }
168
169 static void dash_free(AVFormatContext *s)
170 {
171     DASHContext *c = s->priv_data;
172     int i, j;
173     if (!c->streams)
174         return;
175     for (i = 0; i < s->nb_streams; i++) {
176         OutputStream *os = &c->streams[i];
177         if (os->ctx && os->ctx_inited)
178             av_write_trailer(os->ctx);
179         if (os->ctx && os->ctx->pb)
180             av_free(os->ctx->pb);
181         ff_format_io_close(s, &os->out);
182         if (os->ctx)
183             avformat_free_context(os->ctx);
184         for (j = 0; j < os->nb_segments; j++)
185             av_free(os->segments[j]);
186         av_free(os->segments);
187     }
188     av_freep(&c->streams);
189 }
190
191 static void output_segment_list(OutputStream *os, AVIOContext *out, DASHContext *c)
192 {
193     int i, start_index = 0, start_number = 1;
194     if (c->window_size) {
195         start_index  = FFMAX(os->nb_segments   - c->window_size, 0);
196         start_number = FFMAX(os->segment_index - c->window_size, 1);
197     }
198
199     if (c->use_template) {
200         int timescale = c->use_timeline ? os->ctx->streams[0]->time_base.den : AV_TIME_BASE;
201         avio_printf(out, "\t\t\t\t<SegmentTemplate timescale=\"%d\" ", timescale);
202         if (!c->use_timeline)
203             avio_printf(out, "duration=\"%"PRId64"\" ", c->last_duration);
204         avio_printf(out, "initialization=\"%s\" media=\"%s\" startNumber=\"%d\">\n", c->init_seg_name, c->media_seg_name, c->use_timeline ? start_number : 1);
205         if (c->use_timeline) {
206             int64_t cur_time = 0;
207             avio_printf(out, "\t\t\t\t\t<SegmentTimeline>\n");
208             for (i = start_index; i < os->nb_segments; ) {
209                 Segment *seg = os->segments[i];
210                 int repeat = 0;
211                 avio_printf(out, "\t\t\t\t\t\t<S ");
212                 if (i == start_index || seg->time != cur_time) {
213                     cur_time = seg->time;
214                     avio_printf(out, "t=\"%"PRId64"\" ", seg->time);
215                 }
216                 avio_printf(out, "d=\"%d\" ", seg->duration);
217                 while (i + repeat + 1 < os->nb_segments &&
218                        os->segments[i + repeat + 1]->duration == seg->duration &&
219                        os->segments[i + repeat + 1]->time == os->segments[i + repeat]->time + os->segments[i + repeat]->duration)
220                     repeat++;
221                 if (repeat > 0)
222                     avio_printf(out, "r=\"%d\" ", repeat);
223                 avio_printf(out, "/>\n");
224                 i += 1 + repeat;
225                 cur_time += (1 + repeat) * seg->duration;
226             }
227             avio_printf(out, "\t\t\t\t\t</SegmentTimeline>\n");
228         }
229         avio_printf(out, "\t\t\t\t</SegmentTemplate>\n");
230     } else if (c->single_file) {
231         avio_printf(out, "\t\t\t\t<BaseURL>%s</BaseURL>\n", os->initfile);
232         avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%"PRId64"\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);
233         avio_printf(out, "\t\t\t\t\t<Initialization range=\"%"PRId64"-%"PRId64"\" />\n", os->init_start_pos, os->init_start_pos + os->init_range_length - 1);
234         for (i = start_index; i < os->nb_segments; i++) {
235             Segment *seg = os->segments[i];
236             avio_printf(out, "\t\t\t\t\t<SegmentURL mediaRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->range_length - 1);
237             if (seg->index_length)
238                 avio_printf(out, "indexRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->index_length - 1);
239             avio_printf(out, "/>\n");
240         }
241         avio_printf(out, "\t\t\t\t</SegmentList>\n");
242     } else {
243         avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%"PRId64"\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);
244         avio_printf(out, "\t\t\t\t\t<Initialization sourceURL=\"%s\" />\n", os->initfile);
245         for (i = start_index; i < os->nb_segments; i++) {
246             Segment *seg = os->segments[i];
247             avio_printf(out, "\t\t\t\t\t<SegmentURL media=\"%s\" />\n", seg->file);
248         }
249         avio_printf(out, "\t\t\t\t</SegmentList>\n");
250     }
251 }
252
253 static char *xmlescape(const char *str) {
254     int outlen = strlen(str)*3/2 + 6;
255     char *out = av_realloc(NULL, outlen + 1);
256     int pos = 0;
257     if (!out)
258         return NULL;
259     for (; *str; str++) {
260         if (pos + 6 > outlen) {
261             char *tmp;
262             outlen = 2 * outlen + 6;
263             tmp = av_realloc(out, outlen + 1);
264             if (!tmp) {
265                 av_free(out);
266                 return NULL;
267             }
268             out = tmp;
269         }
270         if (*str == '&') {
271             memcpy(&out[pos], "&amp;", 5);
272             pos += 5;
273         } else if (*str == '<') {
274             memcpy(&out[pos], "&lt;", 4);
275             pos += 4;
276         } else if (*str == '>') {
277             memcpy(&out[pos], "&gt;", 4);
278             pos += 4;
279         } else if (*str == '\'') {
280             memcpy(&out[pos], "&apos;", 6);
281             pos += 6;
282         } else if (*str == '\"') {
283             memcpy(&out[pos], "&quot;", 6);
284             pos += 6;
285         } else {
286             out[pos++] = *str;
287         }
288     }
289     out[pos] = '\0';
290     return out;
291 }
292
293 static void write_time(AVIOContext *out, int64_t time)
294 {
295     int seconds = time / AV_TIME_BASE;
296     int fractions = time % AV_TIME_BASE;
297     int minutes = seconds / 60;
298     int hours = minutes / 60;
299     seconds %= 60;
300     minutes %= 60;
301     avio_printf(out, "PT");
302     if (hours)
303         avio_printf(out, "%dH", hours);
304     if (hours || minutes)
305         avio_printf(out, "%dM", minutes);
306     avio_printf(out, "%d.%dS", seconds, fractions / (AV_TIME_BASE / 10));
307 }
308
309 static void format_date_now(char *buf, int size)
310 {
311     time_t t = time(NULL);
312     struct tm *ptm, tmbuf;
313     ptm = gmtime_r(&t, &tmbuf);
314     if (ptm) {
315         if (!strftime(buf, size, "%Y-%m-%dT%H:%M:%SZ", ptm))
316             buf[0] = '\0';
317     }
318 }
319
320 static int write_manifest(AVFormatContext *s, int final)
321 {
322     DASHContext *c = s->priv_data;
323     AVIOContext *out;
324     char temp_filename[1024];
325     int ret, i, as_id = 0;
326     const char *proto = avio_find_protocol_name(s->filename);
327     int use_rename = proto && !strcmp(proto, "file");
328     static unsigned int warned_non_file = 0;
329     AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
330
331     if (!use_rename && !warned_non_file++)
332         av_log(s, AV_LOG_ERROR, "Cannot use rename on non file protocol, this may lead to races and temporary partial files\n");
333
334     snprintf(temp_filename, sizeof(temp_filename), use_rename ? "%s.tmp" : "%s", s->filename);
335     ret = s->io_open(s, &out, temp_filename, AVIO_FLAG_WRITE, NULL);
336     if (ret < 0) {
337         av_log(s, AV_LOG_ERROR, "Unable to open %s for writing\n", temp_filename);
338         return ret;
339     }
340     avio_printf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
341     avio_printf(out, "<MPD xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
342                 "\txmlns=\"urn:mpeg:dash:schema:mpd:2011\"\n"
343                 "\txmlns:xlink=\"http://www.w3.org/1999/xlink\"\n"
344                 "\txsi:schemaLocation=\"urn:mpeg:DASH:schema:MPD:2011 http://standards.iso.org/ittf/PubliclyAvailableStandards/MPEG-DASH_schema_files/DASH-MPD.xsd\"\n"
345                 "\tprofiles=\"urn:mpeg:dash:profile:isoff-live:2011\"\n"
346                 "\ttype=\"%s\"\n", final ? "static" : "dynamic");
347     if (final) {
348         avio_printf(out, "\tmediaPresentationDuration=\"");
349         write_time(out, c->total_duration);
350         avio_printf(out, "\"\n");
351     } else {
352         int64_t update_period = c->last_duration / AV_TIME_BASE;
353         char now_str[100];
354         if (c->use_template && !c->use_timeline)
355             update_period = 500;
356         avio_printf(out, "\tminimumUpdatePeriod=\"PT%"PRId64"S\"\n", update_period);
357         avio_printf(out, "\tsuggestedPresentationDelay=\"PT%"PRId64"S\"\n", c->last_duration / AV_TIME_BASE);
358         if (!c->availability_start_time[0] && s->nb_streams > 0 && c->streams[0].nb_segments > 0) {
359             format_date_now(c->availability_start_time, sizeof(c->availability_start_time));
360         }
361         if (c->availability_start_time[0])
362             avio_printf(out, "\tavailabilityStartTime=\"%s\"\n", c->availability_start_time);
363         format_date_now(now_str, sizeof(now_str));
364         if (now_str[0])
365             avio_printf(out, "\tpublishTime=\"%s\"\n", now_str);
366         if (c->window_size && c->use_template) {
367             avio_printf(out, "\ttimeShiftBufferDepth=\"");
368             write_time(out, c->last_duration * c->window_size);
369             avio_printf(out, "\"\n");
370         }
371     }
372     avio_printf(out, "\tminBufferTime=\"");
373     write_time(out, c->last_duration * 2);
374     avio_printf(out, "\">\n");
375     avio_printf(out, "\t<ProgramInformation>\n");
376     if (title) {
377         char *escaped = xmlescape(title->value);
378         avio_printf(out, "\t\t<Title>%s</Title>\n", escaped);
379         av_free(escaped);
380     }
381     avio_printf(out, "\t</ProgramInformation>\n");
382     if (c->utc_timing_url)
383         avio_printf(out, "\t<UTCTiming schemeIdUri=\"urn:mpeg:dash:utc:http-xsdate:2014\" value=\"%s\"/>\n", c->utc_timing_url);
384
385     if (c->window_size && s->nb_streams > 0 && c->streams[0].nb_segments > 0 && !c->use_template) {
386         OutputStream *os = &c->streams[0];
387         int start_index = FFMAX(os->nb_segments - c->window_size, 0);
388         int64_t start_time = av_rescale_q(os->segments[start_index]->time, s->streams[0]->time_base, AV_TIME_BASE_Q);
389         avio_printf(out, "\t<Period id=\"0\" start=\"");
390         write_time(out, start_time);
391         avio_printf(out, "\">\n");
392     } else {
393         avio_printf(out, "\t<Period id=\"0\" start=\"PT0.0S\">\n");
394     }
395
396     if (c->has_video) {
397         avio_printf(out, "\t\t<AdaptationSet id=\"%d\" contentType=\"video\" segmentAlignment=\"true\" bitstreamSwitching=\"true\"", as_id++);
398         if (c->max_frame_rate.num && !c->ambiguous_frame_rate)
399             avio_printf(out, " %s=\"%d/%d\"", (av_cmp_q(c->min_frame_rate, c->max_frame_rate) < 0) ? "maxFrameRate" : "frameRate", c->max_frame_rate.num, c->max_frame_rate.den);
400         avio_printf(out, ">\n");
401
402         for (i = 0; i < s->nb_streams; i++) {
403             AVStream *st = s->streams[i];
404             OutputStream *os = &c->streams[i];
405
406             if (st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO)
407                 continue;
408
409             avio_printf(out, "\t\t\t<Representation id=\"%d\" mimeType=\"video/mp4\" codecs=\"%s\"%s width=\"%d\" height=\"%d\"", i, os->codec_str, os->bandwidth_str, st->codecpar->width, st->codecpar->height);
410             if (st->avg_frame_rate.num)
411                 avio_printf(out, " frameRate=\"%d/%d\"", st->avg_frame_rate.num, st->avg_frame_rate.den);
412             avio_printf(out, ">\n");
413
414             output_segment_list(&c->streams[i], out, c);
415             avio_printf(out, "\t\t\t</Representation>\n");
416         }
417         avio_printf(out, "\t\t</AdaptationSet>\n");
418     }
419     if (c->has_audio) {
420         avio_printf(out, "\t\t<AdaptationSet id=\"%d\" contentType=\"audio\" segmentAlignment=\"true\" bitstreamSwitching=\"true\">\n", as_id++);
421         for (i = 0; i < s->nb_streams; i++) {
422             AVStream *st = s->streams[i];
423             OutputStream *os = &c->streams[i];
424
425             if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO)
426                 continue;
427
428             avio_printf(out, "\t\t\t<Representation id=\"%d\" mimeType=\"audio/mp4\" codecs=\"%s\"%s audioSamplingRate=\"%d\">\n", i, os->codec_str, os->bandwidth_str, st->codecpar->sample_rate);
429             avio_printf(out, "\t\t\t\t<AudioChannelConfiguration schemeIdUri=\"urn:mpeg:dash:23003:3:audio_channel_configuration:2011\" value=\"%d\" />\n", st->codecpar->channels);
430             output_segment_list(&c->streams[i], out, c);
431             avio_printf(out, "\t\t\t</Representation>\n");
432         }
433         avio_printf(out, "\t\t</AdaptationSet>\n");
434     }
435     avio_printf(out, "\t</Period>\n");
436     avio_printf(out, "</MPD>\n");
437     avio_flush(out);
438     ff_format_io_close(s, &out);
439
440     if (use_rename)
441         return avpriv_io_move(temp_filename, s->filename);
442
443     return 0;
444 }
445
446 static int set_bitrate(AVFormatContext *s)
447 {
448     DASHContext *c = s->priv_data;
449     int i;
450
451     for (i = 0; i < s->nb_streams; i++) {
452         OutputStream *os = &c->streams[i];
453
454         os->bit_rate = s->streams[i]->codecpar->bit_rate;
455         if (os->bit_rate) {
456             snprintf(os->bandwidth_str, sizeof(os->bandwidth_str),
457                      " bandwidth=\"%d\"", os->bit_rate);
458         } else {
459             int level = s->strict_std_compliance >= FF_COMPLIANCE_STRICT ?
460                         AV_LOG_ERROR : AV_LOG_WARNING;
461             av_log(s, level, "No bit rate set for stream %d\n", i);
462             if (s->strict_std_compliance >= FF_COMPLIANCE_STRICT)
463                 return AVERROR(EINVAL);
464         }
465     }
466
467     return 0;
468 }
469
470 static int dash_init(AVFormatContext *s)
471 {
472     DASHContext *c = s->priv_data;
473     int ret = 0, i;
474     AVOutputFormat *oformat;
475     char *ptr;
476     char basename[1024];
477
478     if (c->single_file_name)
479         c->single_file = 1;
480     if (c->single_file)
481         c->use_template = 0;
482     c->ambiguous_frame_rate = 0;
483
484     av_strlcpy(c->dirname, s->filename, sizeof(c->dirname));
485     ptr = strrchr(c->dirname, '/');
486     if (ptr) {
487         av_strlcpy(basename, &ptr[1], sizeof(basename));
488         ptr[1] = '\0';
489     } else {
490         c->dirname[0] = '\0';
491         av_strlcpy(basename, s->filename, sizeof(basename));
492     }
493
494     ptr = strrchr(basename, '.');
495     if (ptr)
496         *ptr = '\0';
497
498     oformat = av_guess_format("mp4", NULL, NULL);
499     if (!oformat)
500         return AVERROR_MUXER_NOT_FOUND;
501
502     c->streams = av_mallocz(sizeof(*c->streams) * s->nb_streams);
503     if (!c->streams)
504         return AVERROR(ENOMEM);
505
506     ret = set_bitrate(s);
507     if (ret < 0)
508         return ret;
509
510     for (i = 0; i < s->nb_streams; i++) {
511         OutputStream *os = &c->streams[i];
512         AVFormatContext *ctx;
513         AVStream *st;
514         AVDictionary *opts = NULL;
515         char filename[1024];
516
517         ctx = avformat_alloc_context();
518         if (!ctx)
519             return AVERROR(ENOMEM);
520         os->ctx = ctx;
521         ctx->oformat = oformat;
522         ctx->interrupt_callback = s->interrupt_callback;
523         ctx->opaque             = s->opaque;
524         ctx->io_close           = s->io_close;
525         ctx->io_open            = s->io_open;
526
527         if (!(st = avformat_new_stream(ctx, NULL)))
528             return AVERROR(ENOMEM);
529         avcodec_parameters_copy(st->codecpar, s->streams[i]->codecpar);
530         st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
531         st->time_base = s->streams[i]->time_base;
532         ctx->avoid_negative_ts = s->avoid_negative_ts;
533         ctx->flags = s->flags;
534
535         ctx->pb = avio_alloc_context(os->iobuf, sizeof(os->iobuf), AVIO_FLAG_WRITE, os, NULL, dash_write, NULL);
536         if (!ctx->pb)
537             return AVERROR(ENOMEM);
538
539         if (c->single_file) {
540             if (c->single_file_name)
541                 ff_dash_fill_tmpl_params(os->initfile, sizeof(os->initfile), c->single_file_name, i, 0, os->bit_rate, 0);
542             else
543                 snprintf(os->initfile, sizeof(os->initfile), "%s-stream%d.m4s", basename, i);
544         } else {
545             ff_dash_fill_tmpl_params(os->initfile, sizeof(os->initfile), c->init_seg_name, i, 0, os->bit_rate, 0);
546         }
547         snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
548         ret = s->io_open(s, &os->out, filename, AVIO_FLAG_WRITE, NULL);
549         if (ret < 0)
550             return ret;
551         os->init_start_pos = 0;
552
553         av_dict_set(&opts, "movflags", "frag_custom+dash+delay_moov", 0);
554         if ((ret = avformat_init_output(ctx, &opts)) < 0)
555             return ret;
556         os->ctx_inited = 1;
557         avio_flush(ctx->pb);
558         av_dict_free(&opts);
559
560         av_log(s, AV_LOG_VERBOSE, "Representation %d init segment will be written to: %s\n", i, filename);
561
562         s->streams[i]->time_base = st->time_base;
563         // If the muxer wants to shift timestamps, request to have them shifted
564         // already before being handed to this muxer, so we don't have mismatches
565         // between the MPD and the actual segments.
566         s->avoid_negative_ts = ctx->avoid_negative_ts;
567         if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
568             AVRational avg_frame_rate = s->streams[i]->avg_frame_rate;
569             if (avg_frame_rate.num > 0) {
570                 if (av_cmp_q(avg_frame_rate, c->min_frame_rate) < 0)
571                     c->min_frame_rate = avg_frame_rate;
572                 if (av_cmp_q(c->max_frame_rate, avg_frame_rate) < 0)
573                     c->max_frame_rate = avg_frame_rate;
574             } else {
575                 c->ambiguous_frame_rate = 1;
576             }
577             c->has_video = 1;
578         } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
579             c->has_audio = 1;
580         }
581
582         set_codec_str(s, st->codecpar, os->codec_str, sizeof(os->codec_str));
583         os->first_pts = AV_NOPTS_VALUE;
584         os->max_pts = AV_NOPTS_VALUE;
585         os->last_dts = AV_NOPTS_VALUE;
586         os->segment_index = 1;
587     }
588
589     if (!c->has_video && c->min_seg_duration <= 0) {
590         av_log(s, AV_LOG_WARNING, "no video stream and no min seg duration set\n");
591         return AVERROR(EINVAL);
592     }
593     return 0;
594 }
595
596 static int dash_write_header(AVFormatContext *s)
597 {
598     DASHContext *c = s->priv_data;
599     int i, ret;
600     for (i = 0; i < s->nb_streams; i++) {
601         OutputStream *os = &c->streams[i];
602         if ((ret = avformat_write_header(os->ctx, NULL)) < 0) {
603             dash_free(s);
604             return ret;
605         }
606     }
607     ret = write_manifest(s, 0);
608     if (!ret)
609         av_log(s, AV_LOG_VERBOSE, "Manifest written to: %s\n", s->filename);
610     return ret;
611 }
612
613 static int add_segment(OutputStream *os, const char *file,
614                        int64_t time, int duration,
615                        int64_t start_pos, int64_t range_length,
616                        int64_t index_length)
617 {
618     int err;
619     Segment *seg;
620     if (os->nb_segments >= os->segments_size) {
621         os->segments_size = (os->segments_size + 1) * 2;
622         if ((err = av_reallocp(&os->segments, sizeof(*os->segments) *
623                                os->segments_size)) < 0) {
624             os->segments_size = 0;
625             os->nb_segments = 0;
626             return err;
627         }
628     }
629     seg = av_mallocz(sizeof(*seg));
630     if (!seg)
631         return AVERROR(ENOMEM);
632     av_strlcpy(seg->file, file, sizeof(seg->file));
633     seg->time = time;
634     seg->duration = duration;
635     if (seg->time < 0) { // If pts<0, it is expected to be cut away with an edit list
636         seg->duration += seg->time;
637         seg->time = 0;
638     }
639     seg->start_pos = start_pos;
640     seg->range_length = range_length;
641     seg->index_length = index_length;
642     os->segments[os->nb_segments++] = seg;
643     os->segment_index++;
644     return 0;
645 }
646
647 static void write_styp(AVIOContext *pb)
648 {
649     avio_wb32(pb, 24);
650     ffio_wfourcc(pb, "styp");
651     ffio_wfourcc(pb, "msdh");
652     avio_wb32(pb, 0); /* minor */
653     ffio_wfourcc(pb, "msdh");
654     ffio_wfourcc(pb, "msix");
655 }
656
657 static void find_index_range(AVFormatContext *s, const char *full_path,
658                              int64_t pos, int *index_length)
659 {
660     uint8_t buf[8];
661     AVIOContext *pb;
662     int ret;
663
664     ret = s->io_open(s, &pb, full_path, AVIO_FLAG_READ, NULL);
665     if (ret < 0)
666         return;
667     if (avio_seek(pb, pos, SEEK_SET) != pos) {
668         ff_format_io_close(s, &pb);
669         return;
670     }
671     ret = avio_read(pb, buf, 8);
672     ff_format_io_close(s, &pb);
673     if (ret < 8)
674         return;
675     if (AV_RL32(&buf[4]) != MKTAG('s', 'i', 'd', 'x'))
676         return;
677     *index_length = AV_RB32(&buf[0]);
678 }
679
680 static int update_stream_extradata(AVFormatContext *s, OutputStream *os,
681                                    AVCodecParameters *par)
682 {
683     uint8_t *extradata;
684
685     if (os->ctx->streams[0]->codecpar->extradata_size || !par->extradata_size)
686         return 0;
687
688     extradata = av_malloc(par->extradata_size);
689
690     if (!extradata)
691         return AVERROR(ENOMEM);
692
693     memcpy(extradata, par->extradata, par->extradata_size);
694
695     os->ctx->streams[0]->codecpar->extradata = extradata;
696     os->ctx->streams[0]->codecpar->extradata_size = par->extradata_size;
697
698     set_codec_str(s, par, os->codec_str, sizeof(os->codec_str));
699
700     return 0;
701 }
702
703 static int dash_flush(AVFormatContext *s, int final, int stream)
704 {
705     DASHContext *c = s->priv_data;
706     int i, ret = 0;
707
708     const char *proto = avio_find_protocol_name(s->filename);
709     int use_rename = proto && !strcmp(proto, "file");
710
711     int cur_flush_segment_index = 0;
712     if (stream >= 0)
713         cur_flush_segment_index = c->streams[stream].segment_index;
714
715     for (i = 0; i < s->nb_streams; i++) {
716         OutputStream *os = &c->streams[i];
717         char filename[1024] = "", full_path[1024], temp_path[1024];
718         int64_t start_pos;
719         int range_length, index_length = 0;
720
721         if (!os->packets_written)
722             continue;
723
724         // Flush the single stream that got a keyframe right now.
725         // Flush all audio streams as well, in sync with video keyframes,
726         // but not the other video streams.
727         if (stream >= 0 && i != stream) {
728             if (s->streams[i]->codecpar->codec_type != AVMEDIA_TYPE_AUDIO)
729                 continue;
730             // Make sure we don't flush audio streams multiple times, when
731             // all video streams are flushed one at a time.
732             if (c->has_video && os->segment_index > cur_flush_segment_index)
733                 continue;
734         }
735
736         if (!os->init_range_length) {
737             av_write_frame(os->ctx, NULL);
738             os->init_range_length = avio_tell(os->ctx->pb);
739             if (!c->single_file)
740                 ff_format_io_close(s, &os->out);
741         }
742
743         start_pos = avio_tell(os->ctx->pb);
744
745         if (!c->single_file) {
746             ff_dash_fill_tmpl_params(filename, sizeof(filename), c->media_seg_name, i, os->segment_index, os->bit_rate, os->start_pts);
747             snprintf(full_path, sizeof(full_path), "%s%s", c->dirname, filename);
748             snprintf(temp_path, sizeof(temp_path), use_rename ? "%s.tmp" : "%s", full_path);
749             ret = s->io_open(s, &os->out, temp_path, AVIO_FLAG_WRITE, NULL);
750             if (ret < 0)
751                 break;
752             write_styp(os->ctx->pb);
753         } else {
754             snprintf(full_path, sizeof(full_path), "%s%s", c->dirname, os->initfile);
755         }
756
757         av_write_frame(os->ctx, NULL);
758         avio_flush(os->ctx->pb);
759         os->packets_written = 0;
760
761         range_length = avio_tell(os->ctx->pb) - start_pos;
762         if (c->single_file) {
763             find_index_range(s, full_path, start_pos, &index_length);
764         } else {
765             ff_format_io_close(s, &os->out);
766
767             if (use_rename) {
768                 ret = avpriv_io_move(temp_path, full_path);
769                 if (ret < 0)
770                     break;
771             }
772         }
773         add_segment(os, filename, os->start_pts, os->max_pts - os->start_pts, start_pos, range_length, index_length);
774         av_log(s, AV_LOG_VERBOSE, "Representation %d media segment %d written to: %s\n", i, os->segment_index, full_path);
775     }
776
777     if (c->window_size || (final && c->remove_at_exit)) {
778         for (i = 0; i < s->nb_streams; i++) {
779             OutputStream *os = &c->streams[i];
780             int j;
781             int remove = os->nb_segments - c->window_size - c->extra_window_size;
782             if (final && c->remove_at_exit)
783                 remove = os->nb_segments;
784             if (remove > 0) {
785                 for (j = 0; j < remove; j++) {
786                     char filename[1024];
787                     snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->segments[j]->file);
788                     unlink(filename);
789                     av_free(os->segments[j]);
790                 }
791                 os->nb_segments -= remove;
792                 memmove(os->segments, os->segments + remove, os->nb_segments * sizeof(*os->segments));
793             }
794         }
795     }
796
797     if (ret >= 0)
798         ret = write_manifest(s, final);
799     return ret;
800 }
801
802 static int dash_write_packet(AVFormatContext *s, AVPacket *pkt)
803 {
804     DASHContext *c = s->priv_data;
805     AVStream *st = s->streams[pkt->stream_index];
806     OutputStream *os = &c->streams[pkt->stream_index];
807     int ret;
808
809     ret = update_stream_extradata(s, os, st->codecpar);
810     if (ret < 0)
811         return ret;
812
813     // Fill in a heuristic guess of the packet duration, if none is available.
814     // The mp4 muxer will do something similar (for the last packet in a fragment)
815     // if nothing is set (setting it for the other packets doesn't hurt).
816     // By setting a nonzero duration here, we can be sure that the mp4 muxer won't
817     // invoke its heuristic (this doesn't have to be identical to that algorithm),
818     // so that we know the exact timestamps of fragments.
819     if (!pkt->duration && os->last_dts != AV_NOPTS_VALUE)
820         pkt->duration = pkt->dts - os->last_dts;
821     os->last_dts = pkt->dts;
822
823     // If forcing the stream to start at 0, the mp4 muxer will set the start
824     // timestamps to 0. Do the same here, to avoid mismatches in duration/timestamps.
825     if (os->first_pts == AV_NOPTS_VALUE &&
826         s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
827         pkt->pts -= pkt->dts;
828         pkt->dts  = 0;
829     }
830
831     if (os->first_pts == AV_NOPTS_VALUE)
832         os->first_pts = pkt->pts;
833
834     if ((!c->has_video || st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) &&
835         pkt->flags & AV_PKT_FLAG_KEY && os->packets_written &&
836         av_compare_ts(pkt->pts - os->start_pts, st->time_base,
837                       c->min_seg_duration, AV_TIME_BASE_Q) >= 0) {
838         int64_t prev_duration = c->last_duration;
839
840         c->last_duration = av_rescale_q(pkt->pts - os->start_pts,
841                                         st->time_base,
842                                         AV_TIME_BASE_Q);
843         c->total_duration = av_rescale_q(pkt->pts - os->first_pts,
844                                          st->time_base,
845                                          AV_TIME_BASE_Q);
846
847         if ((!c->use_timeline || !c->use_template) && prev_duration) {
848             if (c->last_duration < prev_duration*9/10 ||
849                 c->last_duration > prev_duration*11/10) {
850                 av_log(s, AV_LOG_WARNING,
851                        "Segment durations differ too much, enable use_timeline "
852                        "and use_template, or keep a stricter keyframe interval\n");
853             }
854         }
855
856         if ((ret = dash_flush(s, 0, pkt->stream_index)) < 0)
857             return ret;
858     }
859
860     if (!os->packets_written) {
861         // If we wrote a previous segment, adjust the start time of the segment
862         // to the end of the previous one (which is the same as the mp4 muxer
863         // does). This avoids gaps in the timeline.
864         if (os->max_pts != AV_NOPTS_VALUE)
865             os->start_pts = os->max_pts;
866         else
867             os->start_pts = pkt->pts;
868     }
869     if (os->max_pts == AV_NOPTS_VALUE)
870         os->max_pts = pkt->pts + pkt->duration;
871     else
872         os->max_pts = FFMAX(os->max_pts, pkt->pts + pkt->duration);
873     os->packets_written++;
874     return ff_write_chained(os->ctx, 0, pkt, s, 0);
875 }
876
877 static int dash_write_trailer(AVFormatContext *s)
878 {
879     DASHContext *c = s->priv_data;
880
881     set_bitrate(s);
882
883     if (s->nb_streams > 0) {
884         OutputStream *os = &c->streams[0];
885         // If no segments have been written so far, try to do a crude
886         // guess of the segment duration
887         if (!c->last_duration)
888             c->last_duration = av_rescale_q(os->max_pts - os->start_pts,
889                                             s->streams[0]->time_base,
890                                             AV_TIME_BASE_Q);
891         c->total_duration = av_rescale_q(os->max_pts - os->first_pts,
892                                          s->streams[0]->time_base,
893                                          AV_TIME_BASE_Q);
894     }
895     dash_flush(s, 1, -1);
896
897     if (c->remove_at_exit) {
898         char filename[1024];
899         int i;
900         for (i = 0; i < s->nb_streams; i++) {
901             OutputStream *os = &c->streams[i];
902             snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
903             unlink(filename);
904         }
905         unlink(s->filename);
906     }
907
908     return 0;
909 }
910
911 static int dash_check_bitstream(struct AVFormatContext *s, const AVPacket *avpkt)
912 {
913     DASHContext *c = s->priv_data;
914     OutputStream *os = &c->streams[avpkt->stream_index];
915     AVFormatContext *oc = os->ctx;
916     if (oc->oformat->check_bitstream) {
917         int ret;
918         AVPacket pkt = *avpkt;
919         pkt.stream_index = 0;
920         ret = oc->oformat->check_bitstream(oc, &pkt);
921         if (ret == 1) {
922             AVStream *st = s->streams[avpkt->stream_index];
923             AVStream *ost = oc->streams[0];
924             st->internal->bsfcs = ost->internal->bsfcs;
925             st->internal->nb_bsfcs = ost->internal->nb_bsfcs;
926             ost->internal->bsfcs = NULL;
927             ost->internal->nb_bsfcs = 0;
928         }
929         return ret;
930     }
931     return 1;
932 }
933
934 #define OFFSET(x) offsetof(DASHContext, x)
935 #define E AV_OPT_FLAG_ENCODING_PARAM
936 static const AVOption options[] = {
937     { "window_size", "number of segments kept in the manifest", OFFSET(window_size), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, E },
938     { "extra_window_size", "number of segments kept outside of the manifest before removing from disk", OFFSET(extra_window_size), AV_OPT_TYPE_INT, { .i64 = 5 }, 0, INT_MAX, E },
939     { "min_seg_duration", "minimum segment duration (in microseconds)", OFFSET(min_seg_duration), AV_OPT_TYPE_INT64, { .i64 = 5000000 }, 0, INT_MAX, E },
940     { "remove_at_exit", "remove all segments when finished", OFFSET(remove_at_exit), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
941     { "use_template", "Use SegmentTemplate instead of SegmentList", OFFSET(use_template), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, E },
942     { "use_timeline", "Use SegmentTimeline in SegmentTemplate", OFFSET(use_timeline), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, E },
943     { "single_file", "Store all segments in one file, accessed using byte ranges", OFFSET(single_file), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
944     { "single_file_name", "DASH-templated name to be used for baseURL. Implies storing all segments in one file, accessed using byte ranges", OFFSET(single_file_name), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, E },
945     { "init_seg_name", "DASH-templated name to used for the initialization segment", OFFSET(init_seg_name), AV_OPT_TYPE_STRING, {.str = "init-stream$RepresentationID$.m4s"}, 0, 0, E },
946     { "media_seg_name", "DASH-templated name to used for the media segments", OFFSET(media_seg_name), AV_OPT_TYPE_STRING, {.str = "chunk-stream$RepresentationID$-$Number%05d$.m4s"}, 0, 0, E },
947     { "utc_timing_url", "URL of the page that will return the UTC timestamp in ISO format", OFFSET(utc_timing_url), AV_OPT_TYPE_STRING, { 0 }, 0, 0, E },
948     { NULL },
949 };
950
951 static const AVClass dash_class = {
952     .class_name = "dash muxer",
953     .item_name  = av_default_item_name,
954     .option     = options,
955     .version    = LIBAVUTIL_VERSION_INT,
956 };
957
958 AVOutputFormat ff_dash_muxer = {
959     .name           = "dash",
960     .long_name      = NULL_IF_CONFIG_SMALL("DASH Muxer"),
961     .priv_data_size = sizeof(DASHContext),
962     .audio_codec    = AV_CODEC_ID_AAC,
963     .video_codec    = AV_CODEC_ID_H264,
964     .flags          = AVFMT_GLOBALHEADER | AVFMT_NOFILE | AVFMT_TS_NEGATIVE,
965     .init           = dash_init,
966     .write_header   = dash_write_header,
967     .write_packet   = dash_write_packet,
968     .write_trailer  = dash_write_trailer,
969     .deinit         = dash_free,
970     .check_bitstream = dash_check_bitstream,
971     .priv_class     = &dash_class,
972 };