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

Generated by: LCOV version 1.13