LCOV - code coverage report
Current view: top level - libavformat - hlsenc.c (source / functions) Hit Total Coverage
Test: coverage.info Lines: 466 1300 35.8 %
Date: 2017-12-13 10:57:33 Functions: 22 37 59.5 %

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

Generated by: LCOV version 1.13