]> git.sesse.net Git - ffmpeg/blobdiff - libavformat/hlsenc.c
avformat/hlsenc: Localize initialization of subtitle streams
[ffmpeg] / libavformat / hlsenc.c
index f3e89a033feb6cc622a745c2583ee481a49261b4..3d5b09c9634883747b6e78a8e56ac130c5ce1c90 100644 (file)
@@ -41,6 +41,7 @@
 #include "libavutil/random_seed.h"
 #include "libavutil/opt.h"
 #include "libavutil/log.h"
+#include "libavutil/time.h"
 #include "libavutil/time_internal.h"
 
 #include "avformat.h"
@@ -56,6 +57,8 @@ 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_MICROSECONDS_SINCE_EPOCH = 3,
+    HLS_START_SEQUENCE_LAST, // unused
 } StartSequenceSourceType;
 
 typedef enum {
@@ -119,6 +122,7 @@ typedef struct VariantStream {
     int packets_written;
     int init_range_length;
     uint8_t *temp_buffer;
+    uint8_t *init_buffer;
 
     AVFormatContext *avf;
     AVFormatContext *vtt_avf;
@@ -126,6 +130,7 @@ typedef struct VariantStream {
     int has_video;
     int has_subtitle;
     int new_start;
+    int start_pts_from_audio;
     double dpp;           // duration per packet
     int64_t start_pts;
     int64_t end_pts;
@@ -155,6 +160,13 @@ typedef struct VariantStream {
     char *fmp4_init_filename;
     char *base_output_dirname;
 
+    int encrypt_started;
+
+    char key_file[LINE_BUFFER_SIZE + 1];
+    char key_uri[LINE_BUFFER_SIZE + 1];
+    char key_string[KEYSIZE*2 + 1];
+    char iv_string[KEYSIZE*2 + 1];
+
     AVStream **streams;
     char codec_attr[128];
     CodecAttributeStatus attr_status;
@@ -163,6 +175,7 @@ typedef struct VariantStream {
     int is_default; /* default status of audio group */
     char *language; /* audio lauguage name */
     char *agroup; /* audio group name */
+    char *sgroup; /* subtitle group name */
     char *ccgroup; /* closed caption group name */
     char *baseurl;
     char *varname; // variant name
@@ -191,6 +204,7 @@ typedef struct HLSContext {
     char *segment_filename;
     char *fmp4_init_filename;
     int segment_type;
+    int resend_init_file;  ///< resend init file into disk after refresh m3u8
 
     int use_localtime;      ///< flag to expand filename with localtime
     int use_localtime_mkdir;///< flag to mkdir dirname in timebased filename
@@ -199,7 +213,6 @@ typedef struct HLSContext {
     int64_t max_seg_size; // every segment file max size
 
     char *baseurl;
-    char *format_options_str;
     char *vtt_format_options_str;
     char *subtitle_filename;
     AVDictionary *format_options;
@@ -460,7 +473,6 @@ static int flush_dynbuf(VariantStream *vs, int *range_length)
 
     // flush
     av_write_frame(ctx, NULL);
-    avio_flush(ctx->pb);
 
     // write out to file
     *range_length = avio_close_dyn_buf(ctx->pb, &vs->temp_buffer);
@@ -484,24 +496,44 @@ static void reflush_dynbuf(VariantStream *vs, int *range_length)
 #define SEPARATOR '/'
 #endif
 
+static int hls_delete_file(HLSContext *hls, AVFormatContext *avf,
+                           const char *path, const char *proto)
+{
+    if (hls->method || (proto && !av_strcasecmp(proto, "http"))) {
+        AVDictionary *opt = NULL;
+        AVIOContext  *out = NULL;
+        int ret;
+        av_dict_set(&opt, "method", "DELETE", 0);
+        ret = avf->io_open(avf, &out, path, AVIO_FLAG_WRITE, &opt);
+        av_dict_free(&opt);
+        if (ret < 0)
+            return hls->ignore_io_errors ? 1 : ret;
+        ff_format_io_close(avf, &out);
+    } else if (unlink(path) < 0) {
+        av_log(hls, AV_LOG_ERROR, "failed to delete old segment %s: %s\n",
+               path, strerror(errno));
+    }
+    return 0;
+}
+
 static int hls_delete_old_segments(AVFormatContext *s, HLSContext *hls,
                                    VariantStream *vs)
 {
 
     HLSSegment *segment, *previous_segment = NULL;
     float playlist_duration = 0.0f;
-    int ret = 0, path_size, sub_path_size;
+    int ret = 0;
     int segment_cnt = 0;
-    char *dirname = NULL, *sub_path;
+    AVBPrint path;
+    char *dirname = NULL;
     char *dirname_r = NULL;
     char *dirname_repl = NULL;
-    char *path = NULL;
     char *vtt_dirname = NULL;
     char *vtt_dirname_r = NULL;
-    AVDictionary *options = NULL;
-    AVIOContext *out = NULL;
     const char *proto = NULL;
 
+    av_bprint_init(&path, 0, AV_BPRINT_SIZE_UNLIMITED);
+
     segment = vs->segments;
     while (segment) {
         playlist_duration += segment->duration;
@@ -533,7 +565,6 @@ static int hls_delete_old_segments(AVFormatContext *s, HLSContext *hls,
     /* 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 * dirname_repl = dirname;
         if (!vs->varname) {
             if (replace_int_data_in_filename(&dirname_repl, dirname, 'v', segment->var_stream_idx) < 1) {
                 ret = AVERROR(EINVAL);
@@ -552,73 +583,46 @@ 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);
-        path_size =  (hls->use_localtime_mkdir ? 0 : strlen(dirname)+1) + strlen(segment->filename) + 1;
-        path = av_malloc(path_size);
-        if (!path) {
+        if (!hls->use_localtime_mkdir) // segment->filename contains basename only
+            av_bprintf(&path, "%s%c", dirname, SEPARATOR);
+        av_bprintf(&path, "%s", segment->filename);
+
+        if (!av_bprint_is_complete(&path)) {
             ret = AVERROR(ENOMEM);
             goto fail;
         }
 
-        if (hls->use_localtime_mkdir)
-            av_strlcpy(path, segment->filename, path_size);
-        else { // segment->filename contains basename only
-            snprintf(path, path_size, "%s%c%s", dirname, SEPARATOR, segment->filename);
-        }
-
         proto = avio_find_protocol_name(s->url);
-        if (hls->method || (proto && !av_strcasecmp(proto, "http"))) {
-            av_dict_set(&options, "method", "DELETE", 0);
-            if ((ret = vs->avf->io_open(vs->avf, &out, path, AVIO_FLAG_WRITE, &options)) < 0) {
-                if (hls->ignore_io_errors)
-                    ret = 0;
-                goto fail;
-            }
-            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));
-        }
+        if (ret = hls_delete_file(hls, vs->avf, path.str, proto))
+            goto fail;
 
         if ((segment->sub_filename[0] != '\0')) {
             vtt_dirname_r = av_strdup(vs->vtt_avf->url);
             vtt_dirname = (char*)av_dirname(vtt_dirname_r);
-            sub_path_size = strlen(segment->sub_filename) + 1 + strlen(vtt_dirname) + 1;
-            sub_path = av_malloc(sub_path_size);
-            if (!sub_path) {
-                ret = AVERROR(ENOMEM);
-                goto fail;
-            }
-
-            snprintf(sub_path, sub_path_size, "%s%c%s", vtt_dirname, SEPARATOR, segment->sub_filename);
 
+            av_bprint_clear(&path);
+            av_bprintf(&path, "%s%c%s", vtt_dirname, SEPARATOR,
+                                         segment->sub_filename);
             av_freep(&vtt_dirname_r);
 
-            if (hls->method || (proto && !av_strcasecmp(proto, "http"))) {
-                av_dict_set(&options, "method", "DELETE", 0);
-                if ((ret = vs->vtt_avf->io_open(vs->vtt_avf, &out, sub_path, AVIO_FLAG_WRITE, &options)) < 0) {
-                    if (hls->ignore_io_errors)
-                        ret = 0;
-                    av_freep(&sub_path);
-                    goto fail;
-                }
-                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));
+            if (!av_bprint_is_complete(&path)) {
+                ret = AVERROR(ENOMEM);
+                goto fail;
             }
-            av_freep(&sub_path);
+
+            if (ret = hls_delete_file(hls, vs->vtt_avf, path.str, proto))
+                goto fail;
         }
-        av_freep(&path);
+        av_bprint_clear(&path);
         previous_segment = segment;
         segment = previous_segment->next;
         av_freep(&previous_segment);
     }
 
 fail:
-    av_freep(&path);
+    av_bprint_finalize(&path, NULL);
     av_freep(&dirname_r);
     av_freep(&dirname_repl);
-    av_freep(&vtt_dirname_r);
 
     return ret;
 }
@@ -644,13 +648,14 @@ static int do_encrypt(AVFormatContext *s, VariantStream *vs)
     int len;
     AVIOContext *pb;
     uint8_t key[KEYSIZE];
+    char * key_basename_source = (hls->master_m3u8_url) ? hls->master_m3u8_url : s->url;
 
-    len = strlen(s->url) + 4 + 1;
+    len = strlen(key_basename_source) + 4 + 1;
     hls->key_basename = av_mallocz(len);
     if (!hls->key_basename)
         return AVERROR(ENOMEM);
 
-    av_strlcpy(hls->key_basename, s->url, len);
+    av_strlcpy(hls->key_basename, key_basename_source, len);
     av_strlcat(hls->key_basename, ".key", len);
 
     if (hls->key_url) {
@@ -686,6 +691,7 @@ static int do_encrypt(AVFormatContext *s, VariantStream *vs)
     }
 
     if (!*hls->key_string) {
+        AVDictionary *options = NULL;
         if (!hls->key) {
             if ((ret = randomize(key, sizeof(key))) < 0) {
                 av_log(s, AV_LOG_ERROR, "Cannot generate a strong random key\n");
@@ -696,7 +702,10 @@ static int do_encrypt(AVFormatContext *s, VariantStream *vs)
         }
 
         ff_data_to_hex(hls->key_string, key, sizeof(key), 0);
-        if ((ret = s->io_open(s, &pb, hls->key_file, AVIO_FLAG_WRITE, NULL)) < 0)
+        set_http_options(s, &options, hls);
+        ret = s->io_open(s, &pb, hls->key_file, AVIO_FLAG_WRITE, &options);
+        av_dict_free(&options);
+        if (ret < 0)
             return ret;
         avio_seek(pb, 0, SEEK_CUR);
         avio_write(pb, key, KEYSIZE);
@@ -706,54 +715,61 @@ static int do_encrypt(AVFormatContext *s, VariantStream *vs)
 }
 
 
-static int hls_encryption_start(AVFormatContext *s)
+static int hls_encryption_start(AVFormatContext *s,  VariantStream *vs)
 {
     HLSContext *hls = s->priv_data;
     int ret;
     AVIOContext *pb;
     uint8_t key[KEYSIZE];
+    AVDictionary *options = NULL;
 
-    if ((ret = s->io_open(s, &pb, hls->key_info_file, AVIO_FLAG_READ, NULL)) < 0) {
+    set_http_options(s, &options, hls);
+    ret = s->io_open(s, &pb, hls->key_info_file, AVIO_FLAG_READ, &options);
+    av_dict_free(&options);
+    if (ret < 0) {
         av_log(hls, AV_LOG_ERROR,
                "error opening key info file %s\n", hls->key_info_file);
         return ret;
     }
 
-    ff_get_line(pb, hls->key_uri, sizeof(hls->key_uri));
-    hls->key_uri[strcspn(hls->key_uri, "\r\n")] = '\0';
+    ff_get_line(pb, vs->key_uri, sizeof(vs->key_uri));
+    vs->key_uri[strcspn(vs->key_uri, "\r\n")] = '\0';
 
-    ff_get_line(pb, hls->key_file, sizeof(hls->key_file));
-    hls->key_file[strcspn(hls->key_file, "\r\n")] = '\0';
+    ff_get_line(pb, vs->key_file, sizeof(vs->key_file));
+    vs->key_file[strcspn(vs->key_file, "\r\n")] = '\0';
 
-    ff_get_line(pb, hls->iv_string, sizeof(hls->iv_string));
-    hls->iv_string[strcspn(hls->iv_string, "\r\n")] = '\0';
+    ff_get_line(pb, vs->iv_string, sizeof(vs->iv_string));
+    vs->iv_string[strcspn(vs->iv_string, "\r\n")] = '\0';
 
     ff_format_io_close(s, &pb);
 
-    if (!*hls->key_uri) {
+    if (!*vs->key_uri) {
         av_log(hls, AV_LOG_ERROR, "no key URI specified in key info file\n");
         return AVERROR(EINVAL);
     }
 
-    if (!*hls->key_file) {
+    if (!*vs->key_file) {
         av_log(hls, AV_LOG_ERROR, "no key file specified in key info file\n");
         return AVERROR(EINVAL);
     }
 
-    if ((ret = s->io_open(s, &pb, hls->key_file, AVIO_FLAG_READ, NULL)) < 0) {
-        av_log(hls, AV_LOG_ERROR, "error opening key file %s\n", hls->key_file);
+    set_http_options(s, &options, hls);
+    ret = s->io_open(s, &pb, vs->key_file, AVIO_FLAG_READ, &options);
+    av_dict_free(&options);
+    if (ret < 0) {
+        av_log(hls, AV_LOG_ERROR, "error opening key file %s\n", vs->key_file);
         return ret;
     }
 
     ret = avio_read(pb, key, sizeof(key));
     ff_format_io_close(s, &pb);
     if (ret != sizeof(key)) {
-        av_log(hls, AV_LOG_ERROR, "error reading key file %s\n", hls->key_file);
+        av_log(hls, AV_LOG_ERROR, "error reading key file %s\n", vs->key_file);
         if (ret >= 0 || ret == AVERROR_EOF)
             ret = AVERROR(EINVAL);
         return ret;
     }
-    ff_data_to_hex(hls->key_string, key, sizeof(key), 0);
+    ff_data_to_hex(vs->key_string, key, sizeof(key), 0);
 
     return 0;
 }
@@ -765,6 +781,7 @@ static int hls_mux_init(AVFormatContext *s, VariantStream *vs)
     AVFormatContext *oc;
     AVFormatContext *vtt_oc = NULL;
     int byterange_mode = (hls->flags & HLS_SINGLE_FILE) || (hls->max_seg_size > 0);
+    int remaining_options;
     int i, ret;
 
     ret = avformat_alloc_output_context2(&vs->avf, vs->oformat, NULL, NULL);
@@ -776,7 +793,6 @@ static int hls_mux_init(AVFormatContext *s, VariantStream *vs)
     if (!oc->url)
         return AVERROR(ENOMEM);
 
-    oc->oformat                  = vs->oformat;
     oc->interrupt_callback       = s->interrupt_callback;
     oc->max_delay                = s->max_delay;
     oc->opaque                   = s->opaque;
@@ -790,7 +806,6 @@ static int hls_mux_init(AVFormatContext *s, VariantStream *vs)
         if (ret < 0)
             return ret;
         vtt_oc          = vs->vtt_avf;
-        vtt_oc->oformat = vs->vtt_oformat;
         av_dict_copy(&vtt_oc->metadata, s->metadata, 0);
     }
 
@@ -853,30 +868,25 @@ static int hls_mux_init(AVFormatContext *s, VariantStream *vs)
         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);
     if (hls->segment_type == SEGMENT_TYPE_FMP4) {
-        int remaining_options;
-
-        av_dict_copy(&options, hls->format_options, 0);
         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);
-        remaining_options = av_dict_count(options);
-        av_dict_free(&options);
-        if (ret < 0)
-            return ret;
-        if (remaining_options) {
-            av_log(s, AV_LOG_ERROR, "Some of the provided format options in '%s' are not recognized\n", hls->format_options_str);
-            return AVERROR(EINVAL);
-        }
+    } else {
+        /* We only require one PAT/PMT per segment. */
+        char period[21];
+        snprintf(period, sizeof(period), "%d", (INT_MAX / 2) - 1);
+        av_dict_set(&options, "sdt_period", period, AV_DICT_DONT_OVERWRITE);
+        av_dict_set(&options, "pat_period", period, AV_DICT_DONT_OVERWRITE);
+    }
+    ret = avformat_init_output(oc, &options);
+    remaining_options = av_dict_count(options);
+    av_dict_free(&options);
+    if (ret < 0)
+        return ret;
+    if (remaining_options) {
+        av_log(s, AV_LOG_ERROR, "Some of the provided format options are not recognized\n");
+        return AVERROR(EINVAL);
     }
     avio_flush(oc->pb);
     return 0;
@@ -1079,8 +1089,8 @@ static int hls_append_segment(struct AVFormatContext *s, HLSContext *hls,
     }
 
     if (hls->key_info_file || hls->encrypt) {
-        av_strlcpy(en->key_uri, hls->key_uri, sizeof(en->key_uri));
-        av_strlcpy(en->iv_string, hls->iv_string, sizeof(en->iv_string));
+        av_strlcpy(en->key_uri, vs->key_uri, sizeof(en->key_uri));
+        av_strlcpy(en->iv_string, vs->iv_string, sizeof(en->iv_string));
     }
 
     if (!vs->segments)
@@ -1168,9 +1178,9 @@ static int parse_playlist(AVFormatContext *s, const char *url, VariantStream *vs
                 ptr += strlen("URI=\"");
                 end = av_stristr(ptr, ",");
                 if (end) {
-                    av_strlcpy(hls->key_uri, ptr, end - ptr);
+                    av_strlcpy(vs->key_uri, ptr, end - ptr);
                 } else {
-                    av_strlcpy(hls->key_uri, ptr, sizeof(hls->key_uri));
+                    av_strlcpy(vs->key_uri, ptr, sizeof(vs->key_uri));
                 }
             }
 
@@ -1179,9 +1189,9 @@ static int parse_playlist(AVFormatContext *s, const char *url, VariantStream *vs
                 ptr += strlen("IV=0x");
                 end = av_stristr(ptr, ",");
                 if (end) {
-                    av_strlcpy(hls->iv_string, ptr, end - ptr);
+                    av_strlcpy(vs->iv_string, ptr, end - ptr);
                 } else {
-                    av_strlcpy(hls->iv_string, ptr, sizeof(hls->iv_string));
+                    av_strlcpy(vs->iv_string, ptr, sizeof(vs->iv_string));
                 }
             }
 
@@ -1198,6 +1208,7 @@ static int parse_playlist(AVFormatContext *s, const char *url, VariantStream *vs
                 is_segment = 0;
                 new_start_pos = avio_tell(vs->avf->pb);
                 vs->size = new_start_pos - vs->start_pos;
+                vs->initial_prog_date_time -= vs->duration; // this is a previously existing segment
                 ret = hls_append_segment(s, hls, vs, vs->duration, vs->start_pos, vs->size);
                 if (ret < 0)
                     goto fail;
@@ -1245,14 +1256,16 @@ static const char* get_relative_url(const char *master_url, const char *media_ur
     if (!p) p = strrchr(master_url, '\\');
 
     if (p) {
-        base_len = p + 1 - master_url;
+        base_len = p - master_url;
         if (av_strncasecmp(master_url, media_url, base_len)) {
             av_log(NULL, AV_LOG_WARNING, "Unable to find relative url\n");
             return NULL;
         }
+    } else {
+        return media_url;
     }
 
-    return media_url + base_len;
+    return media_url + base_len + 1;
 }
 
 static int64_t get_stream_bit_rate(AVStream *stream)
@@ -1281,7 +1294,9 @@ static int create_master_playlist(AVFormatContext *s,
     unsigned int i, j;
     int ret, bandwidth;
     const char *m3u8_rel_name = NULL;
+    const char *vtt_m3u8_rel_name = NULL;
     char *ccgroup;
+    char *sgroup = NULL;
     ClosedCaptionsStream *ccs;
     const char *proto = avio_find_protocol_name(hls->master_m3u8_url);
     int is_file_proto = proto && !strcmp(proto, "file");
@@ -1404,13 +1419,24 @@ static int create_master_playlist(AVFormatContext *s,
                         vs->ccgroup);
         }
 
+        if (vid_st && vs->sgroup) {
+            sgroup = vs->sgroup;
+            vtt_m3u8_rel_name = get_relative_url(hls->master_m3u8_url, vs->vtt_m3u8_name);
+            if (!vtt_m3u8_rel_name) {
+                av_log(s, AV_LOG_WARNING, "Unable to find relative subtitle URL\n");
+                break;
+            }
+
+            ff_hls_write_subtitle_rendition(hls->m3u8_out, sgroup, vtt_m3u8_rel_name, vs->language, i, hls->has_default_key ? vs->is_default : 1);
+        }
+
         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);
+                    aud_st ? vs->agroup : NULL, vs->codec_attr, ccgroup, sgroup);
         } 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);
+                                         aud_st ? vs->agroup : NULL, vs->codec_attr, ccgroup, sgroup);
             }
         }
     }
@@ -1614,6 +1640,8 @@ static int hls_start(AVFormatContext *s, VariantStream *vs)
             if (c->use_localtime_mkdir) {
                 const char *dir;
                 char *fn_copy = av_strdup(oc->url);
+                if (!fn_copy)
+                    return AVERROR(ENOMEM);
                 dir = av_dirname(fn_copy);
                 if (ff_mkdir_p(dir) == -1 && errno != EEXIST) {
                     av_log(oc, AV_LOG_ERROR, "Could not create directory %s with use_localtime_mkdir\n", dir);
@@ -1674,33 +1702,32 @@ static int hls_start(AVFormatContext *s, VariantStream *vs)
                   " ignoring -hls_enc\n");
         }
 
-        if (!c->encrypt_started || (c->flags & HLS_PERIODIC_REKEY)) {
+        if (!vs->encrypt_started || (c->flags & HLS_PERIODIC_REKEY)) {
             if (c->key_info_file) {
-                if ((err = hls_encryption_start(s)) < 0)
+                if ((err = hls_encryption_start(s, vs)) < 0)
                     goto fail;
             } else {
-                if ((err = do_encrypt(s, vs)) < 0)
-                    goto fail;
+                if (!c->encrypt_started) {
+                    if ((err = do_encrypt(s, vs)) < 0)
+                        goto fail;
+                    c->encrypt_started = 1;
+                }
+                av_strlcpy(vs->key_uri, c->key_uri, sizeof(vs->key_uri));
+                av_strlcpy(vs->key_string, c->key_string, sizeof(vs->key_string));
+                av_strlcpy(vs->iv_string, c->iv_string, sizeof(vs->iv_string));
             }
-            c->encrypt_started = 1;
+            vs->encrypt_started = 1;
         }
-        err = av_strlcpy(iv_string, c->iv_string, sizeof(iv_string));
+        err = av_strlcpy(iv_string, vs->iv_string, sizeof(iv_string));
         if (!err) {
             snprintf(iv_string, sizeof(iv_string), "%032"PRIx64, vs->sequence);
-            memset(c->iv_string, 0, sizeof(c->iv_string));
-            memcpy(c->iv_string, iv_string, sizeof(iv_string));
+            memset(vs->iv_string, 0, sizeof(vs->iv_string));
+            memcpy(vs->iv_string, iv_string, sizeof(iv_string));
         }
     }
     if (c->segment_type != SEGMENT_TYPE_FMP4) {
-        /* We only require one PAT/PMT per segment. */
         if (oc->oformat->priv_class && oc->priv_data) {
-            char period[21];
-
-            snprintf(period, sizeof(period), "%d", (INT_MAX / 2) - 1);
-
             av_opt_set(oc->priv_data, "mpegts_flags", "resend_headers", 0);
-            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) {
             set_http_options(s, &options, c);
@@ -1781,6 +1808,8 @@ static int validate_name(int nb_vs, const char *fn)
     }
 
     fn_dup = av_strdup(fn);
+    if (!fn_dup)
+        return AVERROR(ENOMEM);
     filename = av_basename(fn);
     subdir_name = av_dirname(fn_dup);
 
@@ -1853,7 +1882,7 @@ fail:
 
 static int get_nth_codec_stream_index(AVFormatContext *s,
                                       enum AVMediaType codec_type,
-                                      int stream_id)
+                                      int64_t stream_id)
 {
     unsigned int stream_index, cnt;
     if (stream_id < 0 || stream_id > s->nb_streams - 1)
@@ -1892,6 +1921,7 @@ static int parse_variant_stream_mapstring(AVFormatContext *s)
      * practical usage)
      *
      * agroup: is key to specify audio group. A string can be given as value.
+     * sgroup: is key to specify subtitle group. A string can be given as value.
      */
     p = av_strdup(hls->var_stream_map);
     if (!p)
@@ -1935,8 +1965,11 @@ static int parse_variant_stream_mapstring(AVFormatContext *s)
 
         nb_streams = 0;
         while (keyval = av_strtok(varstr, ",", &saveptr2)) {
+            int64_t num;
+            char *end;
             varstr = NULL;
             if (av_strstart(keyval, "language:", &val)) {
+                av_free(vs->language);
                 vs->language = av_strdup(val);
                 if (!vs->language)
                     return AVERROR(ENOMEM);
@@ -1947,16 +1980,25 @@ static int parse_variant_stream_mapstring(AVFormatContext *s)
                 hls->has_default_key = 1;
                 continue;
             } else if (av_strstart(keyval, "name:", &val)) {
+                av_free(vs->varname);
                 vs->varname = av_strdup(val);
                 if (!vs->varname)
                     return AVERROR(ENOMEM);
                 continue;
             } else if (av_strstart(keyval, "agroup:", &val)) {
+                av_free(vs->agroup);
                 vs->agroup = av_strdup(val);
                 if (!vs->agroup)
                     return AVERROR(ENOMEM);
                 continue;
+            } else if (av_strstart(keyval, "sgroup:", &val)) {
+                av_free(vs->sgroup);
+                vs->sgroup = av_strdup(val);
+                if (!vs->sgroup)
+                    return AVERROR(ENOMEM);
+                continue;
             } else if (av_strstart(keyval, "ccgroup:", &val)) {
+                av_free(vs->ccgroup);
                 vs->ccgroup = av_strdup(val);
                 if (!vs->ccgroup)
                     return AVERROR(ENOMEM);
@@ -1973,10 +2015,12 @@ static int parse_variant_stream_mapstring(AVFormatContext *s)
                 return AVERROR(EINVAL);
             }
 
-            stream_index = -1;
-            if (av_isdigit(*val))
-                stream_index = get_nth_codec_stream_index (s, codec_type,
-                                                           atoi(val));
+            num = strtoll(val, &end, 0);
+            if (!av_isdigit(*val) || *end != '\0') {
+                av_log(s, AV_LOG_ERROR, "Invalid stream number: '%s'\n", val);
+                return AVERROR(EINVAL);
+            }
+            stream_index = get_nth_codec_stream_index(s, codec_type, num);
 
             if (stream_index >= 0 && nb_streams < vs->nb_streams) {
                 for (i = 0; nb_streams > 0 && i < nb_streams; i++) {
@@ -2048,14 +2092,17 @@ static int parse_cc_stream_mapstring(AVFormatContext *s)
             ccstr = NULL;
 
             if (av_strstart(keyval, "ccgroup:", &val)) {
+                av_free(ccs->ccgroup);
                 ccs->ccgroup = av_strdup(val);
                 if (!ccs->ccgroup)
                     return AVERROR(ENOMEM);
             } else if (av_strstart(keyval, "instreamid:", &val)) {
+                av_free(ccs->instreamid);
                 ccs->instreamid = av_strdup(val);
                 if (!ccs->instreamid)
                     return AVERROR(ENOMEM);
             } else if (av_strstart(keyval, "language:", &val)) {
+                av_free(ccs->language);
                 ccs->language = av_strdup(val);
                 if (!ccs->language)
                     return AVERROR(ENOMEM);
@@ -2143,6 +2190,8 @@ static int update_master_pl_info(AVFormatContext *s)
     int ret = 0;
 
     fn1 = av_strdup(s->url);
+    if (!fn1)
+        return AVERROR(ENOMEM);
     dir = av_dirname(fn1);
 
     /**
@@ -2151,6 +2200,10 @@ static int update_master_pl_info(AVFormatContext *s)
      */
     if (dir && av_stristr(av_basename(dir), "%v")) {
         fn2 = av_strdup(dir);
+        if (!fn2) {
+            ret = AVERROR(ENOMEM);
+            goto fail;
+        }
         dir = av_dirname(fn2);
     }
 
@@ -2226,6 +2279,23 @@ static int hls_write_header(AVFormatContext *s)
     return ret;
 }
 
+static int hls_init_file_resend(AVFormatContext *s, VariantStream *vs)
+{
+    HLSContext *hls = s->priv_data;
+    AVDictionary *options = NULL;
+    int ret = 0;
+
+    set_http_options(s, &options, hls);
+    ret = hlsenc_io_open(s, &vs->out, vs->base_output_dirname, &options);
+    av_dict_free(&options);
+    if (ret < 0)
+        return ret;
+    avio_write(vs->out, vs->init_buffer, vs->init_range_length);
+    hlsenc_io_close(s, &vs->out, hls->fmp4_init_filename);
+
+    return ret;
+}
+
 static int hls_write_packet(AVFormatContext *s, AVPacket *pkt)
 {
     HLSContext *hls = s->priv_data;
@@ -2238,7 +2308,6 @@ static int hls_write_packet(AVFormatContext *s, AVPacket *pkt)
     int range_length = 0;
     const char *proto = NULL;
     int use_temp_file = 0;
-    uint8_t *buffer = NULL;
     VariantStream *vs = NULL;
     char *old_filename = NULL;
 
@@ -2278,6 +2347,12 @@ static int hls_write_packet(AVFormatContext *s, AVPacket *pkt)
 
     if (vs->start_pts == AV_NOPTS_VALUE) {
         vs->start_pts = pkt->pts;
+        if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
+            vs->start_pts_from_audio = 1;
+    }
+    if (vs->start_pts_from_audio && st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && vs->start_pts > pkt->pts) {
+        vs->start_pts = pkt->pts;
+        vs->start_pts_from_audio = 0;
     }
 
    if (vs->has_video) {
@@ -2318,9 +2393,12 @@ static int hls_write_packet(AVFormatContext *s, AVPacket *pkt)
         avio_flush(oc->pb);
         if (hls->segment_type == SEGMENT_TYPE_FMP4) {
             if (!vs->init_range_length) {
-                range_length = avio_close_dyn_buf(oc->pb, &buffer);
-                avio_write(vs->out, buffer, range_length);
-                av_freep(&buffer);
+                range_length = avio_close_dyn_buf(oc->pb, &vs->init_buffer);
+                if (range_length <= 0)
+                    return AVERROR(EINVAL);
+                avio_write(vs->out, vs->init_buffer, range_length);
+                if (!hls->resend_init_file)
+                    av_freep(&vs->init_buffer);
                 vs->init_range_length = range_length;
                 avio_open_dyn_buf(&oc->pb);
                 vs->packets_written = 0;
@@ -2336,11 +2414,6 @@ 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);
-        }
-
         if (hls->flags & HLS_SINGLE_FILE) {
             ret = flush_dynbuf(vs, &range_length);
             av_freep(&vs->temp_buffer);
@@ -2349,12 +2422,18 @@ static int hls_write_packet(AVFormatContext *s, AVPacket *pkt)
             }
             vs->size = range_length;
         } else {
+            if (oc->url[0]) {
+                proto = avio_find_protocol_name(oc->url);
+                use_temp_file = proto && !strcmp(proto, "file")
+                                      && (hls->flags & HLS_TEMP_FILE);
+            }
+
             if ((hls->max_seg_size > 0 && (vs->size >= hls->max_seg_size)) || !byterange_mode) {
                 AVDictionary *options = NULL;
                 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);
+                    av_dict_set(&options, "encryption_key", vs->key_string, 0);
+                    av_dict_set(&options, "encryption_iv", vs->iv_string, 0);
                     filename = av_asprintf("crypto:%s", oc->url);
                 } else {
                     filename = av_asprintf("%s", oc->url);
@@ -2398,10 +2477,9 @@ static int hls_write_packet(AVFormatContext *s, AVPacket *pkt)
                 av_freep(&vs->temp_buffer);
                 av_freep(&filename);
             }
-        }
 
-        if (use_temp_file && !(hls->flags & HLS_SINGLE_FILE)) {
-            hls_rename_temp_file(s, oc);
+            if (use_temp_file)
+                hls_rename_temp_file(s, oc);
         }
 
         old_filename = av_strdup(oc->url);
@@ -2410,7 +2488,8 @@ static int hls_write_packet(AVFormatContext *s, AVPacket *pkt)
         }
 
         if (vs->start_pos || hls->segment_type != SEGMENT_TYPE_FMP4) {
-            ret = hls_append_segment(s, hls, vs, vs->duration, vs->start_pos, vs->size);
+            double cur_duration =  (double)(pkt->pts - vs->end_pts) * st->time_base.num / st->time_base.den;
+            ret = hls_append_segment(s, hls, vs, cur_duration, vs->start_pos, vs->size);
             vs->end_pts = pkt->pts;
             vs->duration = 0;
             if (ret < 0) {
@@ -2432,6 +2511,14 @@ static int hls_write_packet(AVFormatContext *s, AVPacket *pkt)
             }
         }
 
+        if (hls->resend_init_file && hls->segment_type == SEGMENT_TYPE_FMP4) {
+            ret = hls_init_file_resend(s, vs);
+            if (ret < 0) {
+                av_freep(&old_filename);
+                return ret;
+            }
+        }
+
         if (hls->flags & HLS_SINGLE_FILE) {
             vs->number++;
             vs->start_pos += vs->size;
@@ -2476,8 +2563,9 @@ static int hls_write_packet(AVFormatContext *s, AVPacket *pkt)
     return ret;
 }
 
-static void hls_free_variant_streams(struct HLSContext *hls)
+static void hls_deinit(AVFormatContext *s)
 {
+    HLSContext *hls = s->priv_data;
     int i = 0;
     AVFormatContext *vtt_oc = NULL;
     VariantStream *vs = NULL;
@@ -2489,24 +2577,38 @@ static void hls_free_variant_streams(struct HLSContext *hls)
         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);
-            avformat_free_context(vtt_oc);
-        }
+        av_freep(&vs->vtt_basename);
+        av_freep(&vs->vtt_m3u8_name);
 
+        avformat_free_context(vtt_oc);
         avformat_free_context(vs->avf);
-
+        if (hls->resend_init_file)
+            av_freep(&vs->init_buffer);
         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->sgroup);
         av_freep(&vs->language);
         av_freep(&vs->ccgroup);
         av_freep(&vs->baseurl);
         av_freep(&vs->varname);
     }
+
+    for (i = 0; i < hls->nb_ccstreams; i++) {
+        ClosedCaptionsStream *ccs = &hls->cc_streams[i];
+        av_freep(&ccs->ccgroup);
+        av_freep(&ccs->instreamid);
+        av_freep(&ccs->language);
+    }
+
+    ff_format_io_close(s, &hls->m3u8_out);
+    ff_format_io_close(s, &hls->sub_m3u8_out);
+    av_freep(&hls->key_basename);
+    av_freep(&hls->var_streams);
+    av_freep(&hls->cc_streams);
+    av_freep(&hls->master_m3u8_url);
 }
 
 static int hls_write_trailer(struct AVFormatContext *s)
@@ -2535,8 +2637,8 @@ static int hls_write_trailer(struct AVFormatContext *s)
             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);
+            av_dict_set(&options, "encryption_key", vs->key_string, 0);
+            av_dict_set(&options, "encryption_iv", vs->iv_string, 0);
             filename = av_asprintf("crypto:%s", oc->url);
         } else {
             filename = av_asprintf("%s", oc->url);
@@ -2551,7 +2653,6 @@ static int hls_write_trailer(struct AVFormatContext *s)
             if (!vs->init_range_length) {
                 uint8_t *buffer = NULL;
                 av_write_frame(oc, NULL); /* Flush any buffered data */
-                avio_flush(oc->pb);
 
                 range_length = avio_close_dyn_buf(oc->pb, &buffer);
                 avio_write(vs->out, buffer, range_length);
@@ -2640,21 +2741,6 @@ failed:
         av_free(old_filename);
     }
 
-    hls_free_variant_streams(hls);
-
-    for (i = 0; i < hls->nb_ccstreams; i++) {
-        ClosedCaptionsStream *ccs = &hls->cc_streams[i];
-        av_freep(&ccs->ccgroup);
-        av_freep(&ccs->instreamid);
-        av_freep(&ccs->language);
-    }
-
-    ff_format_io_close(s, &hls->m3u8_out);
-    ff_format_io_close(s, &hls->sub_m3u8_out);
-    av_freep(&hls->key_basename);
-    av_freep(&hls->var_streams);
-    av_freep(&hls->cc_streams);
-    av_freep(&hls->master_m3u8_url);
     return 0;
 }
 
@@ -2683,12 +2769,6 @@ static int hls_init(AVFormatContext *s)
                ret);
         goto fail;
     }
-    //TODO: Updates needed to encryption functionality with periodic re-key when more than one variant streams are present
-    if (hls->nb_varstreams > 1 && hls->flags & HLS_PERIODIC_REKEY) {
-        ret = AVERROR(EINVAL);
-        av_log(s, AV_LOG_ERROR, "Periodic re-key not supported when more than one variant streams are present\n");
-        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");
@@ -2729,9 +2809,12 @@ static int hls_init(AVFormatContext *s)
         pattern = "%d.m4s";
     }
     if ((hls->start_sequence_source_type == HLS_START_SEQUENCE_AS_SECONDS_SINCE_EPOCH) ||
+        (hls->start_sequence_source_type == HLS_START_SEQUENCE_AS_MICROSECONDS_SINCE_EPOCH) ||
         (hls->start_sequence_source_type == HLS_START_SEQUENCE_AS_FORMATTED_DATETIME)) {
-        time_t t = time(NULL); // we will need it in either case
-        if (hls->start_sequence_source_type == HLS_START_SEQUENCE_AS_SECONDS_SINCE_EPOCH) {
+        time_t t = time(NULL);
+        if (hls->start_sequence_source_type == HLS_START_SEQUENCE_AS_MICROSECONDS_SINCE_EPOCH) {
+            hls->start_sequence = av_gettime();
+        } else if (hls->start_sequence_source_type == HLS_START_SEQUENCE_AS_SECONDS_SINCE_EPOCH) {
             hls->start_sequence = (int64_t)t;
         } else if (hls->start_sequence_source_type == HLS_START_SEQUENCE_AS_FORMATTED_DATETIME) {
             char b[15];
@@ -2771,13 +2854,6 @@ static int hls_init(AVFormatContext *s)
             time(&now0);
             vs->initial_prog_date_time = now0;
         }
-        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);
-                goto fail;
-            }
-        }
 
         for (j = 0; j < vs->nb_streams; j++) {
             vs->has_video += vs->streams[j]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO;
@@ -2802,13 +2878,6 @@ static int hls_init(AVFormatContext *s)
             goto fail;
         }
 
-        if (vs->has_subtitle) {
-            vs->vtt_oformat = av_guess_format("webvtt", NULL, NULL);
-            if (!vs->oformat) {
-                ret = AVERROR_MUXER_NOT_FOUND;
-                goto fail;
-            }
-        }
         if (hls->segment_filename) {
             ret = format_name(hls->segment_filename, &vs->basename, i, vs->varname);
             if (ret < 0)
@@ -2866,7 +2935,8 @@ static int hls_init(AVFormatContext *s)
                 if (hls->nb_varstreams > 1) {
                     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);
+                        ret = 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);
                     }
@@ -2902,6 +2972,9 @@ static int hls_init(AVFormatContext *s)
             goto fail;
 
         if (vs->has_subtitle) {
+            vs->vtt_oformat = av_guess_format("webvtt", NULL, NULL);
+            if (!vs->vtt_oformat)
+                return AVERROR_MUXER_NOT_FOUND;
 
             if (hls->flags & HLS_SINGLE_FILE)
                 vtt_pattern = ".vtt";
@@ -2922,13 +2995,11 @@ static int hls_init(AVFormatContext *s)
                 if (ret < 0)
                     goto fail;
             } else {
-                vs->vtt_m3u8_name = av_malloc(vtt_basename_size);
+                vs->vtt_m3u8_name = av_asprintf("%s_vtt.m3u8", vs->vtt_basename);
                 if (!vs->vtt_m3u8_name) {
                     ret = AVERROR(ENOMEM);
                     goto fail;
                 }
-                strcpy(vs->vtt_m3u8_name, vs->vtt_basename);
-                av_strlcat(vs->vtt_m3u8_name, "_vtt.m3u8", vtt_basename_size);
             }
             av_strlcat(vs->vtt_basename, vtt_pattern, vtt_basename_size);
         }
@@ -2960,20 +3031,6 @@ static int hls_init(AVFormatContext *s)
     }
 
 fail:
-    if (ret < 0) {
-        hls_free_variant_streams(hls);
-        for (i = 0; i < hls->nb_ccstreams; i++) {
-            ClosedCaptionsStream *ccs = &hls->cc_streams[i];
-            av_freep(&ccs->ccgroup);
-            av_freep(&ccs->instreamid);
-            av_freep(&ccs->language);
-        }
-        av_freep(&hls->key_basename);
-        av_freep(&hls->var_streams);
-        av_freep(&hls->cc_streams);
-        av_freep(&hls->master_m3u8_url);
-    }
-
     return ret;
 }
 
@@ -2985,7 +3042,7 @@ static const AVOption options[] = {
     {"hls_init_time", "set segment length in seconds at init list",           OFFSET(init_time),    AV_OPT_TYPE_FLOAT,  {.dbl = 0},     0, FLT_MAX, E},
     {"hls_list_size", "set maximum number of playlist entries",  OFFSET(max_nb_segments),    AV_OPT_TYPE_INT,    {.i64 = 5},     0, INT_MAX, E},
     {"hls_delete_threshold", "set number of unreferenced segments to keep before deleting",  OFFSET(hls_delete_threshold),    AV_OPT_TYPE_INT,    {.i64 = 1},     1, INT_MAX, E},
-    {"hls_ts_options","set hls mpegts list of options for the container format used for hls", OFFSET(format_options_str), AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,    E},
+    {"hls_ts_options","set hls mpegts list of options for the container format used for hls", OFFSET(format_options), AV_OPT_TYPE_DICT, {.str = NULL},  0, 0,    E},
     {"hls_vtt_options","set hls vtt list of options for the container format used for hls", OFFSET(vtt_format_options_str), AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,    E},
 #if FF_API_HLS_WRAP
     {"hls_wrap",      "set number after which the index wraps (will be deprecated)",  OFFSET(wrap),    AV_OPT_TYPE_INT,    {.i64 = 0},     0, INT_MAX, E},
@@ -3004,6 +3061,7 @@ static const AVOption options[] = {
     {"mpegts",   "make segment file to mpegts files in m3u8", 0, AV_OPT_TYPE_CONST, {.i64 = SEGMENT_TYPE_MPEGTS }, 0, UINT_MAX,   E, "segment_type"},
     {"fmp4",   "make segment file to fragment mp4 files in m3u8", 0, AV_OPT_TYPE_CONST, {.i64 = SEGMENT_TYPE_FMP4 }, 0, UINT_MAX,   E, "segment_type"},
     {"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_fmp4_init_resend", "resend fragment mp4 init file after refresh m3u8 every time", OFFSET(resend_init_file), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, 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 and playlist to temporary file and rename when complete", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_TEMP_FILE }, 0, UINT_MAX,   E, "flags"},
@@ -3032,9 +3090,10 @@ static const AVOption options[] = {
     {"event", "EVENT playlist", 0, AV_OPT_TYPE_CONST, {.i64 = PLAYLIST_TYPE_EVENT }, INT_MIN, INT_MAX, E, "pl_type" },
     {"vod", "VOD playlist", 0, AV_OPT_TYPE_CONST, {.i64 = PLAYLIST_TYPE_VOD }, INT_MIN, INT_MAX, E, "pl_type" },
     {"method", "set the HTTP method(default: PUT)", OFFSET(method), AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,    E},
-    {"hls_start_number_source", "set source of first number in sequence", OFFSET(start_sequence_source_type), AV_OPT_TYPE_INT, {.i64 = HLS_START_SEQUENCE_AS_START_NUMBER }, 0, HLS_START_SEQUENCE_AS_FORMATTED_DATETIME, E, "start_sequence_source_type" },
+    {"hls_start_number_source", "set source of first number in sequence", OFFSET(start_sequence_source_type), AV_OPT_TYPE_INT, {.i64 = HLS_START_SEQUENCE_AS_START_NUMBER }, 0, HLS_START_SEQUENCE_LAST-1, E, "start_sequence_source_type" },
     {"generic", "start_number value (default)", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_START_SEQUENCE_AS_START_NUMBER }, INT_MIN, INT_MAX, E, "start_sequence_source_type" },
     {"epoch", "seconds since epoch", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_START_SEQUENCE_AS_SECONDS_SINCE_EPOCH }, INT_MIN, INT_MAX, E, "start_sequence_source_type" },
+    {"epoch_us", "microseconds since epoch", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_START_SEQUENCE_AS_MICROSECONDS_SINCE_EPOCH }, INT_MIN, INT_MAX, E, "start_sequence_source_type" },
     {"datetime", "current datetime as YYYYMMDDhhmmss", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_START_SEQUENCE_AS_FORMATTED_DATETIME }, INT_MIN, INT_MAX, E, "start_sequence_source_type" },
     {"http_user_agent", "override User-Agent field in HTTP header", OFFSET(user_agent), AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,    E},
     {"var_stream_map", "Variant stream map string", OFFSET(var_stream_map), AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,    E},
@@ -3069,5 +3128,6 @@ AVOutputFormat ff_hls_muxer = {
     .write_header   = hls_write_header,
     .write_packet   = hls_write_packet,
     .write_trailer  = hls_write_trailer,
+    .deinit         = hls_deinit,
     .priv_class     = &hls_class,
 };