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