LCOV - code coverage report
Current view: top level - src/libavformat - dashenc.c (source / functions) Hit Total Coverage
Test: coverage.info Lines: 0 639 0.0 %
Date: 2017-07-21 15:41:20 Functions: 0 21 0.0 %

          Line data    Source code
       1             : /*
       2             :  * MPEG-DASH ISO BMFF segmenter
       3             :  * Copyright (c) 2014 Martin Storsjo
       4             :  *
       5             :  * This file is part of FFmpeg.
       6             :  *
       7             :  * FFmpeg is free software; you can redistribute it and/or
       8             :  * modify it under the terms of the GNU Lesser General Public
       9             :  * License as published by the Free Software Foundation; either
      10             :  * version 2.1 of the License, or (at your option) any later version.
      11             :  *
      12             :  * FFmpeg is distributed in the hope that it will be useful,
      13             :  * but WITHOUT ANY WARRANTY; without even the implied warranty of
      14             :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
      15             :  * Lesser General Public License for more details.
      16             :  *
      17             :  * You should have received a copy of the GNU Lesser General Public
      18             :  * License along with FFmpeg; if not, write to the Free Software
      19             :  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
      20             :  */
      21             : 
      22             : #include "config.h"
      23             : #if HAVE_UNISTD_H
      24             : #include <unistd.h>
      25             : #endif
      26             : 
      27             : #include "libavutil/avassert.h"
      28             : #include "libavutil/avstring.h"
      29             : #include "libavutil/intreadwrite.h"
      30             : #include "libavutil/mathematics.h"
      31             : #include "libavutil/opt.h"
      32             : #include "libavutil/rational.h"
      33             : #include "libavutil/time_internal.h"
      34             : 
      35             : #include "avc.h"
      36             : #include "avformat.h"
      37             : #include "avio_internal.h"
      38             : #include "internal.h"
      39             : #include "isom.h"
      40             : #include "os_support.h"
      41             : #include "url.h"
      42             : 
      43             : // See ISO/IEC 23009-1:2014 5.3.9.4.4
      44             : typedef enum {
      45             :     DASH_TMPL_ID_UNDEFINED = -1,
      46             :     DASH_TMPL_ID_ESCAPE,
      47             :     DASH_TMPL_ID_REP_ID,
      48             :     DASH_TMPL_ID_NUMBER,
      49             :     DASH_TMPL_ID_BANDWIDTH,
      50             :     DASH_TMPL_ID_TIME,
      51             : } DASHTmplId;
      52             : 
      53             : typedef struct Segment {
      54             :     char file[1024];
      55             :     int64_t start_pos;
      56             :     int range_length, index_length;
      57             :     int64_t time;
      58             :     int duration;
      59             :     int n;
      60             : } Segment;
      61             : 
      62             : typedef struct OutputStream {
      63             :     AVFormatContext *ctx;
      64             :     int ctx_inited;
      65             :     uint8_t iobuf[32768];
      66             :     AVIOContext *out;
      67             :     int packets_written;
      68             :     char initfile[1024];
      69             :     int64_t init_start_pos;
      70             :     int init_range_length;
      71             :     int nb_segments, segments_size, segment_index;
      72             :     Segment **segments;
      73             :     int64_t first_pts, start_pts, max_pts;
      74             :     int64_t last_dts;
      75             :     int bit_rate;
      76             :     char bandwidth_str[64];
      77             : 
      78             :     char codec_str[100];
      79             : } OutputStream;
      80             : 
      81             : typedef struct DASHContext {
      82             :     const AVClass *class;  /* Class for private options. */
      83             :     int window_size;
      84             :     int extra_window_size;
      85             :     int min_seg_duration;
      86             :     int remove_at_exit;
      87             :     int use_template;
      88             :     int use_timeline;
      89             :     int single_file;
      90             :     OutputStream *streams;
      91             :     int has_video, has_audio;
      92             :     int64_t last_duration;
      93             :     int64_t total_duration;
      94             :     char availability_start_time[100];
      95             :     char dirname[1024];
      96             :     const char *single_file_name;
      97             :     const char *init_seg_name;
      98             :     const char *media_seg_name;
      99             :     AVRational min_frame_rate, max_frame_rate;
     100             :     int ambiguous_frame_rate;
     101             :     const char *utc_timing_url;
     102             : } DASHContext;
     103             : 
     104           0 : static int dash_write(void *opaque, uint8_t *buf, int buf_size)
     105             : {
     106           0 :     OutputStream *os = opaque;
     107           0 :     if (os->out)
     108           0 :         avio_write(os->out, buf, buf_size);
     109           0 :     return buf_size;
     110             : }
     111             : 
     112             : // RFC 6381
     113           0 : static void set_codec_str(AVFormatContext *s, AVCodecParameters *par,
     114             :                           char *str, int size)
     115             : {
     116           0 :     const AVCodecTag *tags[2] = { NULL, NULL };
     117             :     uint32_t tag;
     118           0 :     if (par->codec_type == AVMEDIA_TYPE_VIDEO)
     119           0 :         tags[0] = ff_codec_movvideo_tags;
     120           0 :     else if (par->codec_type == AVMEDIA_TYPE_AUDIO)
     121           0 :         tags[0] = ff_codec_movaudio_tags;
     122             :     else
     123           0 :         return;
     124             : 
     125           0 :     tag = av_codec_get_tag(tags, par->codec_id);
     126           0 :     if (!tag)
     127           0 :         return;
     128           0 :     if (size < 5)
     129           0 :         return;
     130             : 
     131           0 :     AV_WL32(str, tag);
     132           0 :     str[4] = '\0';
     133           0 :     if (!strcmp(str, "mp4a") || !strcmp(str, "mp4v")) {
     134             :         uint32_t oti;
     135           0 :         tags[0] = ff_mp4_obj_type;
     136           0 :         oti = av_codec_get_tag(tags, par->codec_id);
     137           0 :         if (oti)
     138           0 :             av_strlcatf(str, size, ".%02"PRIx32, oti);
     139             :         else
     140           0 :             return;
     141             : 
     142           0 :         if (tag == MKTAG('m', 'p', '4', 'a')) {
     143           0 :             if (par->extradata_size >= 2) {
     144           0 :                 int aot = par->extradata[0] >> 3;
     145           0 :                 if (aot == 31)
     146           0 :                     aot = ((AV_RB16(par->extradata) >> 5) & 0x3f) + 32;
     147           0 :                 av_strlcatf(str, size, ".%d", aot);
     148             :             }
     149           0 :         } else if (tag == MKTAG('m', 'p', '4', 'v')) {
     150             :             // Unimplemented, should output ProfileLevelIndication as a decimal number
     151           0 :             av_log(s, AV_LOG_WARNING, "Incomplete RFC 6381 codec string for mp4v\n");
     152             :         }
     153           0 :     } else if (!strcmp(str, "avc1")) {
     154           0 :         uint8_t *tmpbuf = NULL;
     155           0 :         uint8_t *extradata = par->extradata;
     156           0 :         int extradata_size = par->extradata_size;
     157           0 :         if (!extradata_size)
     158           0 :             return;
     159           0 :         if (extradata[0] != 1) {
     160             :             AVIOContext *pb;
     161           0 :             if (avio_open_dyn_buf(&pb) < 0)
     162           0 :                 return;
     163           0 :             if (ff_isom_write_avcc(pb, extradata, extradata_size) < 0) {
     164           0 :                 ffio_free_dyn_buf(&pb);
     165           0 :                 return;
     166             :             }
     167           0 :             extradata_size = avio_close_dyn_buf(pb, &extradata);
     168           0 :             tmpbuf = extradata;
     169             :         }
     170             : 
     171           0 :         if (extradata_size >= 4)
     172           0 :             av_strlcatf(str, size, ".%02x%02x%02x",
     173           0 :                         extradata[1], extradata[2], extradata[3]);
     174           0 :         av_free(tmpbuf);
     175             :     }
     176             : }
     177             : 
     178           0 : static void dash_free(AVFormatContext *s)
     179             : {
     180           0 :     DASHContext *c = s->priv_data;
     181             :     int i, j;
     182           0 :     if (!c->streams)
     183           0 :         return;
     184           0 :     for (i = 0; i < s->nb_streams; i++) {
     185           0 :         OutputStream *os = &c->streams[i];
     186           0 :         if (os->ctx && os->ctx_inited)
     187           0 :             av_write_trailer(os->ctx);
     188           0 :         if (os->ctx && os->ctx->pb)
     189           0 :             av_free(os->ctx->pb);
     190           0 :         ff_format_io_close(s, &os->out);
     191           0 :         if (os->ctx)
     192           0 :             avformat_free_context(os->ctx);
     193           0 :         for (j = 0; j < os->nb_segments; j++)
     194           0 :             av_free(os->segments[j]);
     195           0 :         av_free(os->segments);
     196             :     }
     197           0 :     av_freep(&c->streams);
     198             : }
     199             : 
     200           0 : static void output_segment_list(OutputStream *os, AVIOContext *out, DASHContext *c)
     201             : {
     202           0 :     int i, start_index = 0, start_number = 1;
     203           0 :     if (c->window_size) {
     204           0 :         start_index  = FFMAX(os->nb_segments   - c->window_size, 0);
     205           0 :         start_number = FFMAX(os->segment_index - c->window_size, 1);
     206             :     }
     207             : 
     208           0 :     if (c->use_template) {
     209           0 :         int timescale = c->use_timeline ? os->ctx->streams[0]->time_base.den : AV_TIME_BASE;
     210           0 :         avio_printf(out, "\t\t\t\t<SegmentTemplate timescale=\"%d\" ", timescale);
     211           0 :         if (!c->use_timeline)
     212           0 :             avio_printf(out, "duration=\"%"PRId64"\" ", c->last_duration);
     213           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);
     214           0 :         if (c->use_timeline) {
     215           0 :             int64_t cur_time = 0;
     216           0 :             avio_printf(out, "\t\t\t\t\t<SegmentTimeline>\n");
     217           0 :             for (i = start_index; i < os->nb_segments; ) {
     218           0 :                 Segment *seg = os->segments[i];
     219           0 :                 int repeat = 0;
     220           0 :                 avio_printf(out, "\t\t\t\t\t\t<S ");
     221           0 :                 if (i == start_index || seg->time != cur_time) {
     222           0 :                     cur_time = seg->time;
     223           0 :                     avio_printf(out, "t=\"%"PRId64"\" ", seg->time);
     224             :                 }
     225           0 :                 avio_printf(out, "d=\"%d\" ", seg->duration);
     226           0 :                 while (i + repeat + 1 < os->nb_segments &&
     227           0 :                        os->segments[i + repeat + 1]->duration == seg->duration &&
     228           0 :                        os->segments[i + repeat + 1]->time == os->segments[i + repeat]->time + os->segments[i + repeat]->duration)
     229           0 :                     repeat++;
     230           0 :                 if (repeat > 0)
     231           0 :                     avio_printf(out, "r=\"%d\" ", repeat);
     232           0 :                 avio_printf(out, "/>\n");
     233           0 :                 i += 1 + repeat;
     234           0 :                 cur_time += (1 + repeat) * seg->duration;
     235             :             }
     236           0 :             avio_printf(out, "\t\t\t\t\t</SegmentTimeline>\n");
     237             :         }
     238           0 :         avio_printf(out, "\t\t\t\t</SegmentTemplate>\n");
     239           0 :     } else if (c->single_file) {
     240           0 :         avio_printf(out, "\t\t\t\t<BaseURL>%s</BaseURL>\n", os->initfile);
     241           0 :         avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%"PRId64"\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);
     242           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);
     243           0 :         for (i = start_index; i < os->nb_segments; i++) {
     244           0 :             Segment *seg = os->segments[i];
     245           0 :             avio_printf(out, "\t\t\t\t\t<SegmentURL mediaRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->range_length - 1);
     246           0 :             if (seg->index_length)
     247           0 :                 avio_printf(out, "indexRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->index_length - 1);
     248           0 :             avio_printf(out, "/>\n");
     249             :         }
     250           0 :         avio_printf(out, "\t\t\t\t</SegmentList>\n");
     251             :     } else {
     252           0 :         avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%"PRId64"\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);
     253           0 :         avio_printf(out, "\t\t\t\t\t<Initialization sourceURL=\"%s\" />\n", os->initfile);
     254           0 :         for (i = start_index; i < os->nb_segments; i++) {
     255           0 :             Segment *seg = os->segments[i];
     256           0 :             avio_printf(out, "\t\t\t\t\t<SegmentURL media=\"%s\" />\n", seg->file);
     257             :         }
     258           0 :         avio_printf(out, "\t\t\t\t</SegmentList>\n");
     259             :     }
     260           0 : }
     261             : 
     262           0 : static DASHTmplId dash_read_tmpl_id(const char *identifier, char *format_tag,
     263             :                                     size_t format_tag_size, const char **ptr) {
     264             :     const char *next_ptr;
     265           0 :     DASHTmplId id_type = DASH_TMPL_ID_UNDEFINED;
     266             : 
     267           0 :     if (av_strstart(identifier, "$$", &next_ptr)) {
     268           0 :         id_type = DASH_TMPL_ID_ESCAPE;
     269           0 :         *ptr = next_ptr;
     270           0 :     } else if (av_strstart(identifier, "$RepresentationID$", &next_ptr)) {
     271           0 :         id_type = DASH_TMPL_ID_REP_ID;
     272             :         // default to basic format, as $RepresentationID$ identifiers
     273             :         // are not allowed to have custom format-tags.
     274           0 :         av_strlcpy(format_tag, "%d", format_tag_size);
     275           0 :         *ptr = next_ptr;
     276             :     } else { // the following identifiers may have an explicit format_tag
     277           0 :         if (av_strstart(identifier, "$Number", &next_ptr))
     278           0 :             id_type = DASH_TMPL_ID_NUMBER;
     279           0 :         else if (av_strstart(identifier, "$Bandwidth", &next_ptr))
     280           0 :             id_type = DASH_TMPL_ID_BANDWIDTH;
     281           0 :         else if (av_strstart(identifier, "$Time", &next_ptr))
     282           0 :             id_type = DASH_TMPL_ID_TIME;
     283             :         else
     284           0 :             id_type = DASH_TMPL_ID_UNDEFINED;
     285             : 
     286             :         // next parse the dash format-tag and generate a c-string format tag
     287             :         // (next_ptr now points at the first '%' at the beginning of the format-tag)
     288           0 :         if (id_type != DASH_TMPL_ID_UNDEFINED) {
     289           0 :             const char *number_format = (id_type == DASH_TMPL_ID_TIME) ? PRId64 : "d";
     290           0 :             if (next_ptr[0] == '$') { // no dash format-tag
     291           0 :                 snprintf(format_tag, format_tag_size, "%%%s", number_format);
     292           0 :                 *ptr = &next_ptr[1];
     293             :             } else {
     294             :                 const char *width_ptr;
     295             :                 // only tolerate single-digit width-field (i.e. up to 9-digit width)
     296           0 :                 if (av_strstart(next_ptr, "%0", &width_ptr) &&
     297           0 :                     av_isdigit(width_ptr[0]) &&
     298           0 :                     av_strstart(&width_ptr[1], "d$", &next_ptr)) {
     299             :                     // yes, we're using a format tag to build format_tag.
     300           0 :                     snprintf(format_tag, format_tag_size, "%s%c%s", "%0", width_ptr[0], number_format);
     301           0 :                     *ptr = next_ptr;
     302             :                 } else {
     303           0 :                     av_log(NULL, AV_LOG_WARNING, "Failed to parse format-tag beginning with %s. Expected either a "
     304             :                                                  "closing '$' character or a format-string like '%%0[width]d', "
     305             :                                                  "where width must be a single digit\n", next_ptr);
     306           0 :                     id_type = DASH_TMPL_ID_UNDEFINED;
     307             :                 }
     308             :             }
     309             :         }
     310             :     }
     311           0 :     return id_type;
     312             : }
     313             : 
     314           0 : static void dash_fill_tmpl_params(char *dst, size_t buffer_size,
     315             :                                   const char *template, int rep_id,
     316             :                                   int number, int bit_rate,
     317             :                                   int64_t time) {
     318           0 :     int dst_pos = 0;
     319           0 :     const char *t_cur = template;
     320           0 :     while (dst_pos < buffer_size - 1 && *t_cur) {
     321             :         char format_tag[7]; // May be "%d", "%0Xd", or "%0Xlld" (for $Time$), where X is in [0-9]
     322           0 :         int n = 0;
     323             :         DASHTmplId id_type;
     324           0 :         const char *t_next = strchr(t_cur, '$'); // copy over everything up to the first '$' character
     325           0 :         if (t_next) {
     326           0 :             int num_copy_bytes = FFMIN(t_next - t_cur, buffer_size - dst_pos - 1);
     327           0 :             av_strlcpy(&dst[dst_pos], t_cur, num_copy_bytes + 1);
     328             :             // advance
     329           0 :             dst_pos += num_copy_bytes;
     330           0 :             t_cur = t_next;
     331             :         } else { // no more DASH identifiers to substitute - just copy the rest over and break
     332           0 :             av_strlcpy(&dst[dst_pos], t_cur, buffer_size - dst_pos);
     333           0 :             break;
     334             :         }
     335             : 
     336           0 :         if (dst_pos >= buffer_size - 1 || !*t_cur)
     337             :             break;
     338             : 
     339             :         // t_cur is now pointing to a '$' character
     340           0 :         id_type = dash_read_tmpl_id(t_cur, format_tag, sizeof(format_tag), &t_next);
     341           0 :         switch (id_type) {
     342           0 :         case DASH_TMPL_ID_ESCAPE:
     343           0 :             av_strlcpy(&dst[dst_pos], "$", 2);
     344           0 :             n = 1;
     345           0 :             break;
     346           0 :         case DASH_TMPL_ID_REP_ID:
     347           0 :             n = snprintf(&dst[dst_pos], buffer_size - dst_pos, format_tag, rep_id);
     348           0 :             break;
     349           0 :         case DASH_TMPL_ID_NUMBER:
     350           0 :             n = snprintf(&dst[dst_pos], buffer_size - dst_pos, format_tag, number);
     351           0 :             break;
     352           0 :         case DASH_TMPL_ID_BANDWIDTH:
     353           0 :             n = snprintf(&dst[dst_pos], buffer_size - dst_pos, format_tag, bit_rate);
     354           0 :             break;
     355           0 :         case DASH_TMPL_ID_TIME:
     356           0 :             n = snprintf(&dst[dst_pos], buffer_size - dst_pos, format_tag, time);
     357           0 :             break;
     358           0 :         case DASH_TMPL_ID_UNDEFINED:
     359             :             // copy over one byte and advance
     360           0 :             av_strlcpy(&dst[dst_pos], t_cur, 2);
     361           0 :             n = 1;
     362           0 :             t_next = &t_cur[1];
     363           0 :             break;
     364             :         }
     365             :         // t_next points just past the processed identifier
     366             :         // n is the number of bytes that were attempted to be written to dst
     367             :         // (may have failed to write all because buffer_size).
     368             : 
     369             :         // advance
     370           0 :         dst_pos += FFMIN(n, buffer_size - dst_pos - 1);
     371           0 :         t_cur = t_next;
     372             :     }
     373           0 : }
     374             : 
     375           0 : static char *xmlescape(const char *str) {
     376           0 :     int outlen = strlen(str)*3/2 + 6;
     377           0 :     char *out = av_realloc(NULL, outlen + 1);
     378           0 :     int pos = 0;
     379           0 :     if (!out)
     380           0 :         return NULL;
     381           0 :     for (; *str; str++) {
     382           0 :         if (pos + 6 > outlen) {
     383             :             char *tmp;
     384           0 :             outlen = 2 * outlen + 6;
     385           0 :             tmp = av_realloc(out, outlen + 1);
     386           0 :             if (!tmp) {
     387           0 :                 av_free(out);
     388           0 :                 return NULL;
     389             :             }
     390           0 :             out = tmp;
     391             :         }
     392           0 :         if (*str == '&') {
     393           0 :             memcpy(&out[pos], "&amp;", 5);
     394           0 :             pos += 5;
     395           0 :         } else if (*str == '<') {
     396           0 :             memcpy(&out[pos], "&lt;", 4);
     397           0 :             pos += 4;
     398           0 :         } else if (*str == '>') {
     399           0 :             memcpy(&out[pos], "&gt;", 4);
     400           0 :             pos += 4;
     401           0 :         } else if (*str == '\'') {
     402           0 :             memcpy(&out[pos], "&apos;", 6);
     403           0 :             pos += 6;
     404           0 :         } else if (*str == '\"') {
     405           0 :             memcpy(&out[pos], "&quot;", 6);
     406           0 :             pos += 6;
     407             :         } else {
     408           0 :             out[pos++] = *str;
     409             :         }
     410             :     }
     411           0 :     out[pos] = '\0';
     412           0 :     return out;
     413             : }
     414             : 
     415           0 : static void write_time(AVIOContext *out, int64_t time)
     416             : {
     417           0 :     int seconds = time / AV_TIME_BASE;
     418           0 :     int fractions = time % AV_TIME_BASE;
     419           0 :     int minutes = seconds / 60;
     420           0 :     int hours = minutes / 60;
     421           0 :     seconds %= 60;
     422           0 :     minutes %= 60;
     423           0 :     avio_printf(out, "PT");
     424           0 :     if (hours)
     425           0 :         avio_printf(out, "%dH", hours);
     426           0 :     if (hours || minutes)
     427           0 :         avio_printf(out, "%dM", minutes);
     428           0 :     avio_printf(out, "%d.%dS", seconds, fractions / (AV_TIME_BASE / 10));
     429           0 : }
     430             : 
     431           0 : static void format_date_now(char *buf, int size)
     432             : {
     433           0 :     time_t t = time(NULL);
     434             :     struct tm *ptm, tmbuf;
     435           0 :     ptm = gmtime_r(&t, &tmbuf);
     436           0 :     if (ptm) {
     437           0 :         if (!strftime(buf, size, "%Y-%m-%dT%H:%M:%SZ", ptm))
     438           0 :             buf[0] = '\0';
     439             :     }
     440           0 : }
     441             : 
     442           0 : static int write_manifest(AVFormatContext *s, int final)
     443             : {
     444           0 :     DASHContext *c = s->priv_data;
     445             :     AVIOContext *out;
     446             :     char temp_filename[1024];
     447           0 :     int ret, i, as_id = 0;
     448           0 :     const char *proto = avio_find_protocol_name(s->filename);
     449           0 :     int use_rename = proto && !strcmp(proto, "file");
     450             :     static unsigned int warned_non_file = 0;
     451           0 :     AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
     452             : 
     453           0 :     if (!use_rename && !warned_non_file++)
     454           0 :         av_log(s, AV_LOG_ERROR, "Cannot use rename on non file protocol, this may lead to races and temporary partial files\n");
     455             : 
     456           0 :     snprintf(temp_filename, sizeof(temp_filename), use_rename ? "%s.tmp" : "%s", s->filename);
     457           0 :     ret = s->io_open(s, &out, temp_filename, AVIO_FLAG_WRITE, NULL);
     458           0 :     if (ret < 0) {
     459           0 :         av_log(s, AV_LOG_ERROR, "Unable to open %s for writing\n", temp_filename);
     460           0 :         return ret;
     461             :     }
     462           0 :     avio_printf(out, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
     463           0 :     avio_printf(out, "<MPD xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
     464             :                 "\txmlns=\"urn:mpeg:dash:schema:mpd:2011\"\n"
     465             :                 "\txmlns:xlink=\"http://www.w3.org/1999/xlink\"\n"
     466             :                 "\txsi:schemaLocation=\"urn:mpeg:DASH:schema:MPD:2011 http://standards.iso.org/ittf/PubliclyAvailableStandards/MPEG-DASH_schema_files/DASH-MPD.xsd\"\n"
     467             :                 "\tprofiles=\"urn:mpeg:dash:profile:isoff-live:2011\"\n"
     468             :                 "\ttype=\"%s\"\n", final ? "static" : "dynamic");
     469           0 :     if (final) {
     470           0 :         avio_printf(out, "\tmediaPresentationDuration=\"");
     471           0 :         write_time(out, c->total_duration);
     472           0 :         avio_printf(out, "\"\n");
     473             :     } else {
     474           0 :         int64_t update_period = c->last_duration / AV_TIME_BASE;
     475             :         char now_str[100];
     476           0 :         if (c->use_template && !c->use_timeline)
     477           0 :             update_period = 500;
     478           0 :         avio_printf(out, "\tminimumUpdatePeriod=\"PT%"PRId64"S\"\n", update_period);
     479           0 :         avio_printf(out, "\tsuggestedPresentationDelay=\"PT%"PRId64"S\"\n", c->last_duration / AV_TIME_BASE);
     480           0 :         if (!c->availability_start_time[0] && s->nb_streams > 0 && c->streams[0].nb_segments > 0) {
     481           0 :             format_date_now(c->availability_start_time, sizeof(c->availability_start_time));
     482             :         }
     483           0 :         if (c->availability_start_time[0])
     484           0 :             avio_printf(out, "\tavailabilityStartTime=\"%s\"\n", c->availability_start_time);
     485           0 :         format_date_now(now_str, sizeof(now_str));
     486           0 :         if (now_str[0])
     487           0 :             avio_printf(out, "\tpublishTime=\"%s\"\n", now_str);
     488           0 :         if (c->window_size && c->use_template) {
     489           0 :             avio_printf(out, "\ttimeShiftBufferDepth=\"");
     490           0 :             write_time(out, c->last_duration * c->window_size);
     491           0 :             avio_printf(out, "\"\n");
     492             :         }
     493             :     }
     494           0 :     avio_printf(out, "\tminBufferTime=\"");
     495           0 :     write_time(out, c->last_duration * 2);
     496           0 :     avio_printf(out, "\">\n");
     497           0 :     avio_printf(out, "\t<ProgramInformation>\n");
     498           0 :     if (title) {
     499           0 :         char *escaped = xmlescape(title->value);
     500           0 :         avio_printf(out, "\t\t<Title>%s</Title>\n", escaped);
     501           0 :         av_free(escaped);
     502             :     }
     503           0 :     avio_printf(out, "\t</ProgramInformation>\n");
     504           0 :     if (c->utc_timing_url)
     505           0 :         avio_printf(out, "\t<UTCTiming schemeIdUri=\"urn:mpeg:dash:utc:http-xsdate:2014\" value=\"%s\"/>\n", c->utc_timing_url);
     506             : 
     507           0 :     if (c->window_size && s->nb_streams > 0 && c->streams[0].nb_segments > 0 && !c->use_template) {
     508           0 :         OutputStream *os = &c->streams[0];
     509           0 :         int start_index = FFMAX(os->nb_segments - c->window_size, 0);
     510           0 :         int64_t start_time = av_rescale_q(os->segments[start_index]->time, s->streams[0]->time_base, AV_TIME_BASE_Q);
     511           0 :         avio_printf(out, "\t<Period id=\"0\" start=\"");
     512           0 :         write_time(out, start_time);
     513           0 :         avio_printf(out, "\">\n");
     514             :     } else {
     515           0 :         avio_printf(out, "\t<Period id=\"0\" start=\"PT0.0S\">\n");
     516             :     }
     517             : 
     518           0 :     if (c->has_video) {
     519           0 :         avio_printf(out, "\t\t<AdaptationSet id=\"%d\" contentType=\"video\" segmentAlignment=\"true\" bitstreamSwitching=\"true\"", as_id++);
     520           0 :         if (c->max_frame_rate.num && !c->ambiguous_frame_rate)
     521           0 :             avio_printf(out, " %s=\"%d/%d\"", (av_cmp_q(c->min_frame_rate, c->max_frame_rate) < 0) ? "maxFrameRate" : "frameRate", c->max_frame_rate.num, c->max_frame_rate.den);
     522           0 :         avio_printf(out, ">\n");
     523             : 
     524           0 :         for (i = 0; i < s->nb_streams; i++) {
     525           0 :             AVStream *st = s->streams[i];
     526           0 :             OutputStream *os = &c->streams[i];
     527             : 
     528           0 :             if (st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO)
     529           0 :                 continue;
     530             : 
     531           0 :             avio_printf(out, "\t\t\t<Representation id=\"%d\" mimeType=\"video/mp4\" codecs=\"%s\"%s width=\"%d\" height=\"%d\"", i, os->codec_str, os->bandwidth_str, st->codecpar->width, st->codecpar->height);
     532           0 :             if (st->avg_frame_rate.num)
     533           0 :                 avio_printf(out, " frameRate=\"%d/%d\"", st->avg_frame_rate.num, st->avg_frame_rate.den);
     534           0 :             avio_printf(out, ">\n");
     535             : 
     536           0 :             output_segment_list(&c->streams[i], out, c);
     537           0 :             avio_printf(out, "\t\t\t</Representation>\n");
     538             :         }
     539           0 :         avio_printf(out, "\t\t</AdaptationSet>\n");
     540             :     }
     541           0 :     if (c->has_audio) {
     542           0 :         avio_printf(out, "\t\t<AdaptationSet id=\"%d\" contentType=\"audio\" segmentAlignment=\"true\" bitstreamSwitching=\"true\">\n", as_id++);
     543           0 :         for (i = 0; i < s->nb_streams; i++) {
     544           0 :             AVStream *st = s->streams[i];
     545           0 :             OutputStream *os = &c->streams[i];
     546             : 
     547           0 :             if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO)
     548           0 :                 continue;
     549             : 
     550           0 :             avio_printf(out, "\t\t\t<Representation id=\"%d\" mimeType=\"audio/mp4\" codecs=\"%s\"%s audioSamplingRate=\"%d\">\n", i, os->codec_str, os->bandwidth_str, st->codecpar->sample_rate);
     551           0 :             avio_printf(out, "\t\t\t\t<AudioChannelConfiguration schemeIdUri=\"urn:mpeg:dash:23003:3:audio_channel_configuration:2011\" value=\"%d\" />\n", st->codecpar->channels);
     552           0 :             output_segment_list(&c->streams[i], out, c);
     553           0 :             avio_printf(out, "\t\t\t</Representation>\n");
     554             :         }
     555           0 :         avio_printf(out, "\t\t</AdaptationSet>\n");
     556             :     }
     557           0 :     avio_printf(out, "\t</Period>\n");
     558           0 :     avio_printf(out, "</MPD>\n");
     559           0 :     avio_flush(out);
     560           0 :     ff_format_io_close(s, &out);
     561             : 
     562           0 :     if (use_rename)
     563           0 :         return avpriv_io_move(temp_filename, s->filename);
     564             : 
     565           0 :     return 0;
     566             : }
     567             : 
     568           0 : static int set_bitrate(AVFormatContext *s)
     569             : {
     570           0 :     DASHContext *c = s->priv_data;
     571             :     int i;
     572             : 
     573           0 :     for (i = 0; i < s->nb_streams; i++) {
     574           0 :         OutputStream *os = &c->streams[i];
     575             : 
     576           0 :         os->bit_rate = s->streams[i]->codecpar->bit_rate;
     577           0 :         if (os->bit_rate) {
     578           0 :             snprintf(os->bandwidth_str, sizeof(os->bandwidth_str),
     579             :                      " bandwidth=\"%d\"", os->bit_rate);
     580             :         } else {
     581           0 :             int level = s->strict_std_compliance >= FF_COMPLIANCE_STRICT ?
     582           0 :                         AV_LOG_ERROR : AV_LOG_WARNING;
     583           0 :             av_log(s, level, "No bit rate set for stream %d\n", i);
     584           0 :             if (s->strict_std_compliance >= FF_COMPLIANCE_STRICT)
     585           0 :                 return AVERROR(EINVAL);
     586             :         }
     587             :     }
     588             : 
     589           0 :     return 0;
     590             : }
     591             : 
     592           0 : static int dash_init(AVFormatContext *s)
     593             : {
     594           0 :     DASHContext *c = s->priv_data;
     595           0 :     int ret = 0, i;
     596             :     AVOutputFormat *oformat;
     597             :     char *ptr;
     598             :     char basename[1024];
     599             : 
     600           0 :     if (c->single_file_name)
     601           0 :         c->single_file = 1;
     602           0 :     if (c->single_file)
     603           0 :         c->use_template = 0;
     604           0 :     c->ambiguous_frame_rate = 0;
     605             : 
     606           0 :     av_strlcpy(c->dirname, s->filename, sizeof(c->dirname));
     607           0 :     ptr = strrchr(c->dirname, '/');
     608           0 :     if (ptr) {
     609           0 :         av_strlcpy(basename, &ptr[1], sizeof(basename));
     610           0 :         ptr[1] = '\0';
     611             :     } else {
     612           0 :         c->dirname[0] = '\0';
     613           0 :         av_strlcpy(basename, s->filename, sizeof(basename));
     614             :     }
     615             : 
     616           0 :     ptr = strrchr(basename, '.');
     617           0 :     if (ptr)
     618           0 :         *ptr = '\0';
     619             : 
     620           0 :     oformat = av_guess_format("mp4", NULL, NULL);
     621           0 :     if (!oformat)
     622           0 :         return AVERROR_MUXER_NOT_FOUND;
     623             : 
     624           0 :     c->streams = av_mallocz(sizeof(*c->streams) * s->nb_streams);
     625           0 :     if (!c->streams)
     626           0 :         return AVERROR(ENOMEM);
     627             : 
     628           0 :     ret = set_bitrate(s);
     629           0 :     if (ret < 0)
     630           0 :         return ret;
     631             : 
     632           0 :     for (i = 0; i < s->nb_streams; i++) {
     633           0 :         OutputStream *os = &c->streams[i];
     634             :         AVFormatContext *ctx;
     635             :         AVStream *st;
     636           0 :         AVDictionary *opts = NULL;
     637             :         char filename[1024];
     638             : 
     639           0 :         ctx = avformat_alloc_context();
     640           0 :         if (!ctx)
     641           0 :             return AVERROR(ENOMEM);
     642           0 :         os->ctx = ctx;
     643           0 :         ctx->oformat = oformat;
     644           0 :         ctx->interrupt_callback = s->interrupt_callback;
     645           0 :         ctx->opaque             = s->opaque;
     646           0 :         ctx->io_close           = s->io_close;
     647           0 :         ctx->io_open            = s->io_open;
     648             : 
     649           0 :         if (!(st = avformat_new_stream(ctx, NULL)))
     650           0 :             return AVERROR(ENOMEM);
     651           0 :         avcodec_parameters_copy(st->codecpar, s->streams[i]->codecpar);
     652           0 :         st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
     653           0 :         st->time_base = s->streams[i]->time_base;
     654           0 :         ctx->avoid_negative_ts = s->avoid_negative_ts;
     655           0 :         ctx->flags = s->flags;
     656             : 
     657           0 :         ctx->pb = avio_alloc_context(os->iobuf, sizeof(os->iobuf), AVIO_FLAG_WRITE, os, NULL, dash_write, NULL);
     658           0 :         if (!ctx->pb)
     659           0 :             return AVERROR(ENOMEM);
     660             : 
     661           0 :         if (c->single_file) {
     662           0 :             if (c->single_file_name)
     663           0 :                 dash_fill_tmpl_params(os->initfile, sizeof(os->initfile), c->single_file_name, i, 0, os->bit_rate, 0);
     664             :             else
     665           0 :                 snprintf(os->initfile, sizeof(os->initfile), "%s-stream%d.m4s", basename, i);
     666             :         } else {
     667           0 :             dash_fill_tmpl_params(os->initfile, sizeof(os->initfile), c->init_seg_name, i, 0, os->bit_rate, 0);
     668             :         }
     669           0 :         snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
     670           0 :         ret = s->io_open(s, &os->out, filename, AVIO_FLAG_WRITE, NULL);
     671           0 :         if (ret < 0)
     672           0 :             return ret;
     673           0 :         os->init_start_pos = 0;
     674             : 
     675           0 :         av_dict_set(&opts, "movflags", "frag_custom+dash+delay_moov", 0);
     676           0 :         if ((ret = avformat_init_output(ctx, &opts)) < 0)
     677           0 :             return ret;
     678           0 :         os->ctx_inited = 1;
     679           0 :         avio_flush(ctx->pb);
     680           0 :         av_dict_free(&opts);
     681             : 
     682           0 :         av_log(s, AV_LOG_VERBOSE, "Representation %d init segment will be written to: %s\n", i, filename);
     683             : 
     684           0 :         s->streams[i]->time_base = st->time_base;
     685             :         // If the muxer wants to shift timestamps, request to have them shifted
     686             :         // already before being handed to this muxer, so we don't have mismatches
     687             :         // between the MPD and the actual segments.
     688           0 :         s->avoid_negative_ts = ctx->avoid_negative_ts;
     689           0 :         if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
     690           0 :             AVRational avg_frame_rate = s->streams[i]->avg_frame_rate;
     691           0 :             if (avg_frame_rate.num > 0) {
     692           0 :                 if (av_cmp_q(avg_frame_rate, c->min_frame_rate) < 0)
     693           0 :                     c->min_frame_rate = avg_frame_rate;
     694           0 :                 if (av_cmp_q(c->max_frame_rate, avg_frame_rate) < 0)
     695           0 :                     c->max_frame_rate = avg_frame_rate;
     696             :             } else {
     697           0 :                 c->ambiguous_frame_rate = 1;
     698             :             }
     699           0 :             c->has_video = 1;
     700           0 :         } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
     701           0 :             c->has_audio = 1;
     702             :         }
     703             : 
     704           0 :         set_codec_str(s, st->codecpar, os->codec_str, sizeof(os->codec_str));
     705           0 :         os->first_pts = AV_NOPTS_VALUE;
     706           0 :         os->max_pts = AV_NOPTS_VALUE;
     707           0 :         os->last_dts = AV_NOPTS_VALUE;
     708           0 :         os->segment_index = 1;
     709             :     }
     710             : 
     711           0 :     if (!c->has_video && c->min_seg_duration <= 0) {
     712           0 :         av_log(s, AV_LOG_WARNING, "no video stream and no min seg duration set\n");
     713           0 :         return AVERROR(EINVAL);
     714             :     }
     715           0 :     return 0;
     716             : }
     717             : 
     718           0 : static int dash_write_header(AVFormatContext *s)
     719             : {
     720           0 :     DASHContext *c = s->priv_data;
     721             :     int i, ret;
     722           0 :     for (i = 0; i < s->nb_streams; i++) {
     723           0 :         OutputStream *os = &c->streams[i];
     724           0 :         if ((ret = avformat_write_header(os->ctx, NULL)) < 0) {
     725           0 :             dash_free(s);
     726           0 :             return ret;
     727             :         }
     728             :     }
     729           0 :     ret = write_manifest(s, 0);
     730           0 :     if (!ret)
     731           0 :         av_log(s, AV_LOG_VERBOSE, "Manifest written to: %s\n", s->filename);
     732           0 :     return ret;
     733             : }
     734             : 
     735           0 : static int add_segment(OutputStream *os, const char *file,
     736             :                        int64_t time, int duration,
     737             :                        int64_t start_pos, int64_t range_length,
     738             :                        int64_t index_length)
     739             : {
     740             :     int err;
     741             :     Segment *seg;
     742           0 :     if (os->nb_segments >= os->segments_size) {
     743           0 :         os->segments_size = (os->segments_size + 1) * 2;
     744           0 :         if ((err = av_reallocp(&os->segments, sizeof(*os->segments) *
     745           0 :                                os->segments_size)) < 0) {
     746           0 :             os->segments_size = 0;
     747           0 :             os->nb_segments = 0;
     748           0 :             return err;
     749             :         }
     750             :     }
     751           0 :     seg = av_mallocz(sizeof(*seg));
     752           0 :     if (!seg)
     753           0 :         return AVERROR(ENOMEM);
     754           0 :     av_strlcpy(seg->file, file, sizeof(seg->file));
     755           0 :     seg->time = time;
     756           0 :     seg->duration = duration;
     757           0 :     if (seg->time < 0) { // If pts<0, it is expected to be cut away with an edit list
     758           0 :         seg->duration += seg->time;
     759           0 :         seg->time = 0;
     760             :     }
     761           0 :     seg->start_pos = start_pos;
     762           0 :     seg->range_length = range_length;
     763           0 :     seg->index_length = index_length;
     764           0 :     os->segments[os->nb_segments++] = seg;
     765           0 :     os->segment_index++;
     766           0 :     return 0;
     767             : }
     768             : 
     769           0 : static void write_styp(AVIOContext *pb)
     770             : {
     771           0 :     avio_wb32(pb, 24);
     772           0 :     ffio_wfourcc(pb, "styp");
     773           0 :     ffio_wfourcc(pb, "msdh");
     774           0 :     avio_wb32(pb, 0); /* minor */
     775           0 :     ffio_wfourcc(pb, "msdh");
     776           0 :     ffio_wfourcc(pb, "msix");
     777           0 : }
     778             : 
     779           0 : static void find_index_range(AVFormatContext *s, const char *full_path,
     780             :                              int64_t pos, int *index_length)
     781             : {
     782             :     uint8_t buf[8];
     783             :     AVIOContext *pb;
     784             :     int ret;
     785             : 
     786           0 :     ret = s->io_open(s, &pb, full_path, AVIO_FLAG_READ, NULL);
     787           0 :     if (ret < 0)
     788           0 :         return;
     789           0 :     if (avio_seek(pb, pos, SEEK_SET) != pos) {
     790           0 :         ff_format_io_close(s, &pb);
     791           0 :         return;
     792             :     }
     793           0 :     ret = avio_read(pb, buf, 8);
     794           0 :     ff_format_io_close(s, &pb);
     795           0 :     if (ret < 8)
     796           0 :         return;
     797           0 :     if (AV_RL32(&buf[4]) != MKTAG('s', 'i', 'd', 'x'))
     798           0 :         return;
     799           0 :     *index_length = AV_RB32(&buf[0]);
     800             : }
     801             : 
     802           0 : static int update_stream_extradata(AVFormatContext *s, OutputStream *os,
     803             :                                    AVCodecParameters *par)
     804             : {
     805             :     uint8_t *extradata;
     806             : 
     807           0 :     if (os->ctx->streams[0]->codecpar->extradata_size || !par->extradata_size)
     808           0 :         return 0;
     809             : 
     810           0 :     extradata = av_malloc(par->extradata_size);
     811             : 
     812           0 :     if (!extradata)
     813           0 :         return AVERROR(ENOMEM);
     814             : 
     815           0 :     memcpy(extradata, par->extradata, par->extradata_size);
     816             : 
     817           0 :     os->ctx->streams[0]->codecpar->extradata = extradata;
     818           0 :     os->ctx->streams[0]->codecpar->extradata_size = par->extradata_size;
     819             : 
     820           0 :     set_codec_str(s, par, os->codec_str, sizeof(os->codec_str));
     821             : 
     822           0 :     return 0;
     823             : }
     824             : 
     825           0 : static int dash_flush(AVFormatContext *s, int final, int stream)
     826             : {
     827           0 :     DASHContext *c = s->priv_data;
     828           0 :     int i, ret = 0;
     829             : 
     830           0 :     const char *proto = avio_find_protocol_name(s->filename);
     831           0 :     int use_rename = proto && !strcmp(proto, "file");
     832             : 
     833           0 :     int cur_flush_segment_index = 0;
     834           0 :     if (stream >= 0)
     835           0 :         cur_flush_segment_index = c->streams[stream].segment_index;
     836             : 
     837           0 :     for (i = 0; i < s->nb_streams; i++) {
     838           0 :         OutputStream *os = &c->streams[i];
     839           0 :         char filename[1024] = "", full_path[1024], temp_path[1024];
     840             :         int64_t start_pos;
     841           0 :         int range_length, index_length = 0;
     842             : 
     843           0 :         if (!os->packets_written)
     844           0 :             continue;
     845             : 
     846             :         // Flush the single stream that got a keyframe right now.
     847             :         // Flush all audio streams as well, in sync with video keyframes,
     848             :         // but not the other video streams.
     849           0 :         if (stream >= 0 && i != stream) {
     850           0 :             if (s->streams[i]->codecpar->codec_type != AVMEDIA_TYPE_AUDIO)
     851           0 :                 continue;
     852             :             // Make sure we don't flush audio streams multiple times, when
     853             :             // all video streams are flushed one at a time.
     854           0 :             if (c->has_video && os->segment_index > cur_flush_segment_index)
     855           0 :                 continue;
     856             :         }
     857             : 
     858           0 :         if (!os->init_range_length) {
     859           0 :             av_write_frame(os->ctx, NULL);
     860           0 :             os->init_range_length = avio_tell(os->ctx->pb);
     861           0 :             if (!c->single_file)
     862           0 :                 ff_format_io_close(s, &os->out);
     863             :         }
     864             : 
     865           0 :         start_pos = avio_tell(os->ctx->pb);
     866             : 
     867           0 :         if (!c->single_file) {
     868           0 :             dash_fill_tmpl_params(filename, sizeof(filename), c->media_seg_name, i, os->segment_index, os->bit_rate, os->start_pts);
     869           0 :             snprintf(full_path, sizeof(full_path), "%s%s", c->dirname, filename);
     870           0 :             snprintf(temp_path, sizeof(temp_path), use_rename ? "%s.tmp" : "%s", full_path);
     871           0 :             ret = s->io_open(s, &os->out, temp_path, AVIO_FLAG_WRITE, NULL);
     872           0 :             if (ret < 0)
     873           0 :                 break;
     874           0 :             write_styp(os->ctx->pb);
     875             :         } else {
     876           0 :             snprintf(full_path, sizeof(full_path), "%s%s", c->dirname, os->initfile);
     877             :         }
     878             : 
     879           0 :         av_write_frame(os->ctx, NULL);
     880           0 :         avio_flush(os->ctx->pb);
     881           0 :         os->packets_written = 0;
     882             : 
     883           0 :         range_length = avio_tell(os->ctx->pb) - start_pos;
     884           0 :         if (c->single_file) {
     885           0 :             find_index_range(s, full_path, start_pos, &index_length);
     886             :         } else {
     887           0 :             ff_format_io_close(s, &os->out);
     888             : 
     889           0 :             if (use_rename) {
     890           0 :                 ret = avpriv_io_move(temp_path, full_path);
     891           0 :                 if (ret < 0)
     892           0 :                     break;
     893             :             }
     894             :         }
     895           0 :         add_segment(os, filename, os->start_pts, os->max_pts - os->start_pts, start_pos, range_length, index_length);
     896           0 :         av_log(s, AV_LOG_VERBOSE, "Representation %d media segment %d written to: %s\n", i, os->segment_index, full_path);
     897             :     }
     898             : 
     899           0 :     if (c->window_size || (final && c->remove_at_exit)) {
     900           0 :         for (i = 0; i < s->nb_streams; i++) {
     901           0 :             OutputStream *os = &c->streams[i];
     902             :             int j;
     903           0 :             int remove = os->nb_segments - c->window_size - c->extra_window_size;
     904           0 :             if (final && c->remove_at_exit)
     905           0 :                 remove = os->nb_segments;
     906           0 :             if (remove > 0) {
     907           0 :                 for (j = 0; j < remove; j++) {
     908             :                     char filename[1024];
     909           0 :                     snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->segments[j]->file);
     910           0 :                     unlink(filename);
     911           0 :                     av_free(os->segments[j]);
     912             :                 }
     913           0 :                 os->nb_segments -= remove;
     914           0 :                 memmove(os->segments, os->segments + remove, os->nb_segments * sizeof(*os->segments));
     915             :             }
     916             :         }
     917             :     }
     918             : 
     919           0 :     if (ret >= 0)
     920           0 :         ret = write_manifest(s, final);
     921           0 :     return ret;
     922             : }
     923             : 
     924           0 : static int dash_write_packet(AVFormatContext *s, AVPacket *pkt)
     925             : {
     926           0 :     DASHContext *c = s->priv_data;
     927           0 :     AVStream *st = s->streams[pkt->stream_index];
     928           0 :     OutputStream *os = &c->streams[pkt->stream_index];
     929             :     int ret;
     930             : 
     931           0 :     ret = update_stream_extradata(s, os, st->codecpar);
     932           0 :     if (ret < 0)
     933           0 :         return ret;
     934             : 
     935             :     // Fill in a heuristic guess of the packet duration, if none is available.
     936             :     // The mp4 muxer will do something similar (for the last packet in a fragment)
     937             :     // if nothing is set (setting it for the other packets doesn't hurt).
     938             :     // By setting a nonzero duration here, we can be sure that the mp4 muxer won't
     939             :     // invoke its heuristic (this doesn't have to be identical to that algorithm),
     940             :     // so that we know the exact timestamps of fragments.
     941           0 :     if (!pkt->duration && os->last_dts != AV_NOPTS_VALUE)
     942           0 :         pkt->duration = pkt->dts - os->last_dts;
     943           0 :     os->last_dts = pkt->dts;
     944             : 
     945             :     // If forcing the stream to start at 0, the mp4 muxer will set the start
     946             :     // timestamps to 0. Do the same here, to avoid mismatches in duration/timestamps.
     947           0 :     if (os->first_pts == AV_NOPTS_VALUE &&
     948           0 :         s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
     949           0 :         pkt->pts -= pkt->dts;
     950           0 :         pkt->dts  = 0;
     951             :     }
     952             : 
     953           0 :     if (os->first_pts == AV_NOPTS_VALUE)
     954           0 :         os->first_pts = pkt->pts;
     955             : 
     956           0 :     if ((!c->has_video || st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) &&
     957           0 :         pkt->flags & AV_PKT_FLAG_KEY && os->packets_written &&
     958           0 :         av_compare_ts(pkt->pts - os->start_pts, st->time_base,
     959           0 :                       c->min_seg_duration, AV_TIME_BASE_Q) >= 0) {
     960           0 :         int64_t prev_duration = c->last_duration;
     961             : 
     962           0 :         c->last_duration = av_rescale_q(pkt->pts - os->start_pts,
     963             :                                         st->time_base,
     964           0 :                                         AV_TIME_BASE_Q);
     965           0 :         c->total_duration = av_rescale_q(pkt->pts - os->first_pts,
     966             :                                          st->time_base,
     967           0 :                                          AV_TIME_BASE_Q);
     968             : 
     969           0 :         if ((!c->use_timeline || !c->use_template) && prev_duration) {
     970           0 :             if (c->last_duration < prev_duration*9/10 ||
     971           0 :                 c->last_duration > prev_duration*11/10) {
     972           0 :                 av_log(s, AV_LOG_WARNING,
     973             :                        "Segment durations differ too much, enable use_timeline "
     974             :                        "and use_template, or keep a stricter keyframe interval\n");
     975             :             }
     976             :         }
     977             : 
     978           0 :         if ((ret = dash_flush(s, 0, pkt->stream_index)) < 0)
     979           0 :             return ret;
     980             :     }
     981             : 
     982           0 :     if (!os->packets_written) {
     983             :         // If we wrote a previous segment, adjust the start time of the segment
     984             :         // to the end of the previous one (which is the same as the mp4 muxer
     985             :         // does). This avoids gaps in the timeline.
     986           0 :         if (os->max_pts != AV_NOPTS_VALUE)
     987           0 :             os->start_pts = os->max_pts;
     988             :         else
     989           0 :             os->start_pts = pkt->pts;
     990             :     }
     991           0 :     if (os->max_pts == AV_NOPTS_VALUE)
     992           0 :         os->max_pts = pkt->pts + pkt->duration;
     993             :     else
     994           0 :         os->max_pts = FFMAX(os->max_pts, pkt->pts + pkt->duration);
     995           0 :     os->packets_written++;
     996           0 :     return ff_write_chained(os->ctx, 0, pkt, s, 0);
     997             : }
     998             : 
     999           0 : static int dash_write_trailer(AVFormatContext *s)
    1000             : {
    1001           0 :     DASHContext *c = s->priv_data;
    1002             : 
    1003           0 :     set_bitrate(s);
    1004             : 
    1005           0 :     if (s->nb_streams > 0) {
    1006           0 :         OutputStream *os = &c->streams[0];
    1007             :         // If no segments have been written so far, try to do a crude
    1008             :         // guess of the segment duration
    1009           0 :         if (!c->last_duration)
    1010           0 :             c->last_duration = av_rescale_q(os->max_pts - os->start_pts,
    1011           0 :                                             s->streams[0]->time_base,
    1012           0 :                                             AV_TIME_BASE_Q);
    1013           0 :         c->total_duration = av_rescale_q(os->max_pts - os->first_pts,
    1014           0 :                                          s->streams[0]->time_base,
    1015           0 :                                          AV_TIME_BASE_Q);
    1016             :     }
    1017           0 :     dash_flush(s, 1, -1);
    1018             : 
    1019           0 :     if (c->remove_at_exit) {
    1020             :         char filename[1024];
    1021             :         int i;
    1022           0 :         for (i = 0; i < s->nb_streams; i++) {
    1023           0 :             OutputStream *os = &c->streams[i];
    1024           0 :             snprintf(filename, sizeof(filename), "%s%s", c->dirname, os->initfile);
    1025           0 :             unlink(filename);
    1026             :         }
    1027           0 :         unlink(s->filename);
    1028             :     }
    1029             : 
    1030           0 :     return 0;
    1031             : }
    1032             : 
    1033           0 : static int dash_check_bitstream(struct AVFormatContext *s, const AVPacket *avpkt)
    1034             : {
    1035           0 :     DASHContext *c = s->priv_data;
    1036           0 :     OutputStream *os = &c->streams[avpkt->stream_index];
    1037           0 :     AVFormatContext *oc = os->ctx;
    1038           0 :     if (oc->oformat->check_bitstream) {
    1039             :         int ret;
    1040           0 :         AVPacket pkt = *avpkt;
    1041           0 :         pkt.stream_index = 0;
    1042           0 :         ret = oc->oformat->check_bitstream(oc, &pkt);
    1043           0 :         if (ret == 1) {
    1044           0 :             AVStream *st = s->streams[avpkt->stream_index];
    1045           0 :             AVStream *ost = oc->streams[0];
    1046           0 :             st->internal->bsfcs = ost->internal->bsfcs;
    1047           0 :             st->internal->nb_bsfcs = ost->internal->nb_bsfcs;
    1048           0 :             ost->internal->bsfcs = NULL;
    1049           0 :             ost->internal->nb_bsfcs = 0;
    1050             :         }
    1051           0 :         return ret;
    1052             :     }
    1053           0 :     return 1;
    1054             : }
    1055             : 
    1056             : #define OFFSET(x) offsetof(DASHContext, x)
    1057             : #define E AV_OPT_FLAG_ENCODING_PARAM
    1058             : static const AVOption options[] = {
    1059             :     { "window_size", "number of segments kept in the manifest", OFFSET(window_size), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, E },
    1060             :     { "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 },
    1061             :     { "min_seg_duration", "minimum segment duration (in microseconds)", OFFSET(min_seg_duration), AV_OPT_TYPE_INT64, { .i64 = 5000000 }, 0, INT_MAX, E },
    1062             :     { "remove_at_exit", "remove all segments when finished", OFFSET(remove_at_exit), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
    1063             :     { "use_template", "Use SegmentTemplate instead of SegmentList", OFFSET(use_template), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, E },
    1064             :     { "use_timeline", "Use SegmentTimeline in SegmentTemplate", OFFSET(use_timeline), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, E },
    1065             :     { "single_file", "Store all segments in one file, accessed using byte ranges", OFFSET(single_file), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
    1066             :     { "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 },
    1067             :     { "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 },
    1068             :     { "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 },
    1069             :     { "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 },
    1070             :     { NULL },
    1071             : };
    1072             : 
    1073             : static const AVClass dash_class = {
    1074             :     .class_name = "dash muxer",
    1075             :     .item_name  = av_default_item_name,
    1076             :     .option     = options,
    1077             :     .version    = LIBAVUTIL_VERSION_INT,
    1078             : };
    1079             : 
    1080             : AVOutputFormat ff_dash_muxer = {
    1081             :     .name           = "dash",
    1082             :     .long_name      = NULL_IF_CONFIG_SMALL("DASH Muxer"),
    1083             :     .priv_data_size = sizeof(DASHContext),
    1084             :     .audio_codec    = AV_CODEC_ID_AAC,
    1085             :     .video_codec    = AV_CODEC_ID_H264,
    1086             :     .flags          = AVFMT_GLOBALHEADER | AVFMT_NOFILE | AVFMT_TS_NEGATIVE,
    1087             :     .init           = dash_init,
    1088             :     .write_header   = dash_write_header,
    1089             :     .write_packet   = dash_write_packet,
    1090             :     .write_trailer  = dash_write_trailer,
    1091             :     .deinit         = dash_free,
    1092             :     .check_bitstream = dash_check_bitstream,
    1093             :     .priv_class     = &dash_class,
    1094             : };

Generated by: LCOV version 1.13