]> git.sesse.net Git - ffmpeg/blobdiff - libavformat/hlsenc.c
avformat/hlsenc: avformat/hlsenc: reopen new http session for http_persistent
[ffmpeg] / libavformat / hlsenc.c
index 03a32b65d80733b382093ca02d2a33210b72e02c..52ee8941a1e032734a3668e90023cd5018dca14f 100644 (file)
@@ -53,9 +53,9 @@
 #include "os_support.h"
 
 typedef enum {
-  HLS_START_SEQUENCE_AS_START_NUMBER = 0,
-  HLS_START_SEQUENCE_AS_SECONDS_SINCE_EPOCH = 1,
-  HLS_START_SEQUENCE_AS_FORMATTED_DATETIME = 2,  // YYYYMMDDhhmmss
+    HLS_START_SEQUENCE_AS_START_NUMBER = 0,
+    HLS_START_SEQUENCE_AS_SECONDS_SINCE_EPOCH = 1,
+    HLS_START_SEQUENCE_AS_FORMATTED_DATETIME = 2,  // YYYYMMDDhhmmss
 } StartSequenceSourceType;
 
 typedef enum {
@@ -64,17 +64,19 @@ 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;
     int64_t size;
+    int64_t keyframe_pos;
+    int64_t keyframe_size;
     unsigned var_stream_idx;
 
     char key_uri[LINE_BUFFER_SIZE + 1];
@@ -99,6 +101,7 @@ typedef enum HLSFlags {
     HLS_TEMP_FILE = (1 << 11),
     HLS_PERIODIC_REKEY = (1 << 12),
     HLS_INDEPENDENT_SEGMENTS = (1 << 13),
+    HLS_I_FRAMES_ONLY = (1 << 14),
 } HLSFlags;
 
 typedef enum {
@@ -110,11 +113,12 @@ typedef struct VariantStream {
     unsigned var_stream_idx;
     unsigned number;
     int64_t sequence;
-    AVOutputFormat *oformat;
-    AVOutputFormat *vtt_oformat;
+    ff_const59 AVOutputFormat *oformat;
+    ff_const59 AVOutputFormat *vtt_oformat;
     AVIOContext *out;
     int packets_written;
     int init_range_length;
+    uint8_t *temp_buffer;
 
     AVFormatContext *avf;
     AVFormatContext *vtt_avf;
@@ -125,6 +129,9 @@ typedef struct VariantStream {
     double dpp;           // duration per packet
     int64_t start_pts;
     int64_t end_pts;
+    int64_t video_lastpos;
+    int64_t video_keyframe_pos;
+    int64_t video_keyframe_size;
     double duration;      // last segment duration computed so far, in seconds
     int64_t start_pos;    // last segment starting position
     int64_t size;         // last segment size
@@ -143,7 +150,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;
@@ -153,9 +160,12 @@ typedef struct VariantStream {
     CodecAttributeStatus attr_status;
     unsigned int nb_streams;
     int m3u8_created; /* status of media play-list creation */
+    int is_default; /* default status of audio group */
+    char *language; /* audio lauguage name */
     char *agroup; /* audio group name */
     char *ccgroup; /* closed caption group name */
     char *baseurl;
+    char *varname; // variant name
 } VariantStream;
 
 typedef struct ClosedCaptionsStream {
@@ -228,6 +238,9 @@ 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;
 
 static int hlsenc_io_open(AVFormatContext *s, AVIOContext **pb, char *filename,
@@ -250,11 +263,12 @@ static int hlsenc_io_open(AVFormatContext *s, AVIOContext **pb, char *filename,
     return err;
 }
 
-static void hlsenc_io_close(AVFormatContext *s, AVIOContext **pb, char *filename) {
+static int hlsenc_io_close(AVFormatContext *s, AVIOContext **pb, char *filename) {
     HLSContext *hls = s->priv_data;
     int http_base_proto = filename ? ff_is_http_proto(filename) : 0;
+    int ret = 0;
     if (!*pb)
-        return;
+        return ret;
     if (!http_base_proto || !hls->http_persistent || hls->key_info_file || hls->encrypt) {
         ff_format_io_close(s, pb);
 #if CONFIG_HTTP_PROTOCOL
@@ -263,8 +277,10 @@ static void hlsenc_io_close(AVFormatContext *s, AVIOContext **pb, char *filename
         av_assert0(http_url_context);
         avio_flush(*pb);
         ffurl_shutdown(http_url_context, AVIO_FLAG_WRITE);
+        ret = ff_http_get_shutdown_status(http_url_context);
 #endif
     }
+    return ret;
 }
 
 static void set_http_options(AVFormatContext *s, AVDictionary **options, HLSContext *c)
@@ -283,6 +299,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) {
@@ -330,6 +348,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;
@@ -392,7 +451,6 @@ static void write_styp(AVIOContext *pb)
 static int flush_dynbuf(VariantStream *vs, int *range_length)
 {
     AVFormatContext *ctx = vs->avf;
-    uint8_t *buffer;
 
     if (!ctx->pb) {
         return AVERROR(EINVAL);
@@ -403,15 +461,20 @@ static int flush_dynbuf(VariantStream *vs, int *range_length)
     avio_flush(ctx->pb);
 
     // write out to file
-    *range_length = avio_close_dyn_buf(ctx->pb, &buffer);
+    *range_length = avio_close_dyn_buf(ctx->pb, &vs->temp_buffer);
     ctx->pb = NULL;
-    avio_write(vs->out, buffer, *range_length);
-    av_free(buffer);
+    avio_write(vs->out, vs->temp_buffer, *range_length);
 
     // re-open buffer
     return avio_open_dyn_buf(&ctx->pb);
 }
 
+static void reflush_dynbuf(VariantStream *vs, int *range_length)
+{
+    // re-open buffer
+    avio_write(vs->out, vs->temp_buffer, *range_length);;
+}
+
 static int hls_delete_old_segments(AVFormatContext *s, HLSContext *hls,
                                    VariantStream *vs) {
 
@@ -450,36 +513,38 @@ static int hls_delete_old_segments(AVFormatContext *s, HLSContext *hls,
     }
 
     if (segment && !hls->use_localtime_mkdir) {
-        if (hls->segment_filename) {
-            dirname = av_strdup(hls->segment_filename);
-        } else {
-            dirname = av_strdup(vs->avf->url);
-        }
+        dirname = hls->segment_filename ? av_strdup(hls->segment_filename): av_strdup(vs->avf->url);
         if (!dirname) {
             ret = AVERROR(ENOMEM);
             goto fail;
         }
         p = (char *)av_basename(dirname);
         *p = '\0';
-
     }
 
-    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);
+               segment->filename);
         path_size =  (hls->use_localtime_mkdir ? 0 : strlen(dirname)) + strlen(segment->filename) + 1;
         path = av_malloc(path_size);
         if (!path) {
@@ -505,7 +570,7 @@ static int hls_delete_old_segments(AVFormatContext *s, HLSContext *hls,
             ff_format_io_close(vs->avf, &out);
         } else if (unlink(path) < 0) {
             av_log(hls, AV_LOG_ERROR, "failed to delete old segment %s: %s\n",
-                                     path, strerror(errno));
+                   path, strerror(errno));
         }
 
         if ((segment->sub_filename[0] != '\0')) {
@@ -537,7 +602,7 @@ static int hls_delete_old_segments(AVFormatContext *s, HLSContext *hls,
                 ff_format_io_close(vs->vtt_avf, &out);
             } else if (unlink(sub_path) < 0) {
                 av_log(hls, AV_LOG_ERROR, "failed to delete old segment %s: %s\n",
-                                         sub_path, strerror(errno));
+                       sub_path, strerror(errno));
             }
             av_free(sub_path);
         }
@@ -647,7 +712,7 @@ static int hls_encryption_start(AVFormatContext *s)
 
     if ((ret = s->io_open(s, &pb, hls->key_info_file, AVIO_FLAG_READ, NULL)) < 0) {
         av_log(hls, AV_LOG_ERROR,
-                "error opening key info file %s\n", hls->key_info_file);
+               "error opening key info file %s\n", hls->key_info_file);
         return ret;
     }
 
@@ -753,39 +818,47 @@ static int hls_mux_init(AVFormatContext *s, VariantStream *vs)
     vs->start_pos = 0;
     vs->new_start = 1;
 
-    if (hls->segment_type == SEGMENT_TYPE_FMP4) {
+    if (hls->segment_type == SEGMENT_TYPE_FMP4 && hls->max_seg_size > 0) {
+        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;
         }
+    }
 
-        vs->packets_written = 0;
-        vs->init_range_length = 0;
-        set_http_options(s, &options, hls);
-        if ((ret = avio_open_dyn_buf(&oc->pb)) < 0)
-            return ret;
+    vs->packets_written = 0;
+    vs->init_range_length = 0;
+    set_http_options(s, &options, hls);
+    if ((ret = avio_open_dyn_buf(&oc->pb)) < 0)
+        return ret;
 
+    if (hls->segment_type == SEGMENT_TYPE_FMP4) {
         if (byterange_mode) {
             ret = hlsenc_io_open(s, &vs->out, vs->basename, &options);
         } else {
             ret = hlsenc_io_open(s, &vs->out, vs->base_output_dirname, &options);
         }
-        av_dict_free(&options);
+    }
+    av_dict_free(&options);
+    if (ret < 0) {
+        av_log(s, AV_LOG_ERROR, "Failed to open segment '%s'\n", vs->fmp4_init_filename);
+        return ret;
+    }
+
+    if (hls->format_options_str) {
+        ret = av_dict_parse_string(&hls->format_options, hls->format_options_str, "=", ":", 0);
         if (ret < 0) {
-            av_log(s, AV_LOG_ERROR, "Failed to open segment '%s'\n", vs->fmp4_init_filename);
+            av_log(s, AV_LOG_ERROR, "Could not parse format options list '%s'\n",
+                   hls->format_options_str);
             return ret;
         }
+    }
 
-        if (hls->format_options_str) {
-            ret = av_dict_parse_string(&hls->format_options, hls->format_options_str, "=", ":", 0);
-            if (ret < 0) {
-                av_log(s, AV_LOG_ERROR, "Could not parse format options list '%s'\n",
-                       hls->format_options_str);
-                return ret;
-            }
-        }
-
-        av_dict_copy(&options, hls->format_options, 0);
+    av_dict_copy(&options, hls->format_options, 0);
+    if (hls->segment_type == SEGMENT_TYPE_FMP4) {
         av_dict_set(&options, "fflags", "-autobsf", 0);
         av_dict_set(&options, "movflags", "+frag_custom+dash+delay_moov", AV_DICT_APPEND);
         ret = avformat_init_output(oc, &options);
@@ -796,9 +869,9 @@ static int hls_mux_init(AVFormatContext *s, VariantStream *vs)
             av_dict_free(&options);
             return AVERROR(EINVAL);
         }
-        avio_flush(oc->pb);
-        av_dict_free(&options);
     }
+    avio_flush(oc->pb);
+    av_dict_free(&options);
     return 0;
 }
 
@@ -829,7 +902,7 @@ static int sls_flags_filename_process(struct AVFormatContext *s, HLSContext *hls
             if (replace_int_data_in_filename(&filename, vs->avf->url, 's', pos + size) < 1) {
                 av_log(hls, AV_LOG_ERROR,
                        "Invalid second level segment filename template '%s', "
-                        "you can try to remove second_level_segment_size flag\n",
+                       "you can try to remove second_level_segment_size flag\n",
                        vs->avf->url);
                 av_free(filename);
                 av_free(en);
@@ -840,10 +913,10 @@ static int sls_flags_filename_process(struct AVFormatContext *s, HLSContext *hls
         if (hls->flags & HLS_SECOND_LEVEL_SEGMENT_DURATION) {
             char *filename = NULL;
             if (replace_int_data_in_filename(&filename, vs->avf->url,
-                't',  (int64_t)round(duration * HLS_MICROSECOND_UNIT)) < 1) {
+                                             't',  (int64_t)round(duration * HLS_MICROSECOND_UNIT)) < 1) {
                 av_log(hls, AV_LOG_ERROR,
                        "Invalid second level segment filename template '%s', "
-                        "you can try to remove second_level_segment_time flag\n",
+                       "you can try to remove second_level_segment_time flag\n",
                        vs->avf->url);
                 av_free(filename);
                 av_free(en);
@@ -860,14 +933,14 @@ static int sls_flag_check_duration_size_index(HLSContext *hls)
     int ret = 0;
 
     if (hls->flags & HLS_SECOND_LEVEL_SEGMENT_DURATION) {
-         av_log(hls, AV_LOG_ERROR,
-                "second_level_segment_duration hls_flag requires strftime to be true\n");
-         ret = AVERROR(EINVAL);
+        av_log(hls, AV_LOG_ERROR,
+               "second_level_segment_duration hls_flag requires strftime to be true\n");
+        ret = AVERROR(EINVAL);
     }
     if (hls->flags & HLS_SECOND_LEVEL_SEGMENT_SIZE) {
-         av_log(hls, AV_LOG_ERROR,
-                "second_level_segment_size hls_flag requires strfime to be true\n");
-         ret = AVERROR(EINVAL);
+        av_log(hls, AV_LOG_ERROR,
+               "second_level_segment_size hls_flag requires strfime to be true\n");
+        ret = AVERROR(EINVAL);
     }
     if (hls->flags & HLS_SECOND_LEVEL_SEGMENT_INDEX) {
         av_log(hls, AV_LOG_ERROR,
@@ -885,14 +958,14 @@ static int sls_flag_check_duration_size(HLSContext *hls, VariantStream *vs)
     int ret = 0;
 
     if ((hls->flags & HLS_SECOND_LEVEL_SEGMENT_DURATION) && !segment_renaming_ok) {
-         av_log(hls, AV_LOG_ERROR,
-                "second_level_segment_duration hls_flag works only with file protocol segment names\n");
-         ret = AVERROR(EINVAL);
+        av_log(hls, AV_LOG_ERROR,
+               "second_level_segment_duration hls_flag works only with file protocol segment names\n");
+        ret = AVERROR(EINVAL);
     }
     if ((hls->flags & HLS_SECOND_LEVEL_SEGMENT_SIZE) && !segment_renaming_ok) {
-         av_log(hls, AV_LOG_ERROR,
-                "second_level_segment_size hls_flag works only with file protocol segment names\n");
-         ret = AVERROR(EINVAL);
+        av_log(hls, AV_LOG_ERROR,
+               "second_level_segment_size hls_flag works only with file protocol segment names\n");
+        ret = AVERROR(EINVAL);
     }
 
     return ret;
@@ -990,6 +1063,8 @@ static int hls_append_segment(struct AVFormatContext *s, HLSContext *hls,
     en->duration = duration;
     en->pos      = pos;
     en->size     = size;
+    en->keyframe_pos      = vs->video_keyframe_pos;
+    en->keyframe_size     = vs->video_keyframe_size;
     en->next     = NULL;
     en->discont  = 0;
 
@@ -1047,7 +1122,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;
 
@@ -1157,22 +1232,22 @@ static int hls_rename_temp_file(AVFormatContext *s, AVFormatContext *oc)
     return ret;
 }
 
-static int get_relative_url(const char *master_url, const char *media_url,
-                            char *rel_url, int rel_url_buf_size)
+static const char* get_relative_url(const char *master_url, const char *media_url)
 {
-    char *p = NULL;
-    int base_len = -1;
-    p = strrchr(master_url, '/') ? strrchr(master_url, '/') :\
-            strrchr(master_url, '\\');
+    const char *p = strrchr(master_url, '/');
+    size_t base_len = 0;
+
+    if (!p) p = strrchr(master_url, '\\');
+
     if (p) {
-        base_len = FFABS(p - master_url);
+        base_len = p + 1 - master_url;
         if (av_strncasecmp(master_url, media_url, base_len)) {
             av_log(NULL, AV_LOG_WARNING, "Unable to find relative url\n");
-            return AVERROR(EINVAL);
+            return NULL;
         }
     }
-    av_strlcpy(rel_url, &(media_url[base_len + 1]), rel_url_buf_size);
-    return 0;
+
+    return media_url + base_len;
 }
 
 static int64_t get_stream_bit_rate(AVStream *stream) {
@@ -1198,9 +1273,14 @@ static int create_master_playlist(AVFormatContext *s,
     AVStream *vid_st, *aud_st;
     AVDictionary *options = NULL;
     unsigned int i, j;
-    int m3u8_name_size, ret, bandwidth;
-    char *m3u8_rel_name, *ccgroup;
+    int ret, bandwidth;
+    const char *m3u8_rel_name = NULL;
+    char *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) {
@@ -1216,12 +1296,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;
     }
 
@@ -1244,39 +1324,21 @@ static int create_master_playlist(AVFormatContext *s,
         if (vs->has_video || vs->has_subtitle || !vs->agroup)
             continue;
 
-        m3u8_name_size = strlen(vs->m3u8_name) + 1;
-        m3u8_rel_name = av_malloc(m3u8_name_size);
+        m3u8_rel_name = get_relative_url(hls->master_m3u8_url, vs->m3u8_name);
         if (!m3u8_rel_name) {
-            ret = AVERROR(ENOMEM);
-            goto fail;
-        }
-        av_strlcpy(m3u8_rel_name, vs->m3u8_name, m3u8_name_size);
-        ret = get_relative_url(hls->master_m3u8_url, vs->m3u8_name,
-                               m3u8_rel_name, m3u8_name_size);
-        if (ret < 0) {
             av_log(s, AV_LOG_ERROR, "Unable to find relative URL\n");
             goto fail;
         }
 
-        ff_hls_write_audio_rendition(hls->m3u8_out, vs->agroup, m3u8_rel_name, 0, 1);
-
-        av_freep(&m3u8_rel_name);
+        ff_hls_write_audio_rendition(hls->m3u8_out, vs->agroup, m3u8_rel_name, vs->language, i, hls->has_default_key ? vs->is_default : 1);
     }
 
     /* For variant streams with video add #EXT-X-STREAM-INF tag with attributes*/
     for (i = 0; i < hls->nb_varstreams; i++) {
         vs = &(hls->var_streams[i]);
 
-        m3u8_name_size = strlen(vs->m3u8_name) + 1;
-        m3u8_rel_name = av_malloc(m3u8_name_size);
+        m3u8_rel_name = get_relative_url(hls->master_m3u8_url, vs->m3u8_name);
         if (!m3u8_rel_name) {
-            ret = AVERROR(ENOMEM);
-            goto fail;
-        }
-        av_strlcpy(m3u8_rel_name, vs->m3u8_name, m3u8_name_size);
-        ret = get_relative_url(hls->master_m3u8_url, vs->m3u8_name,
-                               m3u8_rel_name, m3u8_name_size);
-        if (ret < 0) {
             av_log(NULL, AV_LOG_ERROR, "Unable to find relative URL\n");
             goto fail;
         }
@@ -1336,16 +1398,23 @@ static int create_master_playlist(AVFormatContext *s,
                         vs->ccgroup);
         }
 
-        ff_hls_write_stream_info(vid_st, hls->m3u8_out, bandwidth, m3u8_rel_name,
-                aud_st ? vs->agroup : NULL, vs->codec_attr, ccgroup);
-
-        av_freep(&m3u8_rel_name);
+        if (!hls->has_default_key || !hls->has_video_m3u8) {
+            ff_hls_write_stream_info(vid_st, hls->m3u8_out, bandwidth, m3u8_rel_name,
+                    aud_st ? vs->agroup : NULL, vs->codec_attr, ccgroup);
+        } else {
+            if (vid_st) {
+                ff_hls_write_stream_info(vid_st, hls->m3u8_out, bandwidth, m3u8_rel_name,
+                                         aud_st ? vs->agroup : NULL, vs->codec_attr, ccgroup);
+            }
+        }
     }
 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;
 }
 
@@ -1355,10 +1424,12 @@ static int hls_window(AVFormatContext *s, int last, VariantStream *vs)
     HLSSegment *en;
     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(s->url);
-    int use_temp_file = proto && !strcmp(proto, "file") && (s->flags & HLS_TEMP_FILE);
+    const char *proto = avio_find_protocol_name(vs->m3u8_name);
+    int is_file_proto = proto && !strcmp(proto, "file");
+    int use_temp_file = is_file_proto && ((hls->flags & HLS_TEMP_FILE) || !(hls->pl_type == PLAYLIST_TYPE_VOD));
     static unsigned warned_non_file;
     char *key_uri = NULL;
     char *iv_string = NULL;
@@ -1381,12 +1452,12 @@ static int hls_window(AVFormatContext *s, int last, VariantStream *vs)
         hls->version = 7;
     }
 
-    if (!use_temp_file && !warned_non_file++)
+    if (!is_file_proto && (hls->flags & HLS_TEMP_FILE) && !warned_non_file++)
         av_log(s, AV_LOG_ERROR, "Cannot use rename on non file protocol, this may lead to races and temporary partial files\n");
 
     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 : &vs->out, temp_filename, &options)) < 0) {
         if (hls->ignore_io_errors)
             ret = 0;
         goto fail;
@@ -1398,56 +1469,57 @@ 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,
-                                 target_duration, sequence, hls->pl_type);
+    ff_hls_write_playlist_header((byterange_mode || hls->segment_type == SEGMENT_TYPE_FMP4) ? hls->m3u8_out : vs->out, 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 : vs->out, "#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 : vs->out, "#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 : vs->out, "#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 : vs->out, ",IV=0x%s", en->iv_string);
+            avio_printf((byterange_mode || hls->segment_type == SEGMENT_TYPE_FMP4) ? hls->m3u8_out : vs->out, "\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 : vs->out, (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 : vs->out, en->discont, byterange_mode,
                                       en->duration, hls->flags & HLS_ROUND_DURATIONS,
                                       en->size, en->pos, vs->baseurl,
-                                      en->filename, prog_date_time_p);
+                                      en->filename, prog_date_time_p, en->keyframe_size, en->keyframe_pos, hls->flags & HLS_I_FRAMES_ONLY);
         if (ret < 0) {
             av_log(s, AV_LOG_WARNING, "ff_hls_write_file_entry get error\n");
         }
     }
 
     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 : vs->out);
 
-    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;
         }
         ff_hls_write_playlist_header(hls->sub_m3u8_out, hls->version, hls->allowcache,
-                                     target_duration, sequence, PLAYLIST_TYPE_NONE);
+                                     target_duration, sequence, PLAYLIST_TYPE_NONE, 0);
         for (en = vs->segments; en; en = en->next) {
             ret = ff_hls_write_file_entry(hls->sub_m3u8_out, 0, byterange_mode,
                                           en->duration, 0, en->size, en->pos,
-                                          vs->baseurl, en->sub_filename, NULL);
+                                          vs->baseurl, en->sub_filename, NULL, 0, 0, 0);
             if (ret < 0) {
                 av_log(s, AV_LOG_WARNING, "ff_hls_write_file_entry get error\n");
             }
@@ -1460,10 +1532,16 @@ static int hls_window(AVFormatContext *s, int last, VariantStream *vs)
 
 fail:
     av_dict_free(&options);
-    hlsenc_io_close(s, &hls->m3u8_out, temp_filename);
+    ret = hlsenc_io_close(s, (byterange_mode || hls->segment_type == SEGMENT_TYPE_FMP4) ? &hls->m3u8_out : &vs->out, temp_filename);
+    if (ret < 0) {
+        return ret;
+    }
     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");
@@ -1477,9 +1555,9 @@ static int hls_start(AVFormatContext *s, VariantStream *vs)
     AVFormatContext *oc = vs->avf;
     AVFormatContext *vtt_oc = vs->vtt_avf;
     AVDictionary *options = NULL;
-    const char *proto = avio_find_protocol_name(s->url);
-    int use_temp_file = proto && !strcmp(proto, "file") && (s->flags & HLS_TEMP_FILE);
-    char *filename, iv_string[KEYSIZE*2 + 1];
+    const char *proto = NULL;
+    int use_temp_file = 0;
+    char iv_string[KEYSIZE*2 + 1];
     int err = 0;
 
     if (c->flags & HLS_SINGLE_FILE) {
@@ -1510,7 +1588,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);
@@ -1574,6 +1652,9 @@ static int hls_start(AVFormatContext *s, VariantStream *vs)
 
     set_http_options(s, &options, c);
 
+    proto = avio_find_protocol_name(oc->url);
+    use_temp_file = proto && !strcmp(proto, "file") && (c->flags & HLS_TEMP_FILE);
+
     if (use_temp_file) {
         char *new_name = av_asprintf("%s.tmp", oc->url);
         if (!new_name)
@@ -1602,42 +1683,13 @@ static int hls_start(AVFormatContext *s, VariantStream *vs)
             }
             c->encrypt_started = 1;
         }
-        if ((err = av_dict_set(&options, "encryption_key", c->key_string, 0))
-                < 0)
-            goto fail;
         err = av_strlcpy(iv_string, c->iv_string, sizeof(iv_string));
-        if (!err)
+        if (!err) {
             snprintf(iv_string, sizeof(iv_string), "%032"PRIx64, vs->sequence);
-        if ((err = av_dict_set(&options, "encryption_iv", iv_string, 0)) < 0)
-           goto fail;
-
-        filename = av_asprintf("crypto:%s", oc->url);
-        if (!filename) {
-            err = AVERROR(ENOMEM);
-            goto fail;
-        }
-        err = hlsenc_io_open(s, &oc->pb, filename, &options);
-        av_free(filename);
-        av_dict_free(&options);
-        if (err < 0)
-            return err;
-    } else if (c->segment_type != SEGMENT_TYPE_FMP4) {
-        if ((err = hlsenc_io_open(s, &oc->pb, oc->url, &options)) < 0) {
-            if (c->ignore_io_errors)
-                err = 0;
-            goto fail;
-        }
-    }
-    if (vs->vtt_basename) {
-        set_http_options(s, &options, c);
-        if ((err = hlsenc_io_open(s, &vtt_oc->pb, vtt_oc->url, &options)) < 0) {
-            if (c->ignore_io_errors)
-                err = 0;
-            goto fail;
+            memset(c->iv_string, 0, sizeof(c->iv_string));
+            memcpy(c->iv_string, iv_string, sizeof(iv_string));
         }
     }
-    av_dict_free(&options);
-
     if (c->segment_type != SEGMENT_TYPE_FMP4) {
         /* We only require one PAT/PMT per segment. */
         if (oc->oformat->priv_class && oc->priv_data) {
@@ -1649,7 +1701,23 @@ static int hls_start(AVFormatContext *s, VariantStream *vs)
             av_opt_set(oc->priv_data, "sdt_period", period, 0);
             av_opt_set(oc->priv_data, "pat_period", period, 0);
         }
+        if (c->flags & HLS_SINGLE_FILE) {
+            if ((err = hlsenc_io_open(s, &vs->out, oc->url, &options)) < 0) {
+                if (c->ignore_io_errors)
+                    err = 0;
+                goto fail;
+            }
+        }
     }
+    if (vs->vtt_basename) {
+        set_http_options(s, &options, c);
+        if ((err = hlsenc_io_open(s, &vtt_oc->pb, vtt_oc->url, &options)) < 0) {
+            if (c->ignore_io_errors)
+                err = 0;
+            goto fail;
+        }
+    }
+    av_dict_free(&options);
 
     if (vs->vtt_basename) {
         err = avformat_write_header(vtt_oc,NULL);
@@ -1720,15 +1788,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;
     }
@@ -1738,33 +1806,41 @@ fail:
     return ret;
 }
 
-static int format_name(char *buf, int buf_len, 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 = NULL, *mod_buf_dup = NULL;
+    char *orig_buf_dup = NULL, *mod_buf_dup = NULL;
     int ret = 0;
 
-    if (!av_stristr(buf, "%v"))
-        return ret;
-
     orig_buf_dup = av_strdup(buf);
     if (!orig_buf_dup) {
         ret = AVERROR(ENOMEM);
         goto fail;
     }
 
-    if (replace_int_data_in_filename(&mod_buf, orig_buf_dup, 'v', index) < 1) {
-        ret = AVERROR(EINVAL);
-        goto fail;
+    if (!av_stristr(buf, "%v")) {
+        *s = orig_buf_dup;
+        return ret;
+    }
+
+    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;
+        }
     }
-    av_strlcpy(buf, mod_buf, buf_len);
 
     proto = avio_find_protocol_name(orig_buf_dup);
     dir = av_dirname(orig_buf_dup);
 
     /* if %v is present in the file's directory, create sub-directory */
     if (av_stristr(dir, "%v") && proto && !strcmp(proto, "file")) {
-        mod_buf_dup = av_strdup(buf);
+        mod_buf_dup = av_strdup(*s);
         if (!mod_buf_dup) {
             ret = AVERROR(ENOMEM);
             goto fail;
@@ -1780,7 +1856,6 @@ static int format_name(char *buf, int buf_len, int index)
 fail:
     av_freep(&orig_buf_dup);
     av_freep(&mod_buf_dup);
-    av_freep(&mod_buf);
     return ret;
 }
 
@@ -1806,7 +1881,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;
@@ -1815,7 +1890,7 @@ static int parse_variant_stream_mapstring(AVFormatContext *s)
     /**
      * Expected format for var_stream_map string is as below:
      * "a:0,v:0 a:1,v:1"
-     * "a:0,agroup:a0 a:1,agroup:a1 v:0,agroup:a0  v:1,agroup:a1"
+     * "a:0,agroup:a0,default:1,language:ENG a:1,agroup:a1,default:0 v:0,agroup:a0  v:1,agroup:a1"
      * This string specifies how to group the audio, video and subtitle streams
      * into different variant streams. The variant stream groups are separated
      * by space.
@@ -1846,6 +1921,7 @@ static int parse_variant_stream_mapstring(AVFormatContext *s)
         if (nb_varstreams < hls->nb_varstreams) {
             vs = &(hls->var_streams[nb_varstreams]);
             vs->var_stream_idx = nb_varstreams;
+            vs->is_default = 0;
             nb_varstreams++;
         } else
             return AVERROR(EINVAL);
@@ -1864,8 +1940,22 @@ static int parse_variant_stream_mapstring(AVFormatContext *s)
         nb_streams = 0;
         while (keyval = av_strtok(varstr, ",", &saveptr2)) {
             varstr = NULL;
-
-            if (av_strstart(keyval, "agroup:", &val)) {
+            if (av_strstart(keyval, "language:", &val)) {
+                vs->language = av_strdup(val);
+                if (!vs->language)
+                    return AVERROR(ENOMEM);
+                continue;
+            } else if (av_strstart(keyval, "default:", &val)) {
+                vs->is_default = (!av_strncasecmp(val, "YES", strlen("YES")) ||
+                                  (!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)
                     return AVERROR(ENOMEM);
@@ -1877,6 +1967,7 @@ static int parse_variant_stream_mapstring(AVFormatContext *s)
                 continue;
             } else if (av_strstart(keyval, "v:", &val)) {
                 codec_type = AVMEDIA_TYPE_VIDEO;
+                hls->has_video_m3u8 = 1;
             } else if (av_strstart(keyval, "a:", &val)) {
                 codec_type = AVMEDIA_TYPE_AUDIO;
             } else if (av_strstart(keyval, "s:", &val)) {
@@ -1892,6 +1983,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);
@@ -2009,14 +2117,18 @@ static int update_variant_stream_info(AVFormatContext *s) {
         hls->var_streams[0].nb_streams = s->nb_streams;
         hls->var_streams[0].streams = av_mallocz(sizeof(AVStream *) *
                                             hls->var_streams[0].nb_streams);
-        if (!hls->var_streams[0].streams)
+        if (!hls->var_streams[0].streams) {
+            av_free(hls->var_streams);
             return AVERROR(ENOMEM);
+        }
 
         //by default, the first available ccgroup is mapped to the variant stream
         if (hls->nb_ccstreams) {
             hls->var_streams[0].ccgroup = av_strdup(hls->cc_streams[0].ccgroup);
-            if (!hls->var_streams[0].ccgroup)
+            if (!hls->var_streams[0].ccgroup) {
+                av_free(hls->var_streams);
                 return AVERROR(ENOMEM);
+            }
         }
 
         for (i = 0; i < s->nb_streams; i++)
@@ -2073,7 +2185,6 @@ static int hls_write_header(AVFormatContext *s)
 {
     HLSContext *hls = s->priv_data;
     int ret, i, j;
-    AVDictionary *options = NULL;
     VariantStream *vs = NULL;
 
     for (i = 0; i < hls->nb_varstreams; i++) {
@@ -2121,7 +2232,6 @@ static int hls_write_header(AVFormatContext *s)
             }
         }
     }
-fail:
 
     return ret;
 }
@@ -2136,8 +2246,8 @@ static int hls_write_packet(AVFormatContext *s, AVPacket *pkt)
     int ret = 0, can_split = 1, i, j;
     int stream_index = 0;
     int range_length = 0;
-    const char *proto = avio_find_protocol_name(s->url);
-    int use_temp_file = proto && !strcmp(proto, "file") && (s->flags & HLS_TEMP_FILE);
+    const char *proto = NULL;
+    int use_temp_file = 0;
     uint8_t *buffer = NULL;
     VariantStream *vs = NULL;
     AVDictionary *options = NULL;
@@ -2171,8 +2281,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 ;
     }
@@ -2181,7 +2291,7 @@ static int hls_write_packet(AVFormatContext *s, AVPacket *pkt)
         vs->start_pts = pkt->pts;
     }
 
-    if (vs->has_video) {
+   if (vs->has_video) {
         can_split = st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
                     ((pkt->flags & AV_PKT_FLAG_KEY) || (hls->flags & HLS_SPLIT_BY_TIME));
         is_ref_pkt = (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) && (pkt->stream_index == vs->reference_stream_index);
@@ -2213,18 +2323,12 @@ static int hls_write_packet(AVFormatContext *s, AVPacket *pkt)
         int64_t new_start_pos;
         int byterange_mode = (hls->flags & HLS_SINGLE_FILE) || (hls->max_seg_size > 0);
 
-        av_write_frame(vs->avf, NULL); /* Flush any buffered data */
-
-        new_start_pos = avio_tell(vs->avf->pb);
-        if (hls->segment_type != SEGMENT_TYPE_FMP4) {
-            vs->size = new_start_pos - vs->start_pos;
-        } else {
-            vs->size = new_start_pos;
-        }
-
+        av_write_frame(oc, NULL); /* Flush any buffered data */
+        new_start_pos = avio_tell(oc->pb);
+        vs->size = new_start_pos - vs->start_pos;
+        avio_flush(oc->pb);
         if (hls->segment_type == SEGMENT_TYPE_FMP4) {
             if (!vs->init_range_length) {
-                avio_flush(oc->pb);
                 range_length = avio_close_dyn_buf(oc->pb, &buffer);
                 avio_write(vs->out, buffer, range_length);
                 av_free(buffer);
@@ -2233,14 +2337,9 @@ static int hls_write_packet(AVFormatContext *s, AVPacket *pkt)
                 vs->packets_written = 0;
                 vs->start_pos = range_length;
                 if (!byterange_mode) {
-                    ff_format_io_close(s, &vs->out);
                     hlsenc_io_close(s, &vs->out, vs->base_output_dirname);
                 }
             }
-        } else {
-            if (!byterange_mode) {
-                hlsenc_io_close(s, &oc->pb, oc->url);
-            }
         }
         if (!byterange_mode) {
             if (vs->vtt_avf) {
@@ -2248,51 +2347,68 @@ static int hls_write_packet(AVFormatContext *s, AVPacket *pkt)
             }
         }
 
+        if (oc->url[0]) {
+            proto = avio_find_protocol_name(oc->url);
+            use_temp_file = proto && !strcmp(proto, "file") && (hls->flags & HLS_TEMP_FILE);
+        }
+
         // look to rename the asset name
-        if (use_temp_file && oc->url[0]) {
-            if (!(hls->flags & HLS_SINGLE_FILE) || (hls->max_seg_size <= 0))
-                if ((vs->avf->oformat->priv_class && vs->avf->priv_data) && hls->segment_type != SEGMENT_TYPE_FMP4) {
-                    av_opt_set(vs->avf->priv_data, "mpegts_flags", "resend_headers", 0);
-                }
+        if (use_temp_file) {
+            av_dict_set(&options, "mpegts_flags", "resend_headers", 0);
         }
 
-        if (hls->segment_type == SEGMENT_TYPE_FMP4) {
-            if (hls->flags & HLS_SINGLE_FILE) {
-                ret = flush_dynbuf(vs, &range_length);
-                if (ret < 0) {
-                    av_free(old_filename);
-                    return ret;
+        if (hls->flags & HLS_SINGLE_FILE) {
+            ret = flush_dynbuf(vs, &range_length);
+            if (ret < 0) {
+                return ret;
+            }
+            vs->size = range_length;
+        } else {
+            set_http_options(s, &options, hls);
+            if ((hls->max_seg_size > 0 && (vs->size >= hls->max_seg_size)) || !byterange_mode) {
+                char *filename = NULL;
+                if (hls->key_info_file || hls->encrypt) {
+                    av_dict_set(&options, "encryption_key", hls->key_string, 0);
+                    av_dict_set(&options, "encryption_iv", hls->iv_string, 0);
+                    filename = av_asprintf("crypto:%s", oc->url);
+                } else {
+                    filename = av_asprintf("%s", oc->url);
                 }
-                vs->size = range_length;
-            } else {
-                set_http_options(s, &options, hls);
-                ret = hlsenc_io_open(s, &vs->out, vs->avf->url, &options);
+                if (!filename) {
+                    return AVERROR(ENOMEM);
+                }
+                ret = hlsenc_io_open(s, &vs->out, filename, &options);
                 if (ret < 0) {
                     av_log(s, hls->ignore_io_errors ? AV_LOG_WARNING : AV_LOG_ERROR,
-                           "Failed to open file '%s'\n", vs->avf->url);
+                           "Failed to open file '%s'\n", filename);
                     return hls->ignore_io_errors ? 0 : ret;
                 }
-                write_styp(vs->out);
+                if (hls->segment_type == SEGMENT_TYPE_FMP4) {
+                    write_styp(vs->out);
+                }
                 ret = flush_dynbuf(vs, &range_length);
                 if (ret < 0) {
                     return ret;
                 }
-                ff_format_io_close(s, &vs->out);
-
-                // rename that segment from .tmp to the real one
-                if (use_temp_file && oc->url[0]) {
-                    hls_rename_temp_file(s, oc);
-                    av_free(old_filename);
-                    old_filename = av_strdup(vs->avf->url);
-
-                    if (!old_filename) {
-                        return AVERROR(ENOMEM);
-                    }
+                ret = hlsenc_io_close(s, &vs->out, filename);
+                if (ret < 0) {
+                    av_log(s, AV_LOG_WARNING, "upload segment failed,"
+                           " will retry with a new http session.\n");
+                    ff_format_io_close(s, &vs->out);
+                    ret = hlsenc_io_open(s, &vs->out, filename, &options);
+                    reflush_dynbuf(vs, &range_length);
+                    ret = hlsenc_io_close(s, &vs->out, filename);
                 }
+                av_free(vs->temp_buffer);
+                av_free(filename);
             }
         }
 
-        old_filename = av_strdup(vs->avf->url);
+        if (use_temp_file && !(hls->flags & HLS_SINGLE_FILE)) {
+            hls_rename_temp_file(s, oc);
+        }
+
+        old_filename = av_strdup(oc->url);
         if (!old_filename) {
             return AVERROR(ENOMEM);
         }
@@ -2307,16 +2423,25 @@ static int hls_write_packet(AVFormatContext *s, AVPacket *pkt)
             }
         }
 
-        if (hls->segment_type != SEGMENT_TYPE_FMP4) {
-            vs->start_pos = new_start_pos;
-        } 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) {
+                av_log(s, AV_LOG_WARNING, "upload playlist failed, will retry with a new http session.\n");
+                ff_format_io_close(s, &vs->out);
+                vs->out = NULL;
+                if ((ret = hls_window(s, 0, vs)) < 0) {
+                    av_free(old_filename);
+                    return ret;
+                }
+            }
         }
 
         if (hls->flags & HLS_SINGLE_FILE) {
             vs->number++;
+            vs->start_pos += vs->size;
         } else if (hls->max_seg_size > 0) {
-            if (vs->start_pos >= hls->max_seg_size) {
+            vs->start_pos = new_start_pos;
+            if (vs->size >= hls->max_seg_size) {
                 vs->sequence++;
                 sls_flag_file_rename(hls, vs, old_filename);
                 ret = hls_start(s, vs);
@@ -2327,6 +2452,7 @@ static int hls_write_packet(AVFormatContext *s, AVPacket *pkt)
             }
             vs->number++;
         } else {
+            vs->start_pos = new_start_pos;
             sls_flag_file_rename(hls, vs, old_filename);
             ret = hls_start(s, vs);
         }
@@ -2336,17 +2462,17 @@ 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++;
     if (oc->pb) {
         ret = ff_write_chained(oc, stream_index, pkt, s, 0);
+        vs->video_keyframe_size += pkt->size;
+        if ((st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) && (pkt->flags & AV_PKT_FLAG_KEY)) {
+            vs->video_keyframe_size = avio_tell(oc->pb);
+        } else {
+            vs->video_keyframe_pos = avio_tell(vs->out);
+        }
         if (hls->ignore_io_errors)
             ret = 0;
     }
@@ -2354,33 +2480,77 @@ static int hls_write_packet(AVFormatContext *s, AVPacket *pkt)
     return ret;
 }
 
+static void hls_free_variant_streams(struct HLSContext *hls)
+{
+    int i = 0;
+    AVFormatContext *vtt_oc = NULL;
+    VariantStream *vs = NULL;
+
+    for (i = 0; i < hls->nb_varstreams; i++) {
+        vs = &hls->var_streams[i];
+        vtt_oc = vs->vtt_avf;
+
+        av_freep(&vs->basename);
+        av_freep(&vs->base_output_dirname);
+        av_freep(&vs->fmp4_init_filename);
+        if (vtt_oc) {
+            av_freep(&vs->vtt_basename);
+            av_freep(&vs->vtt_m3u8_name);
+        }
+
+        hls_free_segments(vs->segments);
+        hls_free_segments(vs->old_segments);
+        av_freep(&vs->m3u8_name);
+        av_freep(&vs->streams);
+        av_freep(&vs->agroup);
+        av_freep(&vs->language);
+        av_freep(&vs->ccgroup);
+        av_freep(&vs->baseurl);
+        av_freep(&vs->varname);
+    }
+}
+
 static int hls_write_trailer(struct AVFormatContext *s)
 {
     HLSContext *hls = s->priv_data;
     AVFormatContext *oc = NULL;
     AVFormatContext *vtt_oc = NULL;
     char *old_filename = NULL;
-    const char *proto = avio_find_protocol_name(s->url);
-    int use_temp_file = proto && !strcmp(proto, "file") && (s->flags & HLS_TEMP_FILE);
+    const char *proto = NULL;
+    int use_temp_file = 0;
     int i;
     int ret = 0;
     VariantStream *vs = NULL;
+    AVDictionary *options = NULL;
+    int range_length, byterange_mode;
 
     for (i = 0; i < hls->nb_varstreams; i++) {
+        char *filename = NULL;
         vs = &hls->var_streams[i];
-
         oc = vs->avf;
         vtt_oc = vs->vtt_avf;
         old_filename = av_strdup(vs->avf->url);
+        use_temp_file = 0;
 
         if (!old_filename) {
             return AVERROR(ENOMEM);
         }
+        if (hls->key_info_file || hls->encrypt) {
+            av_dict_set(&options, "encryption_key", hls->key_string, 0);
+            av_dict_set(&options, "encryption_iv", hls->iv_string, 0);
+            filename = av_asprintf("crypto:%s", vs->avf->url);
+        } else {
+            filename = av_asprintf("%s", vs->avf->url);
+        }
+        if (!filename) {
+            av_free(old_filename);
+            return AVERROR(ENOMEM);
+        }
+
         if ( hls->segment_type == SEGMENT_TYPE_FMP4) {
             int range_length = 0;
             if (!vs->init_range_length) {
                 uint8_t *buffer = NULL;
-                int range_length, byterange_mode;
                 av_write_frame(vs->avf, NULL); /* Flush any buffered data */
                 avio_flush(oc->pb);
 
@@ -2397,46 +2567,59 @@ static int hls_write_trailer(struct AVFormatContext *s)
                     hlsenc_io_close(s, &vs->out, vs->base_output_dirname);
                 }
             }
-            if (!(hls->flags & HLS_SINGLE_FILE)) {
-                ret = hlsenc_io_open(s, &vs->out, vs->avf->url, NULL);
-                if (ret < 0) {
-                    av_log(s, AV_LOG_ERROR, "Failed to open file '%s'\n", vs->avf->url);
-                    goto failed;
-                }
-                write_styp(vs->out);
-            }
-            ret = flush_dynbuf(vs, &range_length);
+        }
+        if (!(hls->flags & HLS_SINGLE_FILE)) {
+            set_http_options(s, &options, hls);
+            ret = hlsenc_io_open(s, &vs->out, filename, &options);
             if (ret < 0) {
+                av_log(s, AV_LOG_ERROR, "Failed to open file '%s'\n", vs->avf->url);
                 goto failed;
             }
-            vs->size = range_length;
+            if (hls->segment_type == SEGMENT_TYPE_FMP4)
+                write_styp(vs->out);
+        }
+        ret = flush_dynbuf(vs, &range_length);
+        if (ret < 0)
+            goto failed;
+
+        vs->size = range_length;
+        hlsenc_io_close(s, &vs->out, filename);
+        ret = hlsenc_io_close(s, &vs->out, filename);
+        if (ret < 0) {
+            av_log(s, AV_LOG_WARNING, "upload segment failed, will retry with a new http session.\n");
             ff_format_io_close(s, &vs->out);
+            ret = hlsenc_io_open(s, &vs->out, filename, &options);
+            if (ret < 0) {
+                av_log(s, AV_LOG_ERROR, "Failed to open file '%s'\n", vs->avf->url);
+                goto failed;
+            }
+            reflush_dynbuf(vs, &range_length);
+            ret = hlsenc_io_close(s, &vs->out, filename);
         }
+        av_free(vs->temp_buffer);
 
 failed:
+        av_free(filename);
         av_write_trailer(oc);
-        if (oc->pb) {
-            if (hls->segment_type != SEGMENT_TYPE_FMP4) {
-                vs->size = avio_tell(vs->avf->pb) - vs->start_pos;
-            }
-            if (hls->segment_type != SEGMENT_TYPE_FMP4)
-                ff_format_io_close(s, &oc->pb);
+        if (oc->url[0]) {
+            proto = avio_find_protocol_name(oc->url);
+            use_temp_file = proto && !strcmp(proto, "file") && (hls->flags & HLS_TEMP_FILE);
+        }
 
-            // rename that segment from .tmp to the real one
-            if (use_temp_file && oc->url[0] && !(hls->flags & HLS_SINGLE_FILE)) {
-                hls_rename_temp_file(s, oc);
-                av_free(old_filename);
-                old_filename = av_strdup(vs->avf->url);
+        // rename that segment from .tmp to the real one
+        if (use_temp_file && !(hls->flags & HLS_SINGLE_FILE)) {
+            hls_rename_temp_file(s, oc);
+            av_free(old_filename);
+            old_filename = av_strdup(vs->avf->url);
 
-                if (!old_filename) {
-                    return AVERROR(ENOMEM);
-                }
+            if (!old_filename) {
+                return AVERROR(ENOMEM);
             }
-
-            /* after av_write_trailer, then duration + 1 duration per packet */
-            hls_append_segment(s, hls, vs, vs->duration + vs->dpp, vs->start_pos, vs->size);
         }
 
+        /* after av_write_trailer, then duration + 1 duration per packet */
+        hls_append_segment(s, hls, vs, vs->duration + vs->dpp, vs->start_pos, vs->size);
+
         sls_flag_file_rename(hls, vs, old_filename);
 
         if (vtt_oc) {
@@ -2444,31 +2627,22 @@ failed:
                 av_write_trailer(vtt_oc);
             vs->size = avio_tell(vs->vtt_avf->pb) - vs->start_pos;
             ff_format_io_close(s, &vtt_oc->pb);
+            avformat_free_context(vtt_oc);
+        }
+        ret = hls_window(s, 1, vs);
+        if (ret < 0) {
+            av_log(s, AV_LOG_WARNING, "upload playlist failed, will retry with a new http session.\n");
+            ff_format_io_close(s, &vs->out);
+            hls_window(s, 1, vs);
         }
-        av_freep(&vs->basename);
-        av_freep(&vs->base_output_dirname);
         avformat_free_context(oc);
 
         vs->avf = NULL;
-        hls_window(s, 1, vs);
-
-        av_freep(&vs->fmp4_init_filename);
-        if (vtt_oc) {
-            av_freep(&vs->vtt_basename);
-            av_freep(&vs->vtt_m3u8_name);
-            avformat_free_context(vtt_oc);
-        }
-
-        hls_free_segments(vs->segments);
-        hls_free_segments(vs->old_segments);
         av_free(old_filename);
-        av_freep(&vs->m3u8_name);
-        av_freep(&vs->streams);
-        av_freep(&vs->agroup);
-        av_freep(&vs->ccgroup);
-        av_freep(&vs->baseurl);
     }
 
+    hls_free_variant_streams(hls);
+
     for (i = 0; i < hls->nb_ccstreams; i++) {
         ClosedCaptionsStream *ccs = &hls->cc_streams[i];
         av_freep(&ccs->ccgroup);
@@ -2501,6 +2675,8 @@ static int hls_init(AVFormatContext *s)
     int vtt_basename_size = 0;
     int fmp4_init_filename_len = strlen(hls->fmp4_init_filename) + 1;
 
+    hls->has_default_key = 0;
+    hls->has_video_m3u8 = 0;
     ret = update_variant_stream_info(s);
     if (ret < 0) {
         av_log(s, AV_LOG_ERROR, "Variant stream info update failed with status %x\n",
@@ -2569,12 +2745,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(vs->m3u8_name, strlen(s->url) + 1, i);
+        ret = format_name(s->url, &vs->m3u8_name, i, vs->varname);
         if (ret < 0)
             goto fail;
 
@@ -2635,15 +2806,7 @@ 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;
         } else {
@@ -2697,7 +2860,12 @@ static int hls_init(AVFormatContext *s)
                 av_strlcpy(vs->fmp4_init_filename, hls->fmp4_init_filename,
                            fmp4_init_filename_len);
                 if (hls->nb_varstreams > 1) {
-                    ret = append_postfix(vs->fmp4_init_filename, fmp4_init_filename_len, i);
+                    if (av_stristr(vs->fmp4_init_filename, "%v")) {
+                        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);
+                    }
                     if (ret < 0)
                         goto fail;
                 }
@@ -2725,17 +2893,10 @@ static int hls_init(AVFormatContext *s)
             }
         }
 
-        if (!hls->use_localtime) {
-            ret = sls_flag_check_duration_size_index(hls);
-            if (ret < 0) {
-                goto fail;
-            }
-        } else {
-            ret = sls_flag_check_duration_size(hls, vs);
-            if (ret < 0) {
-                goto fail;
-            }
-        }
+        ret = hls->use_localtime ? sls_flag_check_duration_size(hls, vs) : sls_flag_check_duration_size_index(hls);
+        if (ret < 0)
+            goto fail;
+
         if (vs->has_subtitle) {
 
             if (hls->flags & HLS_SINGLE_FILE)
@@ -2758,8 +2919,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 {
@@ -2806,9 +2967,11 @@ fail:
             av_freep(&vs->m3u8_name);
             av_freep(&vs->vtt_m3u8_name);
             av_freep(&vs->streams);
+            av_freep(&vs->language);
             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)
@@ -2857,7 +3020,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"},
@@ -2870,6 +3033,7 @@ static const AVOption options[] = {
     {"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"},
     {"periodic_rekey", "reload keyinfo file periodically for re-keying", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_PERIODIC_REKEY }, 0, UINT_MAX,   E, "flags"},
     {"independent_segments", "add EXT-X-INDEPENDENT-SEGMENTS, whenever applicable", 0, AV_OPT_TYPE_CONST, { .i64 = HLS_INDEPENDENT_SEGMENTS }, 0, UINT_MAX, E, "flags"},
+    {"iframes_only", "add EXT-X-I-FRAMES-ONLY, whenever applicable", 0, AV_OPT_TYPE_CONST, { .i64 = HLS_I_FRAMES_ONLY }, 0, UINT_MAX, E, "flags"},
 #if FF_API_HLS_USE_LOCALTIME
     {"use_localtime", "set filename expansion with strftime at segment creation(will be deprecated )", OFFSET(use_localtime), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, E },
 #endif
@@ -2894,6 +3058,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 },
 };