]> git.sesse.net Git - ffmpeg/blob - libavformat/dashenc.c
Merge commit '065923b0781b06a2604f69f4e2c2407b7750a854'
[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/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 typedef struct Segment {
42     char file[1024];
43     int64_t start_pos;
44     int range_length, index_length;
45     int64_t time;
46     int duration;
47     int n;
48 } Segment;
49
50 typedef struct OutputStream {
51     AVFormatContext *ctx;
52     int ctx_inited;
53     uint8_t iobuf[32768];
54     URLContext *out;
55     int packets_written;
56     char initfile[1024];
57     int64_t init_start_pos;
58     int init_range_length;
59     int nb_segments, segments_size, segment_index;
60     Segment **segments;
61     int64_t first_dts, start_dts, end_dts;
62     char bandwidth_str[64];
63
64     char codec_str[100];
65 } OutputStream;
66
67 typedef struct DASHContext {
68     const AVClass *class;  /* Class for private options. */
69     int window_size;
70     int extra_window_size;
71     int min_seg_duration;
72     int remove_at_exit;
73     int use_template;
74     int use_timeline;
75     int single_file;
76     OutputStream *streams;
77     int has_video, has_audio;
78     int nb_segments;
79     int last_duration;
80     int total_duration;
81     char availability_start_time[100];
82     char dirname[1024];
83 } DASHContext;
84
85 static int dash_write(void *opaque, uint8_t *buf, int buf_size)
86 {
87     OutputStream *os = opaque;
88     if (os->out)
89         ffurl_write(os->out, buf, buf_size);
90     return buf_size;
91 }
92
93 // RFC 6381
94 static void set_codec_str(AVFormatContext *s, AVCodecContext *codec,
95                           char *str, int size)
96 {
97     const AVCodecTag *tags[2] = { NULL, NULL };
98     uint32_t tag;
99     if (codec->codec_type == AVMEDIA_TYPE_VIDEO)
100         tags[0] = ff_codec_movvideo_tags;
101     else if (codec->codec_type == AVMEDIA_TYPE_AUDIO)
102         tags[0] = ff_codec_movaudio_tags;
103     else
104         return;
105
106     tag = av_codec_get_tag(tags, codec->codec_id);
107     if (!tag)
108         return;
109     if (size < 5)
110         return;
111
112     AV_WL32(str, tag);
113     str[4] = '\0';
114     if (!strcmp(str, "mp4a") || !strcmp(str, "mp4v")) {
115         uint32_t oti;
116         tags[0] = ff_mp4_obj_type;
117         oti = av_codec_get_tag(tags, codec->codec_id);
118         if (oti)
119             av_strlcatf(str, size, ".%02x", oti);
120         else
121             return;
122
123         if (tag == MKTAG('m', 'p', '4', 'a')) {
124             if (codec->extradata_size >= 2) {
125                 int aot = codec->extradata[0] >> 3;
126                 if (aot == 31)
127                     aot = ((AV_RB16(codec->extradata) >> 5) & 0x3f) + 32;
128                 av_strlcatf(str, size, ".%d", aot);
129             }
130         } else if (tag == MKTAG('m', 'p', '4', 'v')) {
131             // Unimplemented, should output ProfileLevelIndication as a decimal number
132             av_log(s, AV_LOG_WARNING, "Incomplete RFC 6381 codec string for mp4v\n");
133         }
134     } else if (!strcmp(str, "avc1")) {
135         uint8_t *tmpbuf = NULL;
136         uint8_t *extradata = codec->extradata;
137         int extradata_size = codec->extradata_size;
138         if (!extradata_size)
139             return;
140         if (extradata[0] != 1) {
141             AVIOContext *pb;
142             if (avio_open_dyn_buf(&pb) < 0)
143                 return;
144             if (ff_isom_write_avcc(pb, extradata, extradata_size) < 0) {
145                 avio_close_dyn_buf(pb, &tmpbuf);
146                 av_free(tmpbuf);
147                 return;
148             }
149             extradata_size = avio_close_dyn_buf(pb, &extradata);
150             tmpbuf = extradata;
151         }
152
153         if (extradata_size >= 4)
154             av_strlcatf(str, size, ".%02x%02x%02x",
155                         extradata[1], extradata[2], extradata[3]);
156         av_free(tmpbuf);
157     }
158 }
159
160 static void dash_free(AVFormatContext *s)
161 {
162     DASHContext *c = s->priv_data;
163     int i, j;
164     if (!c->streams)
165         return;
166     for (i = 0; i < s->nb_streams; i++) {
167         OutputStream *os = &c->streams[i];
168         if (os->ctx && os->ctx_inited)
169             av_write_trailer(os->ctx);
170         if (os->ctx && os->ctx->pb)
171             av_free(os->ctx->pb);
172         ffurl_close(os->out);
173         os->out =  NULL;
174         if (os->ctx)
175             avformat_free_context(os->ctx);
176         for (j = 0; j < os->nb_segments; j++)
177             av_free(os->segments[j]);
178         av_free(os->segments);
179     }
180     av_freep(&c->streams);
181 }
182
183 static void output_segment_list(OutputStream *os, AVIOContext *out, DASHContext *c)
184 {
185     int i, start_index = 0, start_number = 1;
186     if (c->window_size) {
187         start_index  = FFMAX(os->nb_segments   - c->window_size, 0);
188         start_number = FFMAX(os->segment_index - c->window_size, 1);
189     }
190
191     if (c->use_template) {
192         int timescale = c->use_timeline ? os->ctx->streams[0]->time_base.den : AV_TIME_BASE;
193         avio_printf(out, "\t\t\t\t<SegmentTemplate timescale=\"%d\" ", timescale);
194         if (!c->use_timeline)
195             avio_printf(out, "duration=\"%d\" ", c->last_duration);
196         avio_printf(out, "initialization=\"init-stream$RepresentationID$.m4s\" media=\"chunk-stream$RepresentationID$-$Number%%05d$.m4s\" startNumber=\"%d\">\n", c->use_timeline ? start_number : 1);
197         if (c->use_timeline) {
198             avio_printf(out, "\t\t\t\t\t<SegmentTimeline>\n");
199             for (i = start_index; i < os->nb_segments; ) {
200                 Segment *seg = os->segments[i];
201                 int repeat = 0;
202                 avio_printf(out, "\t\t\t\t\t\t<S ");
203                 if (i == start_index)
204                     avio_printf(out, "t=\"%"PRId64"\" ", seg->time);
205                 avio_printf(out, "d=\"%d\" ", seg->duration);
206                 while (i + repeat + 1 < os->nb_segments && os->segments[i + repeat + 1]->duration == seg->duration)
207                     repeat++;
208                 if (repeat > 0)
209                     avio_printf(out, "r=\"%d\" ", repeat);
210                 avio_printf(out, "/>\n");
211                 i += 1 + repeat;
212             }
213             avio_printf(out, "\t\t\t\t\t</SegmentTimeline>\n");
214         }
215         avio_printf(out, "\t\t\t\t</SegmentTemplate>\n");
216     } else if (c->single_file) {
217         avio_printf(out, "\t\t\t\t<BaseURL>%s</BaseURL>\n", os->initfile);
218         avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%d\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);
219         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);
220         for (i = start_index; i < os->nb_segments; i++) {
221             Segment *seg = os->segments[i];
222             avio_printf(out, "\t\t\t\t\t<SegmentURL mediaRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->range_length - 1);
223             if (seg->index_length)
224                 avio_printf(out, "indexRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->index_length - 1);
225             avio_printf(out, "/>\n");
226         }
227         avio_printf(out, "\t\t\t\t</SegmentList>\n");
228     } else {
229         avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%d\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);
230         avio_printf(out, "\t\t\t\t\t<Initialization sourceURL=\"%s\" />\n", os->initfile);
231         for (i = start_index; i < os->nb_segments; i++) {
232             Segment *seg = os->segments[i];
233             avio_printf(out, "\t\t\t\t\t<SegmentURL media=\"%s\" />\n", seg->file);
234         }
235         avio_printf(out, "\t\t\t\t</SegmentList>\n");
236     }
237 }
238
239 static char *xmlescape(const char *str) {
240     int outlen = strlen(str)*3/2 + 6;
241     char *out = av_realloc(NULL, outlen + 1);
242     int pos = 0;
243     if (!out)
244         return NULL;
245     for (; *str; str++) {
246         if (pos + 6 > outlen) {
247             char *tmp;
248             outlen = 2 * outlen + 6;
249             tmp = av_realloc(out, outlen + 1);
250             if (!tmp) {
251                 av_free(out);
252                 return NULL;
253             }
254             out = tmp;
255         }
256         if (*str == '&') {
257             memcpy(&out[pos], "&amp;", 5);
258             pos += 5;
259         } else if (*str == '<') {
260             memcpy(&out[pos], "&lt;", 4);
261             pos += 4;
262         } else if (*str == '>') {
263             memcpy(&out[pos], "&gt;", 4);
264             pos += 4;
265         } else if (*str == '\'') {
266             memcpy(&out[pos], "&apos;", 6);
267             pos += 6;
268         } else if (*str == '\"') {
269             memcpy(&out[pos], "&quot;", 6);
270             pos += 6;
271         } else {
272             out[pos++] = *str;
273         }
274     }
275     out[pos] = '\0';
276     return out;
277 }
278
279 static void write_time(AVIOContext *out, int64_t time)
280 {
281     int seconds = time / AV_TIME_BASE;
282     int fractions = time % AV_TIME_BASE;
283     int minutes = seconds / 60;
284     int hours = minutes / 60;
285     seconds %= 60;
286     minutes %= 60;
287     avio_printf(out, "PT");
288     if (hours)
289         avio_printf(out, "%dH", hours);
290     if (hours || minutes)
291         avio_printf(out, "%dM", minutes);
292     avio_printf(out, "%d.%dS", seconds, fractions / (AV_TIME_BASE / 10));
293 }
294
295 static int write_manifest(AVFormatContext *s, int final)
296 {
297     DASHContext *c = s->priv_data;
298     AVIOContext *out;
299     char temp_filename[1024];
300     int ret, i;
301     AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
302
303     snprintf(temp_filename, sizeof(temp_filename), "%s.tmp", s->filename);
304     ret = avio_open2(&out, temp_filename, AVIO_FLAG_WRITE, &s->interrupt_callback, NULL);
305     if (ret < 0) {
306         av_log(s, AV_LOG_ERROR, "Unable to open %s for writing\n", temp_filename);
307         return ret;
308     }
309     avio_printf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
310     avio_printf(out, "<MPD xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
311                 "\txmlns=\"urn:mpeg:dash:schema:mpd:2011\"\n"
312                 "\txmlns:xlink=\"http://www.w3.org/1999/xlink\"\n"
313                 "\txsi:schemaLocation=\"urn:mpeg:DASH:schema:MPD:2011 http://standards.iso.org/ittf/PubliclyAvailableStandards/MPEG-DASH_schema_files/DASH-MPD.xsd\"\n"
314                 "\tprofiles=\"urn:mpeg:dash:profile:isoff-live:2011\"\n"
315                 "\ttype=\"%s\"\n", final ? "static" : "dynamic");
316     if (final) {
317         avio_printf(out, "\tmediaPresentationDuration=\"");
318         write_time(out, c->total_duration);
319         avio_printf(out, "\"\n");
320     } else {
321         int update_period = c->last_duration / AV_TIME_BASE;
322         if (c->use_template && !c->use_timeline)
323             update_period = 500;
324         avio_printf(out, "\tminimumUpdatePeriod=\"PT%dS\"\n", update_period);
325         avio_printf(out, "\tsuggestedPresentationDelay=\"PT%dS\"\n", c->last_duration / AV_TIME_BASE);
326         if (!c->availability_start_time[0] && s->nb_streams > 0 && c->streams[0].nb_segments > 0) {
327             time_t t = time(NULL);
328             struct tm *ptm, tmbuf;
329             ptm = gmtime_r(&t, &tmbuf);
330             if (ptm) {
331                 if (!strftime(c->availability_start_time, sizeof(c->availability_start_time),
332                               "%Y-%m-%dT%H:%M:%S", ptm))
333                     c->availability_start_time[0] = '\0';
334             }
335         }
336         if (c->availability_start_time[0])
337             avio_printf(out, "\tavailabilityStartTime=\"%s\"\n", c->availability_start_time);
338         if (c->window_size && c->use_template) {
339             avio_printf(out, "\ttimeShiftBufferDepth=\"");
340             write_time(out, c->last_duration * c->window_size);
341             avio_printf(out, "\"\n");
342         }
343     }
344     avio_printf(out, "\tminBufferTime=\"");
345     write_time(out, c->last_duration);
346     avio_printf(out, "\">\n");
347     avio_printf(out, "\t<ProgramInformation>\n");
348     if (title) {
349         char *escaped = xmlescape(title->value);
350         avio_printf(out, "\t\t<Title>%s</Title>\n", escaped);
351         av_free(escaped);
352     }
353     avio_printf(out, "\t</ProgramInformation>\n");
354     if (c->window_size && s->nb_streams > 0 && c->streams[0].nb_segments > 0 && !c->use_template) {
355         OutputStream *os = &c->streams[0];
356         int start_index = FFMAX(os->nb_segments - c->window_size, 0);
357         int64_t start_time = av_rescale_q(os->segments[start_index]->time, s->streams[0]->time_base, AV_TIME_BASE_Q);
358         avio_printf(out, "\t<Period start=\"");
359         write_time(out, start_time);
360         avio_printf(out, "\">\n");
361     } else {
362         avio_printf(out, "\t<Period start=\"PT0.0S\">\n");
363     }
364
365     if (c->has_video) {
366         avio_printf(out, "\t\t<AdaptationSet id=\"video\" segmentAlignment=\"true\" bitstreamSwitching=\"true\">\n");
367         for (i = 0; i < s->nb_streams; i++) {
368             AVStream *st = s->streams[i];
369             OutputStream *os = &c->streams[i];
370             if (s->streams[i]->codec->codec_type != AVMEDIA_TYPE_VIDEO)
371                 continue;
372             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);
373             output_segment_list(&c->streams[i], out, c);
374             avio_printf(out, "\t\t\t</Representation>\n");
375         }
376         avio_printf(out, "\t\t</AdaptationSet>\n");
377     }
378     if (c->has_audio) {
379         avio_printf(out, "\t\t<AdaptationSet id=\"audio\" segmentAlignment=\"true\" bitstreamSwitching=\"true\">\n");
380         for (i = 0; i < s->nb_streams; i++) {
381             AVStream *st = s->streams[i];
382             OutputStream *os = &c->streams[i];
383             if (s->streams[i]->codec->codec_type != AVMEDIA_TYPE_AUDIO)
384                 continue;
385             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);
386             avio_printf(out, "\t\t\t\t<AudioChannelConfiguration schemeIdUri=\"urn:mpeg:dash:23003:3:audio_channel_configuration:2011\" value=\"%d\" />\n", st->codec->channels);
387             output_segment_list(&c->streams[i], out, c);
388             avio_printf(out, "\t\t\t</Representation>\n");
389         }
390         avio_printf(out, "\t\t</AdaptationSet>\n");
391     }
392     avio_printf(out, "\t</Period>\n");
393     avio_printf(out, "</MPD>\n");
394     avio_flush(out);
395     avio_close(out);
396     return ff_rename(temp_filename, s->filename, s);
397 }
398
399 static int dash_write_header(AVFormatContext *s)
400 {
401     DASHContext *c = s->priv_data;
402     int ret = 0, i;
403     AVOutputFormat *oformat;
404     char *ptr;
405     char basename[1024];
406
407     if (c->single_file)
408         c->use_template = 0;
409
410     av_strlcpy(c->dirname, s->filename, sizeof(c->dirname));
411     ptr = strrchr(c->dirname, '/');
412     if (ptr) {
413         av_strlcpy(basename, &ptr[1], sizeof(basename));
414         ptr[1] = '\0';
415     } else {
416         c->dirname[0] = '\0';
417         av_strlcpy(basename, s->filename, sizeof(basename));
418     }
419
420     ptr = strrchr(basename, '.');
421     if (ptr)
422         *ptr = '\0';
423
424     oformat = av_guess_format("mp4", NULL, NULL);
425     if (!oformat) {
426         ret = AVERROR_MUXER_NOT_FOUND;
427         goto fail;
428     }
429
430     c->streams = av_mallocz(sizeof(*c->streams) * s->nb_streams);
431     if (!c->streams) {
432         ret = AVERROR(ENOMEM);
433         goto fail;
434     }
435
436     for (i = 0; i < s->nb_streams; i++) {
437         OutputStream *os = &c->streams[i];
438         AVFormatContext *ctx;
439         AVStream *st;
440         AVDictionary *opts = NULL;
441         char filename[1024];
442
443         int bit_rate = s->streams[i]->codec->bit_rate ?
444                        s->streams[i]->codec->bit_rate :
445                        s->streams[i]->codec->rc_max_rate;
446         if (bit_rate) {
447             snprintf(os->bandwidth_str, sizeof(os->bandwidth_str),
448                      " bandwidth=\"%d\"", bit_rate);
449         } else {
450             int level = s->strict_std_compliance >= FF_COMPLIANCE_STRICT ?
451                         AV_LOG_ERROR : AV_LOG_WARNING;
452             av_log(s, level, "No bit rate set for stream %d\n", i);
453             if (s->strict_std_compliance >= FF_COMPLIANCE_STRICT) {
454                 ret = AVERROR(EINVAL);
455                 goto fail;
456             }
457         }
458
459         ctx = avformat_alloc_context();
460         if (!ctx) {
461             ret = AVERROR(ENOMEM);
462             goto fail;
463         }
464         os->ctx = ctx;
465         ctx->oformat = oformat;
466         ctx->interrupt_callback = s->interrupt_callback;
467
468         if (!(st = avformat_new_stream(ctx, NULL))) {
469             ret = AVERROR(ENOMEM);
470             goto fail;
471         }
472         avcodec_copy_context(st->codec, s->streams[i]->codec);
473         st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
474         st->time_base = s->streams[i]->time_base;
475         ctx->avoid_negative_ts = s->avoid_negative_ts;
476
477         ctx->pb = avio_alloc_context(os->iobuf, sizeof(os->iobuf), AVIO_FLAG_WRITE, os, NULL, dash_write, NULL);
478         if (!ctx->pb) {
479             ret = AVERROR(ENOMEM);
480             goto fail;
481         }
482
483         if (c->single_file)
484             snprintf(os->initfile, sizeof(os->initfile), "%s-stream%d.m4s", basename, i);
485         else
486             snprintf(os->initfile, sizeof(os->initfile), "init-stream%d.m4s", i);
487         snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
488         ret = ffurl_open(&os->out, filename, AVIO_FLAG_WRITE, &s->interrupt_callback, NULL);
489         if (ret < 0)
490             goto fail;
491         os->init_start_pos = 0;
492
493         av_dict_set(&opts, "movflags", "frag_custom+dash", 0);
494         if ((ret = avformat_write_header(ctx, &opts)) < 0) {
495              goto fail;
496         }
497         os->ctx_inited = 1;
498         avio_flush(ctx->pb);
499         av_dict_free(&opts);
500
501         if (c->single_file) {
502             os->init_range_length = avio_tell(ctx->pb);
503         } else {
504             ffurl_close(os->out);
505             os->out = NULL;
506         }
507
508         s->streams[i]->time_base = st->time_base;
509         // If the muxer wants to shift timestamps, request to have them shifted
510         // already before being handed to this muxer, so we don't have mismatches
511         // between the MPD and the actual segments.
512         s->avoid_negative_ts = ctx->avoid_negative_ts;
513         if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
514             c->has_video = 1;
515         else if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
516             c->has_audio = 1;
517
518         set_codec_str(s, os->ctx->streams[0]->codec, os->codec_str, sizeof(os->codec_str));
519         os->first_dts = AV_NOPTS_VALUE;
520         os->segment_index = 1;
521     }
522
523     if (!c->has_video && c->min_seg_duration <= 0) {
524         av_log(s, AV_LOG_WARNING, "no video stream and no min seg duration set\n");
525         ret = AVERROR(EINVAL);
526     }
527     ret = write_manifest(s, 0);
528
529 fail:
530     if (ret)
531         dash_free(s);
532     return ret;
533 }
534
535 static int add_segment(OutputStream *os, const char *file,
536                        int64_t time, int duration,
537                        int64_t start_pos, int64_t range_length,
538                        int64_t index_length)
539 {
540     int err;
541     Segment *seg;
542     if (os->nb_segments >= os->segments_size) {
543         os->segments_size = (os->segments_size + 1) * 2;
544         if ((err = av_reallocp(&os->segments, sizeof(*os->segments) *
545                                os->segments_size)) < 0) {
546             os->segments_size = 0;
547             os->nb_segments = 0;
548             return err;
549         }
550     }
551     seg = av_mallocz(sizeof(*seg));
552     if (!seg)
553         return AVERROR(ENOMEM);
554     av_strlcpy(seg->file, file, sizeof(seg->file));
555     seg->time = time;
556     seg->duration = duration;
557     seg->start_pos = start_pos;
558     seg->range_length = range_length;
559     seg->index_length = index_length;
560     os->segments[os->nb_segments++] = seg;
561     os->segment_index++;
562     return 0;
563 }
564
565 static void write_styp(AVIOContext *pb)
566 {
567     avio_wb32(pb, 24);
568     ffio_wfourcc(pb, "styp");
569     ffio_wfourcc(pb, "msdh");
570     avio_wb32(pb, 0); /* minor */
571     ffio_wfourcc(pb, "msdh");
572     ffio_wfourcc(pb, "msix");
573 }
574
575 static void find_index_range(AVFormatContext *s, const char *dirname,
576                              const char *filename, int64_t pos,
577                              int *index_length)
578 {
579     char full_path[1024];
580     uint8_t buf[8];
581     URLContext *fd;
582     int ret;
583
584     snprintf(full_path, sizeof(full_path), "%s%s", dirname, filename);
585     ret = ffurl_open(&fd, full_path, AVIO_FLAG_READ, &s->interrupt_callback, NULL);
586     if (ret < 0)
587         return;
588     if (ffurl_seek(fd, pos, SEEK_SET) != pos) {
589         ffurl_close(fd);
590         return;
591     }
592     ret = ffurl_read(fd, buf, 8);
593     ffurl_close(fd);
594     if (ret < 8)
595         return;
596     if (AV_RL32(&buf[4]) != MKTAG('s', 'i', 'd', 'x'))
597         return;
598     *index_length = AV_RB32(&buf[0]);
599 }
600
601 static int dash_flush(AVFormatContext *s, int final)
602 {
603     DASHContext *c = s->priv_data;
604     int i, ret = 0;
605
606     for (i = 0; i < s->nb_streams; i++) {
607         OutputStream *os = &c->streams[i];
608         char filename[1024] = "", full_path[1024], temp_path[1024];
609         int64_t start_pos = avio_tell(os->ctx->pb);
610         int range_length, index_length = 0;
611
612         if (!os->packets_written)
613             continue;
614
615         if (!c->single_file) {
616             snprintf(filename, sizeof(filename), "chunk-stream%d-%05d.m4s", i, os->segment_index);
617             snprintf(full_path, sizeof(full_path), "%s%s", c->dirname, filename);
618             snprintf(temp_path, sizeof(temp_path), "%s.tmp", full_path);
619             ret = ffurl_open(&os->out, temp_path, AVIO_FLAG_WRITE, &s->interrupt_callback, NULL);
620             if (ret < 0)
621                 break;
622             write_styp(os->ctx->pb);
623         }
624         av_write_frame(os->ctx, NULL);
625         avio_flush(os->ctx->pb);
626         os->packets_written = 0;
627
628         range_length = avio_tell(os->ctx->pb) - start_pos;
629         if (c->single_file) {
630             find_index_range(s, c->dirname, os->initfile, start_pos, &index_length);
631         } else {
632             ffurl_close(os->out);
633             os->out = NULL;
634             ret = ff_rename(temp_path, full_path, s);
635             if (ret < 0)
636                 break;
637         }
638         add_segment(os, filename, os->start_dts, os->end_dts - os->start_dts, start_pos, range_length, index_length);
639     }
640
641     if (c->window_size || (final && c->remove_at_exit)) {
642         for (i = 0; i < s->nb_streams; i++) {
643             OutputStream *os = &c->streams[i];
644             int j;
645             int remove = os->nb_segments - c->window_size - c->extra_window_size;
646             if (final && c->remove_at_exit)
647                 remove = os->nb_segments;
648             if (remove > 0) {
649                 for (j = 0; j < remove; j++) {
650                     char filename[1024];
651                     snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->segments[j]->file);
652                     unlink(filename);
653                     av_free(os->segments[j]);
654                 }
655                 os->nb_segments -= remove;
656                 memmove(os->segments, os->segments + remove, os->nb_segments * sizeof(*os->segments));
657             }
658         }
659     }
660
661     if (ret >= 0)
662         ret = write_manifest(s, final);
663     return ret;
664 }
665
666 static int dash_write_packet(AVFormatContext *s, AVPacket *pkt)
667 {
668     DASHContext *c = s->priv_data;
669     AVStream *st = s->streams[pkt->stream_index];
670     OutputStream *os = &c->streams[pkt->stream_index];
671     int64_t seg_end_duration = (c->nb_segments + 1) * (int64_t) c->min_seg_duration;
672     int ret;
673
674     // If forcing the stream to start at 0, the mp4 muxer will set the start
675     // timestamps to 0. Do the same here, to avoid mismatches in duration/timestamps.
676     if (os->first_dts == AV_NOPTS_VALUE &&
677         s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
678         pkt->pts -= pkt->dts;
679         pkt->dts  = 0;
680     }
681
682     if (os->first_dts == AV_NOPTS_VALUE)
683         os->first_dts = pkt->dts;
684
685     if ((!c->has_video || st->codec->codec_type == AVMEDIA_TYPE_VIDEO) &&
686         pkt->flags & AV_PKT_FLAG_KEY && os->packets_written &&
687         av_compare_ts(pkt->dts - os->first_dts, st->time_base,
688                       seg_end_duration, AV_TIME_BASE_Q) >= 0) {
689         int64_t prev_duration = c->last_duration;
690
691         c->last_duration = av_rescale_q(pkt->dts - os->start_dts,
692                                         st->time_base,
693                                         AV_TIME_BASE_Q);
694         c->total_duration = av_rescale_q(pkt->dts - os->first_dts,
695                                          st->time_base,
696                                          AV_TIME_BASE_Q);
697
698         if ((!c->use_timeline || !c->use_template) && prev_duration) {
699             if (c->last_duration < prev_duration*9/10 ||
700                 c->last_duration > prev_duration*11/10) {
701                 av_log(s, AV_LOG_WARNING,
702                        "Segment durations differ too much, enable use_timeline "
703                        "and use_template, or keep a stricter keyframe interval\n");
704             }
705         }
706
707         if ((ret = dash_flush(s, 0)) < 0)
708             return ret;
709         c->nb_segments++;
710     }
711
712     if (!os->packets_written)
713         os->start_dts = pkt->dts;
714     os->end_dts = pkt->dts + pkt->duration;
715     os->packets_written++;
716     return ff_write_chained(os->ctx, 0, pkt, s, 0);
717 }
718
719 static int dash_write_trailer(AVFormatContext *s)
720 {
721     DASHContext *c = s->priv_data;
722
723     if (s->nb_streams > 0) {
724         OutputStream *os = &c->streams[0];
725         // If no segments have been written so far, try to do a crude
726         // guess of the segment duration
727         if (!c->last_duration)
728             c->last_duration = av_rescale_q(os->end_dts - os->start_dts,
729                                             s->streams[0]->time_base,
730                                             AV_TIME_BASE_Q);
731         c->total_duration = av_rescale_q(os->end_dts - os->first_dts,
732                                          s->streams[0]->time_base,
733                                          AV_TIME_BASE_Q);
734     }
735     dash_flush(s, 1);
736
737     if (c->remove_at_exit) {
738         char filename[1024];
739         int i;
740         for (i = 0; i < s->nb_streams; i++) {
741             OutputStream *os = &c->streams[i];
742             snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
743             unlink(filename);
744         }
745         unlink(s->filename);
746     }
747
748     dash_free(s);
749     return 0;
750 }
751
752 #define OFFSET(x) offsetof(DASHContext, x)
753 #define E AV_OPT_FLAG_ENCODING_PARAM
754 static const AVOption options[] = {
755     { "window_size", "number of segments kept in the manifest", OFFSET(window_size), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, E },
756     { "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 },
757     { "min_seg_duration", "minimum segment duration (in microseconds)", OFFSET(min_seg_duration), AV_OPT_TYPE_INT64, { .i64 = 5000000 }, 0, INT_MAX, E },
758     { "remove_at_exit", "remove all segments when finished", OFFSET(remove_at_exit), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, E },
759     { "use_template", "Use SegmentTemplate instead of SegmentList", OFFSET(use_template), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, E },
760     { "use_timeline", "Use SegmentTimeline in SegmentTemplate", OFFSET(use_timeline), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, E },
761     { "single_file", "Store all segments in one file, accessed using byte ranges", OFFSET(single_file), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, E },
762     { NULL },
763 };
764
765 static const AVClass dash_class = {
766     .class_name = "dash muxer",
767     .item_name  = av_default_item_name,
768     .option     = options,
769     .version    = LIBAVUTIL_VERSION_INT,
770 };
771
772 AVOutputFormat ff_dash_muxer = {
773     .name           = "dash",
774     .long_name      = NULL_IF_CONFIG_SMALL("DASH Muxer"),
775     .priv_data_size = sizeof(DASHContext),
776     .audio_codec    = AV_CODEC_ID_AAC,
777     .video_codec    = AV_CODEC_ID_H264,
778     .flags          = AVFMT_GLOBALHEADER | AVFMT_NOFILE | AVFMT_TS_NEGATIVE,
779     .write_header   = dash_write_header,
780     .write_packet   = dash_write_packet,
781     .write_trailer  = dash_write_trailer,
782     .codec_tag      = (const AVCodecTag* const []){ ff_mp4_obj_type, 0 },
783     .priv_class     = &dash_class,
784 };