LCOV - code coverage report
Current view: top level - libavformat - dashenc.c (source / functions) Hit Total Coverage
Test: coverage.info Lines: 0 904 0.0 %
Date: 2018-05-20 11:54:08 Functions: 0 30 0.0 %

          Line data    Source code
       1             : /*
       2             :  * MPEG-DASH ISO BMFF segmenter
       3             :  * Copyright (c) 2014 Martin Storsjo
       4             :  * Copyright (c) 2018 Akamai Technologies, Inc.
       5             :  *
       6             :  * This file is part of FFmpeg.
       7             :  *
       8             :  * FFmpeg is free software; you can redistribute it and/or
       9             :  * modify it under the terms of the GNU Lesser General Public
      10             :  * License as published by the Free Software Foundation; either
      11             :  * version 2.1 of the License, or (at your option) any later version.
      12             :  *
      13             :  * FFmpeg is distributed in the hope that it will be useful,
      14             :  * but WITHOUT ANY WARRANTY; without even the implied warranty of
      15             :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
      16             :  * Lesser General Public License for more details.
      17             :  *
      18             :  * You should have received a copy of the GNU Lesser General Public
      19             :  * License along with FFmpeg; if not, write to the Free Software
      20             :  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
      21             :  */
      22             : 
      23             : #include "config.h"
      24             : #if HAVE_UNISTD_H
      25             : #include <unistd.h>
      26             : #endif
      27             : 
      28             : #include "libavutil/avassert.h"
      29             : #include "libavutil/avutil.h"
      30             : #include "libavutil/avstring.h"
      31             : #include "libavutil/intreadwrite.h"
      32             : #include "libavutil/mathematics.h"
      33             : #include "libavutil/opt.h"
      34             : #include "libavutil/rational.h"
      35             : #include "libavutil/time_internal.h"
      36             : 
      37             : #include "avc.h"
      38             : #include "avformat.h"
      39             : #include "avio_internal.h"
      40             : #include "hlsplaylist.h"
      41             : #if CONFIG_HTTP_PROTOCOL
      42             : #include "http.h"
      43             : #endif
      44             : #include "internal.h"
      45             : #include "isom.h"
      46             : #include "os_support.h"
      47             : #include "url.h"
      48             : #include "vpcc.h"
      49             : #include "dash.h"
      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 AdaptationSet {
      61             :     char id[10];
      62             :     enum AVMediaType media_type;
      63             :     AVDictionary *metadata;
      64             :     AVRational min_frame_rate, max_frame_rate;
      65             :     int ambiguous_frame_rate;
      66             : } AdaptationSet;
      67             : 
      68             : typedef struct OutputStream {
      69             :     AVFormatContext *ctx;
      70             :     int ctx_inited, as_idx;
      71             :     AVIOContext *out;
      72             :     char format_name[8];
      73             :     int packets_written;
      74             :     char initfile[1024];
      75             :     int64_t init_start_pos, pos;
      76             :     int init_range_length;
      77             :     int nb_segments, segments_size, segment_index;
      78             :     Segment **segments;
      79             :     int64_t first_pts, start_pts, max_pts;
      80             :     int64_t last_dts, last_pts;
      81             :     int bit_rate;
      82             : 
      83             :     char codec_str[100];
      84             :     int written_len;
      85             :     char filename[1024];
      86             :     char full_path[1024];
      87             :     char temp_path[1024];
      88             :     double availability_time_offset;
      89             :     int total_pkt_size;
      90             :     int muxer_overhead;
      91             : } OutputStream;
      92             : 
      93             : typedef struct DASHContext {
      94             :     const AVClass *class;  /* Class for private options. */
      95             :     char *adaptation_sets;
      96             :     AdaptationSet *as;
      97             :     int nb_as;
      98             :     int window_size;
      99             :     int extra_window_size;
     100             : #if FF_API_DASH_MIN_SEG_DURATION
     101             :     int min_seg_duration;
     102             : #endif
     103             :     int64_t seg_duration;
     104             :     int remove_at_exit;
     105             :     int use_template;
     106             :     int use_timeline;
     107             :     int single_file;
     108             :     OutputStream *streams;
     109             :     int has_video;
     110             :     int64_t last_duration;
     111             :     int64_t total_duration;
     112             :     char availability_start_time[100];
     113             :     char dirname[1024];
     114             :     const char *single_file_name;
     115             :     const char *init_seg_name;
     116             :     const char *media_seg_name;
     117             :     const char *utc_timing_url;
     118             :     const char *method;
     119             :     const char *user_agent;
     120             :     int hls_playlist;
     121             :     int http_persistent;
     122             :     int master_playlist_created;
     123             :     AVIOContext *mpd_out;
     124             :     AVIOContext *m3u8_out;
     125             :     int streaming;
     126             :     int64_t timeout;
     127             :     int index_correction;
     128             :     char *format_options_str;
     129             : } DASHContext;
     130             : 
     131             : static struct codec_string {
     132             :     int id;
     133             :     const char *str;
     134             : } codecs[] = {
     135             :     { AV_CODEC_ID_VP8, "vp8" },
     136             :     { AV_CODEC_ID_VP9, "vp9" },
     137             :     { AV_CODEC_ID_VORBIS, "vorbis" },
     138             :     { AV_CODEC_ID_OPUS, "opus" },
     139             :     { 0, NULL }
     140             : };
     141             : 
     142           0 : static int dashenc_io_open(AVFormatContext *s, AVIOContext **pb, char *filename,
     143             :                            AVDictionary **options) {
     144           0 :     DASHContext *c = s->priv_data;
     145           0 :     int http_base_proto = filename ? ff_is_http_proto(filename) : 0;
     146           0 :     int err = AVERROR_MUXER_NOT_FOUND;
     147           0 :     if (!*pb || !http_base_proto || !c->http_persistent) {
     148           0 :         err = s->io_open(s, pb, filename, AVIO_FLAG_WRITE, options);
     149             : #if CONFIG_HTTP_PROTOCOL
     150             :     } else {
     151           0 :         URLContext *http_url_context = ffio_geturlcontext(*pb);
     152           0 :         av_assert0(http_url_context);
     153           0 :         err = ff_http_do_new_request(http_url_context, filename);
     154             : #endif
     155             :     }
     156           0 :     return err;
     157             : }
     158             : 
     159           0 : static void dashenc_io_close(AVFormatContext *s, AVIOContext **pb, char *filename) {
     160           0 :     DASHContext *c = s->priv_data;
     161           0 :     int http_base_proto = filename ? ff_is_http_proto(filename) : 0;
     162             : 
     163           0 :     if (!http_base_proto || !c->http_persistent) {
     164           0 :         ff_format_io_close(s, pb);
     165             : #if CONFIG_HTTP_PROTOCOL
     166             :     } else {
     167           0 :         URLContext *http_url_context = ffio_geturlcontext(*pb);
     168           0 :         av_assert0(http_url_context);
     169           0 :         avio_flush(*pb);
     170           0 :         ffurl_shutdown(http_url_context, AVIO_FLAG_WRITE);
     171             : #endif
     172             :     }
     173           0 : }
     174             : 
     175           0 : static void set_vp9_codec_str(AVFormatContext *s, AVCodecParameters *par,
     176             :                               AVRational *frame_rate, char *str, int size) {
     177             :     VPCC vpcc;
     178           0 :     int ret = ff_isom_get_vpcc_features(s, par, frame_rate, &vpcc);
     179           0 :     if (ret == 0) {
     180           0 :         av_strlcatf(str, size, "vp09.%02x.%02x.%02x",
     181             :                     vpcc.profile, vpcc.level, vpcc.bitdepth);
     182             :     } else {
     183             :         // Default to just vp9 in case of error while finding out profile or level
     184           0 :         av_log(s, AV_LOG_WARNING, "Could not find VP9 profile and/or level\n");
     185           0 :         av_strlcpy(str, "vp9", size);
     186             :     }
     187           0 :     return;
     188             : }
     189             : 
     190           0 : static void set_codec_str(AVFormatContext *s, AVCodecParameters *par,
     191             :                           AVRational *frame_rate, char *str, int size)
     192             : {
     193           0 :     const AVCodecTag *tags[2] = { NULL, NULL };
     194             :     uint32_t tag;
     195             :     int i;
     196             : 
     197             :     // common Webm codecs are not part of RFC 6381
     198           0 :     for (i = 0; codecs[i].id; i++)
     199           0 :         if (codecs[i].id == par->codec_id) {
     200           0 :             if (codecs[i].id == AV_CODEC_ID_VP9) {
     201           0 :                 set_vp9_codec_str(s, par, frame_rate, str, size);
     202             :             } else {
     203           0 :                 av_strlcpy(str, codecs[i].str, size);
     204             :             }
     205           0 :             return;
     206             :         }
     207             : 
     208             :     // for codecs part of RFC 6381
     209           0 :     if (par->codec_type == AVMEDIA_TYPE_VIDEO)
     210           0 :         tags[0] = ff_codec_movvideo_tags;
     211           0 :     else if (par->codec_type == AVMEDIA_TYPE_AUDIO)
     212           0 :         tags[0] = ff_codec_movaudio_tags;
     213             :     else
     214           0 :         return;
     215             : 
     216           0 :     tag = av_codec_get_tag(tags, par->codec_id);
     217           0 :     if (!tag)
     218           0 :         return;
     219           0 :     if (size < 5)
     220           0 :         return;
     221             : 
     222           0 :     AV_WL32(str, tag);
     223           0 :     str[4] = '\0';
     224           0 :     if (!strcmp(str, "mp4a") || !strcmp(str, "mp4v")) {
     225             :         uint32_t oti;
     226           0 :         tags[0] = ff_mp4_obj_type;
     227           0 :         oti = av_codec_get_tag(tags, par->codec_id);
     228           0 :         if (oti)
     229           0 :             av_strlcatf(str, size, ".%02"PRIx32, oti);
     230             :         else
     231           0 :             return;
     232             : 
     233           0 :         if (tag == MKTAG('m', 'p', '4', 'a')) {
     234           0 :             if (par->extradata_size >= 2) {
     235           0 :                 int aot = par->extradata[0] >> 3;
     236           0 :                 if (aot == 31)
     237           0 :                     aot = ((AV_RB16(par->extradata) >> 5) & 0x3f) + 32;
     238           0 :                 av_strlcatf(str, size, ".%d", aot);
     239             :             }
     240           0 :         } else if (tag == MKTAG('m', 'p', '4', 'v')) {
     241             :             // Unimplemented, should output ProfileLevelIndication as a decimal number
     242           0 :             av_log(s, AV_LOG_WARNING, "Incomplete RFC 6381 codec string for mp4v\n");
     243             :         }
     244           0 :     } else if (!strcmp(str, "avc1")) {
     245           0 :         uint8_t *tmpbuf = NULL;
     246           0 :         uint8_t *extradata = par->extradata;
     247           0 :         int extradata_size = par->extradata_size;
     248           0 :         if (!extradata_size)
     249           0 :             return;
     250           0 :         if (extradata[0] != 1) {
     251             :             AVIOContext *pb;
     252           0 :             if (avio_open_dyn_buf(&pb) < 0)
     253           0 :                 return;
     254           0 :             if (ff_isom_write_avcc(pb, extradata, extradata_size) < 0) {
     255           0 :                 ffio_free_dyn_buf(&pb);
     256           0 :                 return;
     257             :             }
     258           0 :             extradata_size = avio_close_dyn_buf(pb, &extradata);
     259           0 :             tmpbuf = extradata;
     260             :         }
     261             : 
     262           0 :         if (extradata_size >= 4)
     263           0 :             av_strlcatf(str, size, ".%02x%02x%02x",
     264           0 :                         extradata[1], extradata[2], extradata[3]);
     265           0 :         av_free(tmpbuf);
     266             :     }
     267             : }
     268             : 
     269           0 : static int flush_dynbuf(OutputStream *os, int *range_length)
     270             : {
     271             :     uint8_t *buffer;
     272             : 
     273           0 :     if (!os->ctx->pb) {
     274           0 :         return AVERROR(EINVAL);
     275             :     }
     276             : 
     277             :     // flush
     278           0 :     av_write_frame(os->ctx, NULL);
     279           0 :     avio_flush(os->ctx->pb);
     280             : 
     281             :     // write out to file
     282           0 :     *range_length = avio_close_dyn_buf(os->ctx->pb, &buffer);
     283           0 :     os->ctx->pb = NULL;
     284           0 :     avio_write(os->out, buffer + os->written_len, *range_length - os->written_len);
     285           0 :     os->written_len = 0;
     286           0 :     av_free(buffer);
     287             : 
     288             :     // re-open buffer
     289           0 :     return avio_open_dyn_buf(&os->ctx->pb);
     290             : }
     291             : 
     292           0 : static void set_http_options(AVDictionary **options, DASHContext *c)
     293             : {
     294           0 :     if (c->method)
     295           0 :         av_dict_set(options, "method", c->method, 0);
     296           0 :     if (c->user_agent)
     297           0 :         av_dict_set(options, "user_agent", c->user_agent, 0);
     298           0 :     if (c->http_persistent)
     299           0 :         av_dict_set_int(options, "multiple_requests", 1, 0);
     300           0 :     if (c->timeout >= 0)
     301           0 :         av_dict_set_int(options, "timeout", c->timeout, 0);
     302           0 : }
     303             : 
     304           0 : static void get_hls_playlist_name(char *playlist_name, int string_size,
     305             :                                   const char *base_url, int id) {
     306           0 :     if (base_url)
     307           0 :         snprintf(playlist_name, string_size, "%smedia_%d.m3u8", base_url, id);
     308             :     else
     309           0 :         snprintf(playlist_name, string_size, "media_%d.m3u8", id);
     310           0 : }
     311             : 
     312           0 : static int flush_init_segment(AVFormatContext *s, OutputStream *os)
     313             : {
     314           0 :     DASHContext *c = s->priv_data;
     315             :     int ret, range_length;
     316             : 
     317           0 :     ret = flush_dynbuf(os, &range_length);
     318           0 :     if (ret < 0)
     319           0 :         return ret;
     320             : 
     321           0 :     os->pos = os->init_range_length = range_length;
     322           0 :     if (!c->single_file)
     323           0 :         ff_format_io_close(s, &os->out);
     324           0 :     return 0;
     325             : }
     326             : 
     327           0 : static void dash_free(AVFormatContext *s)
     328             : {
     329           0 :     DASHContext *c = s->priv_data;
     330             :     int i, j;
     331             : 
     332           0 :     if (c->as) {
     333           0 :         for (i = 0; i < c->nb_as; i++)
     334           0 :             av_dict_free(&c->as[i].metadata);
     335           0 :         av_freep(&c->as);
     336           0 :         c->nb_as = 0;
     337             :     }
     338             : 
     339           0 :     if (!c->streams)
     340           0 :         return;
     341           0 :     for (i = 0; i < s->nb_streams; i++) {
     342           0 :         OutputStream *os = &c->streams[i];
     343           0 :         if (os->ctx && os->ctx_inited)
     344           0 :             av_write_trailer(os->ctx);
     345           0 :         if (os->ctx && os->ctx->pb)
     346           0 :             ffio_free_dyn_buf(&os->ctx->pb);
     347           0 :         ff_format_io_close(s, &os->out);
     348           0 :         if (os->ctx)
     349           0 :             avformat_free_context(os->ctx);
     350           0 :         for (j = 0; j < os->nb_segments; j++)
     351           0 :             av_free(os->segments[j]);
     352           0 :         av_free(os->segments);
     353             :     }
     354           0 :     av_freep(&c->streams);
     355             : 
     356           0 :     ff_format_io_close(s, &c->mpd_out);
     357           0 :     ff_format_io_close(s, &c->m3u8_out);
     358             : }
     359             : 
     360           0 : static void output_segment_list(OutputStream *os, AVIOContext *out, AVFormatContext *s,
     361             :                                 int representation_id, int final)
     362             : {
     363           0 :     DASHContext *c = s->priv_data;
     364           0 :     int i, start_index = 0, start_number = 1;
     365           0 :     if (c->window_size) {
     366           0 :         start_index  = FFMAX(os->nb_segments   - c->window_size, 0);
     367           0 :         start_number = FFMAX(os->segment_index - c->window_size, 1);
     368             :     }
     369             : 
     370           0 :     if (c->use_template) {
     371           0 :         int timescale = c->use_timeline ? os->ctx->streams[0]->time_base.den : AV_TIME_BASE;
     372           0 :         avio_printf(out, "\t\t\t\t<SegmentTemplate timescale=\"%d\" ", timescale);
     373           0 :         if (!c->use_timeline) {
     374           0 :             avio_printf(out, "duration=\"%"PRId64"\" ", c->seg_duration);
     375           0 :             if (c->streaming && os->availability_time_offset)
     376           0 :                 avio_printf(out, "availabilityTimeOffset=\"%.3f\" ",
     377             :                             os->availability_time_offset);
     378             :         }
     379           0 :         avio_printf(out, "initialization=\"%s\" media=\"%s\" startNumber=\"%d\">\n", c->init_seg_name, c->media_seg_name, c->use_timeline ? start_number : 1);
     380           0 :         if (c->use_timeline) {
     381           0 :             int64_t cur_time = 0;
     382           0 :             avio_printf(out, "\t\t\t\t\t<SegmentTimeline>\n");
     383           0 :             for (i = start_index; i < os->nb_segments; ) {
     384           0 :                 Segment *seg = os->segments[i];
     385           0 :                 int repeat = 0;
     386           0 :                 avio_printf(out, "\t\t\t\t\t\t<S ");
     387           0 :                 if (i == start_index || seg->time != cur_time) {
     388           0 :                     cur_time = seg->time;
     389           0 :                     avio_printf(out, "t=\"%"PRId64"\" ", seg->time);
     390             :                 }
     391           0 :                 avio_printf(out, "d=\"%d\" ", seg->duration);
     392           0 :                 while (i + repeat + 1 < os->nb_segments &&
     393           0 :                        os->segments[i + repeat + 1]->duration == seg->duration &&
     394           0 :                        os->segments[i + repeat + 1]->time == os->segments[i + repeat]->time + os->segments[i + repeat]->duration)
     395           0 :                     repeat++;
     396           0 :                 if (repeat > 0)
     397           0 :                     avio_printf(out, "r=\"%d\" ", repeat);
     398           0 :                 avio_printf(out, "/>\n");
     399           0 :                 i += 1 + repeat;
     400           0 :                 cur_time += (1 + repeat) * seg->duration;
     401             :             }
     402           0 :             avio_printf(out, "\t\t\t\t\t</SegmentTimeline>\n");
     403             :         }
     404           0 :         avio_printf(out, "\t\t\t\t</SegmentTemplate>\n");
     405           0 :     } else if (c->single_file) {
     406           0 :         avio_printf(out, "\t\t\t\t<BaseURL>%s</BaseURL>\n", os->initfile);
     407           0 :         avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%"PRId64"\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);
     408           0 :         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);
     409           0 :         for (i = start_index; i < os->nb_segments; i++) {
     410           0 :             Segment *seg = os->segments[i];
     411           0 :             avio_printf(out, "\t\t\t\t\t<SegmentURL mediaRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->range_length - 1);
     412           0 :             if (seg->index_length)
     413           0 :                 avio_printf(out, "indexRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->index_length - 1);
     414           0 :             avio_printf(out, "/>\n");
     415             :         }
     416           0 :         avio_printf(out, "\t\t\t\t</SegmentList>\n");
     417             :     } else {
     418           0 :         avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%"PRId64"\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);
     419           0 :         avio_printf(out, "\t\t\t\t\t<Initialization sourceURL=\"%s\" />\n", os->initfile);
     420           0 :         for (i = start_index; i < os->nb_segments; i++) {
     421           0 :             Segment *seg = os->segments[i];
     422           0 :             avio_printf(out, "\t\t\t\t\t<SegmentURL media=\"%s\" />\n", seg->file);
     423             :         }
     424           0 :         avio_printf(out, "\t\t\t\t</SegmentList>\n");
     425             :     }
     426           0 :     if (c->hls_playlist && start_index < os->nb_segments)
     427             :     {
     428           0 :         int timescale = os->ctx->streams[0]->time_base.den;
     429             :         char temp_filename_hls[1024];
     430             :         char filename_hls[1024];
     431           0 :         AVDictionary *http_opts = NULL;
     432           0 :         int target_duration = 0;
     433           0 :         int ret = 0;
     434           0 :         const char *proto = avio_find_protocol_name(c->dirname);
     435           0 :         int use_rename = proto && !strcmp(proto, "file");
     436             : 
     437           0 :         get_hls_playlist_name(filename_hls, sizeof(filename_hls),
     438           0 :                               c->dirname, representation_id);
     439             : 
     440           0 :         snprintf(temp_filename_hls, sizeof(temp_filename_hls), use_rename ? "%s.tmp" : "%s", filename_hls);
     441             : 
     442           0 :         set_http_options(&http_opts, c);
     443           0 :         dashenc_io_open(s, &c->m3u8_out, temp_filename_hls, &http_opts);
     444           0 :         av_dict_free(&http_opts);
     445           0 :         for (i = start_index; i < os->nb_segments; i++) {
     446           0 :             Segment *seg = os->segments[i];
     447           0 :             double duration = (double) seg->duration / timescale;
     448           0 :             if (target_duration <= duration)
     449           0 :                 target_duration = lrint(duration);
     450             :         }
     451             : 
     452           0 :         ff_hls_write_playlist_header(c->m3u8_out, 6, -1, target_duration,
     453             :                                      start_number, PLAYLIST_TYPE_NONE);
     454             : 
     455           0 :         ff_hls_write_init_file(c->m3u8_out, os->initfile, c->single_file,
     456           0 :                                os->init_range_length, os->init_start_pos);
     457             : 
     458           0 :         for (i = start_index; i < os->nb_segments; i++) {
     459           0 :             Segment *seg = os->segments[i];
     460           0 :             ret = ff_hls_write_file_entry(c->m3u8_out, 0, c->single_file,
     461           0 :                                     (double) seg->duration / timescale, 0,
     462           0 :                                     seg->range_length, seg->start_pos, NULL,
     463           0 :                                     c->single_file ? os->initfile : seg->file,
     464             :                                     NULL);
     465           0 :             if (ret < 0) {
     466           0 :                 av_log(os->ctx, AV_LOG_WARNING, "ff_hls_write_file_entry get error\n");
     467             :             }
     468             :         }
     469             : 
     470           0 :         if (final)
     471           0 :             ff_hls_write_end_list(c->m3u8_out);
     472             : 
     473           0 :         dashenc_io_close(s, &c->m3u8_out, temp_filename_hls);
     474             : 
     475           0 :         if (use_rename)
     476           0 :             if (avpriv_io_move(temp_filename_hls, filename_hls) < 0) {
     477           0 :                 av_log(os->ctx, AV_LOG_WARNING, "renaming file %s to %s failed\n\n", temp_filename_hls, filename_hls);
     478             :             }
     479             :     }
     480             : 
     481           0 : }
     482             : 
     483           0 : static char *xmlescape(const char *str) {
     484           0 :     int outlen = strlen(str)*3/2 + 6;
     485           0 :     char *out = av_realloc(NULL, outlen + 1);
     486           0 :     int pos = 0;
     487           0 :     if (!out)
     488           0 :         return NULL;
     489           0 :     for (; *str; str++) {
     490           0 :         if (pos + 6 > outlen) {
     491             :             char *tmp;
     492           0 :             outlen = 2 * outlen + 6;
     493           0 :             tmp = av_realloc(out, outlen + 1);
     494           0 :             if (!tmp) {
     495           0 :                 av_free(out);
     496           0 :                 return NULL;
     497             :             }
     498           0 :             out = tmp;
     499             :         }
     500           0 :         if (*str == '&') {
     501           0 :             memcpy(&out[pos], "&amp;", 5);
     502           0 :             pos += 5;
     503           0 :         } else if (*str == '<') {
     504           0 :             memcpy(&out[pos], "&lt;", 4);
     505           0 :             pos += 4;
     506           0 :         } else if (*str == '>') {
     507           0 :             memcpy(&out[pos], "&gt;", 4);
     508           0 :             pos += 4;
     509           0 :         } else if (*str == '\'') {
     510           0 :             memcpy(&out[pos], "&apos;", 6);
     511           0 :             pos += 6;
     512           0 :         } else if (*str == '\"') {
     513           0 :             memcpy(&out[pos], "&quot;", 6);
     514           0 :             pos += 6;
     515             :         } else {
     516           0 :             out[pos++] = *str;
     517             :         }
     518             :     }
     519           0 :     out[pos] = '\0';
     520           0 :     return out;
     521             : }
     522             : 
     523           0 : static void write_time(AVIOContext *out, int64_t time)
     524             : {
     525           0 :     int seconds = time / AV_TIME_BASE;
     526           0 :     int fractions = time % AV_TIME_BASE;
     527           0 :     int minutes = seconds / 60;
     528           0 :     int hours = minutes / 60;
     529           0 :     seconds %= 60;
     530           0 :     minutes %= 60;
     531           0 :     avio_printf(out, "PT");
     532           0 :     if (hours)
     533           0 :         avio_printf(out, "%dH", hours);
     534           0 :     if (hours || minutes)
     535           0 :         avio_printf(out, "%dM", minutes);
     536           0 :     avio_printf(out, "%d.%dS", seconds, fractions / (AV_TIME_BASE / 10));
     537           0 : }
     538             : 
     539           0 : static void format_date_now(char *buf, int size)
     540             : {
     541           0 :     time_t t = time(NULL);
     542             :     struct tm *ptm, tmbuf;
     543           0 :     ptm = gmtime_r(&t, &tmbuf);
     544           0 :     if (ptm) {
     545           0 :         if (!strftime(buf, size, "%Y-%m-%dT%H:%M:%SZ", ptm))
     546           0 :             buf[0] = '\0';
     547             :     }
     548           0 : }
     549             : 
     550           0 : static int write_adaptation_set(AVFormatContext *s, AVIOContext *out, int as_index,
     551             :                                 int final)
     552             : {
     553           0 :     DASHContext *c = s->priv_data;
     554           0 :     AdaptationSet *as = &c->as[as_index];
     555             :     AVDictionaryEntry *lang, *role;
     556             :     int i;
     557             : 
     558           0 :     avio_printf(out, "\t\t<AdaptationSet id=\"%s\" contentType=\"%s\" segmentAlignment=\"true\" bitstreamSwitching=\"true\"",
     559           0 :                 as->id, as->media_type == AVMEDIA_TYPE_VIDEO ? "video" : "audio");
     560           0 :     if (as->media_type == AVMEDIA_TYPE_VIDEO && as->max_frame_rate.num && !as->ambiguous_frame_rate && av_cmp_q(as->min_frame_rate, as->max_frame_rate) < 0)
     561           0 :         avio_printf(out, " maxFrameRate=\"%d/%d\"", as->max_frame_rate.num, as->max_frame_rate.den);
     562           0 :     lang = av_dict_get(as->metadata, "language", NULL, 0);
     563           0 :     if (lang)
     564           0 :         avio_printf(out, " lang=\"%s\"", lang->value);
     565           0 :     avio_printf(out, ">\n");
     566             : 
     567           0 :     role = av_dict_get(as->metadata, "role", NULL, 0);
     568           0 :     if (role)
     569           0 :         avio_printf(out, "\t\t\t<Role schemeIdUri=\"urn:mpeg:dash:role:2011\" value=\"%s\"/>\n", role->value);
     570             : 
     571           0 :     for (i = 0; i < s->nb_streams; i++) {
     572           0 :         OutputStream *os = &c->streams[i];
     573           0 :         char bandwidth_str[64] = {'\0'};
     574             : 
     575           0 :         if (os->as_idx - 1 != as_index)
     576           0 :             continue;
     577             : 
     578           0 :         if (os->bit_rate > 0)
     579           0 :             snprintf(bandwidth_str, sizeof(bandwidth_str), " bandwidth=\"%d\"",
     580           0 :                      os->bit_rate + os->muxer_overhead);
     581             : 
     582           0 :         if (as->media_type == AVMEDIA_TYPE_VIDEO) {
     583           0 :             AVStream *st = s->streams[i];
     584           0 :             avio_printf(out, "\t\t\t<Representation id=\"%d\" mimeType=\"video/%s\" codecs=\"%s\"%s width=\"%d\" height=\"%d\"",
     585           0 :                 i, os->format_name, os->codec_str, bandwidth_str, s->streams[i]->codecpar->width, s->streams[i]->codecpar->height);
     586           0 :             if (st->avg_frame_rate.num)
     587           0 :                 avio_printf(out, " frameRate=\"%d/%d\"", st->avg_frame_rate.num, st->avg_frame_rate.den);
     588           0 :             avio_printf(out, ">\n");
     589             :         } else {
     590           0 :             avio_printf(out, "\t\t\t<Representation id=\"%d\" mimeType=\"audio/%s\" codecs=\"%s\"%s audioSamplingRate=\"%d\">\n",
     591           0 :                 i, os->format_name, os->codec_str, bandwidth_str, s->streams[i]->codecpar->sample_rate);
     592           0 :             avio_printf(out, "\t\t\t\t<AudioChannelConfiguration schemeIdUri=\"urn:mpeg:dash:23003:3:audio_channel_configuration:2011\" value=\"%d\" />\n",
     593           0 :                 s->streams[i]->codecpar->channels);
     594             :         }
     595           0 :         output_segment_list(os, out, s, i, final);
     596           0 :         avio_printf(out, "\t\t\t</Representation>\n");
     597             :     }
     598           0 :     avio_printf(out, "\t\t</AdaptationSet>\n");
     599             : 
     600           0 :     return 0;
     601             : }
     602             : 
     603           0 : static int add_adaptation_set(AVFormatContext *s, AdaptationSet **as, enum AVMediaType type)
     604             : {
     605           0 :     DASHContext *c = s->priv_data;
     606             : 
     607           0 :     void *mem = av_realloc(c->as, sizeof(*c->as) * (c->nb_as + 1));
     608           0 :     if (!mem)
     609           0 :         return AVERROR(ENOMEM);
     610           0 :     c->as = mem;
     611           0 :     ++c->nb_as;
     612             : 
     613           0 :     *as = &c->as[c->nb_as - 1];
     614           0 :     memset(*as, 0, sizeof(**as));
     615           0 :     (*as)->media_type = type;
     616             : 
     617           0 :     return 0;
     618             : }
     619             : 
     620           0 : static int adaptation_set_add_stream(AVFormatContext *s, int as_idx, int i)
     621             : {
     622           0 :     DASHContext *c = s->priv_data;
     623           0 :     AdaptationSet *as = &c->as[as_idx - 1];
     624           0 :     OutputStream *os = &c->streams[i];
     625             : 
     626           0 :     if (as->media_type != s->streams[i]->codecpar->codec_type) {
     627           0 :         av_log(s, AV_LOG_ERROR, "Codec type of stream %d doesn't match AdaptationSet's media type\n", i);
     628           0 :         return AVERROR(EINVAL);
     629           0 :     } else if (os->as_idx) {
     630           0 :         av_log(s, AV_LOG_ERROR, "Stream %d is already assigned to an AdaptationSet\n", i);
     631           0 :         return AVERROR(EINVAL);
     632             :     }
     633           0 :     os->as_idx = as_idx;
     634             : 
     635           0 :     return 0;
     636             : }
     637             : 
     638           0 : static int parse_adaptation_sets(AVFormatContext *s)
     639             : {
     640           0 :     DASHContext *c = s->priv_data;
     641           0 :     const char *p = c->adaptation_sets;
     642             :     enum { new_set, parse_id, parsing_streams } state;
     643             :     AdaptationSet *as;
     644             :     int i, n, ret;
     645             : 
     646             :     // default: one AdaptationSet for each stream
     647           0 :     if (!p) {
     648           0 :         for (i = 0; i < s->nb_streams; i++) {
     649           0 :             if ((ret = add_adaptation_set(s, &as, s->streams[i]->codecpar->codec_type)) < 0)
     650           0 :                 return ret;
     651           0 :             snprintf(as->id, sizeof(as->id), "%d", i);
     652             : 
     653           0 :             c->streams[i].as_idx = c->nb_as;
     654             :         }
     655           0 :         goto end;
     656             :     }
     657             : 
     658             :     // syntax id=0,streams=0,1,2 id=1,streams=3,4 and so on
     659           0 :     state = new_set;
     660           0 :     while (*p) {
     661           0 :         if (*p == ' ') {
     662           0 :             p++;
     663           0 :             continue;
     664           0 :         } else if (state == new_set && av_strstart(p, "id=", &p)) {
     665             : 
     666           0 :             if ((ret = add_adaptation_set(s, &as, AVMEDIA_TYPE_UNKNOWN)) < 0)
     667           0 :                 return ret;
     668             : 
     669           0 :             n = strcspn(p, ",");
     670           0 :             snprintf(as->id, sizeof(as->id), "%.*s", n, p);
     671             : 
     672           0 :             p += n;
     673           0 :             if (*p)
     674           0 :                 p++;
     675           0 :             state = parse_id;
     676           0 :         } else if (state == parse_id && av_strstart(p, "streams=", &p)) {
     677           0 :             state = parsing_streams;
     678           0 :         } else if (state == parsing_streams) {
     679           0 :             AdaptationSet *as = &c->as[c->nb_as - 1];
     680             :             char idx_str[8], *end_str;
     681             : 
     682           0 :             n = strcspn(p, " ,");
     683           0 :             snprintf(idx_str, sizeof(idx_str), "%.*s", n, p);
     684           0 :             p += n;
     685             : 
     686             :             // if value is "a" or "v", map all streams of that type
     687           0 :             if (as->media_type == AVMEDIA_TYPE_UNKNOWN && (idx_str[0] == 'v' || idx_str[0] == 'a')) {
     688           0 :                 enum AVMediaType type = (idx_str[0] == 'v') ? AVMEDIA_TYPE_VIDEO : AVMEDIA_TYPE_AUDIO;
     689           0 :                 av_log(s, AV_LOG_DEBUG, "Map all streams of type %s\n", idx_str);
     690             : 
     691           0 :                 for (i = 0; i < s->nb_streams; i++) {
     692           0 :                     if (s->streams[i]->codecpar->codec_type != type)
     693           0 :                         continue;
     694             : 
     695           0 :                     as->media_type = s->streams[i]->codecpar->codec_type;
     696             : 
     697           0 :                     if ((ret = adaptation_set_add_stream(s, c->nb_as, i)) < 0)
     698           0 :                         return ret;
     699             :                 }
     700             :             } else { // select single stream
     701           0 :                 i = strtol(idx_str, &end_str, 10);
     702           0 :                 if (idx_str == end_str || i < 0 || i >= s->nb_streams) {
     703           0 :                     av_log(s, AV_LOG_ERROR, "Selected stream \"%s\" not found!\n", idx_str);
     704           0 :                     return AVERROR(EINVAL);
     705             :                 }
     706           0 :                 av_log(s, AV_LOG_DEBUG, "Map stream %d\n", i);
     707             : 
     708           0 :                 if (as->media_type == AVMEDIA_TYPE_UNKNOWN) {
     709           0 :                     as->media_type = s->streams[i]->codecpar->codec_type;
     710             :                 }
     711             : 
     712           0 :                 if ((ret = adaptation_set_add_stream(s, c->nb_as, i)) < 0)
     713           0 :                     return ret;
     714             :             }
     715             : 
     716           0 :             if (*p == ' ')
     717           0 :                 state = new_set;
     718           0 :             if (*p)
     719           0 :                 p++;
     720             :         } else {
     721           0 :             return AVERROR(EINVAL);
     722             :         }
     723             :     }
     724             : 
     725           0 : end:
     726             :     // check for unassigned streams
     727           0 :     for (i = 0; i < s->nb_streams; i++) {
     728           0 :         OutputStream *os = &c->streams[i];
     729           0 :         if (!os->as_idx) {
     730           0 :             av_log(s, AV_LOG_ERROR, "Stream %d is not mapped to an AdaptationSet\n", i);
     731           0 :             return AVERROR(EINVAL);
     732             :         }
     733             :     }
     734           0 :     return 0;
     735             : }
     736             : 
     737           0 : static int write_manifest(AVFormatContext *s, int final)
     738             : {
     739           0 :     DASHContext *c = s->priv_data;
     740             :     AVIOContext *out;
     741             :     char temp_filename[1024];
     742             :     int ret, i;
     743           0 :     const char *proto = avio_find_protocol_name(s->url);
     744           0 :     int use_rename = proto && !strcmp(proto, "file");
     745             :     static unsigned int warned_non_file = 0;
     746           0 :     AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
     747           0 :     AVDictionary *opts = NULL;
     748             : 
     749           0 :     if (!use_rename && !warned_non_file++)
     750           0 :         av_log(s, AV_LOG_ERROR, "Cannot use rename on non file protocol, this may lead to races and temporary partial files\n");
     751             : 
     752           0 :     snprintf(temp_filename, sizeof(temp_filename), use_rename ? "%s.tmp" : "%s", s->url);
     753           0 :     set_http_options(&opts, c);
     754           0 :     ret = dashenc_io_open(s, &c->mpd_out, temp_filename, &opts);
     755           0 :     if (ret < 0) {
     756           0 :         av_log(s, AV_LOG_ERROR, "Unable to open %s for writing\n", temp_filename);
     757           0 :         return ret;
     758             :     }
     759           0 :     out = c->mpd_out;
     760           0 :     av_dict_free(&opts);
     761           0 :     avio_printf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
     762           0 :     avio_printf(out, "<MPD xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
     763             :                 "\txmlns=\"urn:mpeg:dash:schema:mpd:2011\"\n"
     764             :                 "\txmlns:xlink=\"http://www.w3.org/1999/xlink\"\n"
     765             :                 "\txsi:schemaLocation=\"urn:mpeg:DASH:schema:MPD:2011 http://standards.iso.org/ittf/PubliclyAvailableStandards/MPEG-DASH_schema_files/DASH-MPD.xsd\"\n"
     766             :                 "\tprofiles=\"urn:mpeg:dash:profile:isoff-live:2011\"\n"
     767             :                 "\ttype=\"%s\"\n", final ? "static" : "dynamic");
     768           0 :     if (final) {
     769           0 :         avio_printf(out, "\tmediaPresentationDuration=\"");
     770           0 :         write_time(out, c->total_duration);
     771           0 :         avio_printf(out, "\"\n");
     772             :     } else {
     773           0 :         int64_t update_period = c->last_duration / AV_TIME_BASE;
     774             :         char now_str[100];
     775           0 :         if (c->use_template && !c->use_timeline)
     776           0 :             update_period = 500;
     777           0 :         avio_printf(out, "\tminimumUpdatePeriod=\"PT%"PRId64"S\"\n", update_period);
     778           0 :         avio_printf(out, "\tsuggestedPresentationDelay=\"PT%"PRId64"S\"\n", c->last_duration / AV_TIME_BASE);
     779           0 :         if (c->availability_start_time[0])
     780           0 :             avio_printf(out, "\tavailabilityStartTime=\"%s\"\n", c->availability_start_time);
     781           0 :         format_date_now(now_str, sizeof(now_str));
     782           0 :         if (now_str[0])
     783           0 :             avio_printf(out, "\tpublishTime=\"%s\"\n", now_str);
     784           0 :         if (c->window_size && c->use_template) {
     785           0 :             avio_printf(out, "\ttimeShiftBufferDepth=\"");
     786           0 :             write_time(out, c->last_duration * c->window_size);
     787           0 :             avio_printf(out, "\"\n");
     788             :         }
     789             :     }
     790           0 :     avio_printf(out, "\tminBufferTime=\"");
     791           0 :     write_time(out, c->last_duration * 2);
     792           0 :     avio_printf(out, "\">\n");
     793           0 :     avio_printf(out, "\t<ProgramInformation>\n");
     794           0 :     if (title) {
     795           0 :         char *escaped = xmlescape(title->value);
     796           0 :         avio_printf(out, "\t\t<Title>%s</Title>\n", escaped);
     797           0 :         av_free(escaped);
     798             :     }
     799           0 :     avio_printf(out, "\t</ProgramInformation>\n");
     800             : 
     801           0 :     if (c->window_size && s->nb_streams > 0 && c->streams[0].nb_segments > 0 && !c->use_template) {
     802           0 :         OutputStream *os = &c->streams[0];
     803           0 :         int start_index = FFMAX(os->nb_segments - c->window_size, 0);
     804           0 :         int64_t start_time = av_rescale_q(os->segments[start_index]->time, s->streams[0]->time_base, AV_TIME_BASE_Q);
     805           0 :         avio_printf(out, "\t<Period id=\"0\" start=\"");
     806           0 :         write_time(out, start_time);
     807           0 :         avio_printf(out, "\">\n");
     808             :     } else {
     809           0 :         avio_printf(out, "\t<Period id=\"0\" start=\"PT0.0S\">\n");
     810             :     }
     811             : 
     812           0 :     for (i = 0; i < c->nb_as; i++) {
     813           0 :         if ((ret = write_adaptation_set(s, out, i, final)) < 0)
     814           0 :             return ret;
     815             :     }
     816           0 :     avio_printf(out, "\t</Period>\n");
     817             : 
     818           0 :     if (c->utc_timing_url)
     819           0 :         avio_printf(out, "\t<UTCTiming schemeIdUri=\"urn:mpeg:dash:utc:http-xsdate:2014\" value=\"%s\"/>\n", c->utc_timing_url);
     820             : 
     821           0 :     avio_printf(out, "</MPD>\n");
     822           0 :     avio_flush(out);
     823           0 :     dashenc_io_close(s, &c->mpd_out, temp_filename);
     824             : 
     825           0 :     if (use_rename) {
     826           0 :         if ((ret = avpriv_io_move(temp_filename, s->url)) < 0)
     827           0 :             return ret;
     828             :     }
     829             : 
     830           0 :     if (c->hls_playlist && !c->master_playlist_created) {
     831             :         char filename_hls[1024];
     832           0 :         const char *audio_group = "A1";
     833           0 :         int is_default = 1;
     834           0 :         int max_audio_bitrate = 0;
     835             : 
     836           0 :         if (*c->dirname)
     837           0 :             snprintf(filename_hls, sizeof(filename_hls), "%s/master.m3u8", c->dirname);
     838             :         else
     839           0 :             snprintf(filename_hls, sizeof(filename_hls), "master.m3u8");
     840             : 
     841           0 :         snprintf(temp_filename, sizeof(temp_filename), use_rename ? "%s.tmp" : "%s", filename_hls);
     842             : 
     843           0 :         set_http_options(&opts, c);
     844           0 :         ret = avio_open2(&out, temp_filename, AVIO_FLAG_WRITE, NULL, &opts);
     845           0 :         if (ret < 0) {
     846           0 :             av_log(s, AV_LOG_ERROR, "Unable to open %s for writing\n", temp_filename);
     847           0 :             return ret;
     848             :         }
     849           0 :         av_dict_free(&opts);
     850             : 
     851           0 :         ff_hls_write_playlist_version(out, 7);
     852             : 
     853           0 :         for (i = 0; i < s->nb_streams; i++) {
     854             :             char playlist_file[64];
     855           0 :             AVStream *st = s->streams[i];
     856           0 :             OutputStream *os = &c->streams[i];
     857           0 :             if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO)
     858           0 :                 continue;
     859           0 :             get_hls_playlist_name(playlist_file, sizeof(playlist_file), NULL, i);
     860           0 :             ff_hls_write_audio_rendition(out, (char *)audio_group,
     861             :                                          playlist_file, i, is_default);
     862           0 :             max_audio_bitrate = FFMAX(st->codecpar->bit_rate +
     863             :                                       os->muxer_overhead, max_audio_bitrate);
     864           0 :             is_default = 0;
     865             :         }
     866             : 
     867           0 :         for (i = 0; i < s->nb_streams; i++) {
     868             :             char playlist_file[64];
     869           0 :             AVStream *st = s->streams[i];
     870           0 :             OutputStream *os = &c->streams[i];
     871           0 :             char *agroup = NULL;
     872           0 :             int stream_bitrate = st->codecpar->bit_rate + os->muxer_overhead;
     873           0 :             if ((st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) && max_audio_bitrate) {
     874           0 :                 agroup = (char *)audio_group;
     875           0 :                 stream_bitrate += max_audio_bitrate;
     876             :             }
     877           0 :             get_hls_playlist_name(playlist_file, sizeof(playlist_file), NULL, i);
     878           0 :             ff_hls_write_stream_info(st, out, stream_bitrate, playlist_file, agroup, NULL, NULL);
     879             :         }
     880           0 :         avio_close(out);
     881           0 :         if (use_rename)
     882           0 :             if ((ret = avpriv_io_move(temp_filename, filename_hls)) < 0)
     883           0 :                 return ret;
     884           0 :         c->master_playlist_created = 1;
     885             :     }
     886             : 
     887           0 :     return 0;
     888             : }
     889             : 
     890           0 : static int dict_copy_entry(AVDictionary **dst, const AVDictionary *src, const char *key)
     891             : {
     892           0 :     AVDictionaryEntry *entry = av_dict_get(src, key, NULL, 0);
     893           0 :     if (entry)
     894           0 :         av_dict_set(dst, key, entry->value, AV_DICT_DONT_OVERWRITE);
     895           0 :     return 0;
     896             : }
     897             : 
     898           0 : static int dash_init(AVFormatContext *s)
     899             : {
     900           0 :     DASHContext *c = s->priv_data;
     901           0 :     int ret = 0, i;
     902             :     char *ptr;
     903             :     char basename[1024];
     904             : 
     905           0 :     if (c->single_file_name)
     906           0 :         c->single_file = 1;
     907           0 :     if (c->single_file)
     908           0 :         c->use_template = 0;
     909             : 
     910             : #if FF_API_DASH_MIN_SEG_DURATION
     911           0 :     if (c->min_seg_duration != 5000000) {
     912           0 :         av_log(s, AV_LOG_WARNING, "The min_seg_duration option is deprecated and will be removed. Please use the -seg_duration\n");
     913           0 :         c->seg_duration = c->min_seg_duration;
     914             :     }
     915             : #endif
     916             : 
     917           0 :     av_strlcpy(c->dirname, s->url, sizeof(c->dirname));
     918           0 :     ptr = strrchr(c->dirname, '/');
     919           0 :     if (ptr) {
     920           0 :         av_strlcpy(basename, &ptr[1], sizeof(basename));
     921           0 :         ptr[1] = '\0';
     922             :     } else {
     923           0 :         c->dirname[0] = '\0';
     924           0 :         av_strlcpy(basename, s->url, sizeof(basename));
     925             :     }
     926             : 
     927           0 :     ptr = strrchr(basename, '.');
     928           0 :     if (ptr)
     929           0 :         *ptr = '\0';
     930             : 
     931           0 :     c->streams = av_mallocz(sizeof(*c->streams) * s->nb_streams);
     932           0 :     if (!c->streams)
     933           0 :         return AVERROR(ENOMEM);
     934             : 
     935           0 :     if ((ret = parse_adaptation_sets(s)) < 0)
     936           0 :         return ret;
     937             : 
     938           0 :     for (i = 0; i < s->nb_streams; i++) {
     939           0 :         OutputStream *os = &c->streams[i];
     940           0 :         AdaptationSet *as = &c->as[os->as_idx - 1];
     941             :         AVFormatContext *ctx;
     942             :         AVStream *st;
     943           0 :         AVDictionary *opts = NULL;
     944             :         char filename[1024];
     945             : 
     946           0 :         os->bit_rate = s->streams[i]->codecpar->bit_rate;
     947           0 :         if (!os->bit_rate) {
     948           0 :             int level = s->strict_std_compliance >= FF_COMPLIANCE_STRICT ?
     949           0 :                         AV_LOG_ERROR : AV_LOG_WARNING;
     950           0 :             av_log(s, level, "No bit rate set for stream %d\n", i);
     951           0 :             if (s->strict_std_compliance >= FF_COMPLIANCE_STRICT)
     952           0 :                 return AVERROR(EINVAL);
     953             :         }
     954             : 
     955             :         // copy AdaptationSet language and role from stream metadata
     956           0 :         dict_copy_entry(&as->metadata, s->streams[i]->metadata, "language");
     957           0 :         dict_copy_entry(&as->metadata, s->streams[i]->metadata, "role");
     958             : 
     959           0 :         ctx = avformat_alloc_context();
     960           0 :         if (!ctx)
     961           0 :             return AVERROR(ENOMEM);
     962             : 
     963             :         // choose muxer based on codec: webm for VP8 and opus, mp4 otherwise
     964             :         // note: os->format_name is also used as part of the mimetype of the
     965             :         //       representation, e.g. video/<format_name>
     966           0 :         if (s->streams[i]->codecpar->codec_id == AV_CODEC_ID_VP8 ||
     967           0 :             s->streams[i]->codecpar->codec_id == AV_CODEC_ID_OPUS ||
     968           0 :             s->streams[i]->codecpar->codec_id == AV_CODEC_ID_VORBIS) {
     969           0 :             snprintf(os->format_name, sizeof(os->format_name), "webm");
     970             : 
     971           0 :             if (s->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
     972           0 :                 av_log(s, AV_LOG_ERROR,
     973             :                        "WebM support in dashenc is experimental and has not "
     974             :                        "been validated. For testing purposes, make sure "
     975             :                        "to add -strict experimental and override "
     976             :                        "-init_seg_name and -media_seg_name to end with "
     977             :                        "the extension 'webm'.\n");
     978           0 :                 return AVERROR(EINVAL);
     979             :             }
     980             :         } else {
     981           0 :             snprintf(os->format_name, sizeof(os->format_name), "mp4");
     982             :         }
     983           0 :         ctx->oformat = av_guess_format(os->format_name, NULL, NULL);
     984           0 :         if (!ctx->oformat)
     985           0 :             return AVERROR_MUXER_NOT_FOUND;
     986           0 :         os->ctx = ctx;
     987           0 :         ctx->interrupt_callback    = s->interrupt_callback;
     988           0 :         ctx->opaque                = s->opaque;
     989           0 :         ctx->io_close              = s->io_close;
     990           0 :         ctx->io_open               = s->io_open;
     991           0 :         ctx->strict_std_compliance = s->strict_std_compliance;
     992             : 
     993           0 :         if (!(st = avformat_new_stream(ctx, NULL)))
     994           0 :             return AVERROR(ENOMEM);
     995           0 :         avcodec_parameters_copy(st->codecpar, s->streams[i]->codecpar);
     996           0 :         st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
     997           0 :         st->time_base = s->streams[i]->time_base;
     998           0 :         st->avg_frame_rate = s->streams[i]->avg_frame_rate;
     999           0 :         ctx->avoid_negative_ts = s->avoid_negative_ts;
    1000           0 :         ctx->flags = s->flags;
    1001             : 
    1002           0 :         if ((ret = avio_open_dyn_buf(&ctx->pb)) < 0)
    1003           0 :             return ret;
    1004             : 
    1005           0 :         if (c->single_file) {
    1006           0 :             if (c->single_file_name)
    1007           0 :                 ff_dash_fill_tmpl_params(os->initfile, sizeof(os->initfile), c->single_file_name, i, 0, os->bit_rate, 0);
    1008             :             else
    1009           0 :                 snprintf(os->initfile, sizeof(os->initfile), "%s-stream%d.m4s", basename, i);
    1010             :         } else {
    1011           0 :             ff_dash_fill_tmpl_params(os->initfile, sizeof(os->initfile), c->init_seg_name, i, 0, os->bit_rate, 0);
    1012             :         }
    1013           0 :         snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
    1014           0 :         set_http_options(&opts, c);
    1015           0 :         ret = s->io_open(s, &os->out, filename, AVIO_FLAG_WRITE, &opts);
    1016           0 :         if (ret < 0)
    1017           0 :             return ret;
    1018           0 :         av_dict_free(&opts);
    1019           0 :         os->init_start_pos = 0;
    1020             : 
    1021           0 :         if (c->format_options_str) {
    1022           0 :             ret = av_dict_parse_string(&opts, c->format_options_str, "=", ":", 0);
    1023           0 :             if (ret < 0)
    1024           0 :                 return ret;
    1025             :         }
    1026           0 :         if (!strcmp(os->format_name, "mp4")) {
    1027           0 :             if (c->streaming)
    1028           0 :                 av_dict_set(&opts, "movflags", "frag_every_frame+dash+delay_moov", 0);
    1029             :             else
    1030           0 :                 av_dict_set(&opts, "movflags", "frag_custom+dash+delay_moov", 0);
    1031             :         } else {
    1032           0 :             av_dict_set_int(&opts, "cluster_time_limit", c->seg_duration / 1000, 0);
    1033           0 :             av_dict_set_int(&opts, "cluster_size_limit", 5 * 1024 * 1024, 0); // set a large cluster size limit
    1034           0 :             av_dict_set_int(&opts, "dash", 1, 0);
    1035           0 :             av_dict_set_int(&opts, "dash_track_number", i + 1, 0);
    1036           0 :             av_dict_set_int(&opts, "live", 1, 0);
    1037             :         }
    1038           0 :         if ((ret = avformat_init_output(ctx, &opts)) < 0)
    1039           0 :             return ret;
    1040           0 :         os->ctx_inited = 1;
    1041           0 :         avio_flush(ctx->pb);
    1042           0 :         av_dict_free(&opts);
    1043             : 
    1044           0 :         av_log(s, AV_LOG_VERBOSE, "Representation %d init segment will be written to: %s\n", i, filename);
    1045             : 
    1046           0 :         s->streams[i]->time_base = st->time_base;
    1047             :         // If the muxer wants to shift timestamps, request to have them shifted
    1048             :         // already before being handed to this muxer, so we don't have mismatches
    1049             :         // between the MPD and the actual segments.
    1050           0 :         s->avoid_negative_ts = ctx->avoid_negative_ts;
    1051           0 :         if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
    1052           0 :             AVRational avg_frame_rate = s->streams[i]->avg_frame_rate;
    1053           0 :             if (avg_frame_rate.num > 0) {
    1054           0 :                 if (av_cmp_q(avg_frame_rate, as->min_frame_rate) < 0)
    1055           0 :                     as->min_frame_rate = avg_frame_rate;
    1056           0 :                 if (av_cmp_q(as->max_frame_rate, avg_frame_rate) < 0)
    1057           0 :                     as->max_frame_rate = avg_frame_rate;
    1058             :             } else {
    1059           0 :                 as->ambiguous_frame_rate = 1;
    1060             :             }
    1061           0 :             c->has_video = 1;
    1062             :         }
    1063             : 
    1064           0 :         set_codec_str(s, st->codecpar, &st->avg_frame_rate, os->codec_str,
    1065             :                       sizeof(os->codec_str));
    1066           0 :         os->first_pts = AV_NOPTS_VALUE;
    1067           0 :         os->max_pts = AV_NOPTS_VALUE;
    1068           0 :         os->last_dts = AV_NOPTS_VALUE;
    1069           0 :         os->segment_index = 1;
    1070             :     }
    1071             : 
    1072           0 :     if (!c->has_video && c->seg_duration <= 0) {
    1073           0 :         av_log(s, AV_LOG_WARNING, "no video stream and no seg duration set\n");
    1074           0 :         return AVERROR(EINVAL);
    1075             :     }
    1076           0 :     return 0;
    1077             : }
    1078             : 
    1079           0 : static int dash_write_header(AVFormatContext *s)
    1080             : {
    1081           0 :     DASHContext *c = s->priv_data;
    1082             :     int i, ret;
    1083           0 :     for (i = 0; i < s->nb_streams; i++) {
    1084           0 :         OutputStream *os = &c->streams[i];
    1085           0 :         if ((ret = avformat_write_header(os->ctx, NULL)) < 0)
    1086           0 :             return ret;
    1087             : 
    1088             :         // Flush init segment
    1089             :         // Only for WebM segment, since for mp4 delay_moov is set and
    1090             :         // the init segment is thus flushed after the first packets.
    1091           0 :         if (strcmp(os->format_name, "mp4") &&
    1092             :             (ret = flush_init_segment(s, os)) < 0)
    1093           0 :             return ret;
    1094             :     }
    1095           0 :     return ret;
    1096             : }
    1097             : 
    1098           0 : static int add_segment(OutputStream *os, const char *file,
    1099             :                        int64_t time, int duration,
    1100             :                        int64_t start_pos, int64_t range_length,
    1101             :                        int64_t index_length, int next_exp_index)
    1102             : {
    1103             :     int err;
    1104             :     Segment *seg;
    1105           0 :     if (os->nb_segments >= os->segments_size) {
    1106           0 :         os->segments_size = (os->segments_size + 1) * 2;
    1107           0 :         if ((err = av_reallocp(&os->segments, sizeof(*os->segments) *
    1108           0 :                                os->segments_size)) < 0) {
    1109           0 :             os->segments_size = 0;
    1110           0 :             os->nb_segments = 0;
    1111           0 :             return err;
    1112             :         }
    1113             :     }
    1114           0 :     seg = av_mallocz(sizeof(*seg));
    1115           0 :     if (!seg)
    1116           0 :         return AVERROR(ENOMEM);
    1117           0 :     av_strlcpy(seg->file, file, sizeof(seg->file));
    1118           0 :     seg->time = time;
    1119           0 :     seg->duration = duration;
    1120           0 :     if (seg->time < 0) { // If pts<0, it is expected to be cut away with an edit list
    1121           0 :         seg->duration += seg->time;
    1122           0 :         seg->time = 0;
    1123             :     }
    1124           0 :     seg->start_pos = start_pos;
    1125           0 :     seg->range_length = range_length;
    1126           0 :     seg->index_length = index_length;
    1127           0 :     os->segments[os->nb_segments++] = seg;
    1128           0 :     os->segment_index++;
    1129             :     //correcting the segment index if it has fallen behind the expected value
    1130           0 :     if (os->segment_index < next_exp_index) {
    1131           0 :         av_log(NULL, AV_LOG_WARNING, "Correcting the segment index after file %s: current=%d corrected=%d\n",
    1132             :                file, os->segment_index, next_exp_index);
    1133           0 :         os->segment_index = next_exp_index;
    1134             :     }
    1135           0 :     return 0;
    1136             : }
    1137             : 
    1138           0 : static void write_styp(AVIOContext *pb)
    1139             : {
    1140           0 :     avio_wb32(pb, 24);
    1141           0 :     ffio_wfourcc(pb, "styp");
    1142           0 :     ffio_wfourcc(pb, "msdh");
    1143           0 :     avio_wb32(pb, 0); /* minor */
    1144           0 :     ffio_wfourcc(pb, "msdh");
    1145           0 :     ffio_wfourcc(pb, "msix");
    1146           0 : }
    1147             : 
    1148           0 : static void find_index_range(AVFormatContext *s, const char *full_path,
    1149             :                              int64_t pos, int *index_length)
    1150             : {
    1151             :     uint8_t buf[8];
    1152             :     AVIOContext *pb;
    1153             :     int ret;
    1154             : 
    1155           0 :     ret = s->io_open(s, &pb, full_path, AVIO_FLAG_READ, NULL);
    1156           0 :     if (ret < 0)
    1157           0 :         return;
    1158           0 :     if (avio_seek(pb, pos, SEEK_SET) != pos) {
    1159           0 :         ff_format_io_close(s, &pb);
    1160           0 :         return;
    1161             :     }
    1162           0 :     ret = avio_read(pb, buf, 8);
    1163           0 :     ff_format_io_close(s, &pb);
    1164           0 :     if (ret < 8)
    1165           0 :         return;
    1166           0 :     if (AV_RL32(&buf[4]) != MKTAG('s', 'i', 'd', 'x'))
    1167           0 :         return;
    1168           0 :     *index_length = AV_RB32(&buf[0]);
    1169             : }
    1170             : 
    1171           0 : static int update_stream_extradata(AVFormatContext *s, OutputStream *os,
    1172             :                                    AVCodecParameters *par,
    1173             :                                    AVRational *frame_rate)
    1174             : {
    1175             :     uint8_t *extradata;
    1176             : 
    1177           0 :     if (os->ctx->streams[0]->codecpar->extradata_size || !par->extradata_size)
    1178           0 :         return 0;
    1179             : 
    1180           0 :     extradata = av_malloc(par->extradata_size);
    1181             : 
    1182           0 :     if (!extradata)
    1183           0 :         return AVERROR(ENOMEM);
    1184             : 
    1185           0 :     memcpy(extradata, par->extradata, par->extradata_size);
    1186             : 
    1187           0 :     os->ctx->streams[0]->codecpar->extradata = extradata;
    1188           0 :     os->ctx->streams[0]->codecpar->extradata_size = par->extradata_size;
    1189             : 
    1190           0 :     set_codec_str(s, par, frame_rate, os->codec_str, sizeof(os->codec_str));
    1191             : 
    1192           0 :     return 0;
    1193             : }
    1194             : 
    1195           0 : static void dashenc_delete_file(AVFormatContext *s, char *filename) {
    1196           0 :     DASHContext *c = s->priv_data;
    1197           0 :     int http_base_proto = ff_is_http_proto(filename);
    1198             : 
    1199           0 :     if (http_base_proto) {
    1200           0 :         AVIOContext *out = NULL;
    1201           0 :         AVDictionary *http_opts = NULL;
    1202             : 
    1203           0 :         set_http_options(&http_opts, c);
    1204           0 :         av_dict_set(&http_opts, "method", "DELETE", 0);
    1205             : 
    1206           0 :         if (dashenc_io_open(s, &out, filename, &http_opts) < 0) {
    1207           0 :             av_log(s, AV_LOG_ERROR, "failed to delete %s\n", filename);
    1208             :         }
    1209             : 
    1210           0 :         av_dict_free(&http_opts);
    1211           0 :         dashenc_io_close(s, &out, filename);
    1212           0 :     } else if (unlink(filename) < 0) {
    1213           0 :         av_log(s, AV_LOG_ERROR, "failed to delete %s: %s\n", filename, strerror(errno));
    1214             :     }
    1215           0 : }
    1216             : 
    1217           0 : static int dash_flush(AVFormatContext *s, int final, int stream)
    1218             : {
    1219           0 :     DASHContext *c = s->priv_data;
    1220           0 :     int i, ret = 0;
    1221             : 
    1222           0 :     const char *proto = avio_find_protocol_name(s->url);
    1223           0 :     int use_rename = proto && !strcmp(proto, "file");
    1224             : 
    1225           0 :     int cur_flush_segment_index = 0, next_exp_index = -1;
    1226           0 :     if (stream >= 0) {
    1227           0 :         cur_flush_segment_index = c->streams[stream].segment_index;
    1228             : 
    1229             :         //finding the next segment's expected index, based on the current pts value
    1230           0 :         if (c->use_template && !c->use_timeline && c->index_correction &&
    1231           0 :             c->streams[stream].last_pts != AV_NOPTS_VALUE &&
    1232           0 :             c->streams[stream].first_pts != AV_NOPTS_VALUE) {
    1233           0 :             int64_t pts_diff = av_rescale_q(c->streams[stream].last_pts -
    1234           0 :                                             c->streams[stream].first_pts,
    1235           0 :                                             s->streams[stream]->time_base,
    1236           0 :                                             AV_TIME_BASE_Q);
    1237           0 :             next_exp_index = (pts_diff / c->seg_duration) + 1;
    1238             :         }
    1239             :     }
    1240             : 
    1241           0 :     for (i = 0; i < s->nb_streams; i++) {
    1242           0 :         OutputStream *os = &c->streams[i];
    1243           0 :         AVStream *st = s->streams[i];
    1244           0 :         int range_length, index_length = 0;
    1245             : 
    1246           0 :         if (!os->packets_written)
    1247           0 :             continue;
    1248             : 
    1249             :         // Flush the single stream that got a keyframe right now.
    1250             :         // Flush all audio streams as well, in sync with video keyframes,
    1251             :         // but not the other video streams.
    1252           0 :         if (stream >= 0 && i != stream) {
    1253           0 :             if (s->streams[i]->codecpar->codec_type != AVMEDIA_TYPE_AUDIO)
    1254           0 :                 continue;
    1255             :             // Make sure we don't flush audio streams multiple times, when
    1256             :             // all video streams are flushed one at a time.
    1257           0 :             if (c->has_video && os->segment_index > cur_flush_segment_index)
    1258           0 :                 continue;
    1259             :         }
    1260             : 
    1261           0 :         if (!c->single_file) {
    1262           0 :             if (!strcmp(os->format_name, "mp4") && !os->written_len)
    1263           0 :                 write_styp(os->ctx->pb);
    1264             :         } else {
    1265           0 :             snprintf(os->full_path, sizeof(os->full_path), "%s%s", c->dirname, os->initfile);
    1266             :         }
    1267             : 
    1268           0 :         ret = flush_dynbuf(os, &range_length);
    1269           0 :         if (ret < 0)
    1270           0 :             break;
    1271           0 :         os->packets_written = 0;
    1272             : 
    1273           0 :         if (c->single_file) {
    1274           0 :             find_index_range(s, os->full_path, os->pos, &index_length);
    1275             :         } else {
    1276           0 :             dashenc_io_close(s, &os->out, os->temp_path);
    1277             : 
    1278           0 :             if (use_rename) {
    1279           0 :                 ret = avpriv_io_move(os->temp_path, os->full_path);
    1280           0 :                 if (ret < 0)
    1281           0 :                     break;
    1282             :             }
    1283             :         }
    1284             : 
    1285           0 :         if (!os->muxer_overhead)
    1286           0 :             os->muxer_overhead = ((int64_t) (range_length - os->total_pkt_size) *
    1287           0 :                                   8 * AV_TIME_BASE) /
    1288           0 :                                  av_rescale_q(os->max_pts - os->start_pts,
    1289           0 :                                               st->time_base, AV_TIME_BASE_Q);
    1290           0 :         os->total_pkt_size = 0;
    1291             : 
    1292           0 :         if (!os->bit_rate) {
    1293             :             // calculate average bitrate of first segment
    1294           0 :             int64_t bitrate = (int64_t) range_length * 8 * AV_TIME_BASE / av_rescale_q(os->max_pts - os->start_pts,
    1295             :                                                                                        st->time_base,
    1296           0 :                                                                                        AV_TIME_BASE_Q);
    1297           0 :             if (bitrate >= 0)
    1298           0 :                 os->bit_rate = bitrate;
    1299             :         }
    1300           0 :         add_segment(os, os->filename, os->start_pts, os->max_pts - os->start_pts, os->pos, range_length, index_length, next_exp_index);
    1301           0 :         av_log(s, AV_LOG_VERBOSE, "Representation %d media segment %d written to: %s\n", i, os->segment_index, os->full_path);
    1302             : 
    1303           0 :         os->pos += range_length;
    1304             :     }
    1305             : 
    1306           0 :     if (c->window_size || (final && c->remove_at_exit)) {
    1307           0 :         for (i = 0; i < s->nb_streams; i++) {
    1308           0 :             OutputStream *os = &c->streams[i];
    1309             :             int j;
    1310           0 :             int remove = os->nb_segments - c->window_size - c->extra_window_size;
    1311           0 :             if (final && c->remove_at_exit)
    1312           0 :                 remove = os->nb_segments;
    1313           0 :             if (remove > 0) {
    1314           0 :                 for (j = 0; j < remove; j++) {
    1315             :                     char filename[1024];
    1316           0 :                     snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->segments[j]->file);
    1317           0 :                     dashenc_delete_file(s, filename);
    1318           0 :                     av_free(os->segments[j]);
    1319             :                 }
    1320           0 :                 os->nb_segments -= remove;
    1321           0 :                 memmove(os->segments, os->segments + remove, os->nb_segments * sizeof(*os->segments));
    1322             :             }
    1323             :         }
    1324             :     }
    1325             : 
    1326           0 :     if (ret >= 0)
    1327           0 :         ret = write_manifest(s, final);
    1328           0 :     return ret;
    1329             : }
    1330             : 
    1331           0 : static int dash_write_packet(AVFormatContext *s, AVPacket *pkt)
    1332             : {
    1333           0 :     DASHContext *c = s->priv_data;
    1334           0 :     AVStream *st = s->streams[pkt->stream_index];
    1335           0 :     OutputStream *os = &c->streams[pkt->stream_index];
    1336             :     int64_t seg_end_duration, elapsed_duration;
    1337             :     int ret;
    1338             : 
    1339           0 :     ret = update_stream_extradata(s, os, st->codecpar, &st->avg_frame_rate);
    1340           0 :     if (ret < 0)
    1341           0 :         return ret;
    1342             : 
    1343             :     // Fill in a heuristic guess of the packet duration, if none is available.
    1344             :     // The mp4 muxer will do something similar (for the last packet in a fragment)
    1345             :     // if nothing is set (setting it for the other packets doesn't hurt).
    1346             :     // By setting a nonzero duration here, we can be sure that the mp4 muxer won't
    1347             :     // invoke its heuristic (this doesn't have to be identical to that algorithm),
    1348             :     // so that we know the exact timestamps of fragments.
    1349           0 :     if (!pkt->duration && os->last_dts != AV_NOPTS_VALUE)
    1350           0 :         pkt->duration = pkt->dts - os->last_dts;
    1351           0 :     os->last_dts = pkt->dts;
    1352             : 
    1353             :     // If forcing the stream to start at 0, the mp4 muxer will set the start
    1354             :     // timestamps to 0. Do the same here, to avoid mismatches in duration/timestamps.
    1355           0 :     if (os->first_pts == AV_NOPTS_VALUE &&
    1356           0 :         s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
    1357           0 :         pkt->pts -= pkt->dts;
    1358           0 :         pkt->dts  = 0;
    1359             :     }
    1360             : 
    1361           0 :     if (os->first_pts == AV_NOPTS_VALUE)
    1362           0 :         os->first_pts = pkt->pts;
    1363           0 :     os->last_pts = pkt->pts;
    1364             : 
    1365           0 :     if (!c->availability_start_time[0])
    1366           0 :         format_date_now(c->availability_start_time,
    1367             :                         sizeof(c->availability_start_time));
    1368             : 
    1369           0 :     if (!os->availability_time_offset && pkt->duration) {
    1370           0 :         int64_t frame_duration = av_rescale_q(pkt->duration, st->time_base,
    1371           0 :                                               AV_TIME_BASE_Q);
    1372           0 :          os->availability_time_offset = ((double) c->seg_duration -
    1373           0 :                                          frame_duration) / AV_TIME_BASE;
    1374             :     }
    1375             : 
    1376           0 :     if (c->use_template && !c->use_timeline) {
    1377           0 :         elapsed_duration = pkt->pts - os->first_pts;
    1378           0 :         seg_end_duration = (int64_t) os->segment_index * c->seg_duration;
    1379             :     } else {
    1380           0 :         elapsed_duration = pkt->pts - os->start_pts;
    1381           0 :         seg_end_duration = c->seg_duration;
    1382             :     }
    1383             : 
    1384           0 :     if ((!c->has_video || st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) &&
    1385           0 :         pkt->flags & AV_PKT_FLAG_KEY && os->packets_written &&
    1386           0 :         av_compare_ts(elapsed_duration, st->time_base,
    1387           0 :                       seg_end_duration, AV_TIME_BASE_Q) >= 0) {
    1388           0 :         int64_t prev_duration = c->last_duration;
    1389             : 
    1390           0 :         c->last_duration = av_rescale_q(pkt->pts - os->start_pts,
    1391             :                                         st->time_base,
    1392           0 :                                         AV_TIME_BASE_Q);
    1393           0 :         c->total_duration = av_rescale_q(pkt->pts - os->first_pts,
    1394             :                                          st->time_base,
    1395           0 :                                          AV_TIME_BASE_Q);
    1396             : 
    1397           0 :         if ((!c->use_timeline || !c->use_template) && prev_duration) {
    1398           0 :             if (c->last_duration < prev_duration*9/10 ||
    1399           0 :                 c->last_duration > prev_duration*11/10) {
    1400           0 :                 av_log(s, AV_LOG_WARNING,
    1401             :                        "Segment durations differ too much, enable use_timeline "
    1402             :                        "and use_template, or keep a stricter keyframe interval\n");
    1403             :             }
    1404             :         }
    1405             : 
    1406           0 :         if ((ret = dash_flush(s, 0, pkt->stream_index)) < 0)
    1407           0 :             return ret;
    1408             :     }
    1409             : 
    1410           0 :     if (!os->packets_written) {
    1411             :         // If we wrote a previous segment, adjust the start time of the segment
    1412             :         // to the end of the previous one (which is the same as the mp4 muxer
    1413             :         // does). This avoids gaps in the timeline.
    1414           0 :         if (os->max_pts != AV_NOPTS_VALUE)
    1415           0 :             os->start_pts = os->max_pts;
    1416             :         else
    1417           0 :             os->start_pts = pkt->pts;
    1418             :     }
    1419           0 :     if (os->max_pts == AV_NOPTS_VALUE)
    1420           0 :         os->max_pts = pkt->pts + pkt->duration;
    1421             :     else
    1422           0 :         os->max_pts = FFMAX(os->max_pts, pkt->pts + pkt->duration);
    1423           0 :     os->packets_written++;
    1424           0 :     os->total_pkt_size += pkt->size;
    1425           0 :     if ((ret = ff_write_chained(os->ctx, 0, pkt, s, 0)) < 0)
    1426           0 :         return ret;
    1427             : 
    1428           0 :     if (!os->init_range_length)
    1429           0 :         flush_init_segment(s, os);
    1430             : 
    1431             :     //open the output context when the first frame of a segment is ready
    1432           0 :     if (!c->single_file && os->packets_written == 1) {
    1433           0 :         AVDictionary *opts = NULL;
    1434           0 :         const char *proto = avio_find_protocol_name(s->url);
    1435           0 :         int use_rename = proto && !strcmp(proto, "file");
    1436           0 :         os->filename[0] = os->full_path[0] = os->temp_path[0] = '\0';
    1437           0 :         ff_dash_fill_tmpl_params(os->filename, sizeof(os->filename),
    1438             :                                  c->media_seg_name, pkt->stream_index,
    1439             :                                  os->segment_index, os->bit_rate, os->start_pts);
    1440           0 :         snprintf(os->full_path, sizeof(os->full_path), "%s%s", c->dirname,
    1441           0 :                  os->filename);
    1442           0 :         snprintf(os->temp_path, sizeof(os->temp_path),
    1443           0 :                  use_rename ? "%s.tmp" : "%s", os->full_path);
    1444           0 :         set_http_options(&opts, c);
    1445           0 :         ret = dashenc_io_open(s, &os->out, os->temp_path, &opts);
    1446           0 :         if (ret < 0)
    1447           0 :             return ret;
    1448           0 :         av_dict_free(&opts);
    1449             :     }
    1450             : 
    1451             :     //write out the data immediately in streaming mode
    1452           0 :     if (c->streaming && !strcmp(os->format_name, "mp4")) {
    1453           0 :         int len = 0;
    1454           0 :         uint8_t *buf = NULL;
    1455           0 :         if (!os->written_len)
    1456           0 :             write_styp(os->ctx->pb);
    1457           0 :         avio_flush(os->ctx->pb);
    1458           0 :         len = avio_get_dyn_buf (os->ctx->pb, &buf);
    1459           0 :         avio_write(os->out, buf + os->written_len, len - os->written_len);
    1460           0 :         os->written_len = len;
    1461           0 :         avio_flush(os->out);
    1462             :     }
    1463             : 
    1464           0 :     return ret;
    1465             : }
    1466             : 
    1467           0 : static int dash_write_trailer(AVFormatContext *s)
    1468             : {
    1469           0 :     DASHContext *c = s->priv_data;
    1470             : 
    1471           0 :     if (s->nb_streams > 0) {
    1472           0 :         OutputStream *os = &c->streams[0];
    1473             :         // If no segments have been written so far, try to do a crude
    1474             :         // guess of the segment duration
    1475           0 :         if (!c->last_duration)
    1476           0 :             c->last_duration = av_rescale_q(os->max_pts - os->start_pts,
    1477           0 :                                             s->streams[0]->time_base,
    1478           0 :                                             AV_TIME_BASE_Q);
    1479           0 :         c->total_duration = av_rescale_q(os->max_pts - os->first_pts,
    1480           0 :                                          s->streams[0]->time_base,
    1481           0 :                                          AV_TIME_BASE_Q);
    1482             :     }
    1483           0 :     dash_flush(s, 1, -1);
    1484             : 
    1485           0 :     if (c->remove_at_exit) {
    1486             :         char filename[1024];
    1487             :         int i;
    1488           0 :         for (i = 0; i < s->nb_streams; i++) {
    1489           0 :             OutputStream *os = &c->streams[i];
    1490           0 :             snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
    1491           0 :             dashenc_delete_file(s, filename);
    1492             :         }
    1493           0 :         dashenc_delete_file(s, s->url);
    1494             :     }
    1495             : 
    1496           0 :     return 0;
    1497             : }
    1498             : 
    1499           0 : static int dash_check_bitstream(struct AVFormatContext *s, const AVPacket *avpkt)
    1500             : {
    1501           0 :     DASHContext *c = s->priv_data;
    1502           0 :     OutputStream *os = &c->streams[avpkt->stream_index];
    1503           0 :     AVFormatContext *oc = os->ctx;
    1504           0 :     if (oc->oformat->check_bitstream) {
    1505             :         int ret;
    1506           0 :         AVPacket pkt = *avpkt;
    1507           0 :         pkt.stream_index = 0;
    1508           0 :         ret = oc->oformat->check_bitstream(oc, &pkt);
    1509           0 :         if (ret == 1) {
    1510           0 :             AVStream *st = s->streams[avpkt->stream_index];
    1511           0 :             AVStream *ost = oc->streams[0];
    1512           0 :             st->internal->bsfcs = ost->internal->bsfcs;
    1513           0 :             st->internal->nb_bsfcs = ost->internal->nb_bsfcs;
    1514           0 :             ost->internal->bsfcs = NULL;
    1515           0 :             ost->internal->nb_bsfcs = 0;
    1516             :         }
    1517           0 :         return ret;
    1518             :     }
    1519           0 :     return 1;
    1520             : }
    1521             : 
    1522             : #define OFFSET(x) offsetof(DASHContext, x)
    1523             : #define E AV_OPT_FLAG_ENCODING_PARAM
    1524             : static const AVOption options[] = {
    1525             :     { "adaptation_sets", "Adaptation sets. Syntax: id=0,streams=0,1,2 id=1,streams=3,4 and so on", OFFSET(adaptation_sets), AV_OPT_TYPE_STRING, { 0 }, 0, 0, AV_OPT_FLAG_ENCODING_PARAM },
    1526             :     { "window_size", "number of segments kept in the manifest", OFFSET(window_size), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, E },
    1527             :     { "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 },
    1528             : #if FF_API_DASH_MIN_SEG_DURATION
    1529             :     { "min_seg_duration", "minimum segment duration (in microseconds) (will be deprecated)", OFFSET(min_seg_duration), AV_OPT_TYPE_INT, { .i64 = 5000000 }, 0, INT_MAX, E },
    1530             : #endif
    1531             :     { "seg_duration", "segment duration (in seconds, fractional value can be set)", OFFSET(seg_duration), AV_OPT_TYPE_DURATION, { .i64 = 5000000 }, 0, INT_MAX, E },
    1532             :     { "remove_at_exit", "remove all segments when finished", OFFSET(remove_at_exit), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
    1533             :     { "use_template", "Use SegmentTemplate instead of SegmentList", OFFSET(use_template), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, E },
    1534             :     { "use_timeline", "Use SegmentTimeline in SegmentTemplate", OFFSET(use_timeline), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, E },
    1535             :     { "single_file", "Store all segments in one file, accessed using byte ranges", OFFSET(single_file), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
    1536             :     { "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 },
    1537             :     { "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 },
    1538             :     { "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 },
    1539             :     { "utc_timing_url", "URL of the page that will return the UTC timestamp in ISO format", OFFSET(utc_timing_url), AV_OPT_TYPE_STRING, { 0 }, 0, 0, E },
    1540             :     { "method", "set the HTTP method", OFFSET(method), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
    1541             :     { "http_user_agent", "override User-Agent field in HTTP header", OFFSET(user_agent), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
    1542             :     { "http_persistent", "Use persistent HTTP connections", OFFSET(http_persistent), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, E },
    1543             :     { "hls_playlist", "Generate HLS playlist files(master.m3u8, media_%d.m3u8)", OFFSET(hls_playlist), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
    1544             :     { "streaming", "Enable/Disable streaming mode of output. Each frame will be moof fragment", OFFSET(streaming), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
    1545             :     { "timeout", "set timeout for socket I/O operations", OFFSET(timeout), AV_OPT_TYPE_DURATION, { .i64 = -1 }, -1, INT_MAX, .flags = E },
    1546             :     { "index_correction", "Enable/Disable segment index correction logic", OFFSET(index_correction), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
    1547             :     { "format_options","set list of options for the container format (mp4/webm) used for dash", OFFSET(format_options_str), AV_OPT_TYPE_STRING, {.str = NULL},  0, 0, E},
    1548             :     { NULL },
    1549             : };
    1550             : 
    1551             : static const AVClass dash_class = {
    1552             :     .class_name = "dash muxer",
    1553             :     .item_name  = av_default_item_name,
    1554             :     .option     = options,
    1555             :     .version    = LIBAVUTIL_VERSION_INT,
    1556             : };
    1557             : 
    1558             : AVOutputFormat ff_dash_muxer = {
    1559             :     .name           = "dash",
    1560             :     .long_name      = NULL_IF_CONFIG_SMALL("DASH Muxer"),
    1561             :     .extensions     = "mpd",
    1562             :     .priv_data_size = sizeof(DASHContext),
    1563             :     .audio_codec    = AV_CODEC_ID_AAC,
    1564             :     .video_codec    = AV_CODEC_ID_H264,
    1565             :     .flags          = AVFMT_GLOBALHEADER | AVFMT_NOFILE | AVFMT_TS_NEGATIVE,
    1566             :     .init           = dash_init,
    1567             :     .write_header   = dash_write_header,
    1568             :     .write_packet   = dash_write_packet,
    1569             :     .write_trailer  = dash_write_trailer,
    1570             :     .deinit         = dash_free,
    1571             :     .check_bitstream = dash_check_bitstream,
    1572             :     .priv_class     = &dash_class,
    1573             : };

Generated by: LCOV version 1.13