]> git.sesse.net Git - ffmpeg/blobdiff - libavformat/dashenc.c
id3v2: fix reading v2.2 attached pictures
[ffmpeg] / libavformat / dashenc.c
index cacaf922b8ba83b979fbeebb58b5ec378f4fd774..1432fc32fd88184e636279e8c6430659b7e2e665 100644 (file)
 #include "os_support.h"
 #include "url.h"
 
+// See ISO/IEC 23009-1:2014 5.3.9.4.4
+typedef enum {
+    DASH_TMPL_ID_UNDEFINED = -1,
+    DASH_TMPL_ID_ESCAPE,
+    DASH_TMPL_ID_REP_ID,
+    DASH_TMPL_ID_NUMBER,
+    DASH_TMPL_ID_BANDWIDTH,
+    DASH_TMPL_ID_TIME,
+} DASHTmplId;
+
 typedef struct Segment {
     char file[1024];
     int64_t start_pos;
@@ -58,7 +68,9 @@ typedef struct OutputStream {
     int init_range_length;
     int nb_segments, segments_size, segment_index;
     Segment **segments;
-    int64_t first_dts, start_dts, end_dts;
+    int64_t first_pts, start_pts, max_pts;
+    int bit_rate;
+    char bandwidth_str[64];
 
     char codec_str[100];
 } OutputStream;
@@ -74,11 +86,13 @@ typedef struct DASHContext {
     int single_file;
     OutputStream *streams;
     int has_video, has_audio;
-    int nb_segments;
-    int last_duration;
-    int total_duration;
+    int64_t last_duration;
+    int64_t total_duration;
     char availability_start_time[100];
     char dirname[1024];
+    const char *single_file_name;
+    const char *init_seg_name;
+    const char *media_seg_name;
 } DASHContext;
 
 static int dash_write(void *opaque, uint8_t *buf, int buf_size)
@@ -191,30 +205,36 @@ static void output_segment_list(OutputStream *os, AVIOContext *out, DASHContext
         int timescale = c->use_timeline ? os->ctx->streams[0]->time_base.den : AV_TIME_BASE;
         avio_printf(out, "\t\t\t\t<SegmentTemplate timescale=\"%d\" ", timescale);
         if (!c->use_timeline)
-            avio_printf(out, "duration=\"%d\" ", c->last_duration);
-        avio_printf(out, "initialization=\"init-stream$RepresentationID$.m4s\" media=\"chunk-stream$RepresentationID$-$Number%%05d$.m4s\" startNumber=\"%d\">\n", c->use_timeline ? start_number : 1);
+            avio_printf(out, "duration=\"%"PRId64"\" ", c->last_duration);
+        avio_printf(out, "initialization=\"%s\" media=\"%s\" startNumber=\"%d\">\n", c->init_seg_name, c->media_seg_name, c->use_timeline ? start_number : 1);
         if (c->use_timeline) {
+            int64_t cur_time = 0;
             avio_printf(out, "\t\t\t\t\t<SegmentTimeline>\n");
             for (i = start_index; i < os->nb_segments; ) {
                 Segment *seg = os->segments[i];
                 int repeat = 0;
                 avio_printf(out, "\t\t\t\t\t\t<S ");
-                if (i == start_index)
+                if (i == start_index || seg->time != cur_time) {
+                    cur_time = seg->time;
                     avio_printf(out, "t=\"%"PRId64"\" ", seg->time);
+                }
                 avio_printf(out, "d=\"%d\" ", seg->duration);
-                while (i + repeat + 1 < os->nb_segments && os->segments[i + repeat + 1]->duration == seg->duration)
+                while (i + repeat + 1 < os->nb_segments &&
+                       os->segments[i + repeat + 1]->duration == seg->duration &&
+                       os->segments[i + repeat + 1]->time == os->segments[i + repeat]->time + os->segments[i + repeat]->duration)
                     repeat++;
                 if (repeat > 0)
                     avio_printf(out, "r=\"%d\" ", repeat);
                 avio_printf(out, "/>\n");
                 i += 1 + repeat;
+                cur_time += (1 + repeat) * seg->duration;
             }
             avio_printf(out, "\t\t\t\t\t</SegmentTimeline>\n");
         }
         avio_printf(out, "\t\t\t\t</SegmentTemplate>\n");
     } else if (c->single_file) {
         avio_printf(out, "\t\t\t\t<BaseURL>%s</BaseURL>\n", os->initfile);
-        avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%d\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);
+        avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%"PRId64"\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);
         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);
         for (i = start_index; i < os->nb_segments; i++) {
             Segment *seg = os->segments[i];
@@ -225,7 +245,7 @@ static void output_segment_list(OutputStream *os, AVIOContext *out, DASHContext
         }
         avio_printf(out, "\t\t\t\t</SegmentList>\n");
     } else {
-        avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%d\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);
+        avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%"PRId64"\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);
         avio_printf(out, "\t\t\t\t\t<Initialization sourceURL=\"%s\" />\n", os->initfile);
         for (i = start_index; i < os->nb_segments; i++) {
             Segment *seg = os->segments[i];
@@ -235,6 +255,119 @@ static void output_segment_list(OutputStream *os, AVIOContext *out, DASHContext
     }
 }
 
+static DASHTmplId dash_read_tmpl_id(const char *identifier, char *format_tag,
+                                    size_t format_tag_size, const char **ptr) {
+    const char *next_ptr;
+    DASHTmplId id_type = DASH_TMPL_ID_UNDEFINED;
+
+    if (av_strstart(identifier, "$$", &next_ptr)) {
+        id_type = DASH_TMPL_ID_ESCAPE;
+        *ptr = next_ptr;
+    } else if (av_strstart(identifier, "$RepresentationID$", &next_ptr)) {
+        id_type = DASH_TMPL_ID_REP_ID;
+        // default to basic format, as $RepresentationID$ identifiers
+        // are not allowed to have custom format-tags.
+        av_strlcpy(format_tag, "%d", format_tag_size);
+        *ptr = next_ptr;
+    } else { // the following identifiers may have an explicit format_tag
+        if (av_strstart(identifier, "$Number", &next_ptr))
+            id_type = DASH_TMPL_ID_NUMBER;
+        else if (av_strstart(identifier, "$Bandwidth", &next_ptr))
+            id_type = DASH_TMPL_ID_BANDWIDTH;
+        else if (av_strstart(identifier, "$Time", &next_ptr))
+            id_type = DASH_TMPL_ID_TIME;
+        else
+            id_type = DASH_TMPL_ID_UNDEFINED;
+
+        // next parse the dash format-tag and generate a c-string format tag
+        // (next_ptr now points at the first '%' at the beginning of the format-tag)
+        if (id_type != DASH_TMPL_ID_UNDEFINED) {
+            const char *number_format = DASH_TMPL_ID_TIME ? "lld" : "d";
+            if (next_ptr[0] == '$') { // no dash format-tag
+                snprintf(format_tag, format_tag_size, "%%%s", number_format);
+                *ptr = &next_ptr[1];
+            } else {
+                const char *width_ptr;
+                // only tolerate single-digit width-field (i.e. up to 9-digit width)
+                if (av_strstart(next_ptr, "%0", &width_ptr) &&
+                    av_isdigit(width_ptr[0]) &&
+                    av_strstart(&width_ptr[1], "d$", &next_ptr)) {
+                    // yes, we're using a format tag to build format_tag.
+                    snprintf(format_tag, format_tag_size, "%s%c%s", "%0", width_ptr[0], number_format);
+                    *ptr = next_ptr;
+                } else {
+                    av_log(NULL, AV_LOG_WARNING, "Failed to parse format-tag beginning with %s. Expected either a "
+                                                 "closing '$' character or a format-string like '%%0[width]d', "
+                                                 "where width must be a single digit\n", next_ptr);
+                    id_type = DASH_TMPL_ID_UNDEFINED;
+                }
+            }
+        }
+    }
+    return id_type;
+}
+
+static void dash_fill_tmpl_params(char *dst, size_t buffer_size,
+                                  const char *template, int rep_id,
+                                  int number, int bit_rate,
+                                  int64_t time) {
+    int dst_pos = 0;
+    const char *t_cur = template;
+    while (dst_pos < buffer_size - 1 && *t_cur) {
+        char format_tag[7]; // May be "%d", "%0Xd", or "%0Xlld" (for $Time$), where X is in [0-9]
+        int n = 0;
+        DASHTmplId id_type;
+        const char *t_next = strchr(t_cur, '$'); // copy over everything up to the first '$' character
+        if (t_next) {
+            int num_copy_bytes = FFMIN(t_next - t_cur, buffer_size - dst_pos - 1);
+            av_strlcpy(&dst[dst_pos], t_cur, num_copy_bytes + 1);
+            // advance
+            dst_pos += num_copy_bytes;
+            t_cur = t_next;
+        } else { // no more DASH identifiers to substitute - just copy the rest over and break
+            av_strlcpy(&dst[dst_pos], t_cur, buffer_size - dst_pos);
+            break;
+        }
+
+        if (dst_pos >= buffer_size - 1 || !*t_cur)
+            break;
+
+        // t_cur is now pointing to a '$' character
+        id_type = dash_read_tmpl_id(t_cur, format_tag, sizeof(format_tag), &t_next);
+        switch (id_type) {
+        case DASH_TMPL_ID_ESCAPE:
+            av_strlcpy(&dst[dst_pos], "$", 2);
+            n = 1;
+            break;
+        case DASH_TMPL_ID_REP_ID:
+            n = snprintf(&dst[dst_pos], buffer_size - dst_pos, format_tag, rep_id);
+            break;
+        case DASH_TMPL_ID_NUMBER:
+            n = snprintf(&dst[dst_pos], buffer_size - dst_pos, format_tag, number);
+            break;
+        case DASH_TMPL_ID_BANDWIDTH:
+            n = snprintf(&dst[dst_pos], buffer_size - dst_pos, format_tag, bit_rate);
+            break;
+        case DASH_TMPL_ID_TIME:
+            n = snprintf(&dst[dst_pos], buffer_size - dst_pos, format_tag, time);
+            break;
+        case DASH_TMPL_ID_UNDEFINED:
+            // copy over one byte and advance
+            av_strlcpy(&dst[dst_pos], t_cur, 2);
+            n = 1;
+            t_next = &t_cur[1];
+            break;
+        }
+        // t_next points just past the processed identifier
+        // n is the number of bytes that were attempted to be written to dst
+        // (may have failed to write all because buffer_size).
+
+        // advance
+        dst_pos += FFMIN(n, buffer_size - dst_pos - 1);
+        t_cur = t_next;
+    }
+}
+
 static char *xmlescape(const char *str) {
     int outlen = strlen(str)*3/2 + 6;
     char *out = av_realloc(NULL, outlen + 1);
@@ -317,11 +450,11 @@ static int write_manifest(AVFormatContext *s, int final)
         write_time(out, c->total_duration);
         avio_printf(out, "\"\n");
     } else {
-        int update_period = c->last_duration / AV_TIME_BASE;
+        int64_t update_period = c->last_duration / AV_TIME_BASE;
         if (c->use_template && !c->use_timeline)
             update_period = 500;
-        avio_printf(out, "\tminimumUpdatePeriod=\"PT%dS\"\n", update_period);
-        avio_printf(out, "\tsuggestedPresentationDelay=\"PT%dS\"\n", c->last_duration / AV_TIME_BASE);
+        avio_printf(out, "\tminimumUpdatePeriod=\"PT%"PRId64"S\"\n", update_period);
+        avio_printf(out, "\tsuggestedPresentationDelay=\"PT%"PRId64"S\"\n", c->last_duration / AV_TIME_BASE);
         if (!c->availability_start_time[0] && s->nb_streams > 0 && c->streams[0].nb_segments > 0) {
             time_t t = time(NULL);
             struct tm *ptm, tmbuf;
@@ -368,7 +501,7 @@ static int write_manifest(AVFormatContext *s, int final)
             OutputStream *os = &c->streams[i];
             if (s->streams[i]->codec->codec_type != AVMEDIA_TYPE_VIDEO)
                 continue;
-            avio_printf(out, "\t\t\t<Representation id=\"%d\" mimeType=\"video/mp4\" codecs=\"%s\" bandwidth=\"%d\" width=\"%d\" height=\"%d\">\n", i, os->codec_str, st->codec->bit_rate, st->codec->width, st->codec->height);
+            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);
             output_segment_list(&c->streams[i], out, c);
             avio_printf(out, "\t\t\t</Representation>\n");
         }
@@ -381,7 +514,7 @@ static int write_manifest(AVFormatContext *s, int final)
             OutputStream *os = &c->streams[i];
             if (s->streams[i]->codec->codec_type != AVMEDIA_TYPE_AUDIO)
                 continue;
-            avio_printf(out, "\t\t\t<Representation id=\"%d\" mimeType=\"audio/mp4\" codecs=\"%s\" bandwidth=\"%d\" audioSamplingRate=\"%d\">\n", i, os->codec_str, st->codec->bit_rate, st->codec->sample_rate);
+            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);
             avio_printf(out, "\t\t\t\t<AudioChannelConfiguration schemeIdUri=\"urn:mpeg:dash:23003:3:audio_channel_configuration:2011\" value=\"%d\" />\n", st->codec->channels);
             output_segment_list(&c->streams[i], out, c);
             avio_printf(out, "\t\t\t</Representation>\n");
@@ -403,6 +536,8 @@ static int dash_write_header(AVFormatContext *s)
     char *ptr;
     char basename[1024];
 
+    if (c->single_file_name)
+        c->single_file = 1;
     if (c->single_file)
         c->use_template = 0;
 
@@ -439,10 +574,18 @@ static int dash_write_header(AVFormatContext *s)
         AVDictionary *opts = NULL;
         char filename[1024];
 
-        if (!s->streams[i]->codec->bit_rate) {
-            av_log(s, AV_LOG_ERROR, "No bit rate set for stream %d\n", i);
-            ret = AVERROR(EINVAL);
-            goto fail;
+        os->bit_rate = s->streams[i]->codec->bit_rate;
+        if (os->bit_rate) {
+            snprintf(os->bandwidth_str, sizeof(os->bandwidth_str),
+                     " bandwidth=\"%d\"", os->bit_rate);
+        } else {
+            int level = s->strict_std_compliance >= FF_COMPLIANCE_STRICT ?
+                        AV_LOG_ERROR : AV_LOG_WARNING;
+            av_log(s, level, "No bit rate set for stream %d\n", i);
+            if (s->strict_std_compliance >= FF_COMPLIANCE_STRICT) {
+                ret = AVERROR(EINVAL);
+                goto fail;
+            }
         }
 
         ctx = avformat_alloc_context();
@@ -469,17 +612,21 @@ static int dash_write_header(AVFormatContext *s)
             goto fail;
         }
 
-        if (c->single_file)
-            snprintf(os->initfile, sizeof(os->initfile), "%s-stream%d.m4s", basename, i);
-        else
-            snprintf(os->initfile, sizeof(os->initfile), "init-stream%d.m4s", i);
+        if (c->single_file) {
+            if (c->single_file_name)
+                dash_fill_tmpl_params(os->initfile, sizeof(os->initfile), c->single_file_name, i, 0, os->bit_rate, 0);
+            else
+                snprintf(os->initfile, sizeof(os->initfile), "%s-stream%d.m4s", basename, i);
+        } else {
+            dash_fill_tmpl_params(os->initfile, sizeof(os->initfile), c->init_seg_name, i, 0, os->bit_rate, 0);
+        }
         snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
         ret = ffurl_open(&os->out, filename, AVIO_FLAG_WRITE, &s->interrupt_callback, NULL);
         if (ret < 0)
             goto fail;
         os->init_start_pos = 0;
 
-        av_dict_set(&opts, "movflags", "frag_custom+dash", 0);
+        av_dict_set(&opts, "movflags", "frag_custom+dash+delay_moov", 0);
         if ((ret = avformat_write_header(ctx, &opts)) < 0) {
              goto fail;
         }
@@ -487,12 +634,7 @@ static int dash_write_header(AVFormatContext *s)
         avio_flush(ctx->pb);
         av_dict_free(&opts);
 
-        if (c->single_file) {
-            os->init_range_length = avio_tell(ctx->pb);
-        } else {
-            ffurl_close(os->out);
-            os->out = NULL;
-        }
+        av_log(s, AV_LOG_VERBOSE, "Representation %d init segment will be written to: %s\n", i, filename);
 
         s->streams[i]->time_base = st->time_base;
         // If the muxer wants to shift timestamps, request to have them shifted
@@ -505,7 +647,8 @@ static int dash_write_header(AVFormatContext *s)
             c->has_audio = 1;
 
         set_codec_str(s, os->ctx->streams[0]->codec, os->codec_str, sizeof(os->codec_str));
-        os->first_dts = AV_NOPTS_VALUE;
+        os->first_pts = AV_NOPTS_VALUE;
+        os->max_pts = AV_NOPTS_VALUE;
         os->segment_index = 1;
     }
 
@@ -514,6 +657,8 @@ static int dash_write_header(AVFormatContext *s)
         ret = AVERROR(EINVAL);
     }
     ret = write_manifest(s, 0);
+    if (!ret)
+        av_log(s, AV_LOG_VERBOSE, "Manifest written to: %s\n", s->filename);
 
 fail:
     if (ret)
@@ -542,6 +687,8 @@ static int add_segment(OutputStream *os, const char *file,
         return AVERROR(ENOMEM);
     av_strlcpy(seg->file, file, sizeof(seg->file));
     seg->time = time;
+    if (seg->time < 0) // If pts<0, it is expected to be cut away with an edit list
+        seg->time = 0;
     seg->duration = duration;
     seg->start_pos = start_pos;
     seg->range_length = range_length;
@@ -561,16 +708,13 @@ static void write_styp(AVIOContext *pb)
     ffio_wfourcc(pb, "msix");
 }
 
-static void find_index_range(AVFormatContext *s, const char *dirname,
-                             const char *filename, int64_t pos,
-                             int *index_length)
+static void find_index_range(AVFormatContext *s, const char *full_path,
+                             int64_t pos, int *index_length)
 {
-    char full_path[1024];
     uint8_t buf[8];
     URLContext *fd;
     int ret;
 
-    snprintf(full_path, sizeof(full_path), "%s%s", dirname, filename);
     ret = ffurl_open(&fd, full_path, AVIO_FLAG_READ, &s->interrupt_callback, NULL);
     if (ret < 0)
         return;
@@ -587,36 +731,65 @@ static void find_index_range(AVFormatContext *s, const char *dirname,
     *index_length = AV_RB32(&buf[0]);
 }
 
-static int dash_flush(AVFormatContext *s, int final)
+static int dash_flush(AVFormatContext *s, int final, int stream)
 {
     DASHContext *c = s->priv_data;
     int i, ret = 0;
+    int cur_flush_segment_index = 0;
+    if (stream >= 0)
+        cur_flush_segment_index = c->streams[stream].segment_index;
 
     for (i = 0; i < s->nb_streams; i++) {
         OutputStream *os = &c->streams[i];
         char filename[1024] = "", full_path[1024], temp_path[1024];
-        int64_t start_pos = avio_tell(os->ctx->pb);
+        int64_t start_pos;
         int range_length, index_length = 0;
 
         if (!os->packets_written)
             continue;
 
+        // Flush the single stream that got a keyframe right now.
+        // Flush all audio streams as well, in sync with video keyframes,
+        // but not the other video streams.
+        if (stream >= 0 && i != stream) {
+            if (s->streams[i]->codec->codec_type != AVMEDIA_TYPE_AUDIO)
+                continue;
+            // Make sure we don't flush audio streams multiple times, when
+            // all video streams are flushed one at a time.
+            if (c->has_video && os->segment_index > cur_flush_segment_index)
+                continue;
+        }
+
+        if (!os->init_range_length) {
+            av_write_frame(os->ctx, NULL);
+            os->init_range_length = avio_tell(os->ctx->pb);
+            if (!c->single_file) {
+                ffurl_close(os->out);
+                os->out = NULL;
+            }
+        }
+
+        start_pos = avio_tell(os->ctx->pb);
+
         if (!c->single_file) {
-            snprintf(filename, sizeof(filename), "chunk-stream%d-%05d.m4s", i, os->segment_index);
+            dash_fill_tmpl_params(filename, sizeof(filename), c->media_seg_name, i, os->segment_index, os->bit_rate, os->start_pts);
             snprintf(full_path, sizeof(full_path), "%s%s", c->dirname, filename);
             snprintf(temp_path, sizeof(temp_path), "%s.tmp", full_path);
             ret = ffurl_open(&os->out, temp_path, AVIO_FLAG_WRITE, &s->interrupt_callback, NULL);
             if (ret < 0)
                 break;
             write_styp(os->ctx->pb);
+        } else {
+            snprintf(full_path, sizeof(full_path), "%s%s", c->dirname, os->initfile);
         }
+
         av_write_frame(os->ctx, NULL);
         avio_flush(os->ctx->pb);
         os->packets_written = 0;
 
         range_length = avio_tell(os->ctx->pb) - start_pos;
         if (c->single_file) {
-            find_index_range(s, c->dirname, os->initfile, start_pos, &index_length);
+            find_index_range(s, full_path, start_pos, &index_length);
         } else {
             ffurl_close(os->out);
             os->out = NULL;
@@ -624,7 +797,8 @@ static int dash_flush(AVFormatContext *s, int final)
             if (ret < 0)
                 break;
         }
-        add_segment(os, filename, os->start_dts, os->end_dts - os->start_dts, start_pos, range_length, index_length);
+        add_segment(os, filename, os->start_pts, os->max_pts - os->start_pts, start_pos, range_length, index_length);
+        av_log(s, AV_LOG_VERBOSE, "Representation %d media segment %d written to: %s\n", i, os->segment_index, full_path);
     }
 
     if (c->window_size || (final && c->remove_at_exit)) {
@@ -657,30 +831,30 @@ static int dash_write_packet(AVFormatContext *s, AVPacket *pkt)
     DASHContext *c = s->priv_data;
     AVStream *st = s->streams[pkt->stream_index];
     OutputStream *os = &c->streams[pkt->stream_index];
-    int64_t seg_end_duration = (c->nb_segments + 1) * (int64_t) c->min_seg_duration;
+    int64_t seg_end_duration = (os->segment_index) * (int64_t) c->min_seg_duration;
     int ret;
 
     // If forcing the stream to start at 0, the mp4 muxer will set the start
     // timestamps to 0. Do the same here, to avoid mismatches in duration/timestamps.
-    if (os->first_dts == AV_NOPTS_VALUE &&
+    if (os->first_pts == AV_NOPTS_VALUE &&
         s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
         pkt->pts -= pkt->dts;
         pkt->dts  = 0;
     }
 
-    if (os->first_dts == AV_NOPTS_VALUE)
-        os->first_dts = pkt->dts;
+    if (os->first_pts == AV_NOPTS_VALUE)
+        os->first_pts = pkt->pts;
 
     if ((!c->has_video || st->codec->codec_type == AVMEDIA_TYPE_VIDEO) &&
         pkt->flags & AV_PKT_FLAG_KEY && os->packets_written &&
-        av_compare_ts(pkt->dts - os->first_dts, st->time_base,
+        av_compare_ts(pkt->pts - os->first_pts, st->time_base,
                       seg_end_duration, AV_TIME_BASE_Q) >= 0) {
         int64_t prev_duration = c->last_duration;
 
-        c->last_duration = av_rescale_q(pkt->dts - os->start_dts,
+        c->last_duration = av_rescale_q(pkt->pts - os->start_pts,
                                         st->time_base,
                                         AV_TIME_BASE_Q);
-        c->total_duration = av_rescale_q(pkt->dts - os->first_dts,
+        c->total_duration = av_rescale_q(pkt->pts - os->first_pts,
                                          st->time_base,
                                          AV_TIME_BASE_Q);
 
@@ -693,14 +867,23 @@ static int dash_write_packet(AVFormatContext *s, AVPacket *pkt)
             }
         }
 
-        if ((ret = dash_flush(s, 0)) < 0)
+        if ((ret = dash_flush(s, 0, pkt->stream_index)) < 0)
             return ret;
-        c->nb_segments++;
     }
 
-    if (!os->packets_written)
-        os->start_dts = pkt->dts;
-    os->end_dts = pkt->dts + pkt->duration;
+    if (!os->packets_written) {
+        // If we wrote a previous segment, adjust the start time of the segment
+        // to the end of the previous one (which is the same as the mp4 muxer
+        // does). This avoids gaps in the timeline.
+        if (os->max_pts != AV_NOPTS_VALUE)
+            os->start_pts = os->max_pts;
+        else
+            os->start_pts = pkt->pts;
+    }
+    if (os->max_pts == AV_NOPTS_VALUE)
+        os->max_pts = pkt->pts + pkt->duration;
+    else
+        os->max_pts = FFMAX(os->max_pts, pkt->pts + pkt->duration);
     os->packets_written++;
     return ff_write_chained(os->ctx, 0, pkt, s);
 }
@@ -714,14 +897,14 @@ static int dash_write_trailer(AVFormatContext *s)
         // If no segments have been written so far, try to do a crude
         // guess of the segment duration
         if (!c->last_duration)
-            c->last_duration = av_rescale_q(os->end_dts - os->start_dts,
+            c->last_duration = av_rescale_q(os->max_pts - os->start_pts,
                                             s->streams[0]->time_base,
                                             AV_TIME_BASE_Q);
-        c->total_duration = av_rescale_q(os->end_dts - os->first_dts,
+        c->total_duration = av_rescale_q(os->max_pts - os->first_pts,
                                          s->streams[0]->time_base,
                                          AV_TIME_BASE_Q);
     }
-    dash_flush(s, 1);
+    dash_flush(s, 1, -1);
 
     if (c->remove_at_exit) {
         char filename[1024];
@@ -748,6 +931,9 @@ static const AVOption options[] = {
     { "use_template", "Use SegmentTemplate instead of SegmentList", OFFSET(use_template), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, E },
     { "use_timeline", "Use SegmentTimeline in SegmentTemplate", OFFSET(use_timeline), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, E },
     { "single_file", "Store all segments in one file, accessed using byte ranges", OFFSET(single_file), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, E },
+    { "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 },
+    { "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 },
+    { "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 },
     { NULL },
 };