]> git.sesse.net Git - ffmpeg/blob - libavformat/dashenc.c
dashenc: Adjust the start time of a segment to the end of the previous segment
[ffmpeg] / libavformat / dashenc.c
1 /*
2  * MPEG-DASH ISO BMFF segmenter
3  * Copyright (c) 2014 Martin Storsjo
4  *
5  * This file is part of Libav.
6  *
7  * Libav 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  * Libav 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 Libav; 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/avstring.h"
28 #include "libavutil/intreadwrite.h"
29 #include "libavutil/mathematics.h"
30 #include "libavutil/opt.h"
31 #include "libavutil/time_internal.h"
32
33 #include "avc.h"
34 #include "avformat.h"
35 #include "avio_internal.h"
36 #include "internal.h"
37 #include "isom.h"
38 #include "os_support.h"
39 #include "url.h"
40
41 // See ISO/IEC 23009-1:2014 5.3.9.4.4
42 typedef enum {
43     DASH_TMPL_ID_UNDEFINED = -1,
44     DASH_TMPL_ID_ESCAPE,
45     DASH_TMPL_ID_REP_ID,
46     DASH_TMPL_ID_NUMBER,
47     DASH_TMPL_ID_BANDWIDTH,
48     DASH_TMPL_ID_TIME,
49 } DASHTmplId;
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 OutputStream {
61     AVFormatContext *ctx;
62     int ctx_inited;
63     uint8_t iobuf[32768];
64     URLContext *out;
65     int packets_written;
66     char initfile[1024];
67     int64_t init_start_pos;
68     int init_range_length;
69     int nb_segments, segments_size, segment_index;
70     Segment **segments;
71     int64_t first_dts, start_dts, end_dts;
72     int bit_rate;
73     char bandwidth_str[64];
74
75     char codec_str[100];
76 } OutputStream;
77
78 typedef struct DASHContext {
79     const AVClass *class;  /* Class for private options. */
80     int window_size;
81     int extra_window_size;
82     int min_seg_duration;
83     int remove_at_exit;
84     int use_template;
85     int use_timeline;
86     int single_file;
87     OutputStream *streams;
88     int has_video, has_audio;
89     int64_t last_duration;
90     int64_t total_duration;
91     char availability_start_time[100];
92     char dirname[1024];
93     const char *single_file_name;
94     const char *init_seg_name;
95     const char *media_seg_name;
96 } DASHContext;
97
98 static int dash_write(void *opaque, uint8_t *buf, int buf_size)
99 {
100     OutputStream *os = opaque;
101     if (os->out)
102         ffurl_write(os->out, buf, buf_size);
103     return buf_size;
104 }
105
106 // RFC 6381
107 static void set_codec_str(AVFormatContext *s, AVCodecContext *codec,
108                           char *str, int size)
109 {
110     const AVCodecTag *tags[2] = { NULL, NULL };
111     uint32_t tag;
112     if (codec->codec_type == AVMEDIA_TYPE_VIDEO)
113         tags[0] = ff_codec_movvideo_tags;
114     else if (codec->codec_type == AVMEDIA_TYPE_AUDIO)
115         tags[0] = ff_codec_movaudio_tags;
116     else
117         return;
118
119     tag = av_codec_get_tag(tags, codec->codec_id);
120     if (!tag)
121         return;
122     if (size < 5)
123         return;
124
125     AV_WL32(str, tag);
126     str[4] = '\0';
127     if (!strcmp(str, "mp4a") || !strcmp(str, "mp4v")) {
128         uint32_t oti;
129         tags[0] = ff_mp4_obj_type;
130         oti = av_codec_get_tag(tags, codec->codec_id);
131         if (oti)
132             av_strlcatf(str, size, ".%02x", oti);
133         else
134             return;
135
136         if (tag == MKTAG('m', 'p', '4', 'a')) {
137             if (codec->extradata_size >= 2) {
138                 int aot = codec->extradata[0] >> 3;
139                 if (aot == 31)
140                     aot = ((AV_RB16(codec->extradata) >> 5) & 0x3f) + 32;
141                 av_strlcatf(str, size, ".%d", aot);
142             }
143         } else if (tag == MKTAG('m', 'p', '4', 'v')) {
144             // Unimplemented, should output ProfileLevelIndication as a decimal number
145             av_log(s, AV_LOG_WARNING, "Incomplete RFC 6381 codec string for mp4v\n");
146         }
147     } else if (!strcmp(str, "avc1")) {
148         uint8_t *tmpbuf = NULL;
149         uint8_t *extradata = codec->extradata;
150         int extradata_size = codec->extradata_size;
151         if (!extradata_size)
152             return;
153         if (extradata[0] != 1) {
154             AVIOContext *pb;
155             if (avio_open_dyn_buf(&pb) < 0)
156                 return;
157             if (ff_isom_write_avcc(pb, extradata, extradata_size) < 0) {
158                 avio_close_dyn_buf(pb, &tmpbuf);
159                 av_free(tmpbuf);
160                 return;
161             }
162             extradata_size = avio_close_dyn_buf(pb, &extradata);
163             tmpbuf = extradata;
164         }
165
166         if (extradata_size >= 4)
167             av_strlcatf(str, size, ".%02x%02x%02x",
168                         extradata[1], extradata[2], extradata[3]);
169         av_free(tmpbuf);
170     }
171 }
172
173 static void dash_free(AVFormatContext *s)
174 {
175     DASHContext *c = s->priv_data;
176     int i, j;
177     if (!c->streams)
178         return;
179     for (i = 0; i < s->nb_streams; i++) {
180         OutputStream *os = &c->streams[i];
181         if (os->ctx && os->ctx_inited)
182             av_write_trailer(os->ctx);
183         if (os->ctx && os->ctx->pb)
184             av_free(os->ctx->pb);
185         ffurl_close(os->out);
186         os->out =  NULL;
187         if (os->ctx)
188             avformat_free_context(os->ctx);
189         for (j = 0; j < os->nb_segments; j++)
190             av_free(os->segments[j]);
191         av_free(os->segments);
192     }
193     av_freep(&c->streams);
194 }
195
196 static void output_segment_list(OutputStream *os, AVIOContext *out, DASHContext *c)
197 {
198     int i, start_index = 0, start_number = 1;
199     if (c->window_size) {
200         start_index  = FFMAX(os->nb_segments   - c->window_size, 0);
201         start_number = FFMAX(os->segment_index - c->window_size, 1);
202     }
203
204     if (c->use_template) {
205         int timescale = c->use_timeline ? os->ctx->streams[0]->time_base.den : AV_TIME_BASE;
206         avio_printf(out, "\t\t\t\t<SegmentTemplate timescale=\"%d\" ", timescale);
207         if (!c->use_timeline)
208             avio_printf(out, "duration=\"%"PRId64"\" ", c->last_duration);
209         avio_printf(out, "initialization=\"%s\" media=\"%s\" startNumber=\"%d\">\n", c->init_seg_name, c->media_seg_name, c->use_timeline ? start_number : 1);
210         if (c->use_timeline) {
211             int64_t cur_time = 0;
212             avio_printf(out, "\t\t\t\t\t<SegmentTimeline>\n");
213             for (i = start_index; i < os->nb_segments; ) {
214                 Segment *seg = os->segments[i];
215                 int repeat = 0;
216                 avio_printf(out, "\t\t\t\t\t\t<S ");
217                 if (i == start_index || seg->time != cur_time)
218                     avio_printf(out, "t=\"%"PRId64"\" ", seg->time);
219                 avio_printf(out, "d=\"%d\" ", seg->duration);
220                 while (i + repeat + 1 < os->nb_segments &&
221                        os->segments[i + repeat + 1]->duration == seg->duration &&
222                        os->segments[i + repeat + 1]->time == os->segments[i + repeat]->time + os->segments[i + repeat]->duration)
223                     repeat++;
224                 if (repeat > 0)
225                     avio_printf(out, "r=\"%d\" ", repeat);
226                 avio_printf(out, "/>\n");
227                 i += 1 + repeat;
228                 cur_time += (1 + repeat) * seg->duration;
229             }
230             avio_printf(out, "\t\t\t\t\t</SegmentTimeline>\n");
231         }
232         avio_printf(out, "\t\t\t\t</SegmentTemplate>\n");
233     } else if (c->single_file) {
234         avio_printf(out, "\t\t\t\t<BaseURL>%s</BaseURL>\n", os->initfile);
235         avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%"PRId64"\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);
236         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);
237         for (i = start_index; i < os->nb_segments; i++) {
238             Segment *seg = os->segments[i];
239             avio_printf(out, "\t\t\t\t\t<SegmentURL mediaRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->range_length - 1);
240             if (seg->index_length)
241                 avio_printf(out, "indexRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->index_length - 1);
242             avio_printf(out, "/>\n");
243         }
244         avio_printf(out, "\t\t\t\t</SegmentList>\n");
245     } else {
246         avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%"PRId64"\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);
247         avio_printf(out, "\t\t\t\t\t<Initialization sourceURL=\"%s\" />\n", os->initfile);
248         for (i = start_index; i < os->nb_segments; i++) {
249             Segment *seg = os->segments[i];
250             avio_printf(out, "\t\t\t\t\t<SegmentURL media=\"%s\" />\n", seg->file);
251         }
252         avio_printf(out, "\t\t\t\t</SegmentList>\n");
253     }
254 }
255
256 static DASHTmplId dash_read_tmpl_id(const char *identifier, char *format_tag,
257                                     size_t format_tag_size, const char **ptr) {
258     const char *next_ptr;
259     DASHTmplId id_type = DASH_TMPL_ID_UNDEFINED;
260
261     if (av_strstart(identifier, "$$", &next_ptr)) {
262         id_type = DASH_TMPL_ID_ESCAPE;
263         *ptr = next_ptr;
264     } else if (av_strstart(identifier, "$RepresentationID$", &next_ptr)) {
265         id_type = DASH_TMPL_ID_REP_ID;
266         // default to basic format, as $RepresentationID$ identifiers
267         // are not allowed to have custom format-tags.
268         av_strlcpy(format_tag, "%d", format_tag_size);
269         *ptr = next_ptr;
270     } else { // the following identifiers may have an explicit format_tag
271         if (av_strstart(identifier, "$Number", &next_ptr))
272             id_type = DASH_TMPL_ID_NUMBER;
273         else if (av_strstart(identifier, "$Bandwidth", &next_ptr))
274             id_type = DASH_TMPL_ID_BANDWIDTH;
275         else if (av_strstart(identifier, "$Time", &next_ptr))
276             id_type = DASH_TMPL_ID_TIME;
277         else
278             id_type = DASH_TMPL_ID_UNDEFINED;
279
280         // next parse the dash format-tag and generate a c-string format tag
281         // (next_ptr now points at the first '%' at the beginning of the format-tag)
282         if (id_type != DASH_TMPL_ID_UNDEFINED) {
283             const char *number_format = DASH_TMPL_ID_TIME ? "lld" : "d";
284             if (next_ptr[0] == '$') { // no dash format-tag
285                 snprintf(format_tag, format_tag_size, "%%%s", number_format);
286                 *ptr = &next_ptr[1];
287             } else {
288                 const char *width_ptr;
289                 // only tolerate single-digit width-field (i.e. up to 9-digit width)
290                 if (av_strstart(next_ptr, "%0", &width_ptr) &&
291                     av_isdigit(width_ptr[0]) &&
292                     av_strstart(&width_ptr[1], "d$", &next_ptr)) {
293                     // yes, we're using a format tag to build format_tag.
294                     snprintf(format_tag, format_tag_size, "%s%c%s", "%0", width_ptr[0], number_format);
295                     *ptr = next_ptr;
296                 } else {
297                     av_log(NULL, AV_LOG_WARNING, "Failed to parse format-tag beginning with %s. Expected either a "
298                                                  "closing '$' character or a format-string like '%%0[width]d', "
299                                                  "where width must be a single digit\n", next_ptr);
300                     id_type = DASH_TMPL_ID_UNDEFINED;
301                 }
302             }
303         }
304     }
305     return id_type;
306 }
307
308 static void dash_fill_tmpl_params(char *dst, size_t buffer_size,
309                                   const char *template, int rep_id,
310                                   int number, int bit_rate,
311                                   int64_t time) {
312     int dst_pos = 0;
313     const char *t_cur = template;
314     while (dst_pos < buffer_size - 1 && *t_cur) {
315         char format_tag[7]; // May be "%d", "%0Xd", or "%0Xlld" (for $Time$), where X is in [0-9]
316         int n = 0;
317         DASHTmplId id_type;
318         const char *t_next = strchr(t_cur, '$'); // copy over everything up to the first '$' character
319         if (t_next) {
320             int num_copy_bytes = FFMIN(t_next - t_cur, buffer_size - dst_pos - 1);
321             av_strlcpy(&dst[dst_pos], t_cur, num_copy_bytes + 1);
322             // advance
323             dst_pos += num_copy_bytes;
324             t_cur = t_next;
325         } else { // no more DASH identifiers to substitute - just copy the rest over and break
326             av_strlcpy(&dst[dst_pos], t_cur, buffer_size - dst_pos);
327             break;
328         }
329
330         if (dst_pos >= buffer_size - 1 || !*t_cur)
331             break;
332
333         // t_cur is now pointing to a '$' character
334         id_type = dash_read_tmpl_id(t_cur, format_tag, sizeof(format_tag), &t_next);
335         switch (id_type) {
336         case DASH_TMPL_ID_ESCAPE:
337             av_strlcpy(&dst[dst_pos], "$", 2);
338             n = 1;
339             break;
340         case DASH_TMPL_ID_REP_ID:
341             n = snprintf(&dst[dst_pos], buffer_size - dst_pos, format_tag, rep_id);
342             break;
343         case DASH_TMPL_ID_NUMBER:
344             n = snprintf(&dst[dst_pos], buffer_size - dst_pos, format_tag, number);
345             break;
346         case DASH_TMPL_ID_BANDWIDTH:
347             n = snprintf(&dst[dst_pos], buffer_size - dst_pos, format_tag, bit_rate);
348             break;
349         case DASH_TMPL_ID_TIME:
350             n = snprintf(&dst[dst_pos], buffer_size - dst_pos, format_tag, time);
351             break;
352         case DASH_TMPL_ID_UNDEFINED:
353             // copy over one byte and advance
354             av_strlcpy(&dst[dst_pos], t_cur, 2);
355             n = 1;
356             t_next = &t_cur[1];
357             break;
358         }
359         // t_next points just past the processed identifier
360         // n is the number of bytes that were attempted to be written to dst
361         // (may have failed to write all because buffer_size).
362
363         // advance
364         dst_pos += FFMIN(n, buffer_size - dst_pos - 1);
365         t_cur = t_next;
366     }
367 }
368
369 static char *xmlescape(const char *str) {
370     int outlen = strlen(str)*3/2 + 6;
371     char *out = av_realloc(NULL, outlen + 1);
372     int pos = 0;
373     if (!out)
374         return NULL;
375     for (; *str; str++) {
376         if (pos + 6 > outlen) {
377             char *tmp;
378             outlen = 2 * outlen + 6;
379             tmp = av_realloc(out, outlen + 1);
380             if (!tmp) {
381                 av_free(out);
382                 return NULL;
383             }
384             out = tmp;
385         }
386         if (*str == '&') {
387             memcpy(&out[pos], "&amp;", 5);
388             pos += 5;
389         } else if (*str == '<') {
390             memcpy(&out[pos], "&lt;", 4);
391             pos += 4;
392         } else if (*str == '>') {
393             memcpy(&out[pos], "&gt;", 4);
394             pos += 4;
395         } else if (*str == '\'') {
396             memcpy(&out[pos], "&apos;", 6);
397             pos += 6;
398         } else if (*str == '\"') {
399             memcpy(&out[pos], "&quot;", 6);
400             pos += 6;
401         } else {
402             out[pos++] = *str;
403         }
404     }
405     out[pos] = '\0';
406     return out;
407 }
408
409 static void write_time(AVIOContext *out, int64_t time)
410 {
411     int seconds = time / AV_TIME_BASE;
412     int fractions = time % AV_TIME_BASE;
413     int minutes = seconds / 60;
414     int hours = minutes / 60;
415     seconds %= 60;
416     minutes %= 60;
417     avio_printf(out, "PT");
418     if (hours)
419         avio_printf(out, "%dH", hours);
420     if (hours || minutes)
421         avio_printf(out, "%dM", minutes);
422     avio_printf(out, "%d.%dS", seconds, fractions / (AV_TIME_BASE / 10));
423 }
424
425 static int write_manifest(AVFormatContext *s, int final)
426 {
427     DASHContext *c = s->priv_data;
428     AVIOContext *out;
429     char temp_filename[1024];
430     int ret, i;
431     AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
432
433     snprintf(temp_filename, sizeof(temp_filename), "%s.tmp", s->filename);
434     ret = avio_open2(&out, temp_filename, AVIO_FLAG_WRITE, &s->interrupt_callback, NULL);
435     if (ret < 0) {
436         av_log(s, AV_LOG_ERROR, "Unable to open %s for writing\n", temp_filename);
437         return ret;
438     }
439     avio_printf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
440     avio_printf(out, "<MPD xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
441                 "\txmlns=\"urn:mpeg:dash:schema:mpd:2011\"\n"
442                 "\txmlns:xlink=\"http://www.w3.org/1999/xlink\"\n"
443                 "\txsi:schemaLocation=\"urn:mpeg:DASH:schema:MPD:2011 http://standards.iso.org/ittf/PubliclyAvailableStandards/MPEG-DASH_schema_files/DASH-MPD.xsd\"\n"
444                 "\tprofiles=\"urn:mpeg:dash:profile:isoff-live:2011\"\n"
445                 "\ttype=\"%s\"\n", final ? "static" : "dynamic");
446     if (final) {
447         avio_printf(out, "\tmediaPresentationDuration=\"");
448         write_time(out, c->total_duration);
449         avio_printf(out, "\"\n");
450     } else {
451         int64_t update_period = c->last_duration / AV_TIME_BASE;
452         if (c->use_template && !c->use_timeline)
453             update_period = 500;
454         avio_printf(out, "\tminimumUpdatePeriod=\"PT%"PRId64"S\"\n", update_period);
455         avio_printf(out, "\tsuggestedPresentationDelay=\"PT%"PRId64"S\"\n", c->last_duration / AV_TIME_BASE);
456         if (!c->availability_start_time[0] && s->nb_streams > 0 && c->streams[0].nb_segments > 0) {
457             time_t t = time(NULL);
458             struct tm *ptm, tmbuf;
459             ptm = gmtime_r(&t, &tmbuf);
460             if (ptm) {
461                 if (!strftime(c->availability_start_time, sizeof(c->availability_start_time),
462                               "%Y-%m-%dT%H:%M:%S", ptm))
463                     c->availability_start_time[0] = '\0';
464             }
465         }
466         if (c->availability_start_time[0])
467             avio_printf(out, "\tavailabilityStartTime=\"%s\"\n", c->availability_start_time);
468         if (c->window_size && c->use_template) {
469             avio_printf(out, "\ttimeShiftBufferDepth=\"");
470             write_time(out, c->last_duration * c->window_size);
471             avio_printf(out, "\"\n");
472         }
473     }
474     avio_printf(out, "\tminBufferTime=\"");
475     write_time(out, c->last_duration);
476     avio_printf(out, "\">\n");
477     avio_printf(out, "\t<ProgramInformation>\n");
478     if (title) {
479         char *escaped = xmlescape(title->value);
480         avio_printf(out, "\t\t<Title>%s</Title>\n", escaped);
481         av_free(escaped);
482     }
483     avio_printf(out, "\t</ProgramInformation>\n");
484     if (c->window_size && s->nb_streams > 0 && c->streams[0].nb_segments > 0 && !c->use_template) {
485         OutputStream *os = &c->streams[0];
486         int start_index = FFMAX(os->nb_segments - c->window_size, 0);
487         int64_t start_time = av_rescale_q(os->segments[start_index]->time, s->streams[0]->time_base, AV_TIME_BASE_Q);
488         avio_printf(out, "\t<Period start=\"");
489         write_time(out, start_time);
490         avio_printf(out, "\">\n");
491     } else {
492         avio_printf(out, "\t<Period start=\"PT0.0S\">\n");
493     }
494
495     if (c->has_video) {
496         avio_printf(out, "\t\t<AdaptationSet id=\"video\" segmentAlignment=\"true\" bitstreamSwitching=\"true\">\n");
497         for (i = 0; i < s->nb_streams; i++) {
498             AVStream *st = s->streams[i];
499             OutputStream *os = &c->streams[i];
500             if (s->streams[i]->codec->codec_type != AVMEDIA_TYPE_VIDEO)
501                 continue;
502             avio_printf(out, "\t\t\t<Representation id=\"%d\" mimeType=\"video/mp4\" codecs=\"%s\"%s width=\"%d\" height=\"%d\">\n", i, os->codec_str, os->bandwidth_str, st->codec->width, st->codec->height);
503             output_segment_list(&c->streams[i], out, c);
504             avio_printf(out, "\t\t\t</Representation>\n");
505         }
506         avio_printf(out, "\t\t</AdaptationSet>\n");
507     }
508     if (c->has_audio) {
509         avio_printf(out, "\t\t<AdaptationSet id=\"audio\" segmentAlignment=\"true\" bitstreamSwitching=\"true\">\n");
510         for (i = 0; i < s->nb_streams; i++) {
511             AVStream *st = s->streams[i];
512             OutputStream *os = &c->streams[i];
513             if (s->streams[i]->codec->codec_type != AVMEDIA_TYPE_AUDIO)
514                 continue;
515             avio_printf(out, "\t\t\t<Representation id=\"%d\" mimeType=\"audio/mp4\" codecs=\"%s\"%s audioSamplingRate=\"%d\">\n", i, os->codec_str, os->bandwidth_str, st->codec->sample_rate);
516             avio_printf(out, "\t\t\t\t<AudioChannelConfiguration schemeIdUri=\"urn:mpeg:dash:23003:3:audio_channel_configuration:2011\" value=\"%d\" />\n", st->codec->channels);
517             output_segment_list(&c->streams[i], out, c);
518             avio_printf(out, "\t\t\t</Representation>\n");
519         }
520         avio_printf(out, "\t\t</AdaptationSet>\n");
521     }
522     avio_printf(out, "\t</Period>\n");
523     avio_printf(out, "</MPD>\n");
524     avio_flush(out);
525     avio_close(out);
526     return ff_rename(temp_filename, s->filename);
527 }
528
529 static int dash_write_header(AVFormatContext *s)
530 {
531     DASHContext *c = s->priv_data;
532     int ret = 0, i;
533     AVOutputFormat *oformat;
534     char *ptr;
535     char basename[1024];
536
537     if (c->single_file_name)
538         c->single_file = 1;
539     if (c->single_file)
540         c->use_template = 0;
541
542     av_strlcpy(c->dirname, s->filename, sizeof(c->dirname));
543     ptr = strrchr(c->dirname, '/');
544     if (ptr) {
545         av_strlcpy(basename, &ptr[1], sizeof(basename));
546         ptr[1] = '\0';
547     } else {
548         c->dirname[0] = '\0';
549         av_strlcpy(basename, s->filename, sizeof(basename));
550     }
551
552     ptr = strrchr(basename, '.');
553     if (ptr)
554         *ptr = '\0';
555
556     oformat = av_guess_format("mp4", NULL, NULL);
557     if (!oformat) {
558         ret = AVERROR_MUXER_NOT_FOUND;
559         goto fail;
560     }
561
562     c->streams = av_mallocz(sizeof(*c->streams) * s->nb_streams);
563     if (!c->streams) {
564         ret = AVERROR(ENOMEM);
565         goto fail;
566     }
567
568     for (i = 0; i < s->nb_streams; i++) {
569         OutputStream *os = &c->streams[i];
570         AVFormatContext *ctx;
571         AVStream *st;
572         AVDictionary *opts = NULL;
573         char filename[1024];
574
575         os->bit_rate = s->streams[i]->codec->bit_rate;
576         if (os->bit_rate) {
577             snprintf(os->bandwidth_str, sizeof(os->bandwidth_str),
578                      " bandwidth=\"%d\"", os->bit_rate);
579         } else {
580             int level = s->strict_std_compliance >= FF_COMPLIANCE_STRICT ?
581                         AV_LOG_ERROR : AV_LOG_WARNING;
582             av_log(s, level, "No bit rate set for stream %d\n", i);
583             if (s->strict_std_compliance >= FF_COMPLIANCE_STRICT) {
584                 ret = AVERROR(EINVAL);
585                 goto fail;
586             }
587         }
588
589         ctx = avformat_alloc_context();
590         if (!ctx) {
591             ret = AVERROR(ENOMEM);
592             goto fail;
593         }
594         os->ctx = ctx;
595         ctx->oformat = oformat;
596         ctx->interrupt_callback = s->interrupt_callback;
597
598         if (!(st = avformat_new_stream(ctx, NULL))) {
599             ret = AVERROR(ENOMEM);
600             goto fail;
601         }
602         avcodec_copy_context(st->codec, s->streams[i]->codec);
603         st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
604         st->time_base = s->streams[i]->time_base;
605         ctx->avoid_negative_ts = s->avoid_negative_ts;
606
607         ctx->pb = avio_alloc_context(os->iobuf, sizeof(os->iobuf), AVIO_FLAG_WRITE, os, NULL, dash_write, NULL);
608         if (!ctx->pb) {
609             ret = AVERROR(ENOMEM);
610             goto fail;
611         }
612
613         if (c->single_file) {
614             if (c->single_file_name)
615                 dash_fill_tmpl_params(os->initfile, sizeof(os->initfile), c->single_file_name, i, 0, os->bit_rate, 0);
616             else
617                 snprintf(os->initfile, sizeof(os->initfile), "%s-stream%d.m4s", basename, i);
618         } else {
619             dash_fill_tmpl_params(os->initfile, sizeof(os->initfile), c->init_seg_name, i, 0, os->bit_rate, 0);
620         }
621         snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
622         ret = ffurl_open(&os->out, filename, AVIO_FLAG_WRITE, &s->interrupt_callback, NULL);
623         if (ret < 0)
624             goto fail;
625         os->init_start_pos = 0;
626
627         av_dict_set(&opts, "movflags", "frag_custom+dash", 0);
628         if ((ret = avformat_write_header(ctx, &opts)) < 0) {
629              goto fail;
630         }
631         os->ctx_inited = 1;
632         avio_flush(ctx->pb);
633         av_dict_free(&opts);
634
635         if (c->single_file) {
636             os->init_range_length = avio_tell(ctx->pb);
637         } else {
638             ffurl_close(os->out);
639             os->out = NULL;
640         }
641         av_log(s, AV_LOG_VERBOSE, "Representation %d init segment written to: %s\n", i, filename);
642
643         s->streams[i]->time_base = st->time_base;
644         // If the muxer wants to shift timestamps, request to have them shifted
645         // already before being handed to this muxer, so we don't have mismatches
646         // between the MPD and the actual segments.
647         s->avoid_negative_ts = ctx->avoid_negative_ts;
648         if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
649             c->has_video = 1;
650         else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
651             c->has_audio = 1;
652
653         set_codec_str(s, os->ctx->streams[0]->codec, os->codec_str, sizeof(os->codec_str));
654         os->first_dts = AV_NOPTS_VALUE;
655         os->end_dts = AV_NOPTS_VALUE;
656         os->segment_index = 1;
657     }
658
659     if (!c->has_video && c->min_seg_duration <= 0) {
660         av_log(s, AV_LOG_WARNING, "no video stream and no min seg duration set\n");
661         ret = AVERROR(EINVAL);
662     }
663     ret = write_manifest(s, 0);
664     if (!ret)
665         av_log(s, AV_LOG_VERBOSE, "Manifest written to: %s\n", s->filename);
666
667 fail:
668     if (ret)
669         dash_free(s);
670     return ret;
671 }
672
673 static int add_segment(OutputStream *os, const char *file,
674                        int64_t time, int duration,
675                        int64_t start_pos, int64_t range_length,
676                        int64_t index_length)
677 {
678     int err;
679     Segment *seg;
680     if (os->nb_segments >= os->segments_size) {
681         os->segments_size = (os->segments_size + 1) * 2;
682         if ((err = av_reallocp(&os->segments, sizeof(*os->segments) *
683                                os->segments_size)) < 0) {
684             os->segments_size = 0;
685             os->nb_segments = 0;
686             return err;
687         }
688     }
689     seg = av_mallocz(sizeof(*seg));
690     if (!seg)
691         return AVERROR(ENOMEM);
692     av_strlcpy(seg->file, file, sizeof(seg->file));
693     seg->time = time;
694     seg->duration = duration;
695     seg->start_pos = start_pos;
696     seg->range_length = range_length;
697     seg->index_length = index_length;
698     os->segments[os->nb_segments++] = seg;
699     os->segment_index++;
700     return 0;
701 }
702
703 static void write_styp(AVIOContext *pb)
704 {
705     avio_wb32(pb, 24);
706     ffio_wfourcc(pb, "styp");
707     ffio_wfourcc(pb, "msdh");
708     avio_wb32(pb, 0); /* minor */
709     ffio_wfourcc(pb, "msdh");
710     ffio_wfourcc(pb, "msix");
711 }
712
713 static void find_index_range(AVFormatContext *s, const char *full_path,
714                              int64_t pos, int *index_length)
715 {
716     uint8_t buf[8];
717     URLContext *fd;
718     int ret;
719
720     ret = ffurl_open(&fd, full_path, AVIO_FLAG_READ, &s->interrupt_callback, NULL);
721     if (ret < 0)
722         return;
723     if (ffurl_seek(fd, pos, SEEK_SET) != pos) {
724         ffurl_close(fd);
725         return;
726     }
727     ret = ffurl_read(fd, buf, 8);
728     ffurl_close(fd);
729     if (ret < 8)
730         return;
731     if (AV_RL32(&buf[4]) != MKTAG('s', 'i', 'd', 'x'))
732         return;
733     *index_length = AV_RB32(&buf[0]);
734 }
735
736 static int dash_flush(AVFormatContext *s, int final, int stream)
737 {
738     DASHContext *c = s->priv_data;
739     int i, ret = 0;
740     int cur_flush_segment_index = 0;
741     if (stream >= 0)
742         cur_flush_segment_index = c->streams[stream].segment_index;
743
744     for (i = 0; i < s->nb_streams; i++) {
745         OutputStream *os = &c->streams[i];
746         char filename[1024] = "", full_path[1024], temp_path[1024];
747         int64_t start_pos = avio_tell(os->ctx->pb);
748         int range_length, index_length = 0;
749
750         if (!os->packets_written)
751             continue;
752
753         // Flush the single stream that got a keyframe right now.
754         // Flush all audio streams as well, in sync with video keyframes,
755         // but not the other video streams.
756         if (stream >= 0 && i != stream) {
757             if (s->streams[i]->codec->codec_type != AVMEDIA_TYPE_AUDIO)
758                 continue;
759             // Make sure we don't flush audio streams multiple times, when
760             // all video streams are flushed one at a time.
761             if (c->has_video && os->segment_index > cur_flush_segment_index)
762                 continue;
763         }
764
765         if (!c->single_file) {
766             dash_fill_tmpl_params(filename, sizeof(filename), c->media_seg_name, i, os->segment_index, os->bit_rate, os->start_dts);
767             snprintf(full_path, sizeof(full_path), "%s%s", c->dirname, filename);
768             snprintf(temp_path, sizeof(temp_path), "%s.tmp", full_path);
769             ret = ffurl_open(&os->out, temp_path, AVIO_FLAG_WRITE, &s->interrupt_callback, NULL);
770             if (ret < 0)
771                 break;
772             write_styp(os->ctx->pb);
773         } else {
774             snprintf(full_path, sizeof(full_path), "%s%s", c->dirname, os->initfile);
775         }
776
777         av_write_frame(os->ctx, NULL);
778         avio_flush(os->ctx->pb);
779         os->packets_written = 0;
780
781         range_length = avio_tell(os->ctx->pb) - start_pos;
782         if (c->single_file) {
783             find_index_range(s, full_path, start_pos, &index_length);
784         } else {
785             ffurl_close(os->out);
786             os->out = NULL;
787             ret = ff_rename(temp_path, full_path);
788             if (ret < 0)
789                 break;
790         }
791         add_segment(os, filename, os->start_dts, os->end_dts - os->start_dts, start_pos, range_length, index_length);
792         av_log(s, AV_LOG_VERBOSE, "Representation %d media segment %d written to: %s\n", i, os->segment_index, full_path);
793     }
794
795     if (c->window_size || (final && c->remove_at_exit)) {
796         for (i = 0; i < s->nb_streams; i++) {
797             OutputStream *os = &c->streams[i];
798             int j;
799             int remove = os->nb_segments - c->window_size - c->extra_window_size;
800             if (final && c->remove_at_exit)
801                 remove = os->nb_segments;
802             if (remove > 0) {
803                 for (j = 0; j < remove; j++) {
804                     char filename[1024];
805                     snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->segments[j]->file);
806                     unlink(filename);
807                     av_free(os->segments[j]);
808                 }
809                 os->nb_segments -= remove;
810                 memmove(os->segments, os->segments + remove, os->nb_segments * sizeof(*os->segments));
811             }
812         }
813     }
814
815     if (ret >= 0)
816         ret = write_manifest(s, final);
817     return ret;
818 }
819
820 static int dash_write_packet(AVFormatContext *s, AVPacket *pkt)
821 {
822     DASHContext *c = s->priv_data;
823     AVStream *st = s->streams[pkt->stream_index];
824     OutputStream *os = &c->streams[pkt->stream_index];
825     int64_t seg_end_duration = (os->segment_index) * (int64_t) c->min_seg_duration;
826     int ret;
827
828     // If forcing the stream to start at 0, the mp4 muxer will set the start
829     // timestamps to 0. Do the same here, to avoid mismatches in duration/timestamps.
830     if (os->first_dts == AV_NOPTS_VALUE &&
831         s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
832         pkt->pts -= pkt->dts;
833         pkt->dts  = 0;
834     }
835
836     if (os->first_dts == AV_NOPTS_VALUE)
837         os->first_dts = pkt->dts;
838
839     if ((!c->has_video || st->codec->codec_type == AVMEDIA_TYPE_VIDEO) &&
840         pkt->flags & AV_PKT_FLAG_KEY && os->packets_written &&
841         av_compare_ts(pkt->dts - os->first_dts, st->time_base,
842                       seg_end_duration, AV_TIME_BASE_Q) >= 0) {
843         int64_t prev_duration = c->last_duration;
844
845         c->last_duration = av_rescale_q(pkt->dts - os->start_dts,
846                                         st->time_base,
847                                         AV_TIME_BASE_Q);
848         c->total_duration = av_rescale_q(pkt->dts - os->first_dts,
849                                          st->time_base,
850                                          AV_TIME_BASE_Q);
851
852         if ((!c->use_timeline || !c->use_template) && prev_duration) {
853             if (c->last_duration < prev_duration*9/10 ||
854                 c->last_duration > prev_duration*11/10) {
855                 av_log(s, AV_LOG_WARNING,
856                        "Segment durations differ too much, enable use_timeline "
857                        "and use_template, or keep a stricter keyframe interval\n");
858             }
859         }
860
861         if ((ret = dash_flush(s, 0, pkt->stream_index)) < 0)
862             return ret;
863     }
864
865     if (!os->packets_written) {
866         // If we wrote a previous segment, adjust the start time of the segment
867         // to the end of the previous one (which is the same as the mp4 muxer
868         // does). This avoids gaps in the timeline.
869         if (os->end_dts != AV_NOPTS_VALUE)
870             os->start_dts = os->end_dts;
871         else
872             os->start_dts = pkt->dts;
873     }
874     os->end_dts = pkt->dts + pkt->duration;
875     os->packets_written++;
876     return ff_write_chained(os->ctx, 0, pkt, s);
877 }
878
879 static int dash_write_trailer(AVFormatContext *s)
880 {
881     DASHContext *c = s->priv_data;
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->end_dts - os->start_dts,
889                                             s->streams[0]->time_base,
890                                             AV_TIME_BASE_Q);
891         c->total_duration = av_rescale_q(os->end_dts - os->first_dts,
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     dash_free(s);
909     return 0;
910 }
911
912 #define OFFSET(x) offsetof(DASHContext, x)
913 #define E AV_OPT_FLAG_ENCODING_PARAM
914 static const AVOption options[] = {
915     { "window_size", "number of segments kept in the manifest", OFFSET(window_size), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, E },
916     { "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 },
917     { "min_seg_duration", "minimum segment duration (in microseconds)", OFFSET(min_seg_duration), AV_OPT_TYPE_INT64, { .i64 = 5000000 }, 0, INT_MAX, E },
918     { "remove_at_exit", "remove all segments when finished", OFFSET(remove_at_exit), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, E },
919     { "use_template", "Use SegmentTemplate instead of SegmentList", OFFSET(use_template), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, E },
920     { "use_timeline", "Use SegmentTimeline in SegmentTemplate", OFFSET(use_timeline), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, E },
921     { "single_file", "Store all segments in one file, accessed using byte ranges", OFFSET(single_file), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, E },
922     { "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 },
923     { "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 },
924     { "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 },
925     { NULL },
926 };
927
928 static const AVClass dash_class = {
929     .class_name = "dash muxer",
930     .item_name  = av_default_item_name,
931     .option     = options,
932     .version    = LIBAVUTIL_VERSION_INT,
933 };
934
935 AVOutputFormat ff_dash_muxer = {
936     .name           = "dash",
937     .long_name      = NULL_IF_CONFIG_SMALL("DASH Muxer"),
938     .priv_data_size = sizeof(DASHContext),
939     .audio_codec    = AV_CODEC_ID_AAC,
940     .video_codec    = AV_CODEC_ID_H264,
941     .flags          = AVFMT_GLOBALHEADER | AVFMT_NOFILE | AVFMT_TS_NEGATIVE,
942     .write_header   = dash_write_header,
943     .write_packet   = dash_write_packet,
944     .write_trailer  = dash_write_trailer,
945     .codec_tag      = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
946     .priv_class     = &dash_class,
947 };