]> git.sesse.net Git - ffmpeg/blobdiff - libavformat/hlsenc.c
avformat/hlsenc: Remove deprecated localtime options
[ffmpeg] / libavformat / hlsenc.c
index be54957e9dcbf9b3ff59d521b88463cf17f5a02e..6e7d6d554b1bccc2ccff6fd9ea8b7a01e3dde229 100644 (file)
@@ -46,6 +46,7 @@
 
 #include "avformat.h"
 #include "avio_internal.h"
+#include "avc.h"
 #if CONFIG_HTTP_PROTOCOL
 #include "http.h"
 #endif
@@ -69,6 +70,7 @@ typedef enum {
 #define KEYSIZE 16
 #define LINE_BUFFER_SIZE MAX_URL_SIZE
 #define HLS_MICROSECOND_UNIT   1000000
+#define BUFSIZE (16 * 1024)
 #define POSTFIX_PATTERN "_%d"
 
 typedef struct HLSSegment {
@@ -86,6 +88,7 @@ typedef struct HLSSegment {
     char iv_string[KEYSIZE*2 + 1];
 
     struct HLSSegment *next;
+    double discont_program_date_time;
 } HLSSegment;
 
 typedef enum HLSFlags {
@@ -116,9 +119,10 @@ typedef struct VariantStream {
     unsigned var_stream_idx;
     unsigned number;
     int64_t sequence;
-    ff_const59 AVOutputFormat *oformat;
-    ff_const59 AVOutputFormat *vtt_oformat;
+    const AVOutputFormat *oformat;
+    const AVOutputFormat *vtt_oformat;
     AVIOContext *out;
+    AVIOContext *out_single_file;
     int packets_written;
     int init_range_length;
     uint8_t *temp_buffer;
@@ -149,6 +153,7 @@ typedef struct VariantStream {
     HLSSegment *last_segment;
     HLSSegment *old_segments;
 
+    char *basename_tmp;
     char *basename;
     char *vtt_basename;
     char *vtt_m3u8_name;
@@ -173,18 +178,17 @@ typedef struct VariantStream {
     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 *sgroup; /* subtitle group name */
-    char *ccgroup; /* closed caption group name */
-    char *baseurl;
-    char *varname; // variant name
+    const char *language; /* audio lauguage name */
+    const char *agroup;   /* audio group name */
+    const char *sgroup;   /* subtitle group name */
+    const char *ccgroup;  /* closed caption group name */
+    const char *varname;  /* variant name */
 } VariantStream;
 
 typedef struct ClosedCaptionsStream {
-    char *ccgroup; /* closed caption group name */
-    char *instreamid; /* closed captions INSTREAM-ID */
-    char *language; /* closed captions langauge */
+    const char *ccgroup;    /* closed caption group name */
+    const char *instreamid; /* closed captions INSTREAM-ID */
+    const char *language;   /* closed captions langauge */
 } ClosedCaptionsStream;
 
 typedef struct HLSContext {
@@ -192,13 +196,10 @@ typedef struct HLSContext {
     int64_t start_sequence;
     uint32_t start_sequence_source_type;  // enum StartSequenceSourceType
 
-    float time;            // Set by a private option.
-    float init_time;       // Set by a private option.
+    int64_t time;          // Set by a private option.
+    int64_t init_time;     // Set by a private option.
     int max_nb_segments;   // Set by a private option.
     int hls_delete_threshold; // Set by a private option.
-#if FF_API_HLS_WRAP
-    int  wrap;             // Set by a private option.
-#endif
     uint32_t flags;        // enum HLSFlags
     uint32_t pl_type;      // enum PlaylistType
     char *segment_filename;
@@ -256,6 +257,29 @@ typedef struct HLSContext {
     int has_video_m3u8; /* has video stream m3u8 list */
 } HLSContext;
 
+static int strftime_expand(const char *fmt, char **dest)
+{
+    int r = 1;
+    time_t now0;
+    struct tm *tm, tmpbuf;
+    char *buf;
+
+    buf = av_mallocz(MAX_URL_SIZE);
+    if (!buf)
+        return AVERROR(ENOMEM);
+
+    time(&now0);
+    tm = localtime_r(&now0, &tmpbuf);
+    r = strftime(buf, MAX_URL_SIZE, fmt, tm);
+    if (!r) {
+        av_free(buf);
+        return AVERROR(EINVAL);
+    }
+    *dest = buf;
+
+    return r;
+}
+
 static int hlsenc_io_open(AVFormatContext *s, AVIOContext **pb, char *filename,
                           AVDictionary **options)
 {
@@ -335,6 +359,51 @@ static void write_codec_attr(AVStream *st, VariantStream *vs)
         } else {
             goto fail;
         }
+    } else if (st->codecpar->codec_id == AV_CODEC_ID_HEVC) {
+        uint8_t *data = st->codecpar->extradata;
+        int profile = FF_PROFILE_UNKNOWN;
+        int level = FF_LEVEL_UNKNOWN;
+
+        if (st->codecpar->profile != FF_PROFILE_UNKNOWN)
+            profile = st->codecpar->profile;
+        if (st->codecpar->level != FF_LEVEL_UNKNOWN)
+            level = st->codecpar->level;
+
+        /* check the boundary of data which from current position is small than extradata_size */
+        while (data && (data - st->codecpar->extradata + 19) < st->codecpar->extradata_size) {
+            /* get HEVC SPS NAL and seek to profile_tier_level */
+            if (!(data[0] | data[1] | data[2]) && data[3] == 1 && ((data[4] & 0x7E) == 0x42)) {
+                uint8_t *rbsp_buf;
+                int remain_size = 0;
+                int rbsp_size = 0;
+                /* skip start code + nalu header */
+                data += 6;
+                /* process by reference General NAL unit syntax */
+                remain_size = st->codecpar->extradata_size - (data - st->codecpar->extradata);
+                rbsp_buf = ff_nal_unit_extract_rbsp(data, remain_size, &rbsp_size, 0);
+                if (!rbsp_buf)
+                    return;
+                if (rbsp_size < 13) {
+                    av_freep(&rbsp_buf);
+                    break;
+                }
+                /* skip sps_video_parameter_set_id   u(4),
+                 *      sps_max_sub_layers_minus1    u(3),
+                 *  and sps_temporal_id_nesting_flag u(1) */
+                profile = rbsp_buf[1] & 0x1f;
+                /* skip 8 + 8 + 32 + 4 + 43 + 1 bit */
+                level = rbsp_buf[12];
+                av_freep(&rbsp_buf);
+                break;
+            }
+            data++;
+        }
+        if (st->codecpar->codec_tag == MKTAG('h','v','c','1') &&
+            profile != FF_PROFILE_UNKNOWN &&
+            level != FF_LEVEL_UNKNOWN) {
+            snprintf(attr, sizeof(attr), "%s.%d.4.L%d.B01", av_fourcc2str(st->codecpar->codec_tag), profile, level);
+        } else
+            goto fail;
     } else if (st->codecpar->codec_id == AV_CODEC_ID_MP2) {
         snprintf(attr, sizeof(attr), "mp4a.40.33");
     } else if (st->codecpar->codec_id == AV_CODEC_ID_MP3) {
@@ -366,11 +435,11 @@ fail:
 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;
+    int ret;
 
     av_bprint_init(&buf, 0, AV_BPRINT_SIZE_UNLIMITED);
 
@@ -396,22 +465,21 @@ static int replace_str_data_in_filename(char **s, const char *filename, char pla
     }
     if (!av_bprint_is_complete(&buf)) {
         av_bprint_finalize(&buf, NULL);
-        return -1;
+        return AVERROR(ENOMEM);
     }
-    if (av_bprint_finalize(&buf, &new_filename) < 0 || !new_filename)
-        return -1;
-    *s = new_filename;
+    if ((ret = av_bprint_finalize(&buf, s)) < 0)
+        return ret;
     return found_count;
 }
 
 static int replace_int_data_in_filename(char **s, const char *filename, char placeholder, int64_t number)
 {
     const char *p;
-    char *new_filename;
     char c;
     int nd, addchar_count;
     int found_count = 0;
     AVBPrint buf;
+    int ret;
 
     av_bprint_init(&buf, 0, AV_BPRINT_SIZE_UNLIMITED);
 
@@ -445,11 +513,10 @@ static int replace_int_data_in_filename(char **s, const char *filename, char pla
     }
     if (!av_bprint_is_complete(&buf)) {
         av_bprint_finalize(&buf, NULL);
-        return -1;
+        return AVERROR(ENOMEM);
     }
-    if (av_bprint_finalize(&buf, &new_filename) < 0 || !new_filename)
-        return -1;
-    *s = new_filename;
+    if ((ret = av_bprint_finalize(&buf, s)) < 0)
+        return ret;
     return found_count;
 }
 
@@ -993,11 +1060,7 @@ static int sls_flag_use_localtime_filename(AVFormatContext *oc, HLSContext *c, V
     if (c->flags & HLS_SECOND_LEVEL_SEGMENT_INDEX) {
         char *filename = NULL;
         if (replace_int_data_in_filename(&filename,
-#if FF_API_HLS_WRAP
-            oc->url, 'd', c->wrap ? vs->sequence % c->wrap : vs->sequence) < 1) {
-#else
             oc->url, 'd', vs->sequence) < 1) {
-#endif
             av_log(c, AV_LOG_ERROR, "Invalid second level segment filename template '%s', "
                     "you can try to remove second_level_segment_index flag\n",
                    oc->url);
@@ -1078,6 +1141,7 @@ static int hls_append_segment(struct AVFormatContext *s, HLSContext *hls,
     en->keyframe_size     = vs->video_keyframe_size;
     en->next     = NULL;
     en->discont  = 0;
+    en->discont_program_date_time = 0;
 
     if (vs->discontinuity) {
         en->discont = 1;
@@ -1102,14 +1166,11 @@ static int hls_append_segment(struct AVFormatContext *s, HLSContext *hls,
 
     if (hls->max_nb_segments && vs->nb_entries >= hls->max_nb_segments) {
         en = vs->segments;
-        vs->initial_prog_date_time += en->duration;
+        if (!en->next->discont_program_date_time && !en->discont_program_date_time)
+            vs->initial_prog_date_time += en->duration;
         vs->segments = en->next;
         if (en && hls->flags & HLS_DELETE_SEGMENTS &&
-#if FF_API_HLS_WRAP
-                !(hls->flags & HLS_SINGLE_FILE || hls->wrap)) {
-#else
                 !(hls->flags & HLS_SINGLE_FILE)) {
-#endif
             en->next = vs->old_segments;
             vs->old_segments = en;
             if ((ret = hls_delete_old_segments(s, hls, vs)) < 0)
@@ -1136,6 +1197,7 @@ static int parse_playlist(AVFormatContext *s, const char *url, VariantStream *vs
     char line[MAX_URL_SIZE];
     const char *ptr;
     const char *end;
+    double discont_program_date_time = 0;
 
     if ((ret = ffio_open_whitelist(&in, url, AVIO_FLAG_READ,
                                    &s->interrupt_callback, NULL,
@@ -1190,7 +1252,25 @@ static int parse_playlist(AVFormatContext *s, const char *url, VariantStream *vs
                     av_strlcpy(vs->iv_string, ptr, sizeof(vs->iv_string));
                 }
             }
+        } else if (av_strstart(line, "#EXT-X-PROGRAM-DATE-TIME:", &ptr)) {
+            struct tm program_date_time;
+            int y,M,d,h,m,s;
+            double ms;
+            if (sscanf(ptr, "%d-%d-%dT%d:%d:%d.%lf", &y, &M, &d, &h, &m, &s, &ms) != 7) {
+                ret = AVERROR_INVALIDDATA;
+                goto fail;
+            }
 
+            program_date_time.tm_year = y - 1900;
+            program_date_time.tm_mon = M - 1;
+            program_date_time.tm_mday = d;
+            program_date_time.tm_hour = h;
+            program_date_time.tm_min = m;
+            program_date_time.tm_sec = s;
+            program_date_time.tm_isdst = -1;
+
+            discont_program_date_time = mktime(&program_date_time);
+            discont_program_date_time += (double)(ms / 1000);
         } else if (av_strstart(line, "#", NULL)) {
             continue;
         } else if (line[0]) {
@@ -1204,8 +1284,9 @@ 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);
+                vs->last_segment->discont_program_date_time = discont_program_date_time;
+                discont_program_date_time += vs->duration;
                 if (ret < 0)
                     goto fail;
                 vs->start_pos = new_start_pos;
@@ -1291,8 +1372,8 @@ static int create_master_playlist(AVFormatContext *s,
     int ret, bandwidth;
     const char *m3u8_rel_name = NULL;
     const char *vtt_m3u8_rel_name = NULL;
-    char *ccgroup;
-    char *sgroup = NULL;
+    const char *ccgroup;
+    const char *sgroup = NULL;
     ClosedCaptionsStream *ccs;
     const char *proto = avio_find_protocol_name(hls->master_m3u8_url);
     int is_file_proto = proto && !strcmp(proto, "file");
@@ -1472,6 +1553,10 @@ static int hls_window(AVFormatContext *s, int last, VariantStream *vs)
         sequence = 0;
     }
 
+    if (hls->flags & HLS_I_FRAMES_ONLY) {
+        hls->version = 4;
+    }
+
     if (hls->flags & HLS_INDEPENDENT_SEGMENTS) {
         hls->version = 6;
     }
@@ -1525,8 +1610,12 @@ static int hls_window(AVFormatContext *s, int last, VariantStream *vs)
 
         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);
+                                      en->size, en->pos, hls->baseurl,
+                                      en->filename,
+                                      en->discont_program_date_time ? &en->discont_program_date_time : prog_date_time_p,
+                                      en->keyframe_size, en->keyframe_pos, hls->flags & HLS_I_FRAMES_ONLY);
+        if (en->discont_program_date_time)
+            en->discont_program_date_time -= en->duration;
         if (ret < 0) {
             av_log(s, AV_LOG_WARNING, "ff_hls_write_file_entry get error\n");
         }
@@ -1547,7 +1636,7 @@ static int hls_window(AVFormatContext *s, int last, VariantStream *vs)
         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, 0, 0, 0);
+                                          hls->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");
             }
@@ -1602,11 +1691,7 @@ static int hls_start(AVFormatContext *s, VariantStream *vs)
     } else if (c->max_seg_size > 0) {
         char *filename = NULL;
         if (replace_int_data_in_filename(&filename,
-#if FF_API_HLS_WRAP
-            vs->basename, 'd', c->wrap ? vs->sequence % c->wrap : vs->sequence) < 1) {
-#else
             vs->basename, 'd', vs->sequence) < 1) {
-#endif
                 av_freep(&filename);
                 av_log(oc, AV_LOG_ERROR, "Invalid segment filename template '%s', you can try to use -strftime 1 with it\n", vs->basename);
                 return AVERROR(EINVAL);
@@ -1614,19 +1699,15 @@ static int hls_start(AVFormatContext *s, VariantStream *vs)
         ff_format_set_url(oc, filename);
     } else {
         if (c->use_localtime) {
-            time_t now0;
-            struct tm *tm, tmpbuf;
-            int bufsize = strlen(vs->basename) + MAX_URL_SIZE;
-            char *buf = av_mallocz(bufsize);
-            if (!buf)
-                return AVERROR(ENOMEM);
-            time(&now0);
-            tm = localtime_r(&now0, &tmpbuf);
-            ff_format_set_url(oc, buf);
-            if (!strftime(oc->url, bufsize, vs->basename, tm)) {
+            int r;
+            char *expanded = NULL;
+
+            r = strftime_expand(vs->basename, &expanded);
+            if (r < 0) {
                 av_log(oc, AV_LOG_ERROR, "Could not get segment filename with strftime\n");
-                return AVERROR(EINVAL);
+                return r;
             }
+            ff_format_set_url(oc, expanded);
 
             err = sls_flag_use_localtime_filename(oc, c, vs);
             if (err < 0) {
@@ -1649,11 +1730,7 @@ static int hls_start(AVFormatContext *s, VariantStream *vs)
         } else {
             char *filename = NULL;
             if (replace_int_data_in_filename(&filename,
-#if FF_API_HLS_WRAP
-                   vs->basename, 'd', c->wrap ? vs->sequence % c->wrap : vs->sequence) < 1) {
-#else
                    vs->basename, 'd', vs->sequence) < 1) {
-#endif
                 av_freep(&filename);
                 av_log(oc, AV_LOG_ERROR, "Invalid segment filename template '%s' you can try to use -strftime 1 with it\n", vs->basename);
                 return AVERROR(EINVAL);
@@ -1663,11 +1740,7 @@ static int hls_start(AVFormatContext *s, VariantStream *vs)
         if (vs->vtt_basename) {
             char *filename = NULL;
             if (replace_int_data_in_filename(&filename,
-#if FF_API_HLS_WRAP
-                vs->vtt_basename, 'd', c->wrap ? vs->sequence % c->wrap : vs->sequence) < 1) {
-#else
                 vs->vtt_basename, 'd', vs->sequence) < 1) {
-#endif
                 av_freep(&filename);
                 av_log(vtt_oc, AV_LOG_ERROR, "Invalid segment filename template '%s'\n", vs->vtt_basename);
                 return AVERROR(EINVAL);
@@ -1675,7 +1748,6 @@ static int hls_start(AVFormatContext *s, VariantStream *vs)
             ff_format_set_url(vtt_oc, filename);
        }
     }
-    vs->number++;
 
     proto = avio_find_protocol_name(oc->url);
     use_temp_file = proto && !strcmp(proto, "file") && (c->flags & HLS_TEMP_FILE);
@@ -1726,12 +1798,34 @@ static int hls_start(AVFormatContext *s, VariantStream *vs)
             av_opt_set(oc->priv_data, "mpegts_flags", "resend_headers", 0);
         }
         if (c->flags & HLS_SINGLE_FILE) {
+            if (c->key_info_file || c->encrypt) {
+                av_dict_set(&options, "encryption_key", vs->key_string, 0);
+                av_dict_set(&options, "encryption_iv", vs->iv_string, 0);
+
+                /* Write temp file with cryption content */
+                av_freep(&vs->basename_tmp);
+                vs->basename_tmp = av_asprintf("crypto:%s.tmp", oc->url);
+
+                /* append temp file content into single file */
+                av_freep(&vs->basename);
+                vs->basename = av_asprintf("%s", oc->url);
+            } else {
+                vs->basename_tmp = vs->basename;
+            }
             set_http_options(s, &options, c);
-            if ((err = hlsenc_io_open(s, &vs->out, oc->url, &options)) < 0) {
+            if (!vs->out_single_file)
+                if ((err = hlsenc_io_open(s, &vs->out_single_file, vs->basename, &options)) < 0) {
+                    if (c->ignore_io_errors)
+                        err = 0;
+                    goto fail;
+                }
+
+            if ((err = hlsenc_io_open(s, &vs->out, vs->basename_tmp, &options)) < 0) {
                 if (c->ignore_io_errors)
                     err = 0;
                 goto fail;
             }
+
         }
     }
     if (vs->vtt_basename) {
@@ -1945,10 +2039,13 @@ static int parse_variant_stream_mapstring(AVFormatContext *s)
             return AVERROR(EINVAL);
 
         q = varstr;
-        while (q < varstr + strlen(varstr)) {
+        while (1) {
             if (!av_strncasecmp(q, "a:", 2) || !av_strncasecmp(q, "v:", 2) ||
                 !av_strncasecmp(q, "s:", 2))
                 vs->nb_streams++;
+            q = strchr(q, ',');
+            if (!q)
+                break;
             q++;
         }
         vs->streams = av_mallocz(sizeof(AVStream *) * vs->nb_streams);
@@ -1961,10 +2058,7 @@ static int parse_variant_stream_mapstring(AVFormatContext *s)
             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);
+                vs->language = val;
                 continue;
             } else if (av_strstart(keyval, "default:", &val)) {
                 vs->is_default = (!av_strncasecmp(val, "YES", strlen("YES")) ||
@@ -1972,28 +2066,16 @@ 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);
+                vs->varname  = val;
                 continue;
             } else if (av_strstart(keyval, "agroup:", &val)) {
-                av_free(vs->agroup);
-                vs->agroup = av_strdup(val);
-                if (!vs->agroup)
-                    return AVERROR(ENOMEM);
+                vs->agroup   = val;
                 continue;
             } else if (av_strstart(keyval, "sgroup:", &val)) {
-                av_free(vs->sgroup);
-                vs->sgroup = av_strdup(val);
-                if (!vs->sgroup)
-                    return AVERROR(ENOMEM);
+                vs->sgroup   = val;
                 continue;
             } else if (av_strstart(keyval, "ccgroup:", &val)) {
-                av_free(vs->ccgroup);
-                vs->ccgroup = av_strdup(val);
-                if (!vs->ccgroup)
-                    return AVERROR(ENOMEM);
+                vs->ccgroup  = val;
                 continue;
             } else if (av_strstart(keyval, "v:", &val)) {
                 codec_type = AVMEDIA_TYPE_VIDEO;
@@ -2007,7 +2089,7 @@ static int parse_variant_stream_mapstring(AVFormatContext *s)
                 return AVERROR(EINVAL);
             }
 
-            num = strtoll(val, &end, 0);
+            num = strtoll(val, &end, 10);
             if (!av_isdigit(*val) || *end != '\0') {
                 av_log(s, AV_LOG_ERROR, "Invalid stream number: '%s'\n", val);
                 return AVERROR(EINVAL);
@@ -2084,20 +2166,11 @@ 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);
+                ccs->ccgroup    = val;
             } else if (av_strstart(keyval, "instreamid:", &val)) {
-                av_free(ccs->instreamid);
-                ccs->instreamid = av_strdup(val);
-                if (!ccs->instreamid)
-                    return AVERROR(ENOMEM);
+                ccs->instreamid = val;
             } else if (av_strstart(keyval, "language:", &val)) {
-                av_free(ccs->language);
-                ccs->language = av_strdup(val);
-                if (!ccs->language)
-                    return AVERROR(ENOMEM);
+                ccs->language   = val;
             } else {
                 av_log(s, AV_LOG_ERROR, "Invalid keyval %s\n", keyval);
                 return AVERROR(EINVAL);
@@ -2160,11 +2233,8 @@ static int update_variant_stream_info(AVFormatContext *s)
             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)
-                return AVERROR(ENOMEM);
-        }
+        if (hls->nb_ccstreams)
+            hls->var_streams[0].ccgroup = hls->cc_streams[0].ccgroup;
 
         for (i = 0; i < s->nb_streams; i++)
             hls->var_streams[0].streams[i] = s->streams[i];
@@ -2250,6 +2320,10 @@ static int hls_write_header(AVFormatContext *s)
                 continue;
             }
             avpriv_set_pts_info(outer_st, inner_st->pts_wrap_bits, inner_st->time_base.num, inner_st->time_base.den);
+            if (outer_st->codecpar->codec_id == AV_CODEC_ID_HEVC &&
+                outer_st->codecpar->codec_tag != MKTAG('h','v','c','1')) {
+                av_log(s, AV_LOG_WARNING, "Stream HEVC is not hvc1, you should use tag:v hvc1 to set it.\n");
+            }
             write_codec_attr(outer_st, vs);
 
         }
@@ -2286,6 +2360,38 @@ static int hls_init_file_resend(AVFormatContext *s, VariantStream *vs)
     return ret;
 }
 
+static int64_t append_single_file(AVFormatContext *s, VariantStream *vs)
+{
+    int ret = 0;
+    int64_t read_byte = 0;
+    int64_t total_size = 0;
+    char *filename = NULL;
+    char buf[BUFSIZE];
+    AVFormatContext *oc = vs->avf;
+
+    hlsenc_io_close(s, &vs->out, vs->basename_tmp);
+    filename = av_asprintf("%s.tmp", oc->url);
+    ret = s->io_open(s, &vs->out, filename, AVIO_FLAG_READ, NULL);
+    if (ret < 0) {
+        av_free(filename);
+        return ret;
+    }
+
+    do {
+        memset(buf, 0, sizeof(BUFSIZE));
+        read_byte = avio_read(vs->out, buf, BUFSIZE);
+        avio_write(vs->out_single_file, buf, read_byte);
+        if (read_byte > 0) {
+            total_size += read_byte;
+            ret = total_size;
+        }
+    } while (read_byte > 0);
+
+    hlsenc_io_close(s, &vs->out, filename);
+    av_free(filename);
+
+    return ret;
+}
 static int hls_write_packet(AVFormatContext *s, AVPacket *pkt)
 {
     HLSContext *hls = s->priv_data;
@@ -2329,9 +2435,9 @@ 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 */
-        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;
+        int64_t init_list_dur = hls->init_time * vs->nb_entries;
+        int64_t after_init_list_dur = (vs->sequence - hls->start_sequence - vs->nb_entries) * hls->time;
+        hls->recording_time = hls->time;
         end_pts = init_list_dur + after_init_list_dur ;
     }
 
@@ -2345,7 +2451,7 @@ static int hls_write_packet(AVFormatContext *s, AVPacket *pkt)
         vs->start_pts_from_audio = 0;
     }
 
-   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);
@@ -2369,9 +2475,9 @@ static int hls_write_packet(AVFormatContext *s, AVPacket *pkt)
                 vs->duration = (double)(pkt->pts - vs->end_pts) * st->time_base.num / st->time_base.den;
             }
         }
-
     }
 
+    can_split = can_split && (pkt->pts - vs->end_pts > 0);
     if (vs->packets_written && can_split && av_compare_ts(pkt->pts - vs->start_pts, st->time_base,
                                                           end_pts, AV_TIME_BASE_Q) >= 0) {
         int64_t new_start_pos;
@@ -2411,6 +2517,8 @@ static int hls_write_packet(AVFormatContext *s, AVPacket *pkt)
                 return ret;
             }
             vs->size = range_length;
+            if (hls->key_info_file || hls->encrypt)
+                vs->size = append_single_file(s, vs);
         } else {
             if (oc->url[0]) {
                 proto = avio_find_protocol_name(oc->url);
@@ -2418,7 +2526,7 @@ static int hls_write_packet(AVFormatContext *s, AVPacket *pkt)
                                       && (hls->flags & HLS_TEMP_FILE);
             }
 
-            if ((hls->max_seg_size > 0 && (vs->size >= hls->max_seg_size)) || !byterange_mode) {
+            if ((hls->max_seg_size > 0 && (vs->size + vs->start_pos >= hls->max_seg_size)) || !byterange_mode) {
                 AVDictionary *options = NULL;
                 char *filename = NULL;
                 if (hls->key_info_file || hls->encrypt) {
@@ -2443,6 +2551,7 @@ static int hls_write_packet(AVFormatContext *s, AVPacket *pkt)
                 if (ret < 0) {
                     av_log(s, hls->ignore_io_errors ? AV_LOG_WARNING : AV_LOG_ERROR,
                            "Failed to open file '%s'\n", filename);
+                    av_freep(&filename);
                     av_dict_free(&options);
                     return hls->ignore_io_errors ? 0 : ret;
                 }
@@ -2451,6 +2560,7 @@ static int hls_write_packet(AVFormatContext *s, AVPacket *pkt)
                 }
                 ret = flush_dynbuf(vs, &range_length);
                 if (ret < 0) {
+                    av_freep(&filename);
                     av_dict_free(&options);
                     return ret;
                 }
@@ -2509,25 +2619,26 @@ static int hls_write_packet(AVFormatContext *s, AVPacket *pkt)
         }
 
         if (hls->flags & HLS_SINGLE_FILE) {
-            vs->number++;
             vs->start_pos += vs->size;
+            if (hls->key_info_file || hls->encrypt)
+                ret = hls_start(s, vs);
         } else if (hls->max_seg_size > 0) {
-            vs->start_pos = new_start_pos;
-            if (vs->size >= hls->max_seg_size) {
+            if (vs->size + vs->start_pos >= hls->max_seg_size) {
                 vs->sequence++;
                 sls_flag_file_rename(hls, vs, old_filename);
                 ret = hls_start(s, vs);
                 vs->start_pos = 0;
                 /* When split segment by byte, the duration is short than hls_time,
                  * so it is not enough one segment duration as hls_time, */
-                vs->number--;
+            } else {
+                vs->start_pos = new_start_pos;
             }
-            vs->number++;
         } else {
             vs->start_pos = new_start_pos;
             sls_flag_file_rename(hls, vs, old_filename);
             ret = hls_start(s, vs);
         }
+        vs->number++;
         av_freep(&old_filename);
 
         if (ret < 0) {
@@ -2538,13 +2649,14 @@ static int hls_write_packet(AVFormatContext *s, AVPacket *pkt)
 
     vs->packets_written++;
     if (oc->pb) {
+        int64_t keyframe_pre_pos = avio_tell(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 ((st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) &&
+            (pkt->flags & AV_PKT_FLAG_KEY) && !keyframe_pre_pos) {
+            av_write_frame(oc, NULL); /* Flush any buffered data */
+            vs->video_keyframe_size = avio_tell(oc->pb) - keyframe_pre_pos;
         }
+        vs->video_keyframe_pos = vs->start_pos;
         if (hls->ignore_io_errors)
             ret = 0;
     }
@@ -2575,20 +2687,6 @@ static void hls_deinit(AVFormatContext *s)
         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);
@@ -2671,7 +2769,6 @@ static int hls_write_trailer(struct AVFormatContext *s)
             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");
@@ -2686,9 +2783,15 @@ static int hls_write_trailer(struct AVFormatContext *s)
             if (ret < 0)
                 av_log(s, AV_LOG_WARNING, "Failed to upload file '%s' at the end.\n", oc->url);
         }
-        av_freep(&vs->temp_buffer);
-
+        if (hls->flags & HLS_SINGLE_FILE) {
+            if (hls->key_info_file || hls->encrypt) {
+                vs->size = append_single_file(s, vs);
+            }
+            hlsenc_io_close(s, &vs->out_single_file, vs->basename);
+        }
 failed:
+        av_freep(&vs->temp_buffer);
+        av_dict_free(&options);
         av_freep(&filename);
         av_write_trailer(oc);
         if (oc->url[0]) {
@@ -2745,6 +2848,7 @@ static int hls_init(AVFormatContext *s)
     char *p = NULL;
     int http_base_proto = ff_is_http_proto(s->url);
     int fmp4_init_filename_len = strlen(hls->fmp4_init_filename) + 1;
+    double initial_program_date_time = av_gettime() / 1000000.0;
 
     if (hls->use_localtime) {
         pattern = get_default_pattern_localtime_fmt(s);
@@ -2818,7 +2922,7 @@ static int hls_init(AVFormatContext *s)
         av_log(hls, AV_LOG_DEBUG, "start_number evaluated to %"PRId64"\n", hls->start_sequence);
     }
 
-    hls->recording_time = (hls->init_time ? hls->init_time : hls->time) * AV_TIME_BASE;
+    hls->recording_time = hls->init_time ? hls->init_time : hls->time;
 
     if (hls->flags & HLS_SPLIT_BY_TIME && hls->flags & HLS_INDEPENDENT_SEGMENTS) {
         // Independent segments cannot be guaranteed when splitting by time
@@ -2839,12 +2943,7 @@ static int hls_init(AVFormatContext *s)
         vs->start_pts = AV_NOPTS_VALUE;
         vs->end_pts   = AV_NOPTS_VALUE;
         vs->current_segment_final_filename_fmt[0] = '\0';
-
-        if (hls->flags & HLS_PROGRAM_DATE_TIME) {
-            time_t now0;
-            time(&now0);
-            vs->initial_prog_date_time = now0;
-        }
+        vs->initial_prog_date_time = initial_program_date_time;
 
         for (j = 0; j < vs->nb_streams; j++) {
             vs->has_video += vs->streams[j]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO;
@@ -2908,6 +3007,19 @@ static int hls_init(AVFormatContext *s)
                         return ret;
                 }
 
+                if (hls->use_localtime) {
+                    int r;
+                    char *expanded = NULL;
+
+                    r = strftime_expand(vs->fmp4_init_filename, &expanded);
+                    if (r < 0) {
+                        av_log(s, AV_LOG_ERROR, "Could not get segment filename with strftime\n");
+                        return r;
+                    }
+                    av_free(vs->fmp4_init_filename);
+                    vs->fmp4_init_filename = expanded;
+                }
+
                 p = strrchr(vs->m3u8_name, '/');
                 if (p) {
                     char tmp = *(++p);
@@ -2953,12 +3065,6 @@ static int hls_init(AVFormatContext *s)
                 *p = '.';
         }
 
-        if (hls->baseurl) {
-            vs->baseurl = av_strdup(hls->baseurl);
-            if (!vs->baseurl)
-                return AVERROR(ENOMEM);
-        }
-
         if ((ret = hls_mux_init(s, vs)) < 0)
             return ret;
 
@@ -2969,12 +3075,13 @@ static int hls_init(AVFormatContext *s)
                 av_log(s, AV_LOG_WARNING, "append_list mode does not support hls_init_time,"
                        " hls_init_time value will have no effect\n");
                 hls->init_time = 0;
-                hls->recording_time = hls->time * AV_TIME_BASE;
+                hls->recording_time = hls->time;
             }
         }
 
         if ((ret = hls_start(s, vs)) < 0)
             return ret;
+        vs->number++;
     }
 
     return ret;
@@ -2984,15 +3091,12 @@ static int hls_init(AVFormatContext *s)
 #define E AV_OPT_FLAG_ENCODING_PARAM
 static const AVOption options[] = {
     {"start_number",  "set first number in the sequence",        OFFSET(start_sequence),AV_OPT_TYPE_INT64,  {.i64 = 0},     0, INT64_MAX, E},
-    {"hls_time",      "set segment length in seconds",           OFFSET(time),    AV_OPT_TYPE_FLOAT,  {.dbl = 2},     0, FLT_MAX, E},
-    {"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_time",      "set segment length",                      OFFSET(time),          AV_OPT_TYPE_DURATION, {.i64 = 2000000}, 0, INT64_MAX, E},
+    {"hls_init_time", "set segment length at init list",         OFFSET(init_time),     AV_OPT_TYPE_DURATION, {.i64 = 0},       0, INT64_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), 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},
-#endif
     {"hls_allow_cache", "explicitly set whether the client MAY (1) or MUST NOT (0) cache media segments", OFFSET(allowcache), AV_OPT_TYPE_INT, {.i64 = -1}, INT_MIN, INT_MAX, E},
     {"hls_base_url",  "url to prepend to each playlist entry",   OFFSET(baseurl), AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,       E},
     {"hls_segment_filename", "filename template for segment files", OFFSET(segment_filename),   AV_OPT_TYPE_STRING, {.str = NULL},            0,       0,         E},
@@ -3024,13 +3128,7 @@ static const AVOption options[] = {
     {"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
     {"strftime", "set filename expansion with strftime at segment creation", OFFSET(use_localtime), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, E },
-#if FF_API_HLS_USE_LOCALTIME
-    {"use_localtime_mkdir", "create last directory component in strftime-generated filename(will be deprecated)", OFFSET(use_localtime_mkdir), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, E },
-#endif
     {"strftime_mkdir", "create last directory component in strftime-generated filename", OFFSET(use_localtime_mkdir), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, E },
     {"hls_playlist_type", "set the HLS playlist type", OFFSET(pl_type), AV_OPT_TYPE_INT, {.i64 = PLAYLIST_TYPE_NONE }, 0, PLAYLIST_TYPE_NB-1, E, "pl_type" },
     {"event", "EVENT playlist", 0, AV_OPT_TYPE_CONST, {.i64 = PLAYLIST_TYPE_EVENT }, INT_MIN, INT_MAX, E, "pl_type" },