LCOV - code coverage report
Current view: top level - libavformat - hlsenc.c (source / functions) Hit Total Coverage
Test: coverage.info Lines: 516 1627 31.7 %
Date: 2018-05-20 11:54:08 Functions: 23 41 56.1 %

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

Generated by: LCOV version 1.13