]> git.sesse.net Git - ffmpeg/blobdiff - libavformat/hlsenc.c
avformat/utils: Avoid copying packets unnecessarily
[ffmpeg] / libavformat / hlsenc.c
index 73d50a3c676671d3c0184fdef8af3802e8302b76..1f2bdfbe4d47520429378aefc3e1f1691e284e1c 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 {
@@ -118,6 +118,7 @@ typedef struct VariantStream {
     AVIOContext *out;
     int packets_written;
     int init_range_length;
+    uint8_t *temp_buffer;
 
     AVFormatContext *avf;
     AVFormatContext *vtt_avf;
@@ -243,7 +244,8 @@ typedef struct HLSContext {
 } HLSContext;
 
 static int hlsenc_io_open(AVFormatContext *s, AVIOContext **pb, char *filename,
-                          AVDictionary **options) {
+                          AVDictionary **options)
+{
     HLSContext *hls = s->priv_data;
     int http_base_proto = filename ? ff_is_http_proto(filename) : 0;
     int err = AVERROR_MUXER_NOT_FOUND;
@@ -262,11 +264,13 @@ 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
@@ -275,8 +279,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)
@@ -286,7 +292,6 @@ static void set_http_options(AVFormatContext *s, AVDictionary **options, HLSCont
     if (c->method) {
         av_dict_set(options, "method", c->method, 0);
     } else if (http_base_proto) {
-        av_log(c, AV_LOG_WARNING, "No HTTP method set, hls muxer defaulting to method PUT.\n");
         av_dict_set(options, "method", "PUT", 0);
     }
     if (c->user_agent)
@@ -299,7 +304,8 @@ static void set_http_options(AVFormatContext *s, AVDictionary **options, HLSCont
         av_dict_set(options, "headers", c->headers, 0);
 }
 
-static void write_codec_attr(AVStream *st, VariantStream *vs) {
+static void write_codec_attr(AVStream *st, VariantStream *vs)
+{
     int codec_strlen = strlen(vs->codec_attr);
     char attr[32];
 
@@ -447,7 +453,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);
@@ -458,17 +463,24 @@ 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);
+    avio_flush(vs->out);
 
     // 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) {
+                                   VariantStream *vs)
+{
 
     HLSSegment *segment, *previous_segment = NULL;
     float playlist_duration = 0.0f;
@@ -505,18 +517,13 @@ 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';
-
     }
 
     /* if %v is present in the file's directory
@@ -541,7 +548,7 @@ static int hls_delete_old_segments(AVFormatContext *s, HLSContext *hls,
 
     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) {
@@ -567,7 +574,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')) {
@@ -599,7 +606,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);
         }
@@ -709,7 +716,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;
     }
 
@@ -778,7 +785,7 @@ static int hls_mux_init(AVFormatContext *s, VariantStream *vs)
     oc->io_close           = s->io_close;
     av_dict_copy(&oc->metadata, s->metadata, 0);
 
-    if(vs->vtt_oformat) {
+    if (vs->vtt_oformat) {
         ret = avformat_alloc_output_context2(&vs->vtt_avf, vs->vtt_oformat, NULL, NULL);
         if (ret < 0)
             return ret;
@@ -899,7 +906,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);
@@ -910,10 +917,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);
@@ -930,14 +937,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,
@@ -955,14 +962,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;
@@ -1052,7 +1059,7 @@ static int hls_append_segment(struct AVFormatContext *s, HLSContext *hls,
     }
     av_strlcpy(en->filename, filename, sizeof(en->filename));
 
-    if(vs->has_subtitle)
+    if (vs->has_subtitle)
         av_strlcpy(en->sub_filename, av_basename(vs->vtt_avf->url), sizeof(en->sub_filename));
     else
         en->sub_filename[0] = '\0';
@@ -1207,7 +1214,7 @@ static void hls_free_segments(HLSSegment *p)
 {
     HLSSegment *en;
 
-    while(p) {
+    while (p) {
         en = p;
         p = p->next;
         av_free(en);
@@ -1229,25 +1236,26 @@ 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) {
+static int64_t get_stream_bit_rate(AVStream *stream)
+{
     AVCPBProperties *props = (AVCPBProperties*)av_stream_get_side_data(
         stream,
         AV_PKT_DATA_CPB_PROPERTIES,
@@ -1270,8 +1278,9 @@ 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 = NULL, *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");
@@ -1320,39 +1329,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, vs->language, i, hls->has_default_key ? vs->is_default : 1);
-
-        av_freep(&m3u8_rel_name);
     }
 
     /* 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;
         }
@@ -1421,13 +1412,10 @@ static int create_master_playlist(AVFormatContext *s,
                                          aud_st ? vs->agroup : NULL, vs->codec_attr, ccgroup);
             }
         }
-
-        av_freep(&m3u8_rel_name);
     }
 fail:
-    if(ret >=0)
+    if (ret >=0)
         hls->master_m3u8_created = 1;
-    av_freep(&m3u8_rel_name);
     hlsenc_io_close(s, &hls->m3u8_out, temp_filename);
     if (use_temp_file)
         ff_rename(temp_filename, hls->master_m3u8_url, s);
@@ -1474,7 +1462,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, (byterange_mode || hls->segment_type == SEGMENT_TYPE_FMP4) ? &hls->m3u8_out : &vs->out, temp_filename, &options)) < 0) {
+    if ((ret = hlsenc_io_open(s, byterange_mode ? &hls->m3u8_out : &vs->out, temp_filename, &options)) < 0) {
         if (hls->ignore_io_errors)
             ret = 0;
         goto fail;
@@ -1486,33 +1474,33 @@ static int hls_window(AVFormatContext *s, int last, VariantStream *vs)
     }
 
     vs->discontinuity_set = 0;
-    ff_hls_write_playlist_header((byterange_mode || hls->segment_type == SEGMENT_TYPE_FMP4) ? hls->m3u8_out : vs->out, hls->version, hls->allowcache,
+    ff_hls_write_playlist_header(byterange_mode ? 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((byterange_mode || hls->segment_type == SEGMENT_TYPE_FMP4) ? hls->m3u8_out : vs->out, "#EXT-X-DISCONTINUITY\n");
+    if ((hls->flags & HLS_DISCONT_START) && sequence==hls->start_sequence && vs->discontinuity_set==0 ) {
+        avio_printf(byterange_mode ? hls->m3u8_out : vs->out, "#EXT-X-DISCONTINUITY\n");
         vs->discontinuity_set = 1;
     }
     if (vs->has_video && (hls->flags & HLS_INDEPENDENT_SEGMENTS)) {
-        avio_printf((byterange_mode || hls->segment_type == SEGMENT_TYPE_FMP4) ? hls->m3u8_out : vs->out, "#EXT-X-INDEPENDENT-SEGMENTS\n");
+        avio_printf(byterange_mode ? 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((byterange_mode || hls->segment_type == SEGMENT_TYPE_FMP4) ? hls->m3u8_out : vs->out, "#EXT-X-KEY:METHOD=AES-128,URI=\"%s\"", en->key_uri);
+            avio_printf(byterange_mode ? hls->m3u8_out : vs->out, "#EXT-X-KEY:METHOD=AES-128,URI=\"%s\"", en->key_uri);
             if (*en->iv_string)
-                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");
+                avio_printf(byterange_mode ? hls->m3u8_out : vs->out, ",IV=0x%s", en->iv_string);
+            avio_printf(byterange_mode ? 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((byterange_mode || hls->segment_type == SEGMENT_TYPE_FMP4) ? hls->m3u8_out : vs->out, (hls->flags & HLS_SINGLE_FILE) ? en->filename : vs->fmp4_init_filename,
+            ff_hls_write_init_file(byterange_mode ? 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((byterange_mode || hls->segment_type == SEGMENT_TYPE_FMP4) ? hls->m3u8_out : vs->out, en->discont, byterange_mode,
+        ret = ff_hls_write_file_entry(byterange_mode ? 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->keyframe_size, en->keyframe_pos, hls->flags & HLS_I_FRAMES_ONLY);
@@ -1522,7 +1510,7 @@ static int hls_window(AVFormatContext *s, int last, VariantStream *vs)
     }
 
     if (last && (hls->flags & HLS_OMIT_ENDLIST)==0)
-        ff_hls_write_end_list((byterange_mode || hls->segment_type == SEGMENT_TYPE_FMP4) ? hls->m3u8_out : vs->out);
+        ff_hls_write_end_list(byterange_mode ? hls->m3u8_out : vs->out);
 
     if (vs->vtt_m3u8_name) {
         snprintf(temp_vtt_filename, sizeof(temp_vtt_filename), use_temp_file ? "%s.tmp" : "%s", vs->vtt_m3u8_name);
@@ -1549,7 +1537,10 @@ static int hls_window(AVFormatContext *s, int last, VariantStream *vs)
 
 fail:
     av_dict_free(&options);
-    hlsenc_io_close(s, (byterange_mode || hls->segment_type == SEGMENT_TYPE_FMP4) ? &hls->m3u8_out : &vs->out, temp_filename);
+    ret = hlsenc_io_close(s, byterange_mode ? &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) {
         ff_rename(temp_filename, vs->m3u8_name, s);
@@ -1647,7 +1638,7 @@ static int hls_start(AVFormatContext *s, VariantStream *vs)
             }
             ff_format_set_url(oc, filename);
         }
-        if( vs->vtt_basename) {
+        if ( vs->vtt_basename) {
             char *filename = NULL;
             if (replace_int_data_in_filename(&filename,
 #if FF_API_HLS_WRAP
@@ -1917,7 +1908,7 @@ static int parse_variant_stream_mapstring(AVFormatContext *s)
      */
     p = av_strdup(hls->var_stream_map);
     q = p;
-    while(av_strtok(q, " \t", &saveptr1)) {
+    while (av_strtok(q, " \t", &saveptr1)) {
         q = NULL;
         hls->nb_varstreams++;
     }
@@ -1997,15 +1988,15 @@ 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++) {
+                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++) {
+                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",
@@ -2038,7 +2029,7 @@ static int parse_cc_stream_mapstring(AVFormatContext *s)
 
     p = av_strdup(hls->cc_stream_map);
     q = p;
-    while(av_strtok(q, " \t", &saveptr1)) {
+    while (av_strtok(q, " \t", &saveptr1)) {
         q = NULL;
         hls->nb_ccstreams++;
     }
@@ -2085,13 +2076,13 @@ static int parse_cc_stream_mapstring(AVFormatContext *s)
         }
 
         if (av_strstart(ccs->instreamid, "CC", &val)) {
-            if(atoi(val) < 1 || atoi(val) > 4) {
+            if (atoi(val) < 1 || atoi(val) > 4) {
                 av_log(s, AV_LOG_ERROR, "Invalid instream ID CC index %d in %s, range 1-4\n",
                        atoi(val), ccs->instreamid);
                 return AVERROR(EINVAL);
             }
         } else if (av_strstart(ccs->instreamid, "SERVICE", &val)) {
-            if(atoi(val) < 1 || atoi(val) > 63) {
+            if (atoi(val) < 1 || atoi(val) > 63) {
                 av_log(s, AV_LOG_ERROR, "Invalid instream ID SERVICE index %d in %s, range 1-63 \n",
                        atoi(val), ccs->instreamid);
                 return AVERROR(EINVAL);
@@ -2106,7 +2097,8 @@ static int parse_cc_stream_mapstring(AVFormatContext *s)
     return 0;
 }
 
-static int update_variant_stream_info(AVFormatContext *s) {
+static int update_variant_stream_info(AVFormatContext *s)
+{
     HLSContext *hls = s->priv_data;
     unsigned int i;
     int ret = 0;
@@ -2131,14 +2123,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++)
@@ -2147,7 +2143,8 @@ static int update_variant_stream_info(AVFormatContext *s) {
     return 0;
 }
 
-static int update_master_pl_info(AVFormatContext *s) {
+static int update_master_pl_info(AVFormatContext *s)
+{
     HLSContext *hls = s->priv_data;
     const char *dir;
     char *fn1= NULL, *fn2 = NULL;
@@ -2267,7 +2264,7 @@ static int hls_write_packet(AVFormatContext *s, AVPacket *pkt)
         vs = &hls->var_streams[i];
         for (j = 0; j < vs->nb_streams; j++) {
             if (vs->streams[j] == st) {
-                if( st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE ) {
+                if ( st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE ) {
                     oc = vs->vtt_avf;
                     stream_index = 0;
                 } else {
@@ -2369,6 +2366,7 @@ static int hls_write_packet(AVFormatContext *s, AVPacket *pkt)
 
         if (hls->flags & HLS_SINGLE_FILE) {
             ret = flush_dynbuf(vs, &range_length);
+            av_freep(&vs->temp_buffer);
             if (ret < 0) {
                 return ret;
             }
@@ -2400,7 +2398,16 @@ static int hls_write_packet(AVFormatContext *s, AVPacket *pkt)
                 if (ret < 0) {
                     return ret;
                 }
-                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);
+                    reflush_dynbuf(vs, &range_length);
+                    ret = hlsenc_io_close(s, &vs->out, filename);
+                }
+                av_free(vs->temp_buffer);
                 av_free(filename);
             }
         }
@@ -2427,8 +2434,13 @@ static int hls_write_packet(AVFormatContext *s, AVPacket *pkt)
         // 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_free(old_filename);
-                return ret;
+                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;
+                }
             }
         }
 
@@ -2525,7 +2537,7 @@ static int hls_write_trailer(struct AVFormatContext *s)
         vs = &hls->var_streams[i];
         oc = vs->avf;
         vtt_oc = vs->vtt_avf;
-        old_filename = av_strdup(vs->avf->url);
+        old_filename = av_strdup(oc->url);
         use_temp_file = 0;
 
         if (!old_filename) {
@@ -2534,20 +2546,20 @@ static int hls_write_trailer(struct AVFormatContext *s)
         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);
+            filename = av_asprintf("crypto:%s", oc->url);
         } else {
-            filename = av_asprintf("%s", vs->avf->url);
+            filename = av_asprintf("%s", oc->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;
-                av_write_frame(vs->avf, NULL); /* Flush any buffered data */
+                av_write_frame(oc, NULL); /* Flush any buffered data */
                 avio_flush(oc->pb);
 
                 range_length = avio_close_dyn_buf(oc->pb, &buffer);
@@ -2568,7 +2580,7 @@ static int hls_write_trailer(struct AVFormatContext *s)
             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);
+                av_log(s, AV_LOG_ERROR, "Failed to open file '%s'\n", oc->url);
                 goto failed;
             }
             if (hls->segment_type == SEGMENT_TYPE_FMP4)
@@ -2580,30 +2592,43 @@ static int hls_write_trailer(struct AVFormatContext *s)
 
         vs->size = range_length;
         hlsenc_io_close(s, &vs->out, filename);
-        av_free(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", oc->url);
+                goto failed;
+            }
+            reflush_dynbuf(vs, &range_length);
+            ret = hlsenc_io_close(s, &vs->out, filename);
+            if (ret < 0)
+                av_log(s, AV_LOG_WARNING, "Failed to upload file '%s' at the end.\n", oc->url);
+        }
+        av_free(vs->temp_buffer);
 
 failed:
+        av_free(filename);
         av_write_trailer(oc);
-
         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 && !(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(oc->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);
 
@@ -2614,7 +2639,13 @@ failed:
             ff_format_io_close(s, &vtt_oc->pb);
             avformat_free_context(vtt_oc);
         }
-        hls_window(s, 1, vs);
+        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);
+        }
+        ffio_free_dyn_buf(&oc->pb);
         avformat_free_context(oc);
 
         vs->avf = NULL;
@@ -2653,6 +2684,7 @@ static int hls_init(AVFormatContext *s)
     const char *vtt_pattern = "%d.vtt";
     char *p = NULL;
     int vtt_basename_size = 0;
+    int http_base_proto = ff_is_http_proto(s->url);
     int fmp4_init_filename_len = strlen(hls->fmp4_init_filename) + 1;
 
     hls->has_default_key = 0;
@@ -2670,6 +2702,10 @@ static int hls_init(AVFormatContext *s)
         goto fail;
     }
 
+    if (!hls->method && http_base_proto) {
+        av_log(hls, AV_LOG_WARNING, "No HTTP method set, hls muxer defaulting to method PUT.\n");
+    }
+
     ret = validate_name(hls->nb_varstreams, s->url);
     if (ret < 0)
         goto fail;
@@ -2789,7 +2825,6 @@ static int hls_init(AVFormatContext *s)
             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) {
@@ -2874,17 +2909,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)