LCOV - code coverage report
Current view: top level - libavformat - hlsenc.c (source / functions) Hit Total Coverage
Test: coverage.info Lines: 513 1591 32.2 %
Date: 2018-02-24 03:21:38 Functions: 24 41 58.5 %

          Line data    Source code
       1             : /*
       2             :  * Apple HTTP Live Streaming segmenter
       3             :  * Copyright (c) 2012, Luca Barbato
       4             :  * Copyright (c) 2017 Akamai Technologies, Inc.
       5             :  *
       6             :  * This file is part of FFmpeg.
       7             :  *
       8             :  * FFmpeg is free software; you can redistribute it and/or
       9             :  * modify it under the terms of the GNU Lesser General Public
      10             :  * License as published by the Free Software Foundation; either
      11             :  * version 2.1 of the License, or (at your option) any later version.
      12             :  *
      13             :  * FFmpeg is distributed in the hope that it will be useful,
      14             :  * but WITHOUT ANY WARRANTY; without even the implied warranty of
      15             :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
      16             :  * Lesser General Public License for more details.
      17             :  *
      18             :  * You should have received a copy of the GNU Lesser General Public
      19             :  * License along with FFmpeg; if not, write to the Free Software
      20             :  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
      21             :  */
      22             : 
      23             : #include "config.h"
      24             : #include <float.h>
      25             : #include <stdint.h>
      26             : #if HAVE_UNISTD_H
      27             : #include <unistd.h>
      28             : #endif
      29             : 
      30             : #if CONFIG_GCRYPT
      31             : #include <gcrypt.h>
      32             : #elif CONFIG_OPENSSL
      33             : #include <openssl/rand.h>
      34             : #endif
      35             : 
      36             : #include "libavutil/avassert.h"
      37             : #include "libavutil/mathematics.h"
      38             : #include "libavutil/parseutils.h"
      39             : #include "libavutil/avstring.h"
      40             : #include "libavutil/intreadwrite.h"
      41             : #include "libavutil/random_seed.h"
      42             : #include "libavutil/opt.h"
      43             : #include "libavutil/log.h"
      44             : #include "libavutil/time_internal.h"
      45             : 
      46             : #include "avformat.h"
      47             : #include "avio_internal.h"
      48             : #if CONFIG_HTTP_PROTOCOL
      49             : #include "http.h"
      50             : #endif
      51             : #include "hlsplaylist.h"
      52             : #include "internal.h"
      53             : #include "os_support.h"
      54             : 
      55             : typedef enum {
      56             :   HLS_START_SEQUENCE_AS_START_NUMBER = 0,
      57             :   HLS_START_SEQUENCE_AS_SECONDS_SINCE_EPOCH = 1,
      58             :   HLS_START_SEQUENCE_AS_FORMATTED_DATETIME = 2,  // YYYYMMDDhhmmss
      59             : } StartSequenceSourceType;
      60             : 
      61             : typedef enum {
      62             :     CODEC_ATTRIBUTE_WRITTEN = 0,
      63             :     CODEC_ATTRIBUTE_WILL_NOT_BE_WRITTEN,
      64             : } CodecAttributeStatus;
      65             : 
      66             : #define KEYSIZE 16
      67             : #define LINE_BUFFER_SIZE 1024
      68             : #define HLS_MICROSECOND_UNIT   1000000
      69             : #define POSTFIX_PATTERN "_%d"
      70             : 
      71             : typedef struct HLSSegment {
      72             :     char filename[1024];
      73             :     char sub_filename[1024];
      74             :     double duration; /* in seconds */
      75             :     int discont;
      76             :     int64_t pos;
      77             :     int64_t size;
      78             : 
      79             :     char key_uri[LINE_BUFFER_SIZE + 1];
      80             :     char iv_string[KEYSIZE*2 + 1];
      81             : 
      82             :     struct HLSSegment *next;
      83             : } HLSSegment;
      84             : 
      85             : typedef enum HLSFlags {
      86             :     // Generate a single media file and use byte ranges in the playlist.
      87             :     HLS_SINGLE_FILE = (1 << 0),
      88             :     HLS_DELETE_SEGMENTS = (1 << 1),
      89             :     HLS_ROUND_DURATIONS = (1 << 2),
      90             :     HLS_DISCONT_START = (1 << 3),
      91             :     HLS_OMIT_ENDLIST = (1 << 4),
      92             :     HLS_SPLIT_BY_TIME = (1 << 5),
      93             :     HLS_APPEND_LIST = (1 << 6),
      94             :     HLS_PROGRAM_DATE_TIME = (1 << 7),
      95             :     HLS_SECOND_LEVEL_SEGMENT_INDEX = (1 << 8), // include segment index in segment filenames when use_localtime  e.g.: %%03d
      96             :     HLS_SECOND_LEVEL_SEGMENT_DURATION = (1 << 9), // include segment duration (microsec) in segment filenames when use_localtime  e.g.: %%09t
      97             :     HLS_SECOND_LEVEL_SEGMENT_SIZE = (1 << 10), // include segment size (bytes) in segment filenames when use_localtime  e.g.: %%014s
      98             :     HLS_TEMP_FILE = (1 << 11),
      99             :     HLS_PERIODIC_REKEY = (1 << 12),
     100             :     HLS_INDEPENDENT_SEGMENTS = (1 << 13),
     101             : } HLSFlags;
     102             : 
     103             : typedef enum {
     104             :     SEGMENT_TYPE_MPEGTS,
     105             :     SEGMENT_TYPE_FMP4,
     106             : } SegmentType;
     107             : 
     108             : typedef struct VariantStream {
     109             :     unsigned number;
     110             :     int64_t sequence;
     111             :     AVOutputFormat *oformat;
     112             :     AVOutputFormat *vtt_oformat;
     113             :     AVIOContext *out;
     114             :     int packets_written;
     115             :     int init_range_length;
     116             : 
     117             :     AVFormatContext *avf;
     118             :     AVFormatContext *vtt_avf;
     119             : 
     120             :     int has_video;
     121             :     int has_subtitle;
     122             :     int new_start;
     123             :     double dpp;           // duration per packet
     124             :     int64_t start_pts;
     125             :     int64_t end_pts;
     126             :     double duration;      // last segment duration computed so far, in seconds
     127             :     int64_t start_pos;    // last segment starting position
     128             :     int64_t size;         // last segment size
     129             :     int nb_entries;
     130             :     int discontinuity_set;
     131             :     int discontinuity;
     132             : 
     133             :     HLSSegment *segments;
     134             :     HLSSegment *last_segment;
     135             :     HLSSegment *old_segments;
     136             : 
     137             :     char *basename;
     138             :     char *vtt_basename;
     139             :     char *vtt_m3u8_name;
     140             :     char *m3u8_name;
     141             : 
     142             :     double initial_prog_date_time;
     143             :     char current_segment_final_filename_fmt[1024]; // when renaming segments
     144             : 
     145             :     char *fmp4_init_filename;
     146             :     char *base_output_dirname;
     147             :     int fmp4_init_mode;
     148             : 
     149             :     AVStream **streams;
     150             :     char codec_attr[128];
     151             :     CodecAttributeStatus attr_status;
     152             :     unsigned int nb_streams;
     153             :     int m3u8_created; /* status of media play-list creation */
     154             :     char *agroup; /* audio group name */
     155             :     char *ccgroup; /* closed caption group name */
     156             :     char *baseurl;
     157             : } VariantStream;
     158             : 
     159             : typedef struct ClosedCaptionsStream {
     160             :     char *ccgroup; /* closed caption group name */
     161             :     char *instreamid; /* closed captions INSTREAM-ID */
     162             :     char *language; /* closed captions langauge */
     163             : } ClosedCaptionsStream;
     164             : 
     165             : typedef struct HLSContext {
     166             :     const AVClass *class;  // Class for private options.
     167             :     int64_t start_sequence;
     168             :     uint32_t start_sequence_source_type;  // enum StartSequenceSourceType
     169             : 
     170             :     float time;            // Set by a private option.
     171             :     float init_time;       // Set by a private option.
     172             :     int max_nb_segments;   // Set by a private option.
     173             : #if FF_API_HLS_WRAP
     174             :     int  wrap;             // Set by a private option.
     175             : #endif
     176             :     uint32_t flags;        // enum HLSFlags
     177             :     uint32_t pl_type;      // enum PlaylistType
     178             :     char *segment_filename;
     179             :     char *fmp4_init_filename;
     180             :     int segment_type;
     181             : 
     182             :     int use_localtime;      ///< flag to expand filename with localtime
     183             :     int use_localtime_mkdir;///< flag to mkdir dirname in timebased filename
     184             :     int allowcache;
     185             :     int64_t recording_time;
     186             :     int64_t max_seg_size; // every segment file max size
     187             : 
     188             :     char *baseurl;
     189             :     char *format_options_str;
     190             :     char *vtt_format_options_str;
     191             :     char *subtitle_filename;
     192             :     AVDictionary *format_options;
     193             : 
     194             :     int encrypt;
     195             :     char *key;
     196             :     char *key_url;
     197             :     char *iv;
     198             :     char *key_basename;
     199             :     int encrypt_started;
     200             : 
     201             :     char *key_info_file;
     202             :     char key_file[LINE_BUFFER_SIZE + 1];
     203             :     char key_uri[LINE_BUFFER_SIZE + 1];
     204             :     char key_string[KEYSIZE*2 + 1];
     205             :     char iv_string[KEYSIZE*2 + 1];
     206             :     AVDictionary *vtt_format_options;
     207             : 
     208             :     char *method;
     209             :     char *user_agent;
     210             : 
     211             :     VariantStream *var_streams;
     212             :     unsigned int nb_varstreams;
     213             :     ClosedCaptionsStream *cc_streams;
     214             :     unsigned int nb_ccstreams;
     215             : 
     216             :     int master_m3u8_created; /* status of master play-list creation */
     217             :     char *master_m3u8_url; /* URL of the master m3u8 file */
     218             :     int version; /* HLS version */
     219             :     char *var_stream_map; /* user specified variant stream map string */
     220             :     char *cc_stream_map; /* user specified closed caption streams map string */
     221             :     char *master_pl_name;
     222             :     unsigned int master_publish_rate;
     223             :     int http_persistent;
     224             :     AVIOContext *m3u8_out;
     225             :     AVIOContext *sub_m3u8_out;
     226             : } HLSContext;
     227             : 
     228           0 : static int mkdir_p(const char *path) {
     229           0 :     int ret = 0;
     230           0 :     char *temp = av_strdup(path);
     231           0 :     char *pos = temp;
     232           0 :     char tmp_ch = '\0';
     233             : 
     234           0 :     if (!path || !temp) {
     235           0 :         return -1;
     236             :     }
     237             : 
     238           0 :     if (!strncmp(temp, "/", 1) || !strncmp(temp, "\\", 1)) {
     239           0 :         pos++;
     240           0 :     } else if (!strncmp(temp, "./", 2) || !strncmp(temp, ".\\", 2)) {
     241           0 :         pos += 2;
     242             :     }
     243             : 
     244           0 :     for ( ; *pos != '\0'; ++pos) {
     245           0 :         if (*pos == '/' || *pos == '\\') {
     246           0 :             tmp_ch = *pos;
     247           0 :             *pos = '\0';
     248           0 :             ret = mkdir(temp, 0755);
     249           0 :             *pos = tmp_ch;
     250             :         }
     251             :     }
     252             : 
     253           0 :     if ((*(pos - 1) != '/') || (*(pos - 1) != '\\')) {
     254           0 :         ret = mkdir(temp, 0755);
     255             :     }
     256             : 
     257           0 :     av_free(temp);
     258           0 :     return ret;
     259             : }
     260             : 
     261           4 : static int hlsenc_io_open(AVFormatContext *s, AVIOContext **pb, char *filename,
     262             :                           AVDictionary **options) {
     263           4 :     HLSContext *hls = s->priv_data;
     264           4 :     int http_base_proto = filename ? ff_is_http_proto(filename) : 0;
     265           4 :     int err = AVERROR_MUXER_NOT_FOUND;
     266           4 :     if (!*pb || !http_base_proto || !hls->http_persistent) {
     267           4 :         err = s->io_open(s, pb, filename, AVIO_FLAG_WRITE, options);
     268             : #if CONFIG_HTTP_PROTOCOL
     269             :     } else {
     270           0 :         URLContext *http_url_context = ffio_geturlcontext(*pb);
     271           0 :         av_assert0(http_url_context);
     272           0 :         err = ff_http_do_new_request(http_url_context, filename);
     273             : #endif
     274             :     }
     275           4 :     return err;
     276             : }
     277             : 
     278           5 : static void hlsenc_io_close(AVFormatContext *s, AVIOContext **pb, char *filename) {
     279           5 :     HLSContext *hls = s->priv_data;
     280           5 :     int http_base_proto = filename ? ff_is_http_proto(filename) : 0;
     281           5 :     if (!http_base_proto || !hls->http_persistent || hls->key_info_file || hls->encrypt) {
     282           5 :         ff_format_io_close(s, pb);
     283             : #if CONFIG_HTTP_PROTOCOL
     284             :     } else {
     285           0 :         URLContext *http_url_context = ffio_geturlcontext(*pb);
     286           0 :         av_assert0(http_url_context);
     287           0 :         avio_flush(*pb);
     288           0 :         ffurl_shutdown(http_url_context, AVIO_FLAG_WRITE);
     289             : #endif
     290             :     }
     291           5 : }
     292             : 
     293           4 : static void set_http_options(AVFormatContext *s, AVDictionary **options, HLSContext *c)
     294             : {
     295           4 :     int http_base_proto = ff_is_http_proto(s->url);
     296             : 
     297           4 :     if (c->method) {
     298           0 :         av_dict_set(options, "method", c->method, 0);
     299           4 :     } else if (http_base_proto) {
     300           0 :         av_log(c, AV_LOG_WARNING, "No HTTP method set, hls muxer defaulting to method PUT.\n");
     301           0 :         av_dict_set(options, "method", "PUT", 0);
     302             :     }
     303           4 :     if (c->user_agent)
     304           0 :         av_dict_set(options, "user_agent", c->user_agent, 0);
     305           4 :     if (c->http_persistent)
     306           0 :         av_dict_set_int(options, "multiple_requests", 1, 0);
     307             : 
     308           4 : }
     309             : 
     310           1 : static void write_codec_attr(AVStream *st, VariantStream *vs) {
     311           1 :     int codec_strlen = strlen(vs->codec_attr);
     312             :     char attr[32];
     313             : 
     314           1 :     if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE)
     315           0 :         return;
     316           1 :     if (vs->attr_status == CODEC_ATTRIBUTE_WILL_NOT_BE_WRITTEN)
     317           0 :         return;
     318             : 
     319           1 :     if (st->codecpar->codec_id == AV_CODEC_ID_H264) {
     320           0 :         uint8_t *data = st->codecpar->extradata;
     321           0 :         if (data && (data[0] | data[1] | data[2]) == 0 && data[3] == 1 && (data[4] & 0x1F) == 7) {
     322           0 :             snprintf(attr, sizeof(attr),
     323           0 :                      "avc1.%02x%02x%02x", data[5], data[6], data[7]);
     324             :         } else {
     325             :             goto fail;
     326             :         }
     327           1 :     } else if (st->codecpar->codec_id == AV_CODEC_ID_MP2) {
     328           1 :         snprintf(attr, sizeof(attr), "mp4a.40.33");
     329           0 :     } else if (st->codecpar->codec_id == AV_CODEC_ID_MP3) {
     330           0 :         snprintf(attr, sizeof(attr), "mp4a.40.34");
     331           0 :     } else if (st->codecpar->codec_id == AV_CODEC_ID_AAC) {
     332             :         /* TODO : For HE-AAC, HE-AACv2, the last digit needs to be set to 5 and 29 respectively */
     333           0 :         snprintf(attr, sizeof(attr), "mp4a.40.2");
     334           0 :     } else if (st->codecpar->codec_id == AV_CODEC_ID_AC3) {
     335           0 :         snprintf(attr, sizeof(attr), "ac-3");
     336           0 :     } else if (st->codecpar->codec_id == AV_CODEC_ID_EAC3) {
     337           0 :         snprintf(attr, sizeof(attr), "ec-3");
     338             :     } else {
     339           0 :         goto fail;
     340             :     }
     341             :     // Don't write the same attribute multiple times
     342           1 :     if (!av_stristr(vs->codec_attr, attr)) {
     343           1 :         snprintf(vs->codec_attr + codec_strlen,
     344             :                  sizeof(vs->codec_attr) - codec_strlen,
     345             :                  "%s%s", codec_strlen ? "," : "", attr);
     346             :     }
     347           1 :     return;
     348             : 
     349           0 : fail:
     350           0 :     vs->codec_attr[0] = '\0';
     351           0 :     vs->attr_status = CODEC_ATTRIBUTE_WILL_NOT_BE_WRITTEN;
     352           0 :     return;
     353             : }
     354             : 
     355           2 : static int replace_int_data_in_filename(char **s, const char *filename, char placeholder, int64_t number)
     356             : {
     357             :     const char *p;
     358             :     char *new_filename;
     359             :     char c;
     360             :     int nd, addchar_count;
     361           2 :     int found_count = 0;
     362             :     AVBPrint buf;
     363             : 
     364           2 :     av_bprint_init(&buf, 0, AV_BPRINT_SIZE_UNLIMITED);
     365             : 
     366           2 :     p = filename;
     367             :     for (;;) {
     368         346 :         c = *p;
     369         174 :         if (c == '\0')
     370           2 :             break;
     371         172 :         if (c == '%' && *(p+1) == '%')  // %%
     372           0 :             addchar_count = 2;
     373         172 :         else if (c == '%' && (av_isdigit(*(p+1)) || *(p+1) == placeholder)) {
     374           2 :             nd = 0;
     375           2 :             addchar_count = 1;
     376           8 :             while (av_isdigit(*(p + addchar_count))) {
     377           4 :                 nd = nd * 10 + *(p + addchar_count) - '0';
     378           4 :                 addchar_count++;
     379             :             }
     380             : 
     381           4 :             if (*(p + addchar_count) == placeholder) {
     382           2 :                 av_bprintf(&buf, "%0*"PRId64, (number < 0) ? nd : nd++, number);
     383           2 :                 p += (addchar_count + 1);
     384           2 :                 addchar_count = 0;
     385           2 :                 found_count++;
     386             :             }
     387             : 
     388             :         } else
     389         170 :             addchar_count = 1;
     390             : 
     391         172 :         av_bprint_append_data(&buf, p, addchar_count);
     392         172 :         p += addchar_count;
     393             :     }
     394           2 :     if (!av_bprint_is_complete(&buf)) {
     395           0 :         av_bprint_finalize(&buf, NULL);
     396           0 :         return -1;
     397             :     }
     398           2 :     if (av_bprint_finalize(&buf, &new_filename) < 0 || !new_filename)
     399           0 :         return -1;
     400           2 :     *s = new_filename;
     401           2 :     return found_count;
     402             : }
     403             : 
     404           0 : static void write_styp(AVIOContext *pb)
     405             : {
     406           0 :     avio_wb32(pb, 24);
     407           0 :     ffio_wfourcc(pb, "styp");
     408           0 :     ffio_wfourcc(pb, "msdh");
     409           0 :     avio_wb32(pb, 0); /* minor */
     410           0 :     ffio_wfourcc(pb, "msdh");
     411           0 :     ffio_wfourcc(pb, "msix");
     412           0 : }
     413             : 
     414           0 : static int flush_dynbuf(VariantStream *vs, int *range_length)
     415             : {
     416           0 :     AVFormatContext *ctx = vs->avf;
     417             :     uint8_t *buffer;
     418             : 
     419           0 :     if (!ctx->pb) {
     420           0 :         return AVERROR(EINVAL);
     421             :     }
     422             : 
     423             :     // flush
     424           0 :     av_write_frame(ctx, NULL);
     425           0 :     avio_flush(ctx->pb);
     426             : 
     427             :     // write out to file
     428           0 :     *range_length = avio_close_dyn_buf(ctx->pb, &buffer);
     429           0 :     ctx->pb = NULL;
     430           0 :     avio_write(vs->out, buffer, *range_length);
     431           0 :     av_free(buffer);
     432             : 
     433             :     // re-open buffer
     434           0 :     return avio_open_dyn_buf(&ctx->pb);
     435             : }
     436             : 
     437           0 : static int hls_delete_old_segments(AVFormatContext *s, HLSContext *hls,
     438             :                                    VariantStream *vs) {
     439             : 
     440           0 :     HLSSegment *segment, *previous_segment = NULL;
     441           0 :     float playlist_duration = 0.0f;
     442           0 :     int ret = 0, path_size, sub_path_size;
     443           0 :     char *dirname = NULL, *p, *sub_path;
     444           0 :     char *path = NULL;
     445           0 :     AVDictionary *options = NULL;
     446           0 :     AVIOContext *out = NULL;
     447           0 :     const char *proto = NULL;
     448             : 
     449           0 :     segment = vs->segments;
     450           0 :     while (segment) {
     451           0 :         playlist_duration += segment->duration;
     452           0 :         segment = segment->next;
     453             :     }
     454             : 
     455           0 :     segment = vs->old_segments;
     456           0 :     while (segment) {
     457           0 :         playlist_duration -= segment->duration;
     458           0 :         previous_segment = segment;
     459           0 :         segment = previous_segment->next;
     460           0 :         if (playlist_duration <= -previous_segment->duration) {
     461           0 :             previous_segment->next = NULL;
     462           0 :             break;
     463             :         }
     464             :     }
     465             : 
     466           0 :     if (segment && !hls->use_localtime_mkdir) {
     467           0 :         if (hls->segment_filename) {
     468           0 :             dirname = av_strdup(hls->segment_filename);
     469             :         } else {
     470           0 :             dirname = av_strdup(vs->avf->url);
     471             :         }
     472           0 :         if (!dirname) {
     473           0 :             ret = AVERROR(ENOMEM);
     474           0 :             goto fail;
     475             :         }
     476           0 :         p = (char *)av_basename(dirname);
     477           0 :         *p = '\0';
     478             :     }
     479             : 
     480           0 :     while (segment) {
     481           0 :         av_log(hls, AV_LOG_DEBUG, "deleting old segment %s\n",
     482           0 :                                   segment->filename);
     483           0 :         path_size =  (hls->use_localtime_mkdir ? 0 : strlen(dirname)) + strlen(segment->filename) + 1;
     484           0 :         path = av_malloc(path_size);
     485           0 :         if (!path) {
     486           0 :             ret = AVERROR(ENOMEM);
     487           0 :             goto fail;
     488             :         }
     489             : 
     490           0 :         if (hls->use_localtime_mkdir)
     491           0 :             av_strlcpy(path, segment->filename, path_size);
     492             :         else { // segment->filename contains basename only
     493           0 :             av_strlcpy(path, dirname, path_size);
     494           0 :             av_strlcat(path, segment->filename, path_size);
     495             :         }
     496             : 
     497           0 :         proto = avio_find_protocol_name(s->url);
     498           0 :         if (hls->method || (proto && !av_strcasecmp(proto, "http"))) {
     499           0 :             av_dict_set(&options, "method", "DELETE", 0);
     500           0 :             if ((ret = vs->avf->io_open(vs->avf, &out, path, AVIO_FLAG_WRITE, &options)) < 0)
     501           0 :                 goto fail;
     502           0 :             ff_format_io_close(vs->avf, &out);
     503           0 :         } else if (unlink(path) < 0) {
     504           0 :             av_log(hls, AV_LOG_ERROR, "failed to delete old segment %s: %s\n",
     505           0 :                                      path, strerror(errno));
     506             :         }
     507             : 
     508           0 :         if ((segment->sub_filename[0] != '\0')) {
     509           0 :             sub_path_size = strlen(segment->sub_filename) + 1 + (dirname ? strlen(dirname) : 0);
     510           0 :             sub_path = av_malloc(sub_path_size);
     511           0 :             if (!sub_path) {
     512           0 :                 ret = AVERROR(ENOMEM);
     513           0 :                 goto fail;
     514             :             }
     515             : 
     516           0 :             av_strlcpy(sub_path, dirname, sub_path_size);
     517           0 :             av_strlcat(sub_path, segment->sub_filename, sub_path_size);
     518             : 
     519           0 :             if (hls->method || (proto && !av_strcasecmp(proto, "http"))) {
     520           0 :                 av_dict_set(&options, "method", "DELETE", 0);
     521           0 :                 if ((ret = vs->avf->io_open(vs->avf, &out, sub_path, AVIO_FLAG_WRITE, &options)) < 0) {
     522           0 :                     av_free(sub_path);
     523           0 :                     goto fail;
     524             :                 }
     525           0 :                 ff_format_io_close(vs->avf, &out);
     526           0 :             } else if (unlink(sub_path) < 0) {
     527           0 :                 av_log(hls, AV_LOG_ERROR, "failed to delete old segment %s: %s\n",
     528           0 :                                          sub_path, strerror(errno));
     529             :             }
     530           0 :             av_free(sub_path);
     531             :         }
     532           0 :         av_freep(&path);
     533           0 :         previous_segment = segment;
     534           0 :         segment = previous_segment->next;
     535           0 :         av_free(previous_segment);
     536             :     }
     537             : 
     538           0 : fail:
     539           0 :     av_free(path);
     540           0 :     av_free(dirname);
     541             : 
     542           0 :     return ret;
     543             : }
     544             : 
     545           0 : static int randomize(uint8_t *buf, int len)
     546             : {
     547             : #if CONFIG_GCRYPT
     548             :     gcry_randomize(buf, len, GCRY_VERY_STRONG_RANDOM);
     549             :     return 0;
     550             : #elif CONFIG_OPENSSL
     551             :     if (RAND_bytes(buf, len))
     552             :         return 0;
     553             : #else
     554           0 :     return AVERROR(ENOSYS);
     555             : #endif
     556             :     return AVERROR(EINVAL);
     557             : }
     558             : 
     559           0 : static int do_encrypt(AVFormatContext *s, VariantStream *vs)
     560             : {
     561           0 :     HLSContext *hls = s->priv_data;
     562             :     int ret;
     563             :     int len;
     564             :     AVIOContext *pb;
     565             :     uint8_t key[KEYSIZE];
     566             : 
     567           0 :     len = strlen(s->url) + 4 + 1;
     568           0 :     hls->key_basename = av_mallocz(len);
     569           0 :     if (!hls->key_basename)
     570           0 :         return AVERROR(ENOMEM);
     571             : 
     572           0 :     av_strlcpy(hls->key_basename, s->url, len);
     573           0 :     av_strlcat(hls->key_basename, ".key", len);
     574             : 
     575           0 :     if (hls->key_url) {
     576           0 :         av_strlcpy(hls->key_file, hls->key_url, sizeof(hls->key_file));
     577           0 :         av_strlcpy(hls->key_uri, hls->key_url, sizeof(hls->key_uri));
     578             :     } else {
     579           0 :         av_strlcpy(hls->key_file, hls->key_basename, sizeof(hls->key_file));
     580           0 :         av_strlcpy(hls->key_uri, hls->key_basename, sizeof(hls->key_uri));
     581             :     }
     582             : 
     583           0 :     if (!*hls->iv_string) {
     584           0 :         uint8_t iv[16] = { 0 };
     585             :         char buf[33];
     586             : 
     587           0 :         if (!hls->iv) {
     588           0 :             AV_WB64(iv + 8, vs->sequence);
     589             :         } else {
     590           0 :             memcpy(iv, hls->iv, sizeof(iv));
     591             :         }
     592           0 :         ff_data_to_hex(buf, iv, sizeof(iv), 0);
     593           0 :         buf[32] = '\0';
     594           0 :         memcpy(hls->iv_string, buf, sizeof(hls->iv_string));
     595             :     }
     596             : 
     597           0 :     if (!*hls->key_uri) {
     598           0 :         av_log(hls, AV_LOG_ERROR, "no key URI specified in key info file\n");
     599           0 :         return AVERROR(EINVAL);
     600             :     }
     601             : 
     602           0 :     if (!*hls->key_file) {
     603           0 :         av_log(hls, AV_LOG_ERROR, "no key file specified in key info file\n");
     604           0 :         return AVERROR(EINVAL);
     605             :     }
     606             : 
     607           0 :     if (!*hls->key_string) {
     608           0 :         if (!hls->key) {
     609           0 :             if ((ret = randomize(key, sizeof(key))) < 0) {
     610           0 :                 av_log(s, AV_LOG_ERROR, "Cannot generate a strong random key\n");
     611           0 :                 return ret;
     612             :             }
     613             :         } else {
     614           0 :             memcpy(key, hls->key, sizeof(key));
     615             :         }
     616             : 
     617           0 :         ff_data_to_hex(hls->key_string, key, sizeof(key), 0);
     618           0 :         if ((ret = s->io_open(s, &pb, hls->key_file, AVIO_FLAG_WRITE, NULL)) < 0)
     619           0 :             return ret;
     620           0 :         avio_seek(pb, 0, SEEK_CUR);
     621           0 :         avio_write(pb, key, KEYSIZE);
     622           0 :         avio_close(pb);
     623             :     }
     624           0 :     return 0;
     625             : }
     626             : 
     627             : 
     628           0 : static int hls_encryption_start(AVFormatContext *s)
     629             : {
     630           0 :     HLSContext *hls = s->priv_data;
     631             :     int ret;
     632             :     AVIOContext *pb;
     633             :     uint8_t key[KEYSIZE];
     634             : 
     635           0 :     if ((ret = s->io_open(s, &pb, hls->key_info_file, AVIO_FLAG_READ, NULL)) < 0) {
     636           0 :         av_log(hls, AV_LOG_ERROR,
     637             :                 "error opening key info file %s\n", hls->key_info_file);
     638           0 :         return ret;
     639             :     }
     640             : 
     641           0 :     ff_get_line(pb, hls->key_uri, sizeof(hls->key_uri));
     642           0 :     hls->key_uri[strcspn(hls->key_uri, "\r\n")] = '\0';
     643             : 
     644           0 :     ff_get_line(pb, hls->key_file, sizeof(hls->key_file));
     645           0 :     hls->key_file[strcspn(hls->key_file, "\r\n")] = '\0';
     646             : 
     647           0 :     ff_get_line(pb, hls->iv_string, sizeof(hls->iv_string));
     648           0 :     hls->iv_string[strcspn(hls->iv_string, "\r\n")] = '\0';
     649             : 
     650           0 :     ff_format_io_close(s, &pb);
     651             : 
     652           0 :     if (!*hls->key_uri) {
     653           0 :         av_log(hls, AV_LOG_ERROR, "no key URI specified in key info file\n");
     654           0 :         return AVERROR(EINVAL);
     655             :     }
     656             : 
     657           0 :     if (!*hls->key_file) {
     658           0 :         av_log(hls, AV_LOG_ERROR, "no key file specified in key info file\n");
     659           0 :         return AVERROR(EINVAL);
     660             :     }
     661             : 
     662           0 :     if ((ret = s->io_open(s, &pb, hls->key_file, AVIO_FLAG_READ, NULL)) < 0) {
     663           0 :         av_log(hls, AV_LOG_ERROR, "error opening key file %s\n", hls->key_file);
     664           0 :         return ret;
     665             :     }
     666             : 
     667           0 :     ret = avio_read(pb, key, sizeof(key));
     668           0 :     ff_format_io_close(s, &pb);
     669           0 :     if (ret != sizeof(key)) {
     670           0 :         av_log(hls, AV_LOG_ERROR, "error reading key file %s\n", hls->key_file);
     671           0 :         if (ret >= 0 || ret == AVERROR_EOF)
     672           0 :             ret = AVERROR(EINVAL);
     673           0 :         return ret;
     674             :     }
     675           0 :     ff_data_to_hex(hls->key_string, key, sizeof(key), 0);
     676             : 
     677           0 :     return 0;
     678             : }
     679             : 
     680          11 : static int read_chomp_line(AVIOContext *s, char *buf, int maxlen)
     681             : {
     682          11 :     int len = ff_get_line(s, buf, maxlen);
     683          32 :     while (len > 0 && av_isspace(buf[len - 1]))
     684          10 :         buf[--len] = '\0';
     685          11 :     return len;
     686             : }
     687             : 
     688           1 : static int hls_mux_init(AVFormatContext *s, VariantStream *vs)
     689             : {
     690           1 :     AVDictionary *options = NULL;
     691           1 :     HLSContext *hls = s->priv_data;
     692             :     AVFormatContext *oc;
     693           1 :     AVFormatContext *vtt_oc = NULL;
     694           1 :     int byterange_mode = (hls->flags & HLS_SINGLE_FILE) || (hls->max_seg_size > 0);
     695             :     int i, ret;
     696             : 
     697           1 :     ret = avformat_alloc_output_context2(&vs->avf, vs->oformat, NULL, NULL);
     698           1 :     if (ret < 0)
     699           0 :         return ret;
     700           1 :     oc = vs->avf;
     701             : 
     702           1 :     oc->url                = av_strdup("");
     703           1 :     if (!oc->url)
     704           0 :         return AVERROR(ENOMEM);
     705             : 
     706           1 :     oc->oformat            = vs->oformat;
     707           1 :     oc->interrupt_callback = s->interrupt_callback;
     708           1 :     oc->max_delay          = s->max_delay;
     709           1 :     oc->opaque             = s->opaque;
     710           1 :     oc->io_open            = s->io_open;
     711           1 :     oc->io_close           = s->io_close;
     712           1 :     av_dict_copy(&oc->metadata, s->metadata, 0);
     713             : 
     714           1 :     if(vs->vtt_oformat) {
     715           0 :         ret = avformat_alloc_output_context2(&vs->vtt_avf, vs->vtt_oformat, NULL, NULL);
     716           0 :         if (ret < 0)
     717           0 :             return ret;
     718           0 :         vtt_oc          = vs->vtt_avf;
     719           0 :         vtt_oc->oformat = vs->vtt_oformat;
     720           0 :         av_dict_copy(&vtt_oc->metadata, s->metadata, 0);
     721             :     }
     722             : 
     723           2 :     for (i = 0; i < vs->nb_streams; i++) {
     724             :         AVStream *st;
     725             :         AVFormatContext *loc;
     726           1 :         if (vs->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE)
     727           0 :             loc = vtt_oc;
     728             :         else
     729           1 :             loc = oc;
     730             : 
     731           1 :         if (!(st = avformat_new_stream(loc, NULL)))
     732           0 :             return AVERROR(ENOMEM);
     733           1 :         avcodec_parameters_copy(st->codecpar, vs->streams[i]->codecpar);
     734           1 :         if (!oc->oformat->codec_tag ||
     735           0 :             av_codec_get_id (oc->oformat->codec_tag, vs->streams[i]->codecpar->codec_tag) == st->codecpar->codec_id ||
     736           0 :             av_codec_get_tag(oc->oformat->codec_tag, vs->streams[i]->codecpar->codec_id) <= 0) {
     737           1 :             st->codecpar->codec_tag = vs->streams[i]->codecpar->codec_tag;
     738             :         } else {
     739           0 :             st->codecpar->codec_tag = 0;
     740             :         }
     741             : 
     742           1 :         st->sample_aspect_ratio = vs->streams[i]->sample_aspect_ratio;
     743           1 :         st->time_base = vs->streams[i]->time_base;
     744           1 :         av_dict_copy(&st->metadata, vs->streams[i]->metadata, 0);
     745             :     }
     746             : 
     747           1 :     vs->packets_written = 1;
     748           1 :     vs->start_pos = 0;
     749           1 :     vs->new_start = 1;
     750           1 :     vs->fmp4_init_mode = 0;
     751             : 
     752           1 :     if (hls->segment_type == SEGMENT_TYPE_FMP4) {
     753           0 :         if (hls->max_seg_size > 0) {
     754           0 :             av_log(s, AV_LOG_WARNING, "Multi-file byterange mode is currently unsupported in the HLS muxer.\n");
     755           0 :             return AVERROR_PATCHWELCOME;
     756             :         }
     757             : 
     758           0 :         vs->packets_written = 0;
     759           0 :         vs->init_range_length = 0;
     760           0 :         vs->fmp4_init_mode = !byterange_mode;
     761           0 :         set_http_options(s, &options, hls);
     762           0 :         if ((ret = avio_open_dyn_buf(&oc->pb)) < 0)
     763           0 :             return ret;
     764             : 
     765           0 :         ret = hlsenc_io_open(s, &vs->out, vs->base_output_dirname, &options);
     766           0 :         av_dict_free(&options);
     767           0 :         if (ret < 0) {
     768           0 :             av_log(s, AV_LOG_ERROR, "Failed to open segment '%s'\n", vs->fmp4_init_filename);
     769           0 :             return ret;
     770             :         }
     771             : 
     772           0 :         if (hls->format_options_str) {
     773           0 :             ret = av_dict_parse_string(&hls->format_options, hls->format_options_str, "=", ":", 0);
     774           0 :             if (ret < 0) {
     775           0 :                 av_log(s, AV_LOG_ERROR, "Could not parse format options list '%s'\n",
     776             :                        hls->format_options_str);
     777           0 :                 return ret;
     778             :             }
     779             :         }
     780             : 
     781           0 :         av_dict_copy(&options, hls->format_options, 0);
     782           0 :         av_dict_set(&options, "fflags", "-autobsf", 0);
     783           0 :         av_dict_set(&options, "movflags", "frag_custom+dash+delay_moov", 0);
     784           0 :         ret = avformat_init_output(oc, &options);
     785           0 :         if (ret < 0)
     786           0 :             return ret;
     787           0 :         if (av_dict_count(options)) {
     788           0 :             av_log(s, AV_LOG_ERROR, "Some of the provided format options in '%s' are not recognized\n", hls->format_options_str);
     789           0 :             av_dict_free(&options);
     790           0 :             return AVERROR(EINVAL);
     791             :         }
     792           0 :         avio_flush(oc->pb);
     793           0 :         av_dict_free(&options);
     794             :     }
     795           1 :     return 0;
     796             : }
     797             : 
     798           8 : static HLSSegment *find_segment_by_filename(HLSSegment *segment, const char *filename)
     799             : {
     800          22 :     while (segment) {
     801           6 :         if (!av_strcasecmp(segment->filename,filename))
     802           0 :             return segment;
     803           6 :         segment = segment->next;
     804             :     }
     805           8 :     return (HLSSegment *) NULL;
     806             : }
     807             : 
     808           4 : static int sls_flags_filename_process(struct AVFormatContext *s, HLSContext *hls,
     809             :                                       VariantStream *vs, HLSSegment *en,
     810             :                                       double duration, int64_t pos, int64_t size)
     811             : {
     812           4 :     if ((hls->flags & (HLS_SECOND_LEVEL_SEGMENT_SIZE | HLS_SECOND_LEVEL_SEGMENT_DURATION)) &&
     813           0 :         strlen(vs->current_segment_final_filename_fmt)) {
     814           0 :         char * new_url = av_strdup(vs->current_segment_final_filename_fmt);
     815           0 :         if (!new_url) {
     816           0 :             av_free(en);
     817           0 :             return AVERROR(ENOMEM);
     818             :         }
     819           0 :         ff_format_set_url(vs->avf, new_url);
     820           0 :         if (hls->flags & HLS_SECOND_LEVEL_SEGMENT_SIZE) {
     821           0 :             char *filename = NULL;
     822           0 :             if (replace_int_data_in_filename(&filename, vs->avf->url, 's', pos + size) < 1) {
     823           0 :                 av_log(hls, AV_LOG_ERROR,
     824             :                        "Invalid second level segment filename template '%s', "
     825             :                         "you can try to remove second_level_segment_size flag\n",
     826           0 :                        vs->avf->url);
     827           0 :                 av_free(filename);
     828           0 :                 av_free(en);
     829           0 :                 return AVERROR(EINVAL);
     830             :             }
     831           0 :             ff_format_set_url(vs->avf, filename);
     832             :         }
     833           0 :         if (hls->flags & HLS_SECOND_LEVEL_SEGMENT_DURATION) {
     834           0 :             char *filename = NULL;
     835           0 :             if (replace_int_data_in_filename(&filename, vs->avf->url,
     836           0 :                 't',  (int64_t)round(duration * HLS_MICROSECOND_UNIT)) < 1) {
     837           0 :                 av_log(hls, AV_LOG_ERROR,
     838             :                        "Invalid second level segment filename template '%s', "
     839             :                         "you can try to remove second_level_segment_time flag\n",
     840           0 :                        vs->avf->url);
     841           0 :                 av_free(filename);
     842           0 :                 av_free(en);
     843           0 :                 return AVERROR(EINVAL);
     844             :             }
     845           0 :             ff_format_set_url(vs->avf, filename);
     846             :         }
     847             :     }
     848           4 :     return 0;
     849             : }
     850             : 
     851           1 : static int sls_flag_check_duration_size_index(HLSContext *hls)
     852             : {
     853           1 :     int ret = 0;
     854             : 
     855           1 :     if (hls->flags & HLS_SECOND_LEVEL_SEGMENT_DURATION) {
     856           0 :          av_log(hls, AV_LOG_ERROR,
     857             :                 "second_level_segment_duration hls_flag requires use_localtime to be true\n");
     858           0 :          ret = AVERROR(EINVAL);
     859             :     }
     860           1 :     if (hls->flags & HLS_SECOND_LEVEL_SEGMENT_SIZE) {
     861           0 :          av_log(hls, AV_LOG_ERROR,
     862             :                 "second_level_segment_size hls_flag requires use_localtime to be true\n");
     863           0 :          ret = AVERROR(EINVAL);
     864             :     }
     865           1 :     if (hls->flags & HLS_SECOND_LEVEL_SEGMENT_INDEX) {
     866           0 :         av_log(hls, AV_LOG_ERROR,
     867             :                "second_level_segment_index hls_flag requires use_localtime to be true\n");
     868           0 :         ret = AVERROR(EINVAL);
     869             :     }
     870             : 
     871           1 :     return ret;
     872             : }
     873             : 
     874           0 : static int sls_flag_check_duration_size(HLSContext *hls, VariantStream *vs)
     875             : {
     876           0 :     const char *proto = avio_find_protocol_name(vs->basename);
     877           0 :     int segment_renaming_ok = proto && !strcmp(proto, "file");
     878           0 :     int ret = 0;
     879             : 
     880           0 :     if ((hls->flags & HLS_SECOND_LEVEL_SEGMENT_DURATION) && !segment_renaming_ok) {
     881           0 :          av_log(hls, AV_LOG_ERROR,
     882             :                 "second_level_segment_duration hls_flag works only with file protocol segment names\n");
     883           0 :          ret = AVERROR(EINVAL);
     884             :     }
     885           0 :     if ((hls->flags & HLS_SECOND_LEVEL_SEGMENT_SIZE) && !segment_renaming_ok) {
     886           0 :          av_log(hls, AV_LOG_ERROR,
     887             :                 "second_level_segment_size hls_flag works only with file protocol segment names\n");
     888           0 :          ret = AVERROR(EINVAL);
     889             :     }
     890             : 
     891           0 :     return ret;
     892             : }
     893             : 
     894           2 : static void sls_flag_file_rename(HLSContext *hls, VariantStream *vs, char *old_filename) {
     895           2 :     if ((hls->flags & (HLS_SECOND_LEVEL_SEGMENT_SIZE | HLS_SECOND_LEVEL_SEGMENT_DURATION)) &&
     896           0 :         strlen(vs->current_segment_final_filename_fmt)) {
     897           0 :         ff_rename(old_filename, vs->avf->url, hls);
     898             :     }
     899           2 : }
     900             : 
     901           0 : static int sls_flag_use_localtime_filename(AVFormatContext *oc, HLSContext *c, VariantStream *vs)
     902             : {
     903           0 :     if (c->flags & HLS_SECOND_LEVEL_SEGMENT_INDEX) {
     904           0 :         char *filename = NULL;
     905           0 :         if (replace_int_data_in_filename(&filename,
     906             : #if FF_API_HLS_WRAP
     907           0 :             oc->url, 'd', c->wrap ? vs->sequence % c->wrap : vs->sequence) < 1) {
     908             : #else
     909             :             oc->url, 'd', vs->sequence) < 1) {
     910             : #endif
     911           0 :             av_log(c, AV_LOG_ERROR, "Invalid second level segment filename template '%s', "
     912             :                     "you can try to remove second_level_segment_index flag\n",
     913             :                    oc->url);
     914           0 :             av_free(filename);
     915           0 :             return AVERROR(EINVAL);
     916             :         }
     917           0 :         ff_format_set_url(oc, filename);
     918             :     }
     919           0 :     if (c->flags & (HLS_SECOND_LEVEL_SEGMENT_SIZE | HLS_SECOND_LEVEL_SEGMENT_DURATION)) {
     920           0 :         av_strlcpy(vs->current_segment_final_filename_fmt, oc->url,
     921             :                    sizeof(vs->current_segment_final_filename_fmt));
     922           0 :         if (c->flags & HLS_SECOND_LEVEL_SEGMENT_SIZE) {
     923           0 :             char *filename = NULL;
     924           0 :             if (replace_int_data_in_filename(&filename, oc->url, 's', 0) < 1) {
     925           0 :                 av_log(c, AV_LOG_ERROR, "Invalid second level segment filename template '%s', "
     926             :                         "you can try to remove second_level_segment_size flag\n",
     927             :                        oc->url);
     928           0 :                 av_free(filename);
     929           0 :                 return AVERROR(EINVAL);
     930             :             }
     931           0 :             ff_format_set_url(oc, filename);
     932             :         }
     933           0 :         if (c->flags & HLS_SECOND_LEVEL_SEGMENT_DURATION) {
     934           0 :             char *filename = NULL;
     935           0 :             if (replace_int_data_in_filename(&filename, oc->url, 't', 0) < 1) {
     936           0 :                 av_log(c, AV_LOG_ERROR, "Invalid second level segment filename template '%s', "
     937             :                         "you can try to remove second_level_segment_time flag\n",
     938             :                        oc->url);
     939           0 :                 av_free(filename);
     940           0 :                 return AVERROR(EINVAL);
     941             :             }
     942           0 :             ff_format_set_url(oc, filename);
     943             :         }
     944             :     }
     945           0 :     return 0;
     946             : }
     947             : 
     948             : /* Create a new segment and append it to the segment list */
     949           4 : static int hls_append_segment(struct AVFormatContext *s, HLSContext *hls,
     950             :                               VariantStream *vs, double duration, int64_t pos,
     951             :                               int64_t size)
     952             : {
     953           4 :     HLSSegment *en = av_malloc(sizeof(*en));
     954             :     const char  *filename;
     955           4 :     int byterange_mode = (hls->flags & HLS_SINGLE_FILE) || (hls->max_seg_size > 0);
     956             :     int ret;
     957             : 
     958           4 :     if (!en)
     959           0 :         return AVERROR(ENOMEM);
     960             : 
     961           4 :     ret = sls_flags_filename_process(s, hls, vs, en, duration, pos, size);
     962           4 :     if (ret < 0) {
     963           0 :         return ret;
     964             :     }
     965             : 
     966           4 :     filename = av_basename(vs->avf->url);
     967             : 
     968           4 :     if (hls->use_localtime_mkdir) {
     969           0 :         filename = vs->avf->url;
     970             :     }
     971           4 :     if ((find_segment_by_filename(vs->segments, filename) || find_segment_by_filename(vs->old_segments, filename))
     972           0 :         && !byterange_mode) {
     973           0 :         av_log(hls, AV_LOG_WARNING, "Duplicated segment filename detected: %s\n", filename);
     974             :     }
     975           4 :     av_strlcpy(en->filename, filename, sizeof(en->filename));
     976             : 
     977           4 :     if(vs->has_subtitle)
     978           0 :         av_strlcpy(en->sub_filename, av_basename(vs->vtt_avf->url), sizeof(en->sub_filename));
     979             :     else
     980           4 :         en->sub_filename[0] = '\0';
     981             : 
     982           4 :     en->duration = duration;
     983           4 :     en->pos      = pos;
     984           4 :     en->size     = size;
     985           4 :     en->next     = NULL;
     986           4 :     en->discont  = 0;
     987             : 
     988           4 :     if (vs->discontinuity) {
     989           1 :         en->discont = 1;
     990           1 :         vs->discontinuity = 0;
     991             :     }
     992             : 
     993           4 :     if (hls->key_info_file || hls->encrypt) {
     994           0 :         av_strlcpy(en->key_uri, hls->key_uri, sizeof(en->key_uri));
     995           0 :         av_strlcpy(en->iv_string, hls->iv_string, sizeof(en->iv_string));
     996             :     }
     997             : 
     998           4 :     if (!vs->segments)
     999           1 :         vs->segments = en;
    1000             :     else
    1001           3 :         vs->last_segment->next = en;
    1002             : 
    1003           4 :     vs->last_segment = en;
    1004             : 
    1005             :     // EVENT or VOD playlists imply sliding window cannot be used
    1006           4 :     if (hls->pl_type != PLAYLIST_TYPE_NONE)
    1007           0 :         hls->max_nb_segments = 0;
    1008             : 
    1009           4 :     if (hls->max_nb_segments && vs->nb_entries >= hls->max_nb_segments) {
    1010           0 :         en = vs->segments;
    1011           0 :         vs->initial_prog_date_time += en->duration;
    1012           0 :         vs->segments = en->next;
    1013           0 :         if (en && hls->flags & HLS_DELETE_SEGMENTS &&
    1014             : #if FF_API_HLS_WRAP
    1015           0 :                 !(hls->flags & HLS_SINGLE_FILE || hls->wrap)) {
    1016             : #else
    1017             :                 !(hls->flags & HLS_SINGLE_FILE)) {
    1018             : #endif
    1019           0 :             en->next = vs->old_segments;
    1020           0 :             vs->old_segments = en;
    1021           0 :             if ((ret = hls_delete_old_segments(s, hls, vs)) < 0)
    1022           0 :                 return ret;
    1023             :         } else
    1024           0 :             av_free(en);
    1025             :     } else
    1026           4 :         vs->nb_entries++;
    1027             : 
    1028           4 :     if (hls->max_seg_size > 0) {
    1029           0 :         return 0;
    1030             :     }
    1031           4 :     vs->sequence++;
    1032             : 
    1033           4 :     return 0;
    1034             : }
    1035             : 
    1036           1 : static int parse_playlist(AVFormatContext *s, const char *url, VariantStream *vs)
    1037             : {
    1038           1 :     HLSContext *hls = s->priv_data;
    1039             :     AVIOContext *in;
    1040           1 :     int ret = 0, is_segment = 0;
    1041             :     int64_t new_start_pos;
    1042             :     char line[1024];
    1043             :     const char *ptr;
    1044             :     const char *end;
    1045             : 
    1046           1 :     if ((ret = ffio_open_whitelist(&in, url, AVIO_FLAG_READ,
    1047           1 :                                    &s->interrupt_callback, NULL,
    1048           1 :                                    s->protocol_whitelist, s->protocol_blacklist)) < 0)
    1049           0 :         return ret;
    1050             : 
    1051           1 :     read_chomp_line(in, line, sizeof(line));
    1052           1 :     if (strcmp(line, "#EXTM3U")) {
    1053           0 :         ret = AVERROR_INVALIDDATA;
    1054           0 :         goto fail;
    1055             :     }
    1056             : 
    1057           1 :     vs->discontinuity = 0;
    1058          12 :     while (!avio_feof(in)) {
    1059          10 :         read_chomp_line(in, line, sizeof(line));
    1060          10 :         if (av_strstart(line, "#EXT-X-MEDIA-SEQUENCE:", &ptr)) {
    1061           1 :             int64_t tmp_sequence = strtoll(ptr, NULL, 10);
    1062           1 :             if (tmp_sequence < vs->sequence)
    1063           0 :               av_log(hls, AV_LOG_VERBOSE,
    1064             :                      "Found playlist sequence number was smaller """
    1065             :                      "than specified start sequence number: %"PRId64" < %"PRId64", "
    1066             :                      "omitting\n", tmp_sequence, hls->start_sequence);
    1067             :             else {
    1068           1 :               av_log(hls, AV_LOG_DEBUG, "Found playlist sequence number: %"PRId64"\n", tmp_sequence);
    1069           1 :               vs->sequence = tmp_sequence;
    1070             :             }
    1071           9 :         } else if (av_strstart(line, "#EXT-X-DISCONTINUITY", &ptr)) {
    1072           0 :             is_segment = 1;
    1073           0 :             vs->discontinuity = 1;
    1074           9 :         } else if (av_strstart(line, "#EXTINF:", &ptr)) {
    1075           2 :             is_segment = 1;
    1076           2 :             vs->duration = atof(ptr);
    1077           7 :         } else if (av_stristart(line, "#EXT-X-KEY:", &ptr)) {
    1078           0 :             ptr = av_stristr(line, "URI=\"");
    1079           0 :             if (ptr) {
    1080           0 :                 ptr += strlen("URI=\"");
    1081           0 :                 end = av_stristr(ptr, ",");
    1082           0 :                 if (end) {
    1083           0 :                     av_strlcpy(hls->key_uri, ptr, end - ptr);
    1084             :                 } else {
    1085           0 :                     av_strlcpy(hls->key_uri, ptr, sizeof(hls->key_uri));
    1086             :                 }
    1087             :             }
    1088             : 
    1089           0 :             ptr = av_stristr(line, "IV=0x");
    1090           0 :             if (ptr) {
    1091           0 :                 ptr += strlen("IV=0x");
    1092           0 :                 end = av_stristr(ptr, ",");
    1093           0 :                 if (end) {
    1094           0 :                     av_strlcpy(hls->iv_string, ptr, end - ptr);
    1095             :                 } else {
    1096           0 :                     av_strlcpy(hls->iv_string, ptr, sizeof(hls->iv_string));
    1097             :                 }
    1098             :             }
    1099             : 
    1100           7 :         } else if (av_strstart(line, "#", NULL)) {
    1101           4 :             continue;
    1102           3 :         } else if (line[0]) {
    1103           2 :             if (is_segment) {
    1104           2 :                 char *new_file = av_strdup(line);
    1105           2 :                 if (!new_file) {
    1106           0 :                     ret = AVERROR(ENOMEM);
    1107           0 :                     goto fail;
    1108             :                 }
    1109           2 :                 ff_format_set_url(vs->avf, new_file);
    1110           2 :                 is_segment = 0;
    1111           2 :                 new_start_pos = avio_tell(vs->avf->pb);
    1112           2 :                 vs->size = new_start_pos - vs->start_pos;
    1113           2 :                 ret = hls_append_segment(s, hls, vs, vs->duration, vs->start_pos, vs->size);
    1114           2 :                 if (ret < 0)
    1115           0 :                     goto fail;
    1116           2 :                 vs->start_pos = new_start_pos;
    1117             :             }
    1118             :         }
    1119             :     }
    1120             : 
    1121           1 : fail:
    1122           1 :     avio_close(in);
    1123           1 :     return ret;
    1124             : }
    1125             : 
    1126           2 : static void hls_free_segments(HLSSegment *p)
    1127             : {
    1128             :     HLSSegment *en;
    1129             : 
    1130           8 :     while(p) {
    1131           4 :         en = p;
    1132           4 :         p = p->next;
    1133           4 :         av_free(en);
    1134             :     }
    1135           2 : }
    1136             : 
    1137           0 : static int hls_rename_temp_file(AVFormatContext *s, AVFormatContext *oc)
    1138             : {
    1139           0 :     size_t len = strlen(oc->url);
    1140           0 :     char *final_filename = av_strdup(oc->url);
    1141             :     int ret;
    1142             : 
    1143           0 :     if (!final_filename)
    1144           0 :         return AVERROR(ENOMEM);
    1145           0 :     final_filename[len-4] = '\0';
    1146           0 :     ret = ff_rename(oc->url, final_filename, s);
    1147           0 :     oc->url[len-4] = '\0';
    1148           0 :     av_freep(&final_filename);
    1149           0 :     return ret;
    1150             : }
    1151             : 
    1152           0 : static int get_relative_url(const char *master_url, const char *media_url,
    1153             :                             char *rel_url, int rel_url_buf_size)
    1154             : {
    1155           0 :     char *p = NULL;
    1156           0 :     int base_len = -1;
    1157           0 :     p = strrchr(master_url, '/') ? strrchr(master_url, '/') :\
    1158             :             strrchr(master_url, '\\');
    1159           0 :     if (p) {
    1160           0 :         base_len = FFABS(p - master_url);
    1161           0 :         if (av_strncasecmp(master_url, media_url, base_len)) {
    1162           0 :             av_log(NULL, AV_LOG_WARNING, "Unable to find relative url\n");
    1163           0 :             return AVERROR(EINVAL);
    1164             :         }
    1165             :     }
    1166           0 :     av_strlcpy(rel_url, &(media_url[base_len + 1]), rel_url_buf_size);
    1167           0 :     return 0;
    1168             : }
    1169             : 
    1170           0 : static int create_master_playlist(AVFormatContext *s,
    1171             :                                   VariantStream * const input_vs)
    1172             : {
    1173           0 :     HLSContext *hls = s->priv_data;
    1174             :     VariantStream *vs, *temp_vs;
    1175             :     AVStream *vid_st, *aud_st;
    1176           0 :     AVDictionary *options = NULL;
    1177             :     unsigned int i, j;
    1178             :     int m3u8_name_size, ret, bandwidth;
    1179             :     char *m3u8_rel_name, *ccgroup;
    1180             :     ClosedCaptionsStream *ccs;
    1181             : 
    1182           0 :     input_vs->m3u8_created = 1;
    1183           0 :     if (!hls->master_m3u8_created) {
    1184             :         /* For the first time, wait until all the media playlists are created */
    1185           0 :         for (i = 0; i < hls->nb_varstreams; i++)
    1186           0 :             if (!hls->var_streams[i].m3u8_created)
    1187           0 :                 return 0;
    1188             :     } else {
    1189             :          /* Keep publishing the master playlist at the configured rate */
    1190           0 :         if (&hls->var_streams[0] != input_vs || !hls->master_publish_rate ||
    1191           0 :             input_vs->number % hls->master_publish_rate)
    1192           0 :             return 0;
    1193             :     }
    1194             : 
    1195           0 :     set_http_options(s, &options, hls);
    1196             : 
    1197           0 :     ret = hlsenc_io_open(s, &hls->m3u8_out, hls->master_m3u8_url, &options);
    1198           0 :     av_dict_free(&options);
    1199           0 :     if (ret < 0) {
    1200           0 :         av_log(NULL, AV_LOG_ERROR, "Failed to open master play list file '%s'\n",
    1201             :                 hls->master_m3u8_url);
    1202           0 :         goto fail;
    1203             :     }
    1204             : 
    1205           0 :     ff_hls_write_playlist_version(hls->m3u8_out, hls->version);
    1206             : 
    1207           0 :     for (i = 0; i < hls->nb_ccstreams; i++) {
    1208           0 :         ccs = &(hls->cc_streams[i]);
    1209           0 :         avio_printf(hls->m3u8_out, "#EXT-X-MEDIA:TYPE=CLOSED-CAPTIONS");
    1210           0 :         avio_printf(hls->m3u8_out, ",GROUP-ID=\"%s\"", ccs->ccgroup);
    1211           0 :         avio_printf(hls->m3u8_out, ",NAME=\"%s\"", ccs->instreamid);
    1212           0 :         if (ccs->language)
    1213           0 :             avio_printf(hls->m3u8_out, ",LANGUAGE=\"%s\"", ccs->language);
    1214           0 :         avio_printf(hls->m3u8_out, ",INSTREAM-ID=\"%s\"\n", ccs->instreamid);
    1215             :     }
    1216             : 
    1217             :     /* For audio only variant streams add #EXT-X-MEDIA tag with attributes*/
    1218           0 :     for (i = 0; i < hls->nb_varstreams; i++) {
    1219           0 :         vs = &(hls->var_streams[i]);
    1220             : 
    1221           0 :         if (vs->has_video || vs->has_subtitle || !vs->agroup)
    1222           0 :             continue;
    1223             : 
    1224           0 :         m3u8_name_size = strlen(vs->m3u8_name) + 1;
    1225           0 :         m3u8_rel_name = av_malloc(m3u8_name_size);
    1226           0 :         if (!m3u8_rel_name) {
    1227           0 :             ret = AVERROR(ENOMEM);
    1228           0 :             goto fail;
    1229             :         }
    1230           0 :         av_strlcpy(m3u8_rel_name, vs->m3u8_name, m3u8_name_size);
    1231           0 :         ret = get_relative_url(hls->master_m3u8_url, vs->m3u8_name,
    1232             :                                m3u8_rel_name, m3u8_name_size);
    1233           0 :         if (ret < 0) {
    1234           0 :             av_log(s, AV_LOG_ERROR, "Unable to find relative URL\n");
    1235           0 :             goto fail;
    1236             :         }
    1237             : 
    1238           0 :         ff_hls_write_audio_rendition(hls->m3u8_out, vs->agroup, m3u8_rel_name, 0, 1);
    1239             : 
    1240           0 :         av_freep(&m3u8_rel_name);
    1241             :     }
    1242             : 
    1243             :     /* For variant streams with video add #EXT-X-STREAM-INF tag with attributes*/
    1244           0 :     for (i = 0; i < hls->nb_varstreams; i++) {
    1245           0 :         vs = &(hls->var_streams[i]);
    1246             : 
    1247           0 :         m3u8_name_size = strlen(vs->m3u8_name) + 1;
    1248           0 :         m3u8_rel_name = av_malloc(m3u8_name_size);
    1249           0 :         if (!m3u8_rel_name) {
    1250           0 :             ret = AVERROR(ENOMEM);
    1251           0 :             goto fail;
    1252             :         }
    1253           0 :         av_strlcpy(m3u8_rel_name, vs->m3u8_name, m3u8_name_size);
    1254           0 :         ret = get_relative_url(hls->master_m3u8_url, vs->m3u8_name,
    1255             :                                m3u8_rel_name, m3u8_name_size);
    1256           0 :         if (ret < 0) {
    1257           0 :             av_log(NULL, AV_LOG_ERROR, "Unable to find relative URL\n");
    1258           0 :             goto fail;
    1259             :         }
    1260             : 
    1261           0 :         vid_st = NULL;
    1262           0 :         aud_st = NULL;
    1263           0 :         for (j = 0; j < vs->nb_streams; j++) {
    1264           0 :             if (vs->streams[j]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
    1265           0 :                 vid_st = vs->streams[j];
    1266           0 :             else if (vs->streams[j]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
    1267           0 :                 aud_st = vs->streams[j];
    1268             :         }
    1269             : 
    1270           0 :         if (!vid_st && !aud_st) {
    1271           0 :             av_log(NULL, AV_LOG_WARNING, "Media stream not found\n");
    1272           0 :             continue;
    1273             :         }
    1274             : 
    1275             :         /**
    1276             :          * Traverse through the list of audio only rendition streams and find
    1277             :          * the rendition which has highest bitrate in the same audio group
    1278             :          */
    1279           0 :         if (vs->agroup) {
    1280           0 :             for (j = 0; j < hls->nb_varstreams; j++) {
    1281           0 :                 temp_vs = &(hls->var_streams[j]);
    1282           0 :                 if (!temp_vs->has_video && !temp_vs->has_subtitle &&
    1283           0 :                     temp_vs->agroup &&
    1284           0 :                     !av_strcasecmp(temp_vs->agroup, vs->agroup)) {
    1285           0 :                     if (!aud_st)
    1286           0 :                         aud_st = temp_vs->streams[0];
    1287           0 :                     if (temp_vs->streams[0]->codecpar->bit_rate >
    1288           0 :                             aud_st->codecpar->bit_rate)
    1289           0 :                         aud_st = temp_vs->streams[0];
    1290             :                 }
    1291             :             }
    1292             :         }
    1293             : 
    1294           0 :         bandwidth = 0;
    1295           0 :         if (vid_st)
    1296           0 :             bandwidth += vid_st->codecpar->bit_rate;
    1297           0 :         if (aud_st)
    1298           0 :             bandwidth += aud_st->codecpar->bit_rate;
    1299           0 :         bandwidth += bandwidth / 10;
    1300             : 
    1301           0 :         ccgroup = NULL;
    1302           0 :         if (vid_st && vs->ccgroup) {
    1303             :             /* check if this group name is available in the cc map string */
    1304           0 :             for (j = 0; j < hls->nb_ccstreams; j++) {
    1305           0 :                 ccs = &(hls->cc_streams[j]);
    1306           0 :                 if (!av_strcasecmp(ccs->ccgroup, vs->ccgroup)) {
    1307           0 :                     ccgroup = vs->ccgroup;
    1308           0 :                     break;
    1309             :                 }
    1310             :             }
    1311           0 :             if (j == hls->nb_ccstreams)
    1312           0 :                 av_log(NULL, AV_LOG_WARNING, "mapping ccgroup %s not found\n",
    1313             :                         vs->ccgroup);
    1314             :         }
    1315             : 
    1316           0 :         ff_hls_write_stream_info(vid_st, hls->m3u8_out, bandwidth, m3u8_rel_name,
    1317           0 :                 aud_st ? vs->agroup : NULL, vs->codec_attr, ccgroup);
    1318             : 
    1319           0 :         av_freep(&m3u8_rel_name);
    1320             :     }
    1321           0 : fail:
    1322           0 :     if(ret >=0)
    1323           0 :         hls->master_m3u8_created = 1;
    1324           0 :     av_freep(&m3u8_rel_name);
    1325           0 :     hlsenc_io_close(s, &hls->m3u8_out, hls->master_m3u8_url);
    1326           0 :     return ret;
    1327             : }
    1328             : 
    1329           2 : static int hls_window(AVFormatContext *s, int last, VariantStream *vs)
    1330             : {
    1331           2 :     HLSContext *hls = s->priv_data;
    1332             :     HLSSegment *en;
    1333           2 :     int target_duration = 0;
    1334           2 :     int ret = 0;
    1335             :     char temp_filename[1024];
    1336           2 :     int64_t sequence = FFMAX(hls->start_sequence, vs->sequence - vs->nb_entries);
    1337           2 :     const char *proto = avio_find_protocol_name(s->url);
    1338           2 :     int use_rename = proto && !strcmp(proto, "file");
    1339             :     static unsigned warned_non_file;
    1340           2 :     char *key_uri = NULL;
    1341           2 :     char *iv_string = NULL;
    1342           2 :     AVDictionary *options = NULL;
    1343           2 :     double prog_date_time = vs->initial_prog_date_time;
    1344           2 :     double *prog_date_time_p = (hls->flags & HLS_PROGRAM_DATE_TIME) ? &prog_date_time : NULL;
    1345           2 :     int byterange_mode = (hls->flags & HLS_SINGLE_FILE) || (hls->max_seg_size > 0);
    1346             : 
    1347           2 :     hls->version = 3;
    1348           2 :     if (byterange_mode) {
    1349           0 :         hls->version = 4;
    1350           0 :         sequence = 0;
    1351             :     }
    1352             : 
    1353           2 :     if (hls->flags & HLS_INDEPENDENT_SEGMENTS) {
    1354           0 :         hls->version = 6;
    1355             :     }
    1356             : 
    1357           2 :     if (hls->segment_type == SEGMENT_TYPE_FMP4) {
    1358           0 :         hls->version = 7;
    1359             :     }
    1360             : 
    1361           2 :     if (!use_rename && !warned_non_file++)
    1362           0 :         av_log(s, AV_LOG_ERROR, "Cannot use rename on non file protocol, this may lead to races and temporary partial files\n");
    1363             : 
    1364           2 :     set_http_options(s, &options, hls);
    1365           2 :     snprintf(temp_filename, sizeof(temp_filename), use_rename ? "%s.tmp" : "%s", vs->m3u8_name);
    1366           2 :     if ((ret = hlsenc_io_open(s, &hls->m3u8_out, temp_filename, &options)) < 0)
    1367           0 :         goto fail;
    1368             : 
    1369           9 :     for (en = vs->segments; en; en = en->next) {
    1370           7 :         if (target_duration <= en->duration)
    1371           7 :             target_duration = lrint(en->duration);
    1372             :     }
    1373             : 
    1374           2 :     vs->discontinuity_set = 0;
    1375           2 :     ff_hls_write_playlist_header(hls->m3u8_out, hls->version, hls->allowcache,
    1376             :                                  target_duration, sequence, hls->pl_type);
    1377             : 
    1378           2 :     if((hls->flags & HLS_DISCONT_START) && sequence==hls->start_sequence && vs->discontinuity_set==0 ){
    1379           0 :         avio_printf(hls->m3u8_out, "#EXT-X-DISCONTINUITY\n");
    1380           0 :         vs->discontinuity_set = 1;
    1381             :     }
    1382           2 :     if (vs->has_video && (hls->flags & HLS_INDEPENDENT_SEGMENTS)) {
    1383           0 :         avio_printf(hls->m3u8_out, "#EXT-X-INDEPENDENT-SEGMENTS\n");
    1384             :     }
    1385           9 :     for (en = vs->segments; en; en = en->next) {
    1386           7 :         if ((hls->encrypt || hls->key_info_file) && (!key_uri || strcmp(en->key_uri, key_uri) ||
    1387           0 :                                     av_strcasecmp(en->iv_string, iv_string))) {
    1388           0 :             avio_printf(hls->m3u8_out, "#EXT-X-KEY:METHOD=AES-128,URI=\"%s\"", en->key_uri);
    1389           0 :             if (*en->iv_string)
    1390           0 :                 avio_printf(hls->m3u8_out, ",IV=0x%s", en->iv_string);
    1391           0 :             avio_printf(hls->m3u8_out, "\n");
    1392           0 :             key_uri = en->key_uri;
    1393           0 :             iv_string = en->iv_string;
    1394             :         }
    1395             : 
    1396           7 :         if ((hls->segment_type == SEGMENT_TYPE_FMP4) && (en == vs->segments)) {
    1397           0 :             ff_hls_write_init_file(hls->m3u8_out, vs->fmp4_init_filename,
    1398           0 :                                    hls->flags & HLS_SINGLE_FILE, en->size, en->pos);
    1399             :         }
    1400             : 
    1401          14 :         ret = ff_hls_write_file_entry(hls->m3u8_out, en->discont, byterange_mode,
    1402           7 :                                       en->duration, hls->flags & HLS_ROUND_DURATIONS,
    1403             :                                       en->size, en->pos, vs->baseurl,
    1404           7 :                                       en->filename, prog_date_time_p);
    1405           7 :         if (ret < 0) {
    1406           0 :             av_log(s, AV_LOG_WARNING, "ff_hls_write_file_entry get error\n");
    1407             :         }
    1408             :     }
    1409             : 
    1410           2 :     if (last && (hls->flags & HLS_OMIT_ENDLIST)==0)
    1411           1 :         ff_hls_write_end_list(hls->m3u8_out);
    1412             : 
    1413           2 :     if( vs->vtt_m3u8_name ) {
    1414           0 :         if ((ret = hlsenc_io_open(s, &hls->sub_m3u8_out, vs->vtt_m3u8_name, &options)) < 0)
    1415           0 :             goto fail;
    1416           0 :         ff_hls_write_playlist_header(hls->sub_m3u8_out, hls->version, hls->allowcache,
    1417             :                                      target_duration, sequence, PLAYLIST_TYPE_NONE);
    1418           0 :         for (en = vs->segments; en; en = en->next) {
    1419           0 :             ret = ff_hls_write_file_entry(hls->sub_m3u8_out, 0, byterange_mode,
    1420             :                                           en->duration, 0, en->size, en->pos,
    1421           0 :                                           vs->baseurl, en->sub_filename, NULL);
    1422           0 :             if (ret < 0) {
    1423           0 :                 av_log(s, AV_LOG_WARNING, "ff_hls_write_file_entry get error\n");
    1424             :             }
    1425             :         }
    1426             : 
    1427           0 :         if (last)
    1428           0 :             ff_hls_write_end_list(hls->sub_m3u8_out);
    1429             : 
    1430             :     }
    1431             : 
    1432           4 : fail:
    1433           2 :     av_dict_free(&options);
    1434           2 :     hlsenc_io_close(s, &hls->m3u8_out, temp_filename);
    1435           2 :     hlsenc_io_close(s, &hls->sub_m3u8_out, vs->vtt_m3u8_name);
    1436           2 :     if (ret >= 0 && use_rename)
    1437           2 :         ff_rename(temp_filename, vs->m3u8_name, s);
    1438             : 
    1439           2 :     if (ret >= 0 && hls->master_pl_name)
    1440           0 :         if (create_master_playlist(s, vs) < 0)
    1441           0 :             av_log(s, AV_LOG_WARNING, "Master playlist creation failed\n");
    1442             : 
    1443           2 :     return ret;
    1444             : }
    1445             : 
    1446           2 : static int hls_start(AVFormatContext *s, VariantStream *vs)
    1447             : {
    1448           2 :     HLSContext *c = s->priv_data;
    1449           2 :     AVFormatContext *oc = vs->avf;
    1450           2 :     AVFormatContext *vtt_oc = vs->vtt_avf;
    1451           2 :     AVDictionary *options = NULL;
    1452             :     char *filename, iv_string[KEYSIZE*2 + 1];
    1453           2 :     int err = 0;
    1454             : 
    1455           2 :     if (c->flags & HLS_SINGLE_FILE) {
    1456           0 :         char *new_name = av_strdup(vs->basename);
    1457           0 :         if (!new_name)
    1458           0 :             return AVERROR(ENOMEM);
    1459           0 :         ff_format_set_url(oc, new_name);
    1460           0 :         if (vs->vtt_basename) {
    1461           0 :             new_name = av_strdup(vs->vtt_basename);
    1462           0 :             if (!new_name)
    1463           0 :                 return AVERROR(ENOMEM);
    1464           0 :             ff_format_set_url(vtt_oc, new_name);
    1465             :         }
    1466           2 :     } else if (c->max_seg_size > 0) {
    1467           0 :         char *filename = NULL;
    1468           0 :         if (replace_int_data_in_filename(&filename,
    1469             : #if FF_API_HLS_WRAP
    1470           0 :             vs->basename, 'd', c->wrap ? vs->sequence % c->wrap : vs->sequence) < 1) {
    1471             : #else
    1472             :             vs->basename, 'd', vs->sequence) < 1) {
    1473             : #endif
    1474           0 :                 av_free(filename);
    1475           0 :                 av_log(oc, AV_LOG_ERROR, "Invalid segment filename template '%s', you can try to use -use_localtime 1 with it\n", vs->basename);
    1476           0 :                 return AVERROR(EINVAL);
    1477             :         }
    1478           0 :         ff_format_set_url(oc, filename);
    1479             :     } else {
    1480           2 :         if (c->use_localtime) {
    1481             :             time_t now0;
    1482             :             struct tm *tm, tmpbuf;
    1483           0 :             int bufsize = strlen(vs->basename) + 1024;
    1484           0 :             char *buf = av_mallocz(bufsize);
    1485           0 :             if (!buf)
    1486           0 :                 return AVERROR(ENOMEM);
    1487           0 :             time(&now0);
    1488           0 :             tm = localtime_r(&now0, &tmpbuf);
    1489           0 :             ff_format_set_url(oc, buf);
    1490           0 :             if (!strftime(oc->url, bufsize, vs->basename, tm)) {
    1491           0 :                 av_log(oc, AV_LOG_ERROR, "Could not get segment filename with use_localtime\n");
    1492           0 :                 return AVERROR(EINVAL);
    1493             :             }
    1494             : 
    1495           0 :             err = sls_flag_use_localtime_filename(oc, c, vs);
    1496           0 :             if (err < 0) {
    1497           0 :                 return AVERROR(ENOMEM);
    1498             :             }
    1499             : 
    1500           0 :             if (c->use_localtime_mkdir) {
    1501             :                 const char *dir;
    1502           0 :                 char *fn_copy = av_strdup(oc->url);
    1503           0 :                 if (!fn_copy) {
    1504           0 :                     return AVERROR(ENOMEM);
    1505             :                 }
    1506           0 :                 dir = av_dirname(fn_copy);
    1507           0 :                 if (mkdir_p(dir) == -1 && errno != EEXIST) {
    1508           0 :                     av_log(oc, AV_LOG_ERROR, "Could not create directory %s with use_localtime_mkdir\n", dir);
    1509           0 :                     av_free(fn_copy);
    1510           0 :                     return AVERROR(errno);
    1511             :                 }
    1512           0 :                 av_free(fn_copy);
    1513             :             }
    1514             :         } else {
    1515           2 :             char *filename = NULL;
    1516           4 :             if (replace_int_data_in_filename(&filename,
    1517             : #if FF_API_HLS_WRAP
    1518           4 :                    vs->basename, 'd', c->wrap ? vs->sequence % c->wrap : vs->sequence) < 1) {
    1519             : #else
    1520             :                    vs->basename, 'd', vs->sequence) < 1) {
    1521             : #endif
    1522           0 :                 av_free(filename);
    1523           0 :                 av_log(oc, AV_LOG_ERROR, "Invalid segment filename template '%s' you can try to use -use_localtime 1 with it\n", vs->basename);
    1524           0 :                 return AVERROR(EINVAL);
    1525             :             }
    1526           2 :             ff_format_set_url(oc, filename);
    1527             :         }
    1528           2 :         if( vs->vtt_basename) {
    1529           0 :             char *filename = NULL;
    1530           0 :             if (replace_int_data_in_filename(&filename,
    1531             : #if FF_API_HLS_WRAP
    1532           0 :                 vs->vtt_basename, 'd', c->wrap ? vs->sequence % c->wrap : vs->sequence) < 1) {
    1533             : #else
    1534             :                 vs->vtt_basename, 'd', vs->sequence) < 1) {
    1535             : #endif
    1536           0 :                 av_free(filename);
    1537           0 :                 av_log(vtt_oc, AV_LOG_ERROR, "Invalid segment filename template '%s'\n", vs->vtt_basename);
    1538           0 :                 return AVERROR(EINVAL);
    1539             :             }
    1540           0 :             ff_format_set_url(vtt_oc, filename);
    1541             :        }
    1542             :     }
    1543           2 :     vs->number++;
    1544             : 
    1545           2 :     set_http_options(s, &options, c);
    1546             : 
    1547           2 :     if (c->flags & HLS_TEMP_FILE) {
    1548           0 :         char *new_name = av_asprintf("%s.tmp", oc->url);
    1549           0 :         if (!new_name)
    1550           0 :             return AVERROR(ENOMEM);
    1551           0 :         ff_format_set_url(oc, new_name);
    1552             :     }
    1553             : 
    1554           2 :     if (c->key_info_file || c->encrypt) {
    1555           0 :         if (c->key_info_file && c->encrypt) {
    1556           0 :             av_log(s, AV_LOG_WARNING, "Cannot use both -hls_key_info_file and -hls_enc,"
    1557             :                   " will use -hls_key_info_file priority\n");
    1558             :         }
    1559             : 
    1560           0 :         if (!c->encrypt_started || (c->flags & HLS_PERIODIC_REKEY)) {
    1561           0 :             if (c->key_info_file) {
    1562           0 :                 if ((err = hls_encryption_start(s)) < 0)
    1563           0 :                     goto fail;
    1564             :             } else {
    1565           0 :                 if ((err = do_encrypt(s, vs)) < 0)
    1566           0 :                     goto fail;
    1567             :             }
    1568           0 :             c->encrypt_started = 1;
    1569             :         }
    1570           0 :         if ((err = av_dict_set(&options, "encryption_key", c->key_string, 0))
    1571             :                 < 0)
    1572           0 :             goto fail;
    1573           0 :         err = av_strlcpy(iv_string, c->iv_string, sizeof(iv_string));
    1574           0 :         if (!err)
    1575           0 :             snprintf(iv_string, sizeof(iv_string), "%032"PRIx64, vs->sequence);
    1576           0 :         if ((err = av_dict_set(&options, "encryption_iv", iv_string, 0)) < 0)
    1577           0 :            goto fail;
    1578             : 
    1579           0 :         filename = av_asprintf("crypto:%s", oc->url);
    1580           0 :         if (!filename) {
    1581           0 :             err = AVERROR(ENOMEM);
    1582           0 :             goto fail;
    1583             :         }
    1584           0 :         err = hlsenc_io_open(s, &oc->pb, filename, &options);
    1585           0 :         av_free(filename);
    1586           0 :         av_dict_free(&options);
    1587           0 :         if (err < 0)
    1588           0 :             return err;
    1589           2 :     } else if (c->segment_type != SEGMENT_TYPE_FMP4) {
    1590           2 :         if ((err = hlsenc_io_open(s, &oc->pb, oc->url, &options)) < 0)
    1591           0 :             goto fail;
    1592             :     }
    1593           2 :     if (vs->vtt_basename) {
    1594           0 :         set_http_options(s, &options, c);
    1595           0 :         if ((err = hlsenc_io_open(s, &vtt_oc->pb, vtt_oc->url, &options)) < 0)
    1596           0 :             goto fail;
    1597             :     }
    1598           2 :     av_dict_free(&options);
    1599             : 
    1600           2 :     if (c->segment_type != SEGMENT_TYPE_FMP4) {
    1601             :         /* We only require one PAT/PMT per segment. */
    1602           2 :         if (oc->oformat->priv_class && oc->priv_data) {
    1603             :             char period[21];
    1604             : 
    1605           2 :             snprintf(period, sizeof(period), "%d", (INT_MAX / 2) - 1);
    1606             : 
    1607           2 :             av_opt_set(oc->priv_data, "mpegts_flags", "resend_headers", 0);
    1608           2 :             av_opt_set(oc->priv_data, "sdt_period", period, 0);
    1609           2 :             av_opt_set(oc->priv_data, "pat_period", period, 0);
    1610             :         }
    1611             :     }
    1612             : 
    1613           2 :     if (vs->vtt_basename) {
    1614           0 :         err = avformat_write_header(vtt_oc,NULL);
    1615           0 :         if (err < 0)
    1616           0 :             return err;
    1617             :     }
    1618             : 
    1619           2 :     return 0;
    1620           0 : fail:
    1621           0 :     av_dict_free(&options);
    1622             : 
    1623           0 :     return err;
    1624             : }
    1625             : 
    1626           1 : static const char * get_default_pattern_localtime_fmt(AVFormatContext *s)
    1627             : {
    1628             :     char b[21];
    1629           1 :     time_t t = time(NULL);
    1630             :     struct tm *p, tmbuf;
    1631           1 :     HLSContext *hls = s->priv_data;
    1632             : 
    1633           1 :     p = localtime_r(&t, &tmbuf);
    1634             :     // no %s support when strftime returned error or left format string unchanged
    1635             :     // also no %s support on MSVC, which invokes the invalid parameter handler on unsupported format strings, instead of returning an error
    1636           1 :     if (hls->segment_type == SEGMENT_TYPE_FMP4) {
    1637           0 :         return (HAVE_LIBC_MSVCRT || !strftime(b, sizeof(b), "%s", p) || !strcmp(b, "%s")) ? "-%Y%m%d%H%M%S.m4s" : "-%s.m4s";
    1638             :     }
    1639           1 :     return (HAVE_LIBC_MSVCRT || !strftime(b, sizeof(b), "%s", p) || !strcmp(b, "%s")) ? "-%Y%m%d%H%M%S.ts" : "-%s.ts";
    1640             : }
    1641             : 
    1642           0 : static int append_postfix(char *name, int name_buf_len, int i)
    1643             : {
    1644             :     char *p;
    1645           0 :     char extension[10] = {'\0'};
    1646             : 
    1647           0 :     p = strrchr(name, '.');
    1648           0 :     if (p) {
    1649           0 :         av_strlcpy(extension, p, sizeof(extension));
    1650           0 :         *p = '\0';
    1651             :     }
    1652             : 
    1653           0 :     snprintf(name + strlen(name), name_buf_len - strlen(name), POSTFIX_PATTERN, i);
    1654             : 
    1655           0 :     if (strlen(extension))
    1656           0 :         av_strlcat(name, extension, name_buf_len);
    1657             : 
    1658           0 :     return 0;
    1659             : }
    1660             : 
    1661           2 : static int validate_name(int nb_vs, const char *fn)
    1662             : {
    1663             :     const char *filename, *subdir_name;
    1664           2 :     char *fn_dup = NULL;
    1665           2 :     int ret = 0;
    1666             : 
    1667           2 :     if (!fn) {
    1668           0 :         ret = AVERROR(EINVAL);
    1669           0 :         goto fail;
    1670             :     }
    1671             : 
    1672           2 :     fn_dup = av_strdup(fn);
    1673           2 :     if (!fn_dup) {
    1674           0 :         ret = AVERROR(ENOMEM);
    1675           0 :         goto fail;
    1676             :     }
    1677             : 
    1678           2 :     filename = av_basename(fn);
    1679           2 :     subdir_name = av_dirname(fn_dup);
    1680             : 
    1681           2 :     if (nb_vs > 1 && !av_stristr(filename, "%v") && !av_stristr(subdir_name, "%v")) {
    1682           0 :         av_log(NULL, AV_LOG_ERROR, "More than 1 variant streams are present, %%v is expected in the filename %s\n",
    1683             :                 fn);
    1684           0 :         ret = AVERROR(EINVAL);
    1685           0 :         goto fail;
    1686             :     }
    1687             : 
    1688           2 :     if (av_stristr(filename, "%v") && av_stristr(subdir_name, "%v")) {
    1689           0 :         av_log(NULL, AV_LOG_ERROR, "%%v is expected either in filename or in the sub-directory name of file %s\n",
    1690             :                 fn);
    1691           0 :         ret = AVERROR(EINVAL);
    1692           0 :         goto fail;
    1693             :     }
    1694             : 
    1695           4 : fail:
    1696           2 :     av_freep(&fn_dup);
    1697           2 :     return ret;
    1698             : }
    1699             : 
    1700           2 : static int format_name(char *buf, int buf_len, int index)
    1701             : {
    1702             :     const char *proto, *dir;
    1703           2 :     char *orig_buf_dup = NULL, *mod_buf = NULL, *mod_buf_dup = NULL;
    1704           2 :     int ret = 0;
    1705             : 
    1706           2 :     if (!av_stristr(buf, "%v"))
    1707           2 :         return ret;
    1708             : 
    1709           0 :     orig_buf_dup = av_strdup(buf);
    1710           0 :     if (!orig_buf_dup) {
    1711           0 :         ret = AVERROR(ENOMEM);
    1712           0 :         goto fail;
    1713             :     }
    1714             : 
    1715           0 :     if (replace_int_data_in_filename(&mod_buf, orig_buf_dup, 'v', index) < 1) {
    1716           0 :         ret = AVERROR(EINVAL);
    1717           0 :         goto fail;
    1718             :     }
    1719           0 :     av_strlcpy(buf, mod_buf, buf_len);
    1720             : 
    1721           0 :     proto = avio_find_protocol_name(orig_buf_dup);
    1722           0 :     dir = av_dirname(orig_buf_dup);
    1723             : 
    1724             :     /* if %v is present in the file's directory, create sub-directory */
    1725           0 :     if (av_stristr(dir, "%v") && proto && !strcmp(proto, "file")) {
    1726           0 :         mod_buf_dup = av_strdup(buf);
    1727           0 :         if (!mod_buf_dup) {
    1728           0 :             ret = AVERROR(ENOMEM);
    1729           0 :             goto fail;
    1730             :         }
    1731             : 
    1732           0 :         dir = av_dirname(mod_buf_dup);
    1733           0 :         if (mkdir_p(dir) == -1 && errno != EEXIST) {
    1734           0 :             ret = AVERROR(errno);
    1735           0 :             goto fail;
    1736             :         }
    1737             :     }
    1738             : 
    1739           0 : fail:
    1740           0 :     av_freep(&orig_buf_dup);
    1741           0 :     av_freep(&mod_buf_dup);
    1742           0 :     av_freep(&mod_buf);
    1743           0 :     return ret;
    1744             : }
    1745             : 
    1746           0 : static int get_nth_codec_stream_index(AVFormatContext *s,
    1747             :                                       enum AVMediaType codec_type,
    1748             :                                       int stream_id)
    1749             : {
    1750             :     unsigned int stream_index, cnt;
    1751           0 :     if (stream_id < 0 || stream_id > s->nb_streams - 1)
    1752           0 :         return -1;
    1753           0 :     cnt = 0;
    1754           0 :     for (stream_index = 0; stream_index < s->nb_streams; stream_index++) {
    1755           0 :         if (s->streams[stream_index]->codecpar->codec_type != codec_type)
    1756           0 :             continue;
    1757           0 :         if (cnt == stream_id)
    1758           0 :             return stream_index;
    1759           0 :         cnt++;
    1760             :     }
    1761           0 :     return -1;
    1762             : }
    1763             : 
    1764           0 : static int parse_variant_stream_mapstring(AVFormatContext *s)
    1765             : {
    1766           0 :     HLSContext *hls = s->priv_data;
    1767             :     VariantStream *vs;
    1768             :     int stream_index;
    1769             :     enum AVMediaType codec_type;
    1770             :     int nb_varstreams, nb_streams;
    1771             :     char *p, *q, *saveptr1, *saveptr2, *varstr, *keyval;
    1772             :     const char *val;
    1773             : 
    1774             :     /**
    1775             :      * Expected format for var_stream_map string is as below:
    1776             :      * "a:0,v:0 a:1,v:1"
    1777             :      * "a:0,agroup:a0 a:1,agroup:a1 v:0,agroup:a0  v:1,agroup:a1"
    1778             :      * This string specifies how to group the audio, video and subtitle streams
    1779             :      * into different variant streams. The variant stream groups are separated
    1780             :      * by space.
    1781             :      *
    1782             :      * a:, v:, s: are keys to specify audio, video and subtitle streams
    1783             :      * respectively. Allowed values are 0 to 9 digits (limited just based on
    1784             :      * practical usage)
    1785             :      *
    1786             :      * agroup: is key to specify audio group. A string can be given as value.
    1787             :      */
    1788           0 :     p = av_strdup(hls->var_stream_map);
    1789           0 :     q = p;
    1790           0 :     while(av_strtok(q, " \t", &saveptr1)) {
    1791           0 :         q = NULL;
    1792           0 :         hls->nb_varstreams++;
    1793             :     }
    1794           0 :     av_freep(&p);
    1795             : 
    1796           0 :     hls->var_streams = av_mallocz(sizeof(*hls->var_streams) * hls->nb_varstreams);
    1797           0 :     if (!hls->var_streams)
    1798           0 :         return AVERROR(ENOMEM);
    1799             : 
    1800           0 :     p = hls->var_stream_map;
    1801           0 :     nb_varstreams = 0;
    1802           0 :     while (varstr = av_strtok(p, " \t", &saveptr1)) {
    1803           0 :         p = NULL;
    1804             : 
    1805           0 :         if (nb_varstreams < hls->nb_varstreams)
    1806           0 :             vs = &(hls->var_streams[nb_varstreams++]);
    1807             :         else
    1808           0 :             return AVERROR(EINVAL);
    1809             : 
    1810           0 :         q = varstr;
    1811           0 :         while (q < varstr + strlen(varstr)) {
    1812           0 :             if (!av_strncasecmp(q, "a:", 2) || !av_strncasecmp(q, "v:", 2) ||
    1813           0 :                 !av_strncasecmp(q, "s:", 2))
    1814           0 :                 vs->nb_streams++;
    1815           0 :             q++;
    1816             :         }
    1817           0 :         vs->streams = av_mallocz(sizeof(AVStream *) * vs->nb_streams);
    1818           0 :         if (!vs->streams)
    1819           0 :             return AVERROR(ENOMEM);
    1820             : 
    1821           0 :         nb_streams = 0;
    1822           0 :         while (keyval = av_strtok(varstr, ",", &saveptr2)) {
    1823           0 :             varstr = NULL;
    1824             : 
    1825           0 :             if (av_strstart(keyval, "agroup:", &val)) {
    1826           0 :                 vs->agroup = av_strdup(val);
    1827           0 :                 if (!vs->agroup)
    1828           0 :                     return AVERROR(ENOMEM);
    1829           0 :                 continue;
    1830           0 :             } else if (av_strstart(keyval, "ccgroup:", &val)) {
    1831           0 :                 vs->ccgroup = av_strdup(val);
    1832           0 :                 if (!vs->ccgroup)
    1833           0 :                     return AVERROR(ENOMEM);
    1834           0 :                 continue;
    1835           0 :             } else if (av_strstart(keyval, "v:", &val)) {
    1836           0 :                 codec_type = AVMEDIA_TYPE_VIDEO;
    1837           0 :             } else if (av_strstart(keyval, "a:", &val)) {
    1838           0 :                 codec_type = AVMEDIA_TYPE_AUDIO;
    1839           0 :             } else if (av_strstart(keyval, "s:", &val)) {
    1840           0 :                 codec_type = AVMEDIA_TYPE_SUBTITLE;
    1841             :             } else {
    1842           0 :                 av_log(s, AV_LOG_ERROR, "Invalid keyval %s\n", keyval);
    1843           0 :                 return AVERROR(EINVAL);
    1844             :             }
    1845             : 
    1846           0 :             stream_index = -1;
    1847           0 :             if (av_isdigit(*val))
    1848           0 :                 stream_index = get_nth_codec_stream_index (s, codec_type,
    1849             :                                                            atoi(val));
    1850             : 
    1851           0 :             if (stream_index >= 0 && nb_streams < vs->nb_streams) {
    1852           0 :                 vs->streams[nb_streams++] = s->streams[stream_index];
    1853             :             } else {
    1854           0 :                 av_log(s, AV_LOG_ERROR, "Unable to map stream at %s\n", keyval);
    1855           0 :                 return AVERROR(EINVAL);
    1856             :             }
    1857             :         }
    1858             :     }
    1859           0 :     av_log(s, AV_LOG_DEBUG, "Number of variant streams %d\n",
    1860             :             hls->nb_varstreams);
    1861             : 
    1862           0 :     return 0;
    1863             : }
    1864             : 
    1865           0 : static int parse_cc_stream_mapstring(AVFormatContext *s)
    1866             : {
    1867           0 :     HLSContext *hls = s->priv_data;
    1868             :     int nb_ccstreams;
    1869             :     char *p, *q, *saveptr1, *saveptr2, *ccstr, *keyval;
    1870             :     const char *val;
    1871             :     ClosedCaptionsStream *ccs;
    1872             : 
    1873           0 :     p = av_strdup(hls->cc_stream_map);
    1874           0 :     q = p;
    1875           0 :     while(av_strtok(q, " \t", &saveptr1)) {
    1876           0 :         q = NULL;
    1877           0 :         hls->nb_ccstreams++;
    1878             :     }
    1879           0 :     av_freep(&p);
    1880             : 
    1881           0 :     hls->cc_streams = av_mallocz(sizeof(*hls->cc_streams) * hls->nb_ccstreams);
    1882           0 :     if (!hls->cc_streams)
    1883           0 :         return AVERROR(ENOMEM);
    1884             : 
    1885           0 :     p = hls->cc_stream_map;
    1886           0 :     nb_ccstreams = 0;
    1887           0 :     while (ccstr = av_strtok(p, " \t", &saveptr1)) {
    1888           0 :         p = NULL;
    1889             : 
    1890           0 :         if (nb_ccstreams < hls->nb_ccstreams)
    1891           0 :             ccs = &(hls->cc_streams[nb_ccstreams++]);
    1892             :         else
    1893           0 :             return AVERROR(EINVAL);
    1894             : 
    1895           0 :         while (keyval = av_strtok(ccstr, ",", &saveptr2)) {
    1896           0 :             ccstr = NULL;
    1897             : 
    1898           0 :             if (av_strstart(keyval, "ccgroup:", &val)) {
    1899           0 :                 ccs->ccgroup = av_strdup(val);
    1900           0 :                 if (!ccs->ccgroup)
    1901           0 :                     return AVERROR(ENOMEM);
    1902           0 :             } else if (av_strstart(keyval, "instreamid:", &val)) {
    1903           0 :                 ccs->instreamid = av_strdup(val);
    1904           0 :                 if (!ccs->instreamid)
    1905           0 :                     return AVERROR(ENOMEM);
    1906           0 :             } else if (av_strstart(keyval, "language:", &val)) {
    1907           0 :                 ccs->language = av_strdup(val);
    1908           0 :                 if (!ccs->language)
    1909           0 :                     return AVERROR(ENOMEM);
    1910             :             } else {
    1911           0 :                 av_log(s, AV_LOG_ERROR, "Invalid keyval %s\n", keyval);
    1912           0 :                 return AVERROR(EINVAL);
    1913             :             }
    1914             :         }
    1915             : 
    1916           0 :         if (!ccs->ccgroup || !ccs->instreamid) {
    1917           0 :             av_log(s, AV_LOG_ERROR, "Insufficient parameters in cc stream map string\n");
    1918           0 :             return AVERROR(EINVAL);
    1919             :         }
    1920             : 
    1921           0 :         if (av_strstart(ccs->instreamid, "CC", &val)) {
    1922           0 :             if(atoi(val) < 1 || atoi(val) > 4) {
    1923           0 :                 av_log(s, AV_LOG_ERROR, "Invalid instream ID CC index %d in %s, range 1-4\n",
    1924             :                        atoi(val), ccs->instreamid);
    1925           0 :                 return AVERROR(EINVAL);
    1926             :             }
    1927           0 :         } else if (av_strstart(ccs->instreamid, "SERVICE", &val)) {
    1928           0 :             if(atoi(val) < 1 || atoi(val) > 63) {
    1929           0 :                 av_log(s, AV_LOG_ERROR, "Invalid instream ID SERVICE index %d in %s, range 1-63 \n",
    1930             :                        atoi(val), ccs->instreamid);
    1931           0 :                 return AVERROR(EINVAL);
    1932             :             }
    1933             :         } else {
    1934           0 :             av_log(s, AV_LOG_ERROR, "Invalid instream ID %s, supported are CCn or SERIVICEn\n",
    1935             :                    ccs->instreamid);
    1936           0 :             return AVERROR(EINVAL);
    1937             :         }
    1938             :     }
    1939             : 
    1940           0 :     return 0;
    1941             : }
    1942             : 
    1943           1 : static int update_variant_stream_info(AVFormatContext *s) {
    1944           1 :     HLSContext *hls = s->priv_data;
    1945             :     unsigned int i;
    1946           1 :     int ret = 0;
    1947             : 
    1948           1 :     if (hls->cc_stream_map) {
    1949           0 :         ret = parse_cc_stream_mapstring(s);
    1950           0 :         if (ret < 0)
    1951           0 :             return ret;
    1952             :     }
    1953             : 
    1954           1 :     if (hls->var_stream_map) {
    1955           0 :         return parse_variant_stream_mapstring(s);
    1956             :     } else {
    1957             :         //By default, a single variant stream with all the codec streams is created
    1958           1 :         hls->nb_varstreams = 1;
    1959           1 :         hls->var_streams = av_mallocz(sizeof(*hls->var_streams) *
    1960           1 :                                              hls->nb_varstreams);
    1961           1 :         if (!hls->var_streams)
    1962           0 :             return AVERROR(ENOMEM);
    1963             : 
    1964           1 :         hls->var_streams[0].nb_streams = s->nb_streams;
    1965           1 :         hls->var_streams[0].streams = av_mallocz(sizeof(AVStream *) *
    1966           1 :                                             hls->var_streams[0].nb_streams);
    1967           1 :         if (!hls->var_streams[0].streams)
    1968           0 :             return AVERROR(ENOMEM);
    1969             : 
    1970             :         //by default, the first available ccgroup is mapped to the variant stream
    1971           1 :         if (hls->nb_ccstreams) {
    1972           0 :             hls->var_streams[0].ccgroup = av_strdup(hls->cc_streams[0].ccgroup);
    1973           0 :             if (!hls->var_streams[0].ccgroup)
    1974           0 :                 return AVERROR(ENOMEM);
    1975             :         }
    1976             : 
    1977           2 :         for (i = 0; i < s->nb_streams; i++)
    1978           1 :             hls->var_streams[0].streams[i] = s->streams[i];
    1979             :     }
    1980           1 :     return 0;
    1981             : }
    1982             : 
    1983           0 : static int update_master_pl_info(AVFormatContext *s) {
    1984           0 :     HLSContext *hls = s->priv_data;
    1985             :     const char *dir;
    1986           0 :     char *fn1= NULL, *fn2 = NULL;
    1987           0 :     int ret = 0;
    1988             : 
    1989           0 :     fn1 = av_strdup(s->url);
    1990           0 :     if (!fn1) {
    1991           0 :         ret = AVERROR(ENOMEM);
    1992           0 :         goto fail;
    1993             :     }
    1994             : 
    1995           0 :     dir = av_dirname(fn1);
    1996             : 
    1997             :     /**
    1998             :      * if output file's directory has %v, variants are created in sub-directories
    1999             :      * then master is created at the sub-directories level
    2000             :      */
    2001           0 :     if (dir && av_stristr(av_basename(dir), "%v")) {
    2002           0 :         fn2 = av_strdup(dir);
    2003           0 :         if (!fn2) {
    2004           0 :             ret = AVERROR(ENOMEM);
    2005           0 :             goto fail;
    2006             :         }
    2007           0 :         dir = av_dirname(fn2);
    2008             :     }
    2009             : 
    2010           0 :     if (dir && strcmp(dir, "."))
    2011           0 :         hls->master_m3u8_url = av_append_path_component(dir, hls->master_pl_name);
    2012             :     else
    2013           0 :         hls->master_m3u8_url = av_strdup(hls->master_pl_name);
    2014             : 
    2015           0 :     if (!hls->master_m3u8_url) {
    2016           0 :         ret = AVERROR(ENOMEM);
    2017           0 :         goto fail;
    2018             :     }
    2019             : 
    2020           0 : fail:
    2021           0 :     av_freep(&fn1);
    2022           0 :     av_freep(&fn2);
    2023             : 
    2024           0 :     return ret;
    2025             : }
    2026             : 
    2027           1 : static int hls_write_header(AVFormatContext *s)
    2028             : {
    2029           1 :     HLSContext *hls = s->priv_data;
    2030             :     int ret, i, j;
    2031           1 :     AVDictionary *options = NULL;
    2032           1 :     VariantStream *vs = NULL;
    2033             : 
    2034           2 :     for (i = 0; i < hls->nb_varstreams; i++) {
    2035           1 :         vs = &hls->var_streams[i];
    2036             : 
    2037           1 :         av_dict_copy(&options, hls->format_options, 0);
    2038           1 :         ret = avformat_write_header(vs->avf, &options);
    2039           1 :         if (av_dict_count(options)) {
    2040           0 :             av_log(s, AV_LOG_ERROR, "Some of provided format options in '%s' are not recognized\n", hls->format_options_str);
    2041           0 :             ret = AVERROR(EINVAL);
    2042           0 :             av_dict_free(&options);
    2043           0 :             goto fail;
    2044             :         }
    2045           1 :         av_dict_free(&options);
    2046             :         //av_assert0(s->nb_streams == hls->avf->nb_streams);
    2047           2 :         for (j = 0; j < vs->nb_streams; j++) {
    2048             :             AVStream *inner_st;
    2049           1 :             AVStream *outer_st = vs->streams[j];
    2050             : 
    2051           1 :             if (hls->max_seg_size > 0) {
    2052           0 :                 if ((outer_st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) &&
    2053           0 :                     (outer_st->codecpar->bit_rate > hls->max_seg_size)) {
    2054           0 :                     av_log(s, AV_LOG_WARNING, "Your video bitrate is bigger than hls_segment_size, "
    2055             :                            "(%"PRId64 " > %"PRId64 "), the result maybe not be what you want.",
    2056           0 :                            outer_st->codecpar->bit_rate, hls->max_seg_size);
    2057             :                 }
    2058             :             }
    2059             : 
    2060           1 :             if (outer_st->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE)
    2061           1 :                 inner_st = vs->avf->streams[j];
    2062           0 :             else if (vs->vtt_avf)
    2063           0 :                 inner_st = vs->vtt_avf->streams[0];
    2064             :             else {
    2065             :                 /* We have a subtitle stream, when the user does not want one */
    2066           0 :                 inner_st = NULL;
    2067           0 :                 continue;
    2068             :             }
    2069           1 :             avpriv_set_pts_info(outer_st, inner_st->pts_wrap_bits, inner_st->time_base.num, inner_st->time_base.den);
    2070           1 :             write_codec_attr(outer_st, vs);
    2071             : 
    2072             :         }
    2073             :         /* Update the Codec Attr string for the mapped audio groups */
    2074           1 :         if (vs->has_video && vs->agroup) {
    2075           0 :             for (j = 0; j < hls->nb_varstreams; j++) {
    2076           0 :                 VariantStream *vs_agroup = &(hls->var_streams[j]);
    2077           0 :                 if (!vs_agroup->has_video && !vs_agroup->has_subtitle &&
    2078           0 :                     vs_agroup->agroup &&
    2079           0 :                     !av_strcasecmp(vs_agroup->agroup, vs->agroup)) {
    2080           0 :                     write_codec_attr(vs_agroup->streams[0], vs);
    2081             :                 }
    2082             :             }
    2083             :         }
    2084             :     }
    2085           1 : fail:
    2086             : 
    2087           1 :     return ret;
    2088             : }
    2089             : 
    2090         766 : static int hls_write_packet(AVFormatContext *s, AVPacket *pkt)
    2091             : {
    2092         766 :     HLSContext *hls = s->priv_data;
    2093         766 :     AVFormatContext *oc = NULL;
    2094         766 :     AVStream *st = s->streams[pkt->stream_index];
    2095         766 :     int64_t end_pts = 0;
    2096         766 :     int is_ref_pkt = 1;
    2097         766 :     int ret = 0, can_split = 1, i, j;
    2098         766 :     int stream_index = 0;
    2099         766 :     int range_length = 0;
    2100         766 :     uint8_t *buffer = NULL;
    2101         766 :     VariantStream *vs = NULL;
    2102             : 
    2103         766 :     for (i = 0; i < hls->nb_varstreams; i++) {
    2104         766 :         vs = &hls->var_streams[i];
    2105         766 :         for (j = 0; j < vs->nb_streams; j++) {
    2106         766 :             if (vs->streams[j] == st) {
    2107         766 :                 if( st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE ) {
    2108           0 :                     oc = vs->vtt_avf;
    2109           0 :                     stream_index = 0;
    2110             :                 } else {
    2111         766 :                     oc = vs->avf;
    2112         766 :                     stream_index = j;
    2113             :                 }
    2114         766 :                 break;
    2115             :             }
    2116             :         }
    2117             : 
    2118         766 :         if (oc)
    2119         766 :             break;
    2120             :     }
    2121             : 
    2122         766 :     if (!oc) {
    2123           0 :         av_log(s, AV_LOG_ERROR, "Unable to find mapping variant stream\n");
    2124           0 :         return AVERROR(ENOMEM);
    2125             :     }
    2126             : 
    2127         766 :     end_pts = hls->recording_time * vs->number;
    2128             : 
    2129         766 :     if (vs->sequence - vs->nb_entries > hls->start_sequence && hls->init_time > 0) {
    2130             :         /* reset end_pts, hls->recording_time at end of the init hls list */
    2131           0 :         int init_list_dur = hls->init_time * vs->nb_entries * AV_TIME_BASE;
    2132           0 :         int after_init_list_dur = (vs->sequence - vs->nb_entries ) * hls->time * AV_TIME_BASE;
    2133           0 :         hls->recording_time = hls->time * AV_TIME_BASE;
    2134           0 :         end_pts = init_list_dur + after_init_list_dur ;
    2135             :     }
    2136             : 
    2137         766 :     if (vs->start_pts == AV_NOPTS_VALUE) {
    2138           1 :         vs->start_pts = pkt->pts;
    2139             :     }
    2140             : 
    2141         766 :     if (vs->has_video) {
    2142           0 :         can_split = st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
    2143           0 :                     ((pkt->flags & AV_PKT_FLAG_KEY) || (hls->flags & HLS_SPLIT_BY_TIME));
    2144           0 :         is_ref_pkt = st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO;
    2145             :     }
    2146         766 :     if (pkt->pts == AV_NOPTS_VALUE)
    2147           0 :         is_ref_pkt = can_split = 0;
    2148             : 
    2149         766 :     if (is_ref_pkt) {
    2150         766 :         if (vs->end_pts == AV_NOPTS_VALUE)
    2151           1 :             vs->end_pts = pkt->pts;
    2152         766 :         if (vs->new_start) {
    2153           1 :             vs->new_start = 0;
    2154           2 :             vs->duration = (double)(pkt->pts - vs->end_pts)
    2155           1 :                                        * st->time_base.num / st->time_base.den;
    2156           1 :             vs->dpp = (double)(pkt->duration) * st->time_base.num / st->time_base.den;
    2157             :         } else {
    2158         765 :             if (pkt->duration) {
    2159         765 :                 vs->duration += (double)(pkt->duration) * st->time_base.num / st->time_base.den;
    2160             :             } else {
    2161           0 :                 av_log(s, AV_LOG_WARNING, "pkt->duration = 0, maybe the hls segment duration will not precise\n");
    2162           0 :                 vs->duration = (double)(pkt->pts - vs->end_pts) * st->time_base.num / st->time_base.den;
    2163             :             }
    2164             :         }
    2165             : 
    2166             :     }
    2167             : 
    2168        1532 :     if (vs->packets_written && can_split && av_compare_ts(pkt->pts - vs->start_pts, st->time_base,
    2169         766 :                                    end_pts, AV_TIME_BASE_Q) >= 0) {
    2170             :         int64_t new_start_pos;
    2171           1 :         char *old_filename = NULL;
    2172           1 :         int byterange_mode = (hls->flags & HLS_SINGLE_FILE) || (hls->max_seg_size > 0);
    2173             : 
    2174           1 :         av_write_frame(vs->avf, NULL); /* Flush any buffered data */
    2175             : 
    2176           1 :         new_start_pos = avio_tell(vs->avf->pb);
    2177           1 :         vs->size = new_start_pos - vs->start_pos;
    2178             : 
    2179           1 :         if (!byterange_mode) {
    2180           1 :             if (hls->segment_type == SEGMENT_TYPE_FMP4) {
    2181           0 :                 if (!vs->init_range_length) {
    2182           0 :                     avio_flush(oc->pb);
    2183           0 :                     range_length = avio_close_dyn_buf(oc->pb, &buffer);
    2184           0 :                     avio_write(vs->out, buffer, range_length);
    2185           0 :                     vs->init_range_length = range_length;
    2186           0 :                     avio_open_dyn_buf(&oc->pb);
    2187           0 :                     vs->packets_written = 0;
    2188           0 :                     ff_format_io_close(s, &vs->out);
    2189           0 :                     hlsenc_io_close(s, &vs->out, vs->base_output_dirname);
    2190             :                 }
    2191             :             } else {
    2192           1 :                 hlsenc_io_close(s, &oc->pb, oc->url);
    2193             :             }
    2194           1 :             if (vs->vtt_avf) {
    2195           0 :                 hlsenc_io_close(s, &vs->vtt_avf->pb, vs->vtt_avf->url);
    2196             :             }
    2197             :         }
    2198           1 :         if ((hls->flags & HLS_TEMP_FILE) && oc->url[0]) {
    2199           0 :             if (!(hls->flags & HLS_SINGLE_FILE) || (hls->max_seg_size <= 0))
    2200           0 :                 if ((vs->avf->oformat->priv_class && vs->avf->priv_data) && hls->segment_type != SEGMENT_TYPE_FMP4)
    2201           0 :                     av_opt_set(vs->avf->priv_data, "mpegts_flags", "resend_headers", 0);
    2202           0 :             hls_rename_temp_file(s, oc);
    2203             :         }
    2204             : 
    2205           1 :         if (vs->fmp4_init_mode) {
    2206           0 :             vs->number--;
    2207             :         }
    2208             : 
    2209           1 :         if (hls->segment_type == SEGMENT_TYPE_FMP4) {
    2210           0 :             ret = hlsenc_io_open(s, &vs->out, vs->avf->url, NULL);
    2211           0 :             if (ret < 0) {
    2212           0 :                 av_log(NULL, AV_LOG_ERROR, "Failed to open file '%s'\n",
    2213           0 :                     vs->avf->url);
    2214           0 :                 return ret;
    2215             :             }
    2216           0 :             write_styp(vs->out);
    2217           0 :             ret = flush_dynbuf(vs, &range_length);
    2218           0 :             if (ret < 0) {
    2219           0 :                 return ret;
    2220             :             }
    2221           0 :             ff_format_io_close(s, &vs->out);
    2222             :         }
    2223             : 
    2224           1 :         old_filename = av_strdup(vs->avf->url);
    2225           1 :         if (!old_filename) {
    2226           0 :             return AVERROR(ENOMEM);
    2227             :         }
    2228             : 
    2229           1 :         ret = hls_append_segment(s, hls, vs, vs->duration, vs->start_pos, vs->size);
    2230           1 :         vs->start_pos = new_start_pos;
    2231           1 :         if (ret < 0) {
    2232           0 :             av_free(old_filename);
    2233           0 :             return ret;
    2234             :         }
    2235             : 
    2236           1 :         vs->end_pts = pkt->pts;
    2237           1 :         vs->duration = 0;
    2238             : 
    2239           1 :         vs->fmp4_init_mode = 0;
    2240           1 :         if (hls->flags & HLS_SINGLE_FILE) {
    2241           0 :             vs->number++;
    2242           1 :         } else if (hls->max_seg_size > 0) {
    2243           0 :             if (vs->start_pos >= hls->max_seg_size) {
    2244           0 :                 vs->sequence++;
    2245           0 :                 sls_flag_file_rename(hls, vs, old_filename);
    2246           0 :                 ret = hls_start(s, vs);
    2247           0 :                 vs->start_pos = 0;
    2248             :                 /* When split segment by byte, the duration is short than hls_time,
    2249             :                  * so it is not enough one segment duration as hls_time, */
    2250           0 :                 vs->number--;
    2251             :             }
    2252           0 :             vs->number++;
    2253             :         } else {
    2254           1 :             sls_flag_file_rename(hls, vs, old_filename);
    2255           1 :             ret = hls_start(s, vs);
    2256             :         }
    2257           1 :         av_free(old_filename);
    2258             : 
    2259           1 :         if (ret < 0) {
    2260           0 :             return ret;
    2261             :         }
    2262             : 
    2263           1 :         if (!vs->fmp4_init_mode || byterange_mode)
    2264           1 :             if ((ret = hls_window(s, 0, vs)) < 0) {
    2265           0 :                 return ret;
    2266             :             }
    2267             :     }
    2268             : 
    2269         766 :     vs->packets_written++;
    2270         766 :     ret = ff_write_chained(oc, stream_index, pkt, s, 0);
    2271             : 
    2272         766 :     return ret;
    2273             : }
    2274             : 
    2275           1 : static int hls_write_trailer(struct AVFormatContext *s)
    2276             : {
    2277           1 :     HLSContext *hls = s->priv_data;
    2278           1 :     AVFormatContext *oc = NULL;
    2279           1 :     AVFormatContext *vtt_oc = NULL;
    2280           1 :     char *old_filename = NULL;
    2281             :     int i;
    2282           1 :     int ret = 0;
    2283           1 :     VariantStream *vs = NULL;
    2284             : 
    2285           2 :     for (i = 0; i < hls->nb_varstreams; i++) {
    2286           1 :         vs = &hls->var_streams[i];
    2287             : 
    2288           1 :     oc = vs->avf;
    2289           1 :     vtt_oc = vs->vtt_avf;
    2290           1 :     old_filename = av_strdup(vs->avf->url);
    2291             : 
    2292           1 :     if (!old_filename) {
    2293           0 :         return AVERROR(ENOMEM);
    2294             :     }
    2295           1 :     if ( hls->segment_type == SEGMENT_TYPE_FMP4) {
    2296           0 :         int range_length = 0;
    2297           0 :         ret = hlsenc_io_open(s, &vs->out, vs->avf->url, NULL);
    2298           0 :         if (ret < 0) {
    2299           0 :             av_log(NULL, AV_LOG_ERROR, "Failed to open file '%s'\n", vs->avf->url);
    2300           0 :             goto failed;
    2301             :         }
    2302           0 :         write_styp(vs->out);
    2303           0 :         ret = flush_dynbuf(vs, &range_length);
    2304           0 :         if (ret < 0) {
    2305           0 :             goto failed;
    2306             :         }
    2307           0 :         ff_format_io_close(s, &vs->out);
    2308             :     }
    2309             : 
    2310           2 : failed:
    2311           1 :     av_write_trailer(oc);
    2312           1 :     if (oc->pb) {
    2313           1 :         vs->size = avio_tell(vs->avf->pb) - vs->start_pos;
    2314           1 :         if (hls->segment_type != SEGMENT_TYPE_FMP4)
    2315           1 :             ff_format_io_close(s, &oc->pb);
    2316             : 
    2317           1 :         if ((hls->flags & HLS_TEMP_FILE) && oc->url[0]) {
    2318           0 :             hls_rename_temp_file(s, oc);
    2319           0 :             av_free(old_filename);
    2320           0 :             old_filename = av_strdup(vs->avf->url);
    2321             : 
    2322           0 :             if (!old_filename) {
    2323           0 :                 return AVERROR(ENOMEM);
    2324             :             }
    2325             :         }
    2326             : 
    2327             :         /* after av_write_trailer, then duration + 1 duration per packet */
    2328           1 :         hls_append_segment(s, hls, vs, vs->duration + vs->dpp, vs->start_pos, vs->size);
    2329             :     }
    2330             : 
    2331           1 :     sls_flag_file_rename(hls, vs, old_filename);
    2332             : 
    2333           1 :     if (vtt_oc) {
    2334           0 :         if (vtt_oc->pb)
    2335           0 :             av_write_trailer(vtt_oc);
    2336           0 :         vs->size = avio_tell(vs->vtt_avf->pb) - vs->start_pos;
    2337           0 :         ff_format_io_close(s, &vtt_oc->pb);
    2338             :     }
    2339           1 :     av_freep(&vs->basename);
    2340           1 :     av_freep(&vs->base_output_dirname);
    2341           1 :     avformat_free_context(oc);
    2342             : 
    2343           1 :     vs->avf = NULL;
    2344           1 :     hls_window(s, 1, vs);
    2345             : 
    2346           1 :     av_freep(&vs->fmp4_init_filename);
    2347           1 :     if (vtt_oc) {
    2348           0 :         av_freep(&vs->vtt_basename);
    2349           0 :         av_freep(&vs->vtt_m3u8_name);
    2350           0 :         avformat_free_context(vtt_oc);
    2351             :     }
    2352             : 
    2353           1 :     hls_free_segments(vs->segments);
    2354           1 :     hls_free_segments(vs->old_segments);
    2355           1 :     av_free(old_filename);
    2356           1 :     av_freep(&vs->m3u8_name);
    2357           1 :     av_freep(&vs->streams);
    2358           1 :     av_freep(&vs->agroup);
    2359           1 :     av_freep(&vs->ccgroup);
    2360           1 :     av_freep(&vs->baseurl);
    2361             :     }
    2362             : 
    2363           1 :     for (i = 0; i < hls->nb_ccstreams; i++) {
    2364           0 :         ClosedCaptionsStream *ccs = &hls->cc_streams[i];
    2365           0 :         av_freep(&ccs->ccgroup);
    2366           0 :         av_freep(&ccs->instreamid);
    2367           0 :         av_freep(&ccs->language);
    2368             :     }
    2369             : 
    2370           1 :     ff_format_io_close(s, &hls->m3u8_out);
    2371           1 :     ff_format_io_close(s, &hls->sub_m3u8_out);
    2372           1 :     av_freep(&hls->key_basename);
    2373           1 :     av_freep(&hls->var_streams);
    2374           1 :     av_freep(&hls->cc_streams);
    2375           1 :     av_freep(&hls->master_m3u8_url);
    2376           1 :     return 0;
    2377             : }
    2378             : 
    2379             : 
    2380           1 : static int hls_init(AVFormatContext *s)
    2381             : {
    2382           1 :     int ret = 0;
    2383           1 :     int i = 0;
    2384           1 :     int j = 0;
    2385           1 :     HLSContext *hls = s->priv_data;
    2386           1 :     const char *pattern = "%d.ts";
    2387           1 :     VariantStream *vs = NULL;
    2388           1 :     int basename_size = 0;
    2389           1 :     const char *pattern_localtime_fmt = get_default_pattern_localtime_fmt(s);
    2390           1 :     const char *vtt_pattern = "%d.vtt";
    2391           1 :     char *p = NULL;
    2392           1 :     int vtt_basename_size = 0;
    2393           1 :     int fmp4_init_filename_len = strlen(hls->fmp4_init_filename) + 1;
    2394             : 
    2395           1 :     ret = update_variant_stream_info(s);
    2396           1 :     if (ret < 0) {
    2397           0 :         av_log(s, AV_LOG_ERROR, "Variant stream info update failed with status %x\n",
    2398             :                 ret);
    2399           0 :         goto fail;
    2400             :     }
    2401             :     //TODO: Updates needed to encryption functionality with periodic re-key when more than one variant streams are present
    2402           1 :     if (hls->nb_varstreams > 1 && hls->flags & HLS_PERIODIC_REKEY) {
    2403           0 :         ret = AVERROR(EINVAL);
    2404           0 :         av_log(s, AV_LOG_ERROR, "Periodic re-key not supported when more than one variant streams are present\n");
    2405           0 :         goto fail;
    2406             :     }
    2407             : 
    2408           1 :     ret = validate_name(hls->nb_varstreams, s->url);
    2409           1 :     if (ret < 0)
    2410           0 :         goto fail;
    2411             : 
    2412           1 :     if (hls->segment_filename) {
    2413           1 :         ret = validate_name(hls->nb_varstreams, hls->segment_filename);
    2414           1 :         if (ret < 0)
    2415           0 :             goto fail;
    2416             :     }
    2417             : 
    2418           1 :     if (av_strcasecmp(hls->fmp4_init_filename, "init.mp4")) {
    2419           0 :         ret = validate_name(hls->nb_varstreams, hls->fmp4_init_filename);
    2420           0 :         if (ret < 0)
    2421           0 :             goto fail;
    2422             :     }
    2423             : 
    2424           1 :     if (hls->subtitle_filename) {
    2425           0 :         ret = validate_name(hls->nb_varstreams, hls->subtitle_filename);
    2426           0 :         if (ret < 0)
    2427           0 :             goto fail;
    2428             :     }
    2429             : 
    2430           1 :     if (hls->master_pl_name) {
    2431           0 :         ret = update_master_pl_info(s);
    2432           0 :         if (ret < 0) {
    2433           0 :             av_log(s, AV_LOG_ERROR, "Master stream info update failed with status %x\n",
    2434             :                     ret);
    2435           0 :             goto fail;
    2436             :         }
    2437             :     }
    2438             : 
    2439           1 :     if (hls->segment_type == SEGMENT_TYPE_FMP4) {
    2440           0 :         pattern = "%d.m4s";
    2441             :     }
    2442           2 :     if ((hls->start_sequence_source_type == HLS_START_SEQUENCE_AS_SECONDS_SINCE_EPOCH) ||
    2443           1 :         (hls->start_sequence_source_type == HLS_START_SEQUENCE_AS_FORMATTED_DATETIME)) {
    2444           0 :         time_t t = time(NULL); // we will need it in either case
    2445           0 :         if (hls->start_sequence_source_type == HLS_START_SEQUENCE_AS_SECONDS_SINCE_EPOCH) {
    2446           0 :             hls->start_sequence = (int64_t)t;
    2447           0 :         } else if (hls->start_sequence_source_type == HLS_START_SEQUENCE_AS_FORMATTED_DATETIME) {
    2448             :             char b[15];
    2449             :             struct tm *p, tmbuf;
    2450           0 :             if (!(p = localtime_r(&t, &tmbuf)))
    2451           0 :                 return AVERROR(ENOMEM);
    2452           0 :             if (!strftime(b, sizeof(b), "%Y%m%d%H%M%S", p))
    2453           0 :                 return AVERROR(ENOMEM);
    2454           0 :             hls->start_sequence = strtoll(b, NULL, 10);
    2455             :         }
    2456           0 :         av_log(hls, AV_LOG_DEBUG, "start_number evaluated to %"PRId64"\n", hls->start_sequence);
    2457             :     }
    2458             : 
    2459           1 :     hls->recording_time = (hls->init_time ? hls->init_time : hls->time) * AV_TIME_BASE;
    2460           2 :     for (i = 0; i < hls->nb_varstreams; i++) {
    2461           1 :         vs = &hls->var_streams[i];
    2462             : 
    2463           1 :         vs->m3u8_name = av_strdup(s->url);
    2464           1 :         if (!vs->m3u8_name ) {
    2465           0 :             ret = AVERROR(ENOMEM);
    2466           0 :             goto fail;
    2467             :         }
    2468           1 :         ret = format_name(vs->m3u8_name, strlen(s->url) + 1, i);
    2469           1 :         if (ret < 0)
    2470           0 :             goto fail;
    2471             : 
    2472           1 :         vs->sequence       = hls->start_sequence;
    2473           1 :         vs->start_pts      = AV_NOPTS_VALUE;
    2474           1 :         vs->end_pts      = AV_NOPTS_VALUE;
    2475           1 :         vs->current_segment_final_filename_fmt[0] = '\0';
    2476             : 
    2477           1 :         if (hls->flags & HLS_SPLIT_BY_TIME && hls->flags & HLS_INDEPENDENT_SEGMENTS) {
    2478             :             // Independent segments cannot be guaranteed when splitting by time
    2479           0 :             hls->flags &= ~HLS_INDEPENDENT_SEGMENTS;
    2480           0 :             av_log(s, AV_LOG_WARNING,
    2481             :                    "'split_by_time' and 'independent_segments' cannot be enabled together. "
    2482             :                    "Disabling 'independent_segments' flag\n");
    2483             :         }
    2484             : 
    2485           1 :         if (hls->flags & HLS_PROGRAM_DATE_TIME) {
    2486             :             time_t now0;
    2487           0 :             time(&now0);
    2488           0 :             vs->initial_prog_date_time = now0;
    2489             :         }
    2490           1 :         if (hls->format_options_str) {
    2491           0 :             ret = av_dict_parse_string(&hls->format_options, hls->format_options_str, "=", ":", 0);
    2492           0 :             if (ret < 0) {
    2493           0 :                 av_log(s, AV_LOG_ERROR, "Could not parse format options list '%s'\n", hls->format_options_str);
    2494           0 :                 goto fail;
    2495             :             }
    2496             :         }
    2497             : 
    2498           2 :         for (j = 0; j < vs->nb_streams; j++) {
    2499           1 :             vs->has_video += vs->streams[j]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO;
    2500           1 :             vs->has_subtitle += vs->streams[j]->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE;
    2501             :         }
    2502             : 
    2503           1 :         if (vs->has_video > 1)
    2504           0 :             av_log(s, AV_LOG_WARNING, "More than a single video stream present, expect issues decoding it.\n");
    2505           1 :         if (hls->segment_type == SEGMENT_TYPE_FMP4) {
    2506           0 :             vs->oformat = av_guess_format("mp4", NULL, NULL);
    2507             :         } else {
    2508           1 :             vs->oformat = av_guess_format("mpegts", NULL, NULL);
    2509             :         }
    2510             : 
    2511           1 :         if (!vs->oformat) {
    2512           0 :             ret = AVERROR_MUXER_NOT_FOUND;
    2513           0 :             goto fail;
    2514             :         }
    2515             : 
    2516           1 :         if (vs->has_subtitle) {
    2517           0 :             vs->vtt_oformat = av_guess_format("webvtt", NULL, NULL);
    2518           0 :             if (!vs->oformat) {
    2519           0 :                 ret = AVERROR_MUXER_NOT_FOUND;
    2520           0 :                 goto fail;
    2521             :             }
    2522             :         }
    2523           1 :         if (hls->segment_filename) {
    2524           1 :             basename_size = strlen(hls->segment_filename) + 1;
    2525           1 :             vs->basename = av_malloc(basename_size);
    2526           1 :             if (!vs->basename) {
    2527           0 :                 ret = AVERROR(ENOMEM);
    2528           0 :                 goto fail;
    2529             :             }
    2530             : 
    2531           1 :             av_strlcpy(vs->basename, hls->segment_filename, basename_size);
    2532           1 :             ret = format_name(vs->basename, basename_size, i);
    2533           1 :             if (ret < 0)
    2534           0 :                 goto fail;
    2535             :         } else {
    2536           0 :             if (hls->flags & HLS_SINGLE_FILE) {
    2537           0 :                 if (hls->segment_type == SEGMENT_TYPE_FMP4) {
    2538           0 :                     pattern = ".m4s";
    2539             :                 } else {
    2540           0 :                     pattern = ".ts";
    2541             :                 }
    2542             :             }
    2543             : 
    2544           0 :             if (hls->use_localtime) {
    2545           0 :                 basename_size = strlen(vs->m3u8_name) + strlen(pattern_localtime_fmt) + 1;
    2546             :             } else {
    2547           0 :                 basename_size = strlen(vs->m3u8_name) + strlen(pattern) + 1;
    2548             :             }
    2549             : 
    2550           0 :             vs->basename = av_malloc(basename_size);
    2551           0 :             if (!vs->basename) {
    2552           0 :                 ret = AVERROR(ENOMEM);
    2553           0 :                 goto fail;
    2554             :             }
    2555             : 
    2556           0 :             av_strlcpy(vs->basename, vs->m3u8_name, basename_size);
    2557             : 
    2558           0 :             p = strrchr(vs->basename, '.');
    2559           0 :             if (p)
    2560           0 :                 *p = '\0';
    2561           0 :             if (hls->use_localtime) {
    2562           0 :                 av_strlcat(vs->basename, pattern_localtime_fmt, basename_size);
    2563             :             } else {
    2564           0 :                 av_strlcat(vs->basename, pattern, basename_size);
    2565             :             }
    2566             :         }
    2567             : 
    2568           1 :         if (hls->segment_type == SEGMENT_TYPE_FMP4) {
    2569           0 :             if (hls->nb_varstreams > 1)
    2570           0 :                 fmp4_init_filename_len += strlen(POSTFIX_PATTERN);
    2571           0 :             vs->fmp4_init_filename = av_malloc(fmp4_init_filename_len);
    2572           0 :             if (!vs->fmp4_init_filename ) {
    2573           0 :                 ret = AVERROR(ENOMEM);
    2574           0 :                 goto fail;
    2575             :             }
    2576           0 :             av_strlcpy(vs->fmp4_init_filename, hls->fmp4_init_filename,
    2577             :                        fmp4_init_filename_len);
    2578             : 
    2579           0 :             if (av_strcasecmp(hls->fmp4_init_filename, "init.mp4")) {
    2580           0 :                 ret = format_name(vs->fmp4_init_filename, fmp4_init_filename_len, i);
    2581           0 :                 if (ret < 0)
    2582           0 :                     goto fail;
    2583             : 
    2584           0 :                 fmp4_init_filename_len = strlen(vs->fmp4_init_filename) + 1;
    2585           0 :                 vs->base_output_dirname = av_malloc(fmp4_init_filename_len);
    2586           0 :                 if (!vs->base_output_dirname) {
    2587           0 :                     ret = AVERROR(ENOMEM);
    2588           0 :                     goto fail;
    2589             :                 }
    2590           0 :                 av_strlcpy(vs->base_output_dirname, vs->fmp4_init_filename,
    2591             :                            fmp4_init_filename_len);
    2592             :             } else {
    2593           0 :                 if (hls->nb_varstreams > 1) {
    2594           0 :                     ret = append_postfix(vs->fmp4_init_filename, fmp4_init_filename_len, i);
    2595           0 :                     if (ret < 0)
    2596           0 :                          goto fail;
    2597             :                 }
    2598             : 
    2599           0 :                 fmp4_init_filename_len = strlen(vs->m3u8_name) +
    2600           0 :                     strlen(vs->fmp4_init_filename) + 1;
    2601             : 
    2602           0 :                 vs->base_output_dirname = av_malloc(fmp4_init_filename_len);
    2603           0 :                 if (!vs->base_output_dirname) {
    2604           0 :                     ret = AVERROR(ENOMEM);
    2605           0 :                     goto fail;
    2606             :                 }
    2607             : 
    2608           0 :                 av_strlcpy(vs->base_output_dirname, vs->m3u8_name,
    2609             :                            fmp4_init_filename_len);
    2610           0 :                 p = strrchr(vs->base_output_dirname, '/');
    2611           0 :                 if (p) {
    2612           0 :                     *(p + 1) = '\0';
    2613           0 :                     av_strlcat(vs->base_output_dirname, vs->fmp4_init_filename,
    2614             :                                fmp4_init_filename_len);
    2615             :                 } else {
    2616           0 :                     av_strlcpy(vs->base_output_dirname, vs->fmp4_init_filename,
    2617             :                                fmp4_init_filename_len);
    2618             :                 }
    2619             :             }
    2620             :         }
    2621             : 
    2622           1 :         if (!hls->use_localtime) {
    2623           1 :             ret = sls_flag_check_duration_size_index(hls);
    2624           1 :             if (ret < 0) {
    2625           0 :                 goto fail;
    2626             :             }
    2627             :         } else {
    2628           0 :             ret = sls_flag_check_duration_size(hls, vs);
    2629           0 :             if (ret < 0) {
    2630           0 :                 goto fail;
    2631             :             }
    2632             :         }
    2633           1 :         if (vs->has_subtitle) {
    2634             : 
    2635           0 :             if (hls->flags & HLS_SINGLE_FILE)
    2636           0 :                 vtt_pattern = ".vtt";
    2637           0 :             vtt_basename_size = strlen(vs->m3u8_name) + strlen(vtt_pattern) + 1;
    2638             : 
    2639           0 :             vs->vtt_basename = av_malloc(vtt_basename_size);
    2640           0 :             if (!vs->vtt_basename) {
    2641           0 :                 ret = AVERROR(ENOMEM);
    2642           0 :                 goto fail;
    2643             :             }
    2644           0 :             vs->vtt_m3u8_name = av_malloc(vtt_basename_size);
    2645           0 :             if (!vs->vtt_m3u8_name ) {
    2646           0 :                 ret = AVERROR(ENOMEM);
    2647           0 :                 goto fail;
    2648             :             }
    2649           0 :             av_strlcpy(vs->vtt_basename, vs->m3u8_name, vtt_basename_size);
    2650           0 :             p = strrchr(vs->vtt_basename, '.');
    2651           0 :             if (p)
    2652           0 :                 *p = '\0';
    2653             : 
    2654           0 :             if ( hls->subtitle_filename ) {
    2655           0 :                 strcpy(vs->vtt_m3u8_name, hls->subtitle_filename);
    2656           0 :                 ret = format_name(vs->vtt_m3u8_name, vtt_basename_size, i);
    2657           0 :                 if (ret < 0)
    2658           0 :                     goto fail;
    2659             :             } else {
    2660           0 :                 strcpy(vs->vtt_m3u8_name, vs->vtt_basename);
    2661           0 :                 av_strlcat(vs->vtt_m3u8_name, "_vtt.m3u8", vtt_basename_size);
    2662             :             }
    2663           0 :             av_strlcat(vs->vtt_basename, vtt_pattern, vtt_basename_size);
    2664             :         }
    2665             : 
    2666           1 :         if (hls->baseurl) {
    2667           0 :             vs->baseurl = av_strdup(hls->baseurl);
    2668           0 :             if (!vs->baseurl) {
    2669           0 :                 ret = AVERROR(ENOMEM);
    2670           0 :                 goto fail;
    2671             :             }
    2672             :         }
    2673             : 
    2674           1 :         if ((hls->flags & HLS_SINGLE_FILE) && (hls->segment_type == SEGMENT_TYPE_FMP4)) {
    2675           0 :             vs->fmp4_init_filename  = av_strdup(vs->basename);
    2676           0 :             if (!vs->fmp4_init_filename) {
    2677           0 :                 ret = AVERROR(ENOMEM);
    2678           0 :                 goto fail;
    2679             :             }
    2680             :         }
    2681           1 :         if ((ret = hls_mux_init(s, vs)) < 0)
    2682           0 :             goto fail;
    2683             : 
    2684           1 :         if (hls->flags & HLS_APPEND_LIST) {
    2685           1 :             parse_playlist(s, vs->m3u8_name, vs);
    2686           1 :             vs->discontinuity = 1;
    2687           1 :             if (hls->init_time > 0) {
    2688           0 :                 av_log(s, AV_LOG_WARNING, "append_list mode does not support hls_init_time,"
    2689             :                        " hls_init_time value will have no effect\n");
    2690           0 :                 hls->init_time = 0;
    2691           0 :                 hls->recording_time = hls->time * AV_TIME_BASE;
    2692             :             }
    2693             :         }
    2694             : 
    2695           1 :         if ((ret = hls_start(s, vs)) < 0)
    2696           0 :             goto fail;
    2697             :     }
    2698             : 
    2699           1 : fail:
    2700           1 :     if (ret < 0) {
    2701           0 :         av_freep(&hls->key_basename);
    2702           0 :         for (i = 0; i < hls->nb_varstreams && hls->var_streams; i++) {
    2703           0 :             vs = &hls->var_streams[i];
    2704           0 :             av_freep(&vs->basename);
    2705           0 :             av_freep(&vs->vtt_basename);
    2706           0 :             av_freep(&vs->fmp4_init_filename);
    2707           0 :             av_freep(&vs->m3u8_name);
    2708           0 :             av_freep(&vs->vtt_m3u8_name);
    2709           0 :             av_freep(&vs->streams);
    2710           0 :             av_freep(&vs->agroup);
    2711           0 :             av_freep(&vs->ccgroup);
    2712           0 :             av_freep(&vs->baseurl);
    2713           0 :             if (vs->avf)
    2714           0 :                 avformat_free_context(vs->avf);
    2715           0 :             if (vs->vtt_avf)
    2716           0 :                 avformat_free_context(vs->vtt_avf);
    2717             :         }
    2718           0 :         for (i = 0; i < hls->nb_ccstreams; i++) {
    2719           0 :             ClosedCaptionsStream *ccs = &hls->cc_streams[i];
    2720           0 :             av_freep(&ccs->ccgroup);
    2721           0 :             av_freep(&ccs->instreamid);
    2722           0 :             av_freep(&ccs->language);
    2723             :         }
    2724           0 :         av_freep(&hls->var_streams);
    2725           0 :         av_freep(&hls->cc_streams);
    2726           0 :         av_freep(&hls->master_m3u8_url);
    2727             :     }
    2728             : 
    2729           1 :     return ret;
    2730             : }
    2731             : 
    2732             : #define OFFSET(x) offsetof(HLSContext, x)
    2733             : #define E AV_OPT_FLAG_ENCODING_PARAM
    2734             : static const AVOption options[] = {
    2735             :     {"start_number",  "set first number in the sequence",        OFFSET(start_sequence),AV_OPT_TYPE_INT64,  {.i64 = 0},     0, INT64_MAX, E},
    2736             :     {"hls_time",      "set segment length in seconds",           OFFSET(time),    AV_OPT_TYPE_FLOAT,  {.dbl = 2},     0, FLT_MAX, E},
    2737             :     {"hls_init_time", "set segment length in seconds at init list",           OFFSET(init_time),    AV_OPT_TYPE_FLOAT,  {.dbl = 0},     0, FLT_MAX, E},
    2738             :     {"hls_list_size", "set maximum number of playlist entries",  OFFSET(max_nb_segments),    AV_OPT_TYPE_INT,    {.i64 = 5},     0, INT_MAX, E},
    2739             :     {"hls_ts_options","set hls mpegts list of options for the container format used for hls", OFFSET(format_options_str), AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,    E},
    2740             :     {"hls_vtt_options","set hls vtt list of options for the container format used for hls", OFFSET(vtt_format_options_str), AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,    E},
    2741             : #if FF_API_HLS_WRAP
    2742             :     {"hls_wrap",      "set number after which the index wraps (will be deprecated)",  OFFSET(wrap),    AV_OPT_TYPE_INT,    {.i64 = 0},     0, INT_MAX, E},
    2743             : #endif
    2744             :     {"hls_allow_cache", "explicitly set whether the client MAY (1) or MUST NOT (0) cache media segments", OFFSET(allowcache), AV_OPT_TYPE_INT, {.i64 = -1}, INT_MIN, INT_MAX, E},
    2745             :     {"hls_base_url",  "url to prepend to each playlist entry",   OFFSET(baseurl), AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,       E},
    2746             :     {"hls_segment_filename", "filename template for segment files", OFFSET(segment_filename),   AV_OPT_TYPE_STRING, {.str = NULL},            0,       0,         E},
    2747             :     {"hls_segment_size", "maximum size per segment file, (in bytes)",  OFFSET(max_seg_size),    AV_OPT_TYPE_INT,    {.i64 = 0},               0,       INT_MAX,   E},
    2748             :     {"hls_key_info_file",    "file with key URI and key file path", OFFSET(key_info_file),      AV_OPT_TYPE_STRING, {.str = NULL},            0,       0,         E},
    2749             :     {"hls_enc",    "enable AES128 encryption support", OFFSET(encrypt),      AV_OPT_TYPE_BOOL, {.i64 = 0},            0,       1,         E},
    2750             :     {"hls_enc_key",    "hex-coded 16 byte key to encrypt the segments", OFFSET(key),      AV_OPT_TYPE_STRING, .flags = E},
    2751             :     {"hls_enc_key_url",    "url to access the key to decrypt the segments", OFFSET(key_url),      AV_OPT_TYPE_STRING, {.str = NULL},            0,       0,         E},
    2752             :     {"hls_enc_iv",    "hex-coded 16 byte initialization vector", OFFSET(iv),      AV_OPT_TYPE_STRING, .flags = E},
    2753             :     {"hls_subtitle_path",     "set path of hls subtitles", OFFSET(subtitle_filename), AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,    E},
    2754             :     {"hls_segment_type",     "set hls segment files type", OFFSET(segment_type), AV_OPT_TYPE_INT, {.i64 = SEGMENT_TYPE_MPEGTS }, 0, SEGMENT_TYPE_FMP4, E, "segment_type"},
    2755             :     {"mpegts",   "make segment file to mpegts files in m3u8", 0, AV_OPT_TYPE_CONST, {.i64 = SEGMENT_TYPE_MPEGTS }, 0, UINT_MAX,   E, "segment_type"},
    2756             :     {"fmp4",   "make segment file to fragment mp4 files in m3u8", 0, AV_OPT_TYPE_CONST, {.i64 = SEGMENT_TYPE_FMP4 }, 0, UINT_MAX,   E, "segment_type"},
    2757             :     {"hls_fmp4_init_filename", "set fragment mp4 file init filename", OFFSET(fmp4_init_filename),   AV_OPT_TYPE_STRING, {.str = "init.mp4"},            0,       0,         E},
    2758             :     {"hls_flags",     "set flags affecting HLS playlist and media file generation", OFFSET(flags), AV_OPT_TYPE_FLAGS, {.i64 = 0 }, 0, UINT_MAX, E, "flags"},
    2759             :     {"single_file",   "generate a single media file indexed with byte ranges", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_SINGLE_FILE }, 0, UINT_MAX,   E, "flags"},
    2760             :     {"temp_file", "write segment to temporary file and rename when complete", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_TEMP_FILE }, 0, UINT_MAX,   E, "flags"},
    2761             :     {"delete_segments", "delete segment files that are no longer part of the playlist", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_DELETE_SEGMENTS }, 0, UINT_MAX,   E, "flags"},
    2762             :     {"round_durations", "round durations in m3u8 to whole numbers", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_ROUND_DURATIONS }, 0, UINT_MAX,   E, "flags"},
    2763             :     {"discont_start", "start the playlist with a discontinuity tag", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_DISCONT_START }, 0, UINT_MAX,   E, "flags"},
    2764             :     {"omit_endlist", "Do not append an endlist when ending stream", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_OMIT_ENDLIST }, 0, UINT_MAX,   E, "flags"},
    2765             :     {"split_by_time", "split the hls segment by time which user set by hls_time", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_SPLIT_BY_TIME }, 0, UINT_MAX,   E, "flags"},
    2766             :     {"append_list", "append the new segments into old hls segment list", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_APPEND_LIST }, 0, UINT_MAX,   E, "flags"},
    2767             :     {"program_date_time", "add EXT-X-PROGRAM-DATE-TIME", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_PROGRAM_DATE_TIME }, 0, UINT_MAX,   E, "flags"},
    2768             :     {"second_level_segment_index", "include segment index in segment filenames when use_localtime", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_SECOND_LEVEL_SEGMENT_INDEX }, 0, UINT_MAX,   E, "flags"},
    2769             :     {"second_level_segment_duration", "include segment duration in segment filenames when use_localtime", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_SECOND_LEVEL_SEGMENT_DURATION }, 0, UINT_MAX,   E, "flags"},
    2770             :     {"second_level_segment_size", "include segment size in segment filenames when use_localtime", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_SECOND_LEVEL_SEGMENT_SIZE }, 0, UINT_MAX,   E, "flags"},
    2771             :     {"periodic_rekey", "reload keyinfo file periodically for re-keying", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_PERIODIC_REKEY }, 0, UINT_MAX,   E, "flags"},
    2772             :     {"independent_segments", "add EXT-X-INDEPENDENT-SEGMENTS, whenever applicable", 0, AV_OPT_TYPE_CONST, { .i64 = HLS_INDEPENDENT_SEGMENTS }, 0, UINT_MAX, E, "flags"},
    2773             :     {"use_localtime", "set filename expansion with strftime at segment creation", OFFSET(use_localtime), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, E },
    2774             :     {"use_localtime_mkdir", "create last directory component in strftime-generated filename", OFFSET(use_localtime_mkdir), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, E },
    2775             :     {"hls_playlist_type", "set the HLS playlist type", OFFSET(pl_type), AV_OPT_TYPE_INT, {.i64 = PLAYLIST_TYPE_NONE }, 0, PLAYLIST_TYPE_NB-1, E, "pl_type" },
    2776             :     {"event", "EVENT playlist", 0, AV_OPT_TYPE_CONST, {.i64 = PLAYLIST_TYPE_EVENT }, INT_MIN, INT_MAX, E, "pl_type" },
    2777             :     {"vod", "VOD playlist", 0, AV_OPT_TYPE_CONST, {.i64 = PLAYLIST_TYPE_VOD }, INT_MIN, INT_MAX, E, "pl_type" },
    2778             :     {"method", "set the HTTP method(default: PUT)", OFFSET(method), AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,    E},
    2779             :     {"hls_start_number_source", "set source of first number in sequence", OFFSET(start_sequence_source_type), AV_OPT_TYPE_INT, {.i64 = HLS_START_SEQUENCE_AS_START_NUMBER }, 0, HLS_START_SEQUENCE_AS_FORMATTED_DATETIME, E, "start_sequence_source_type" },
    2780             :     {"generic", "start_number value (default)", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_START_SEQUENCE_AS_START_NUMBER }, INT_MIN, INT_MAX, E, "start_sequence_source_type" },
    2781             :     {"epoch", "seconds since epoch", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_START_SEQUENCE_AS_SECONDS_SINCE_EPOCH }, INT_MIN, INT_MAX, E, "start_sequence_source_type" },
    2782             :     {"datetime", "current datetime as YYYYMMDDhhmmss", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_START_SEQUENCE_AS_FORMATTED_DATETIME }, INT_MIN, INT_MAX, E, "start_sequence_source_type" },
    2783             :     {"http_user_agent", "override User-Agent field in HTTP header", OFFSET(user_agent), AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,    E},
    2784             :     {"var_stream_map", "Variant stream map string", OFFSET(var_stream_map), AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,    E},
    2785             :     {"cc_stream_map", "Closed captions stream map string", OFFSET(cc_stream_map), AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,    E},
    2786             :     {"master_pl_name", "Create HLS master playlist with this name", OFFSET(master_pl_name), AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,    E},
    2787             :     {"master_pl_publish_rate", "Publish master play list every after this many segment intervals", OFFSET(master_publish_rate), AV_OPT_TYPE_INT, {.i64 = 0}, 0, UINT_MAX, E},
    2788             :     {"http_persistent", "Use persistent HTTP connections", OFFSET(http_persistent), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, E },
    2789             :     { NULL },
    2790             : };
    2791             : 
    2792             : static const AVClass hls_class = {
    2793             :     .class_name = "hls muxer",
    2794             :     .item_name  = av_default_item_name,
    2795             :     .option     = options,
    2796             :     .version    = LIBAVUTIL_VERSION_INT,
    2797             : };
    2798             : 
    2799             : 
    2800             : AVOutputFormat ff_hls_muxer = {
    2801             :     .name           = "hls",
    2802             :     .long_name      = NULL_IF_CONFIG_SMALL("Apple HTTP Live Streaming"),
    2803             :     .extensions     = "m3u8",
    2804             :     .priv_data_size = sizeof(HLSContext),
    2805             :     .audio_codec    = AV_CODEC_ID_AAC,
    2806             :     .video_codec    = AV_CODEC_ID_H264,
    2807             :     .subtitle_codec = AV_CODEC_ID_WEBVTT,
    2808             :     .flags          = AVFMT_NOFILE | AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH,
    2809             :     .init           = hls_init,
    2810             :     .write_header   = hls_write_header,
    2811             :     .write_packet   = hls_write_packet,
    2812             :     .write_trailer  = hls_write_trailer,
    2813             :     .priv_class     = &hls_class,
    2814             : };

Generated by: LCOV version 1.13