]> git.sesse.net Git - ffmpeg/blobdiff - libavformat/hlsenc.c
lavf/hls: add http_seekable option for HTTP partial requests
[ffmpeg] / libavformat / hlsenc.c
index ebe1ab62e534e1d9884e665486a6cfc3eedbdd22..51310fb52870892af74d12c84d8a5e87a743cd2a 100644 (file)
@@ -64,13 +64,13 @@ typedef enum {
 } CodecAttributeStatus;
 
 #define KEYSIZE 16
-#define LINE_BUFFER_SIZE 1024
+#define LINE_BUFFER_SIZE MAX_URL_SIZE
 #define HLS_MICROSECOND_UNIT   1000000
 #define POSTFIX_PATTERN "_%d"
 
 typedef struct HLSSegment {
-    char filename[1024];
-    char sub_filename[1024];
+    char filename[MAX_URL_SIZE];
+    char sub_filename[MAX_URL_SIZE];
     double duration; /* in seconds */
     int discont;
     int64_t pos;
@@ -149,7 +149,7 @@ typedef struct VariantStream {
     char *m3u8_name;
 
     double initial_prog_date_time;
-    char current_segment_final_filename_fmt[1024]; // when renaming segments
+    char current_segment_final_filename_fmt[MAX_URL_SIZE]; // when renaming segments
 
     char *fmp4_init_filename;
     char *base_output_dirname;
@@ -164,6 +164,7 @@ typedef struct VariantStream {
     char *agroup; /* audio group name */
     char *ccgroup; /* closed caption group name */
     char *baseurl;
+    char *varname; // variant name
 } VariantStream;
 
 typedef struct ClosedCaptionsStream {
@@ -236,6 +237,7 @@ typedef struct HLSContext {
     AVIOContext *sub_m3u8_out;
     int64_t timeout;
     int ignore_io_errors;
+    char *headers;
     int has_default_key; /* has DEFAULT field of var_stream_map */
     int has_video_m3u8; /* has video stream m3u8 list */
 } HLSContext;
@@ -293,6 +295,8 @@ static void set_http_options(AVFormatContext *s, AVDictionary **options, HLSCont
         av_dict_set_int(options, "multiple_requests", 1, 0);
     if (c->timeout >= 0)
         av_dict_set_int(options, "timeout", c->timeout, 0);
+    if (c->headers)
+        av_dict_set(options, "headers", c->headers, 0);
 }
 
 static void write_codec_attr(AVStream *st, VariantStream *vs) {
@@ -340,6 +344,47 @@ fail:
     return;
 }
 
+static int replace_str_data_in_filename(char **s, const char *filename, char placeholder, const char *datastring)
+{
+    const char *p;
+    char *new_filename;
+    char c;
+    int addchar_count;
+    int found_count = 0;
+    AVBPrint buf;
+
+    av_bprint_init(&buf, 0, AV_BPRINT_SIZE_UNLIMITED);
+
+    p = filename;
+    for (;;) {
+        c = *p;
+        if (c == '\0')
+            break;
+        if (c == '%' && *(p+1) == '%')  // %%
+            addchar_count = 2;
+        else if (c == '%' && *(p+1) == placeholder) {
+            av_bprintf(&buf, "%s", datastring);
+            p += 2;
+            addchar_count = 0;
+            found_count ++;
+        } else
+            addchar_count = 1;
+
+        if (addchar_count > 0) {
+            av_bprint_append_data(&buf, p, addchar_count);
+            p += addchar_count;
+        }
+    }
+    if (!av_bprint_is_complete(&buf)) {
+        av_bprint_finalize(&buf, NULL);
+        return -1;
+    }
+    if (av_bprint_finalize(&buf, &new_filename) < 0 || !new_filename)
+        return -1;
+    *s = new_filename;
+    return found_count;
+}
+
 static int replace_int_data_in_filename(char **s, const char *filename, char placeholder, int64_t number)
 {
     const char *p;
@@ -474,20 +519,27 @@ static int hls_delete_old_segments(AVFormatContext *s, HLSContext *hls,
 
     }
 
-    while (segment) {
+    /* if %v is present in the file's directory
+     * all segment belongs to the same variant, so do it only once before the loop*/
+    if (dirname && av_stristr(dirname, "%v")) {
         char * r_dirname = dirname;
-
-        /* if %v is present in the file's directory */
-        if (dirname && av_stristr(dirname, "%v")) {
-
+        if (!vs->varname) {
             if (replace_int_data_in_filename(&r_dirname, dirname, 'v', segment->var_stream_idx) < 1) {
                 ret = AVERROR(EINVAL);
                 goto fail;
             }
-            av_free(dirname);
-            dirname = r_dirname;
+        } else {
+            if (replace_str_data_in_filename(&r_dirname, dirname, 'v', vs->varname) < 1) {
+                ret = AVERROR(EINVAL);
+                goto fail;
+            }
         }
 
+        av_free(dirname);
+        dirname = r_dirname;
+    }
+
+    while (segment) {
         av_log(hls, AV_LOG_DEBUG, "deleting old segment %s\n",
                                   segment->filename);
         path_size =  (hls->use_localtime_mkdir ? 0 : strlen(dirname)) + strlen(segment->filename) + 1;
@@ -764,6 +816,10 @@ static int hls_mux_init(AVFormatContext *s, VariantStream *vs)
     vs->new_start = 1;
 
     if (hls->segment_type == SEGMENT_TYPE_FMP4) {
+        if (hls->http_persistent > 0) {
+            //TODO: Support fragment fmp4 for http persistent in HLS muxer.
+            av_log(s, AV_LOG_WARNING, "http persistent mode is currently unsupported for fragment mp4 in the HLS muxer.\n");
+        }
         if (hls->max_seg_size > 0) {
             av_log(s, AV_LOG_WARNING, "Multi-file byterange mode is currently unsupported in the HLS muxer.\n");
             return AVERROR_PATCHWELCOME;
@@ -1059,7 +1115,7 @@ static int parse_playlist(AVFormatContext *s, const char *url, VariantStream *vs
     AVIOContext *in;
     int ret = 0, is_segment = 0;
     int64_t new_start_pos;
-    char line[1024];
+    char line[MAX_URL_SIZE];
     const char *ptr;
     const char *end;
 
@@ -1211,8 +1267,12 @@ static int create_master_playlist(AVFormatContext *s,
     AVDictionary *options = NULL;
     unsigned int i, j;
     int m3u8_name_size, ret, bandwidth;
-    char *m3u8_rel_name, *ccgroup;
+    char *m3u8_rel_name = NULL, *ccgroup;
     ClosedCaptionsStream *ccs;
+    const char *proto = avio_find_protocol_name(hls->master_m3u8_url);
+    int is_file_proto = proto && !strcmp(proto, "file");
+    int use_temp_file = is_file_proto && ((hls->flags & HLS_TEMP_FILE) || hls->master_publish_rate);
+    char temp_filename[MAX_URL_SIZE];
 
     input_vs->m3u8_created = 1;
     if (!hls->master_m3u8_created) {
@@ -1228,12 +1288,12 @@ static int create_master_playlist(AVFormatContext *s,
     }
 
     set_http_options(s, &options, hls);
-
-    ret = hlsenc_io_open(s, &hls->m3u8_out, hls->master_m3u8_url, &options);
+    snprintf(temp_filename, sizeof(temp_filename), use_temp_file ? "%s.tmp" : "%s", hls->master_m3u8_url);
+    ret = hlsenc_io_open(s, &hls->m3u8_out, temp_filename, &options);
     av_dict_free(&options);
     if (ret < 0) {
         av_log(NULL, AV_LOG_ERROR, "Failed to open master play list file '%s'\n",
-                hls->master_m3u8_url);
+                temp_filename);
         goto fail;
     }
 
@@ -1364,7 +1424,10 @@ fail:
     if(ret >=0)
         hls->master_m3u8_created = 1;
     av_freep(&m3u8_rel_name);
-    hlsenc_io_close(s, &hls->m3u8_out, hls->master_m3u8_url);
+    hlsenc_io_close(s, &hls->m3u8_out, temp_filename);
+    if (use_temp_file)
+        ff_rename(temp_filename, hls->master_m3u8_url, s);
+
     return ret;
 }
 
@@ -1372,9 +1435,11 @@ static int hls_window(AVFormatContext *s, int last, VariantStream *vs)
 {
     HLSContext *hls = s->priv_data;
     HLSSegment *en;
+    AVFormatContext *oc = vs->avf;
     int target_duration = 0;
     int ret = 0;
-    char temp_filename[1024];
+    char temp_filename[MAX_URL_SIZE];
+    char temp_vtt_filename[MAX_URL_SIZE];
     int64_t sequence = FFMAX(hls->start_sequence, vs->sequence - vs->nb_entries);
     const char *proto = avio_find_protocol_name(vs->m3u8_name);
     int is_file_proto = proto && !strcmp(proto, "file");
@@ -1406,7 +1471,7 @@ static int hls_window(AVFormatContext *s, int last, VariantStream *vs)
 
     set_http_options(s, &options, hls);
     snprintf(temp_filename, sizeof(temp_filename), use_temp_file ? "%s.tmp" : "%s", vs->m3u8_name);
-    if ((ret = hlsenc_io_open(s, &hls->m3u8_out, temp_filename, &options)) < 0) {
+    if ((ret = hlsenc_io_open(s, (byterange_mode || hls->segment_type == SEGMENT_TYPE_FMP4) ? &hls->m3u8_out : &oc->pb, temp_filename, &options)) < 0) {
         if (hls->ignore_io_errors)
             ret = 0;
         goto fail;
@@ -1418,33 +1483,33 @@ static int hls_window(AVFormatContext *s, int last, VariantStream *vs)
     }
 
     vs->discontinuity_set = 0;
-    ff_hls_write_playlist_header(hls->m3u8_out, hls->version, hls->allowcache,
+    ff_hls_write_playlist_header((byterange_mode || hls->segment_type == SEGMENT_TYPE_FMP4) ? hls->m3u8_out : oc->pb, hls->version, hls->allowcache,
                                  target_duration, sequence, hls->pl_type, hls->flags & HLS_I_FRAMES_ONLY);
 
     if((hls->flags & HLS_DISCONT_START) && sequence==hls->start_sequence && vs->discontinuity_set==0 ){
-        avio_printf(hls->m3u8_out, "#EXT-X-DISCONTINUITY\n");
+        avio_printf((byterange_mode || hls->segment_type == SEGMENT_TYPE_FMP4) ? hls->m3u8_out : oc->pb, "#EXT-X-DISCONTINUITY\n");
         vs->discontinuity_set = 1;
     }
     if (vs->has_video && (hls->flags & HLS_INDEPENDENT_SEGMENTS)) {
-        avio_printf(hls->m3u8_out, "#EXT-X-INDEPENDENT-SEGMENTS\n");
+        avio_printf((byterange_mode || hls->segment_type == SEGMENT_TYPE_FMP4) ? hls->m3u8_out : oc->pb, "#EXT-X-INDEPENDENT-SEGMENTS\n");
     }
     for (en = vs->segments; en; en = en->next) {
         if ((hls->encrypt || hls->key_info_file) && (!key_uri || strcmp(en->key_uri, key_uri) ||
                                     av_strcasecmp(en->iv_string, iv_string))) {
-            avio_printf(hls->m3u8_out, "#EXT-X-KEY:METHOD=AES-128,URI=\"%s\"", en->key_uri);
+            avio_printf((byterange_mode || hls->segment_type == SEGMENT_TYPE_FMP4) ? hls->m3u8_out : oc->pb, "#EXT-X-KEY:METHOD=AES-128,URI=\"%s\"", en->key_uri);
             if (*en->iv_string)
-                avio_printf(hls->m3u8_out, ",IV=0x%s", en->iv_string);
-            avio_printf(hls->m3u8_out, "\n");
+                avio_printf((byterange_mode || hls->segment_type == SEGMENT_TYPE_FMP4) ? hls->m3u8_out : oc->pb, ",IV=0x%s", en->iv_string);
+            avio_printf((byterange_mode || hls->segment_type == SEGMENT_TYPE_FMP4) ? hls->m3u8_out : oc->pb, "\n");
             key_uri = en->key_uri;
             iv_string = en->iv_string;
         }
 
         if ((hls->segment_type == SEGMENT_TYPE_FMP4) && (en == vs->segments)) {
-            ff_hls_write_init_file(hls->m3u8_out, (hls->flags & HLS_SINGLE_FILE) ? en->filename : vs->fmp4_init_filename,
+            ff_hls_write_init_file((byterange_mode || hls->segment_type == SEGMENT_TYPE_FMP4) ? hls->m3u8_out : oc->pb, (hls->flags & HLS_SINGLE_FILE) ? en->filename : vs->fmp4_init_filename,
                                    hls->flags & HLS_SINGLE_FILE, vs->init_range_length, 0);
         }
 
-        ret = ff_hls_write_file_entry(hls->m3u8_out, en->discont, byterange_mode,
+        ret = ff_hls_write_file_entry((byterange_mode || hls->segment_type == SEGMENT_TYPE_FMP4) ? hls->m3u8_out : oc->pb, en->discont, byterange_mode,
                                       en->duration, hls->flags & HLS_ROUND_DURATIONS,
                                       en->size, en->pos, vs->baseurl,
                                       en->filename, prog_date_time_p, en->keyframe_size, en->keyframe_pos, hls->flags & HLS_I_FRAMES_ONLY);
@@ -1454,10 +1519,11 @@ static int hls_window(AVFormatContext *s, int last, VariantStream *vs)
     }
 
     if (last && (hls->flags & HLS_OMIT_ENDLIST)==0)
-        ff_hls_write_end_list(hls->m3u8_out);
+        ff_hls_write_end_list((byterange_mode || hls->segment_type == SEGMENT_TYPE_FMP4) ? hls->m3u8_out : oc->pb);
 
-    if( vs->vtt_m3u8_name ) {
-        if ((ret = hlsenc_io_open(s, &hls->sub_m3u8_out, vs->vtt_m3u8_name, &options)) < 0) {
+    if (vs->vtt_m3u8_name) {
+        snprintf(temp_vtt_filename, sizeof(temp_vtt_filename), use_temp_file ? "%s.tmp" : "%s", vs->vtt_m3u8_name);
+        if ((ret = hlsenc_io_open(s, &hls->sub_m3u8_out, temp_vtt_filename, &options)) < 0) {
             if (hls->ignore_io_errors)
                 ret = 0;
             goto fail;
@@ -1480,10 +1546,13 @@ static int hls_window(AVFormatContext *s, int last, VariantStream *vs)
 
 fail:
     av_dict_free(&options);
-    hlsenc_io_close(s, &hls->m3u8_out, temp_filename);
+    hlsenc_io_close(s, (byterange_mode || hls->segment_type == SEGMENT_TYPE_FMP4) ? &hls->m3u8_out : &oc->pb, temp_filename);
     hlsenc_io_close(s, &hls->sub_m3u8_out, vs->vtt_m3u8_name);
-    if (use_temp_file)
+    if (use_temp_file) {
         ff_rename(temp_filename, vs->m3u8_name, s);
+        if (vs->vtt_m3u8_name)
+            ff_rename(temp_vtt_filename, vs->vtt_m3u8_name, s);
+    }
     if (ret >= 0 && hls->master_pl_name)
         if (create_master_playlist(s, vs) < 0)
             av_log(s, AV_LOG_WARNING, "Master playlist creation failed\n");
@@ -1530,7 +1599,7 @@ static int hls_start(AVFormatContext *s, VariantStream *vs)
         if (c->use_localtime) {
             time_t now0;
             struct tm *tm, tmpbuf;
-            int bufsize = strlen(vs->basename) + 1024;
+            int bufsize = strlen(vs->basename) + MAX_URL_SIZE;
             char *buf = av_mallocz(bufsize);
             if (!buf)
                 return AVERROR(ENOMEM);
@@ -1743,15 +1812,15 @@ static int validate_name(int nb_vs, const char *fn)
     subdir_name = av_dirname(fn_dup);
 
     if (nb_vs > 1 && !av_stristr(filename, "%v") && !av_stristr(subdir_name, "%v")) {
-        av_log(NULL, AV_LOG_ERROR, "More than 1 variant streams are present, %%v is expected in the filename %s\n",
-                fn);
+        av_log(NULL, AV_LOG_ERROR, "More than 1 variant streams are present, %%v is expected "
+               "either in the filename or in the sub-directory name of file %s\n", fn);
         ret = AVERROR(EINVAL);
         goto fail;
     }
 
     if (av_stristr(filename, "%v") && av_stristr(subdir_name, "%v")) {
-        av_log(NULL, AV_LOG_ERROR, "%%v is expected either in filename or in the sub-directory name of file %s\n",
-                fn);
+        av_log(NULL, AV_LOG_ERROR, "%%v is expected either in the filename or "
+               "in the sub-directory name of file %s, but only in one of them\n", fn);
         ret = AVERROR(EINVAL);
         goto fail;
     }
@@ -1761,7 +1830,7 @@ fail:
     return ret;
 }
 
-static int format_name(const char *buf, char **s, int index)
+static int format_name(const char *buf, char **s, int index, const char *varname)
 {
     const char *proto, *dir;
     char *orig_buf_dup = NULL, *mod_buf_dup = NULL;
@@ -1778,9 +1847,16 @@ static int format_name(const char *buf, char **s, int index)
         return ret;
     }
 
-    if (replace_int_data_in_filename(s, orig_buf_dup, 'v', index) < 1) {
-        ret = AVERROR(EINVAL);
-        goto fail;
+    if (!varname) {
+        if (replace_int_data_in_filename(s, orig_buf_dup, 'v', index) < 1) {
+            ret = AVERROR(EINVAL);
+            goto fail;
+        }
+    } else {
+        if (replace_str_data_in_filename(s, orig_buf_dup, 'v', varname) < 1) {
+            ret = AVERROR(EINVAL);
+            goto fail;
+        }
     }
 
     proto = avio_find_protocol_name(orig_buf_dup);
@@ -1829,7 +1905,7 @@ static int parse_variant_stream_mapstring(AVFormatContext *s)
 {
     HLSContext *hls = s->priv_data;
     VariantStream *vs;
-    int stream_index;
+    int stream_index, i, j;
     enum AVMediaType codec_type;
     int nb_varstreams, nb_streams;
     char *p, *q, *saveptr1, *saveptr2, *varstr, *keyval;
@@ -1898,6 +1974,11 @@ static int parse_variant_stream_mapstring(AVFormatContext *s)
                                   (!av_strncasecmp(val, "1", strlen("1"))));
                 hls->has_default_key = 1;
                 continue;
+            } else if (av_strstart(keyval, "name:", &val)) {
+                vs->varname = av_strdup(val);
+                if (!vs->varname)
+                    return AVERROR(ENOMEM);
+                continue;
             } else if (av_strstart(keyval, "agroup:", &val)) {
                 vs->agroup = av_strdup(val);
                 if (!vs->agroup)
@@ -1926,6 +2007,23 @@ static int parse_variant_stream_mapstring(AVFormatContext *s)
                                                            atoi(val));
 
             if (stream_index >= 0 && nb_streams < vs->nb_streams) {
+                for(i = 0; nb_streams > 0 && i < nb_streams; i++) {
+                    if (vs->streams[i] == s->streams[stream_index]) {
+                        av_log(s, AV_LOG_ERROR, "Same elementary stream found more than once inside "
+                               "variant definition #%d\n", nb_varstreams - 1);
+                        return AVERROR(EINVAL);
+                    }
+                }
+                for(j = 0; nb_varstreams > 1 && j < nb_varstreams - 1; j++) {
+                    for(i = 0; i < hls->var_streams[j].nb_streams; i++) {
+                        if (hls->var_streams[j].streams[i] == s->streams[stream_index]) {
+                            av_log(s, AV_LOG_ERROR, "Same elementary stream found more than once "
+                                   "in two different variant definitions #%d and #%d\n",
+                                   j, nb_varstreams - 1);
+                            return AVERROR(EINVAL);
+                        }
+                    }
+                }
                 vs->streams[nb_streams++] = s->streams[stream_index];
             } else {
                 av_log(s, AV_LOG_ERROR, "Unable to map stream at %s\n", keyval);
@@ -2203,8 +2301,8 @@ static int hls_write_packet(AVFormatContext *s, AVPacket *pkt)
 
     if (vs->sequence - vs->nb_entries > hls->start_sequence && hls->init_time > 0) {
         /* reset end_pts, hls->recording_time at end of the init hls list */
-        int init_list_dur = hls->init_time * vs->nb_entries * AV_TIME_BASE;
-        int after_init_list_dur = (vs->sequence - hls->start_sequence - vs->nb_entries ) * (hls->time * AV_TIME_BASE);
+        int64_t init_list_dur = hls->init_time * vs->nb_entries * AV_TIME_BASE;
+        int64_t after_init_list_dur = (vs->sequence - hls->start_sequence - vs->nb_entries ) * (hls->time * AV_TIME_BASE);
         hls->recording_time = hls->time * AV_TIME_BASE;
         end_pts = init_list_dur + after_init_list_dur ;
     }
@@ -2342,6 +2440,12 @@ static int hls_write_packet(AVFormatContext *s, AVPacket *pkt)
         } else {
             vs->start_pos += vs->size;
         }
+        // if we're building a VOD playlist, skip writing the manifest multiple times, and just wait until the end
+        if (hls->pl_type != PLAYLIST_TYPE_VOD) {
+            if ((ret = hls_window(s, 0, vs)) < 0) {
+                return ret;
+            }
+        }
 
         if (hls->flags & HLS_SINGLE_FILE) {
             vs->number++;
@@ -2366,12 +2470,6 @@ static int hls_write_packet(AVFormatContext *s, AVPacket *pkt)
             return ret;
         }
 
-        // if we're building a VOD playlist, skip writing the manifest multiple times, and just wait until the end
-        if (hls->pl_type != PLAYLIST_TYPE_VOD) {
-            if ((ret = hls_window(s, 0, vs)) < 0) {
-                return ret;
-            }
-        }
     }
 
     vs->packets_written++;
@@ -2417,6 +2515,7 @@ static void hls_free_variant_streams(struct HLSContext *hls)
         av_freep(&vs->language);
         av_freep(&vs->ccgroup);
         av_freep(&vs->baseurl);
+        av_freep(&vs->varname);
     }
 }
 
@@ -2491,7 +2590,7 @@ failed:
         if (oc->pb) {
             if (hls->segment_type != SEGMENT_TYPE_FMP4) {
                 vs->size = avio_tell(vs->avf->pb) - vs->start_pos;
-                ff_format_io_close(s, &oc->pb);
+                hlsenc_io_close(s, &vs->avf->pb, vs->avf->url);
             }
 
             // rename that segment from .tmp to the real one
@@ -2518,10 +2617,10 @@ failed:
             ff_format_io_close(s, &vtt_oc->pb);
             avformat_free_context(vtt_oc);
         }
+        hls_window(s, 1, vs);
         avformat_free_context(oc);
 
         vs->avf = NULL;
-        hls_window(s, 1, vs);
         av_free(old_filename);
     }
 
@@ -2629,12 +2728,7 @@ static int hls_init(AVFormatContext *s)
     for (i = 0; i < hls->nb_varstreams; i++) {
         vs = &hls->var_streams[i];
 
-        vs->m3u8_name = av_strdup(s->url);
-        if (!vs->m3u8_name ) {
-            ret = AVERROR(ENOMEM);
-            goto fail;
-        }
-        ret = format_name(s->url, i, vs->m3u8_name);
+        ret = format_name(s->url, &vs->m3u8_name, i, vs->varname);
         if (ret < 0)
             goto fail;
 
@@ -2695,17 +2789,10 @@ static int hls_init(AVFormatContext *s)
             }
         }
         if (hls->segment_filename) {
-            basename_size = strlen(hls->segment_filename) + 1;
-            vs->basename = av_malloc(basename_size);
-            if (!vs->basename) {
-                ret = AVERROR(ENOMEM);
-                goto fail;
-            }
-
-            av_strlcpy(vs->basename, hls->segment_filename, basename_size);
-            ret = format_name(vs->basename, basename_size, i);
+            ret = format_name(hls->segment_filename, &vs->basename, i, vs->varname);
             if (ret < 0)
                 goto fail;
+            basename_size = strlen(vs->basename) + 1;
         } else {
             if (hls->flags & HLS_SINGLE_FILE) {
                 if (hls->segment_type == SEGMENT_TYPE_FMP4) {
@@ -2758,7 +2845,8 @@ static int hls_init(AVFormatContext *s)
                            fmp4_init_filename_len);
                 if (hls->nb_varstreams > 1) {
                     if (av_stristr(vs->fmp4_init_filename, "%v")) {
-                        format_name(vs->fmp4_init_filename, fmp4_init_filename_len, i);
+                        av_freep(&vs->fmp4_init_filename);
+                        format_name(hls->fmp4_init_filename, &vs->fmp4_init_filename, i, vs->varname);
                     } else {
                         ret = append_postfix(vs->fmp4_init_filename, fmp4_init_filename_len, i);
                     }
@@ -2822,8 +2910,8 @@ static int hls_init(AVFormatContext *s)
                 *p = '\0';
 
             if ( hls->subtitle_filename ) {
-                strcpy(vs->vtt_m3u8_name, hls->subtitle_filename);
-                ret = format_name(vs->vtt_m3u8_name, vtt_basename_size, i);
+                av_freep(&vs->vtt_m3u8_name);
+                ret = format_name(hls->subtitle_filename, &vs->vtt_m3u8_name, i, vs->varname);
                 if (ret < 0)
                     goto fail;
             } else {
@@ -2874,6 +2962,7 @@ fail:
             av_freep(&vs->agroup);
             av_freep(&vs->ccgroup);
             av_freep(&vs->baseurl);
+            av_freep(&vs->varname);
             if (vs->avf)
                 avformat_free_context(vs->avf);
             if (vs->vtt_avf)
@@ -2922,7 +3011,7 @@ static const AVOption options[] = {
     {"hls_fmp4_init_filename", "set fragment mp4 file init filename", OFFSET(fmp4_init_filename),   AV_OPT_TYPE_STRING, {.str = "init.mp4"},            0,       0,         E},
     {"hls_flags",     "set flags affecting HLS playlist and media file generation", OFFSET(flags), AV_OPT_TYPE_FLAGS, {.i64 = 0 }, 0, UINT_MAX, E, "flags"},
     {"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"},
-    {"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"},
+    {"temp_file", "write segment and playlist to temporary file and rename when complete", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_TEMP_FILE }, 0, UINT_MAX,   E, "flags"},
     {"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"},
     {"round_durations", "round durations in m3u8 to whole numbers", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_ROUND_DURATIONS }, 0, UINT_MAX,   E, "flags"},
     {"discont_start", "start the playlist with a discontinuity tag", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_DISCONT_START }, 0, UINT_MAX,   E, "flags"},
@@ -2960,6 +3049,7 @@ static const AVOption options[] = {
     {"http_persistent", "Use persistent HTTP connections", OFFSET(http_persistent), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, E },
     {"timeout", "set timeout for socket I/O operations", OFFSET(timeout), AV_OPT_TYPE_DURATION, { .i64 = -1 }, -1, INT_MAX, .flags = E },
     {"ignore_io_errors", "Ignore IO errors for stable long-duration runs with network output", OFFSET(ignore_io_errors), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
+    {"headers", "set custom HTTP headers, can override built in default headers", OFFSET(headers), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, E },
     { NULL },
 };