]> git.sesse.net Git - ffmpeg/blob - libavformat/hlsenc.c
Merge commit '9b0aff51a7ae03215c4e1a3e7220fdbcfb858b08'
[ffmpeg] / libavformat / hlsenc.c
1 /*
2  * Apple HTTP Live Streaming segmenter
3  * Copyright (c) 2012, Luca Barbato
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 #include "config.h"
23 #include <float.h>
24 #include <stdint.h>
25 #if HAVE_UNISTD_H
26 #include <unistd.h>
27 #endif
28
29 #if CONFIG_GCRYPT
30 #include <gcrypt.h>
31 #elif CONFIG_OPENSSL
32 #include <openssl/rand.h>
33 #endif
34
35 #include "libavutil/avassert.h"
36 #include "libavutil/mathematics.h"
37 #include "libavutil/parseutils.h"
38 #include "libavutil/avstring.h"
39 #include "libavutil/intreadwrite.h"
40 #include "libavutil/random_seed.h"
41 #include "libavutil/opt.h"
42 #include "libavutil/log.h"
43 #include "libavutil/time_internal.h"
44
45 #include "avformat.h"
46 #include "avio_internal.h"
47 #include "internal.h"
48 #include "os_support.h"
49
50 typedef enum {
51   HLS_START_SEQUENCE_AS_START_NUMBER = 0,
52   HLS_START_SEQUENCE_AS_SECONDS_SINCE_EPOCH = 1,
53   HLS_START_SEQUENCE_AS_FORMATTED_DATETIME = 2,  // YYYYMMDDhhmmss
54 } StartSequenceSourceType;
55
56 #define KEYSIZE 16
57 #define LINE_BUFFER_SIZE 1024
58 #define HLS_MICROSECOND_UNIT   1000000
59
60 typedef struct HLSSegment {
61     char filename[1024];
62     char sub_filename[1024];
63     double duration; /* in seconds */
64     int discont;
65     int64_t pos;
66     int64_t size;
67
68     char key_uri[LINE_BUFFER_SIZE + 1];
69     char iv_string[KEYSIZE*2 + 1];
70
71     struct HLSSegment *next;
72 } HLSSegment;
73
74 typedef enum HLSFlags {
75     // Generate a single media file and use byte ranges in the playlist.
76     HLS_SINGLE_FILE = (1 << 0),
77     HLS_DELETE_SEGMENTS = (1 << 1),
78     HLS_ROUND_DURATIONS = (1 << 2),
79     HLS_DISCONT_START = (1 << 3),
80     HLS_OMIT_ENDLIST = (1 << 4),
81     HLS_SPLIT_BY_TIME = (1 << 5),
82     HLS_APPEND_LIST = (1 << 6),
83     HLS_PROGRAM_DATE_TIME = (1 << 7),
84     HLS_SECOND_LEVEL_SEGMENT_INDEX = (1 << 8), // include segment index in segment filenames when use_localtime  e.g.: %%03d
85     HLS_SECOND_LEVEL_SEGMENT_DURATION = (1 << 9), // include segment duration (microsec) in segment filenames when use_localtime  e.g.: %%09t
86     HLS_SECOND_LEVEL_SEGMENT_SIZE = (1 << 10), // include segment size (bytes) in segment filenames when use_localtime  e.g.: %%014s
87     HLS_TEMP_FILE = (1 << 11),
88     HLS_PERIODIC_REKEY = (1 << 12),
89 } HLSFlags;
90
91 typedef enum {
92     SEGMENT_TYPE_MPEGTS,
93     SEGMENT_TYPE_FMP4,
94 } SegmentType;
95
96 typedef enum {
97     PLAYLIST_TYPE_NONE,
98     PLAYLIST_TYPE_EVENT,
99     PLAYLIST_TYPE_VOD,
100     PLAYLIST_TYPE_NB,
101 } PlaylistType;
102
103 typedef struct HLSContext {
104     const AVClass *class;  // Class for private options.
105     unsigned number;
106     int64_t sequence;
107     int64_t start_sequence;
108     uint32_t start_sequence_source_type;  // enum StartSequenceSourceType
109     AVOutputFormat *oformat;
110     AVOutputFormat *vtt_oformat;
111
112     AVFormatContext *avf;
113     AVFormatContext *vtt_avf;
114
115     float time;            // Set by a private option.
116     float init_time;       // Set by a private option.
117     int max_nb_segments;   // Set by a private option.
118 #if FF_API_HLS_WRAP
119     int  wrap;             // Set by a private option.
120 #endif
121     uint32_t flags;        // enum HLSFlags
122     uint32_t pl_type;      // enum PlaylistType
123     char *segment_filename;
124     char *fmp4_init_filename;
125     int segment_type;
126     int fmp4_init_mode;
127
128     int use_localtime;      ///< flag to expand filename with localtime
129     int use_localtime_mkdir;///< flag to mkdir dirname in timebased filename
130     int allowcache;
131     int64_t recording_time;
132     int has_video;
133     int has_subtitle;
134     int new_start;
135     double dpp;           // duration per packet
136     int64_t start_pts;
137     int64_t end_pts;
138     double duration;      // last segment duration computed so far, in seconds
139     int64_t start_pos;    // last segment starting position
140     int64_t size;         // last segment size
141     int64_t max_seg_size; // every segment file max size
142     int nb_entries;
143     int discontinuity_set;
144     int discontinuity;
145
146     HLSSegment *segments;
147     HLSSegment *last_segment;
148     HLSSegment *old_segments;
149
150     char *basename;
151     char *base_output_dirname;
152     char *vtt_basename;
153     char *vtt_m3u8_name;
154     char *baseurl;
155     char *format_options_str;
156     char *vtt_format_options_str;
157     char *subtitle_filename;
158     AVDictionary *format_options;
159
160     int encrypt;
161     char *key;
162     char *key_url;
163     char *iv;
164     char *key_basename;
165
166     char *key_info_file;
167     char key_file[LINE_BUFFER_SIZE + 1];
168     char key_uri[LINE_BUFFER_SIZE + 1];
169     char key_string[KEYSIZE*2 + 1];
170     char iv_string[KEYSIZE*2 + 1];
171     AVDictionary *vtt_format_options;
172
173     char *method;
174
175     double initial_prog_date_time;
176     char current_segment_final_filename_fmt[1024]; // when renaming segments
177     char *user_agent;
178 } HLSContext;
179
180 static int get_int_from_double(double val)
181 {
182     return (int)((val - (int)val) >= 0.001) ? (int)(val + 1) : (int)val;
183 }
184
185 static int mkdir_p(const char *path) {
186     int ret = 0;
187     char *temp = av_strdup(path);
188     char *pos = temp;
189     char tmp_ch = '\0';
190
191     if (!path || !temp) {
192         return -1;
193     }
194
195     if (!strncmp(temp, "/", 1) || !strncmp(temp, "\\", 1)) {
196         pos++;
197     } else if (!strncmp(temp, "./", 2) || !strncmp(temp, ".\\", 2)) {
198         pos += 2;
199     }
200
201     for ( ; *pos != '\0'; ++pos) {
202         if (*pos == '/' || *pos == '\\') {
203             tmp_ch = *pos;
204             *pos = '\0';
205             ret = mkdir(temp, 0755);
206             *pos = tmp_ch;
207         }
208     }
209
210     if ((*(pos - 1) != '/') || (*(pos - 1) != '\\')) {
211         ret = mkdir(temp, 0755);
212     }
213
214     av_free(temp);
215     return ret;
216 }
217
218 static void set_http_options(AVFormatContext *s, AVDictionary **options, HLSContext *c)
219 {
220     const char *proto = avio_find_protocol_name(s->filename);
221     int http_base_proto = proto ? (!av_strcasecmp(proto, "http") || !av_strcasecmp(proto, "https")) : 0;
222
223     if (c->method) {
224         av_dict_set(options, "method", c->method, 0);
225     } else if (http_base_proto) {
226         av_log(c, AV_LOG_WARNING, "No HTTP method set, hls muxer defaulting to method PUT.\n");
227         av_dict_set(options, "method", "PUT", 0);
228     }
229     if (c->user_agent)
230         av_dict_set(options, "user_agent", c->user_agent, 0);
231
232 }
233
234 static int replace_int_data_in_filename(char *buf, int buf_size, const char *filename, char placeholder, int64_t number)
235 {
236     const char *p;
237     char *q, buf1[20], c;
238     int nd, len, addchar_count;
239     int found_count = 0;
240
241     q = buf;
242     p = filename;
243     for (;;) {
244         c = *p;
245         if (c == '\0')
246             break;
247         if (c == '%' && *(p+1) == '%')  // %%
248             addchar_count = 2;
249         else if (c == '%' && (av_isdigit(*(p+1)) || *(p+1) == placeholder)) {
250             nd = 0;
251             addchar_count = 1;
252             while (av_isdigit(*(p + addchar_count))) {
253                 nd = nd * 10 + *(p + addchar_count) - '0';
254                 addchar_count++;
255             }
256
257             if (*(p + addchar_count) == placeholder) {
258                 len = snprintf(buf1, sizeof(buf1), "%0*"PRId64, (number < 0) ? nd : nd++, number);
259                 if (len < 1)  // returned error or empty buf1
260                     goto fail;
261                 if ((q - buf + len) > buf_size - 1)
262                     goto fail;
263                 memcpy(q, buf1, len);
264                 q += len;
265                 p += (addchar_count + 1);
266                 addchar_count = 0;
267                 found_count++;
268             }
269
270         } else
271             addchar_count = 1;
272
273         while (addchar_count--)
274             if ((q - buf) < buf_size - 1)
275                 *q++ = *p++;
276             else
277                 goto fail;
278     }
279     *q = '\0';
280     return found_count;
281 fail:
282     *q = '\0';
283     return -1;
284 }
285
286 static void write_styp(AVIOContext *pb)
287 {
288     avio_wb32(pb, 24);
289     ffio_wfourcc(pb, "styp");
290     ffio_wfourcc(pb, "msdh");
291     avio_wb32(pb, 0); /* minor */
292     ffio_wfourcc(pb, "msdh");
293     ffio_wfourcc(pb, "msix");
294 }
295
296 static int hls_delete_old_segments(AVFormatContext *s, HLSContext *hls) {
297
298     HLSSegment *segment, *previous_segment = NULL;
299     float playlist_duration = 0.0f;
300     int ret = 0, path_size, sub_path_size;
301     char *dirname = NULL, *p, *sub_path;
302     char *path = NULL;
303     AVDictionary *options = NULL;
304     AVIOContext *out = NULL;
305     const char *proto = NULL;
306
307     segment = hls->segments;
308     while (segment) {
309         playlist_duration += segment->duration;
310         segment = segment->next;
311     }
312
313     segment = hls->old_segments;
314     while (segment) {
315         playlist_duration -= segment->duration;
316         previous_segment = segment;
317         segment = previous_segment->next;
318         if (playlist_duration <= -previous_segment->duration) {
319             previous_segment->next = NULL;
320             break;
321         }
322     }
323
324     if (segment && !hls->use_localtime_mkdir) {
325         if (hls->segment_filename) {
326             dirname = av_strdup(hls->segment_filename);
327         } else {
328             dirname = av_strdup(hls->avf->filename);
329         }
330         if (!dirname) {
331             ret = AVERROR(ENOMEM);
332             goto fail;
333         }
334         p = (char *)av_basename(dirname);
335         *p = '\0';
336     }
337
338     while (segment) {
339         av_log(hls, AV_LOG_DEBUG, "deleting old segment %s\n",
340                                   segment->filename);
341         path_size =  (hls->use_localtime_mkdir ? 0 : strlen(dirname)) + strlen(segment->filename) + 1;
342         path = av_malloc(path_size);
343         if (!path) {
344             ret = AVERROR(ENOMEM);
345             goto fail;
346         }
347
348         if (hls->use_localtime_mkdir)
349             av_strlcpy(path, segment->filename, path_size);
350         else { // segment->filename contains basename only
351             av_strlcpy(path, dirname, path_size);
352             av_strlcat(path, segment->filename, path_size);
353         }
354
355         proto = avio_find_protocol_name(s->filename);
356         if (hls->method || (proto && !av_strcasecmp(proto, "http"))) {
357             av_dict_set(&options, "method", "DELETE", 0);
358             if ((ret = hls->avf->io_open(hls->avf, &out, path, AVIO_FLAG_WRITE, &options)) < 0)
359                 goto fail;
360             ff_format_io_close(hls->avf, &out);
361         } else if (unlink(path) < 0) {
362             av_log(hls, AV_LOG_ERROR, "failed to delete old segment %s: %s\n",
363                                      path, strerror(errno));
364         }
365
366         if ((segment->sub_filename[0] != '\0')) {
367             sub_path_size = strlen(segment->sub_filename) + 1 + (dirname ? strlen(dirname) : 0);
368             sub_path = av_malloc(sub_path_size);
369             if (!sub_path) {
370                 ret = AVERROR(ENOMEM);
371                 goto fail;
372             }
373
374             av_strlcpy(sub_path, dirname, sub_path_size);
375             av_strlcat(sub_path, segment->sub_filename, sub_path_size);
376
377             if (hls->method || (proto && !av_strcasecmp(proto, "http"))) {
378                 av_dict_set(&options, "method", "DELETE", 0);
379                 if ((ret = hls->avf->io_open(hls->avf, &out, sub_path, AVIO_FLAG_WRITE, &options)) < 0) {
380                     av_free(sub_path);
381                     goto fail;
382                 }
383                 ff_format_io_close(hls->avf, &out);
384             } else if (unlink(sub_path) < 0) {
385                 av_log(hls, AV_LOG_ERROR, "failed to delete old segment %s: %s\n",
386                                          sub_path, strerror(errno));
387             }
388             av_free(sub_path);
389         }
390         av_freep(&path);
391         previous_segment = segment;
392         segment = previous_segment->next;
393         av_free(previous_segment);
394     }
395
396 fail:
397     av_free(path);
398     av_free(dirname);
399
400     return ret;
401 }
402
403 static int randomize(uint8_t *buf, int len)
404 {
405 #if CONFIG_GCRYPT
406     gcry_randomize(buf, len, GCRY_VERY_STRONG_RANDOM);
407     return 0;
408 #elif CONFIG_OPENSSL
409     if (RAND_bytes(buf, len))
410         return 0;
411 #else
412     return AVERROR(ENOSYS);
413 #endif
414     return AVERROR(EINVAL);
415 }
416
417 static int do_encrypt(AVFormatContext *s)
418 {
419     HLSContext *hls = s->priv_data;
420     int ret;
421     int len;
422     AVIOContext *pb;
423     uint8_t key[KEYSIZE];
424
425     len = strlen(hls->basename) + 4 + 1;
426     hls->key_basename = av_mallocz(len);
427     if (!hls->key_basename)
428         return AVERROR(ENOMEM);
429
430     av_strlcpy(hls->key_basename, s->filename, len);
431     av_strlcat(hls->key_basename, ".key", len);
432
433     if (hls->key_url) {
434         av_strlcpy(hls->key_file, hls->key_url, sizeof(hls->key_file));
435         av_strlcpy(hls->key_uri, hls->key_url, sizeof(hls->key_uri));
436     } else {
437         av_strlcpy(hls->key_file, hls->key_basename, sizeof(hls->key_file));
438         av_strlcpy(hls->key_uri, hls->key_basename, sizeof(hls->key_uri));
439     }
440
441     if (!*hls->iv_string) {
442         uint8_t iv[16] = { 0 };
443         char buf[33];
444
445         if (!hls->iv) {
446             AV_WB64(iv + 8, hls->sequence);
447         } else {
448             memcpy(iv, hls->iv, sizeof(iv));
449         }
450         ff_data_to_hex(buf, iv, sizeof(iv), 0);
451         buf[32] = '\0';
452         memcpy(hls->iv_string, buf, sizeof(hls->iv_string));
453     }
454
455     if (!*hls->key_uri) {
456         av_log(hls, AV_LOG_ERROR, "no key URI specified in key info file\n");
457         return AVERROR(EINVAL);
458     }
459
460     if (!*hls->key_file) {
461         av_log(hls, AV_LOG_ERROR, "no key file specified in key info file\n");
462         return AVERROR(EINVAL);
463     }
464
465     if (!*hls->key_string) {
466         if (!hls->key) {
467             if ((ret = randomize(key, sizeof(key))) < 0) {
468                 av_log(s, AV_LOG_ERROR, "Cannot generate a strong random key\n");
469                 return ret;
470             }
471         } else {
472             memcpy(key, hls->key, sizeof(key));
473         }
474
475         ff_data_to_hex(hls->key_string, key, sizeof(key), 0);
476         if ((ret = s->io_open(s, &pb, hls->key_file, AVIO_FLAG_WRITE, NULL)) < 0)
477             return ret;
478         avio_seek(pb, 0, SEEK_CUR);
479         avio_write(pb, key, KEYSIZE);
480         avio_close(pb);
481     }
482     return 0;
483 }
484
485
486 static int hls_encryption_start(AVFormatContext *s)
487 {
488     HLSContext *hls = s->priv_data;
489     int ret;
490     AVIOContext *pb;
491     uint8_t key[KEYSIZE];
492
493     if ((ret = s->io_open(s, &pb, hls->key_info_file, AVIO_FLAG_READ, NULL)) < 0) {
494         av_log(hls, AV_LOG_ERROR,
495                 "error opening key info file %s\n", hls->key_info_file);
496         return ret;
497     }
498
499     ff_get_line(pb, hls->key_uri, sizeof(hls->key_uri));
500     hls->key_uri[strcspn(hls->key_uri, "\r\n")] = '\0';
501
502     ff_get_line(pb, hls->key_file, sizeof(hls->key_file));
503     hls->key_file[strcspn(hls->key_file, "\r\n")] = '\0';
504
505     ff_get_line(pb, hls->iv_string, sizeof(hls->iv_string));
506     hls->iv_string[strcspn(hls->iv_string, "\r\n")] = '\0';
507
508     ff_format_io_close(s, &pb);
509
510     if (!*hls->key_uri) {
511         av_log(hls, AV_LOG_ERROR, "no key URI specified in key info file\n");
512         return AVERROR(EINVAL);
513     }
514
515     if (!*hls->key_file) {
516         av_log(hls, AV_LOG_ERROR, "no key file specified in key info file\n");
517         return AVERROR(EINVAL);
518     }
519
520     if ((ret = s->io_open(s, &pb, hls->key_file, AVIO_FLAG_READ, NULL)) < 0) {
521         av_log(hls, AV_LOG_ERROR, "error opening key file %s\n", hls->key_file);
522         return ret;
523     }
524
525     ret = avio_read(pb, key, sizeof(key));
526     ff_format_io_close(s, &pb);
527     if (ret != sizeof(key)) {
528         av_log(hls, AV_LOG_ERROR, "error reading key file %s\n", hls->key_file);
529         if (ret >= 0 || ret == AVERROR_EOF)
530             ret = AVERROR(EINVAL);
531         return ret;
532     }
533     ff_data_to_hex(hls->key_string, key, sizeof(key), 0);
534
535     return 0;
536 }
537
538 static int read_chomp_line(AVIOContext *s, char *buf, int maxlen)
539 {
540     int len = ff_get_line(s, buf, maxlen);
541     while (len > 0 && av_isspace(buf[len - 1]))
542         buf[--len] = '\0';
543     return len;
544 }
545
546 static int hls_mux_init(AVFormatContext *s)
547 {
548     AVDictionary *options = NULL;
549     HLSContext *hls = s->priv_data;
550     AVFormatContext *oc;
551     AVFormatContext *vtt_oc = NULL;
552     int byterange_mode = (hls->flags & HLS_SINGLE_FILE) || (hls->max_seg_size > 0);
553     int i, ret;
554
555     ret = avformat_alloc_output_context2(&hls->avf, hls->oformat, NULL, NULL);
556     if (ret < 0)
557         return ret;
558     oc = hls->avf;
559
560     oc->filename[0]        = '\0';
561     oc->oformat            = hls->oformat;
562     oc->interrupt_callback = s->interrupt_callback;
563     oc->max_delay          = s->max_delay;
564     oc->opaque             = s->opaque;
565     oc->io_open            = s->io_open;
566     oc->io_close           = s->io_close;
567     av_dict_copy(&oc->metadata, s->metadata, 0);
568
569     if(hls->vtt_oformat) {
570         ret = avformat_alloc_output_context2(&hls->vtt_avf, hls->vtt_oformat, NULL, NULL);
571         if (ret < 0)
572             return ret;
573         vtt_oc          = hls->vtt_avf;
574         vtt_oc->oformat = hls->vtt_oformat;
575         av_dict_copy(&vtt_oc->metadata, s->metadata, 0);
576     }
577
578     for (i = 0; i < s->nb_streams; i++) {
579         AVStream *st;
580         AVFormatContext *loc;
581         if (s->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE)
582             loc = vtt_oc;
583         else
584             loc = oc;
585
586         if (!(st = avformat_new_stream(loc, NULL)))
587             return AVERROR(ENOMEM);
588         avcodec_parameters_copy(st->codecpar, s->streams[i]->codecpar);
589         if (!oc->oformat->codec_tag ||
590             av_codec_get_id (oc->oformat->codec_tag, s->streams[i]->codecpar->codec_tag) == st->codecpar->codec_id ||
591             av_codec_get_tag(oc->oformat->codec_tag, s->streams[i]->codecpar->codec_id) <= 0) {
592             st->codecpar->codec_tag = s->streams[i]->codecpar->codec_tag;
593         } else {
594             st->codecpar->codec_tag = 0;
595         }
596
597         st->sample_aspect_ratio = s->streams[i]->sample_aspect_ratio;
598         st->time_base = s->streams[i]->time_base;
599         av_dict_copy(&st->metadata, s->streams[i]->metadata, 0);
600     }
601     hls->start_pos = 0;
602     hls->new_start = 1;
603     hls->fmp4_init_mode = 0;
604
605     if (hls->segment_type == SEGMENT_TYPE_FMP4) {
606         if (hls->max_seg_size > 0) {
607             av_log(s, AV_LOG_WARNING, "Multi-file byterange mode is currently unsupported in the HLS muxer.\n");
608             return AVERROR_PATCHWELCOME;
609         }
610         hls->fmp4_init_mode = !byterange_mode;
611         set_http_options(s, &options, hls);
612         if ((ret = s->io_open(s, &oc->pb, hls->base_output_dirname, AVIO_FLAG_WRITE, &options)) < 0) {
613             av_log(s, AV_LOG_ERROR, "Failed to open segment '%s'\n", hls->fmp4_init_filename);
614             return ret;
615         }
616
617         if (hls->format_options_str) {
618             ret = av_dict_parse_string(&hls->format_options, hls->format_options_str, "=", ":", 0);
619             if (ret < 0) {
620                 av_log(s, AV_LOG_ERROR, "Could not parse format options list '%s'\n",
621                        hls->format_options_str);
622                 return ret;
623             }
624         }
625
626         av_dict_copy(&options, hls->format_options, 0);
627         av_dict_set(&options, "fflags", "-autobsf", 0);
628         av_dict_set(&options, "movflags", "frag_custom+dash+delay_moov", 0);
629         ret = avformat_init_output(oc, &options);
630         if (ret < 0)
631             return ret;
632         if (av_dict_count(options)) {
633             av_log(s, AV_LOG_ERROR, "Some of the provided format options in '%s' are not recognized\n", hls->format_options_str);
634             av_dict_free(&options);
635             return AVERROR(EINVAL);
636         }
637         av_dict_free(&options);
638     }
639     return 0;
640 }
641
642 static HLSSegment *find_segment_by_filename(HLSSegment *segment, const char *filename)
643 {
644     while (segment) {
645         if (!av_strcasecmp(segment->filename,filename))
646             return segment;
647         segment = segment->next;
648     }
649     return (HLSSegment *) NULL;
650 }
651
652 static int sls_flags_filename_process(struct AVFormatContext *s, HLSContext *hls, HLSSegment *en, double duration,
653                                          int64_t pos, int64_t size)
654 {
655     if ((hls->flags & (HLS_SECOND_LEVEL_SEGMENT_SIZE | HLS_SECOND_LEVEL_SEGMENT_DURATION)) &&
656         strlen(hls->current_segment_final_filename_fmt)) {
657         av_strlcpy(hls->avf->filename, hls->current_segment_final_filename_fmt, sizeof(hls->avf->filename));
658         if (hls->flags & HLS_SECOND_LEVEL_SEGMENT_SIZE) {
659             char * filename = av_strdup(hls->avf->filename);  // %%s will be %s after strftime
660             if (!filename) {
661                 av_free(en);
662                 return AVERROR(ENOMEM);
663             }
664             if (replace_int_data_in_filename(hls->avf->filename, sizeof(hls->avf->filename),
665                 filename, 's', pos + size) < 1) {
666                 av_log(hls, AV_LOG_ERROR,
667                        "Invalid second level segment filename template '%s', "
668                         "you can try to remove second_level_segment_size flag\n",
669                        filename);
670                 av_free(filename);
671                 av_free(en);
672                 return AVERROR(EINVAL);
673             }
674             av_free(filename);
675         }
676         if (hls->flags & HLS_SECOND_LEVEL_SEGMENT_DURATION) {
677             char * filename = av_strdup(hls->avf->filename);  // %%t will be %t after strftime
678             if (!filename) {
679                 av_free(en);
680                 return AVERROR(ENOMEM);
681             }
682             if (replace_int_data_in_filename(hls->avf->filename, sizeof(hls->avf->filename),
683                 filename, 't',  (int64_t)round(duration * HLS_MICROSECOND_UNIT)) < 1) {
684                 av_log(hls, AV_LOG_ERROR,
685                        "Invalid second level segment filename template '%s', "
686                         "you can try to remove second_level_segment_time flag\n",
687                        filename);
688                 av_free(filename);
689                 av_free(en);
690                 return AVERROR(EINVAL);
691             }
692             av_free(filename);
693         }
694     }
695     return 0;
696 }
697
698 static int sls_flag_check_duration_size_index(HLSContext *hls)
699 {
700     int ret = 0;
701
702     if (hls->flags & HLS_SECOND_LEVEL_SEGMENT_DURATION) {
703          av_log(hls, AV_LOG_ERROR,
704                 "second_level_segment_duration hls_flag requires use_localtime to be true\n");
705          ret = AVERROR(EINVAL);
706     }
707     if (hls->flags & HLS_SECOND_LEVEL_SEGMENT_SIZE) {
708          av_log(hls, AV_LOG_ERROR,
709                 "second_level_segment_size hls_flag requires use_localtime to be true\n");
710          ret = AVERROR(EINVAL);
711     }
712     if (hls->flags & HLS_SECOND_LEVEL_SEGMENT_INDEX) {
713         av_log(hls, AV_LOG_ERROR,
714                "second_level_segment_index hls_flag requires use_localtime to be true\n");
715         ret = AVERROR(EINVAL);
716     }
717
718     return ret;
719 }
720
721 static int sls_flag_check_duration_size(HLSContext *hls)
722 {
723     const char *proto = avio_find_protocol_name(hls->basename);
724     int segment_renaming_ok = proto && !strcmp(proto, "file");
725     int ret = 0;
726
727     if ((hls->flags & HLS_SECOND_LEVEL_SEGMENT_DURATION) && !segment_renaming_ok) {
728          av_log(hls, AV_LOG_ERROR,
729                 "second_level_segment_duration hls_flag works only with file protocol segment names\n");
730          ret = AVERROR(EINVAL);
731     }
732     if ((hls->flags & HLS_SECOND_LEVEL_SEGMENT_SIZE) && !segment_renaming_ok) {
733          av_log(hls, AV_LOG_ERROR,
734                 "second_level_segment_size hls_flag works only with file protocol segment names\n");
735          ret = AVERROR(EINVAL);
736     }
737
738     return ret;
739 }
740
741 static void sls_flag_file_rename(HLSContext *hls, char *old_filename) {
742     if ((hls->flags & (HLS_SECOND_LEVEL_SEGMENT_SIZE | HLS_SECOND_LEVEL_SEGMENT_DURATION)) &&
743         strlen(hls->current_segment_final_filename_fmt)) {
744         ff_rename(old_filename, hls->avf->filename, hls);
745     }
746 }
747
748 static int sls_flag_use_localtime_filename(AVFormatContext *oc, HLSContext *c)
749 {
750     if (c->flags & HLS_SECOND_LEVEL_SEGMENT_INDEX) {
751         char * filename = av_strdup(oc->filename);  // %%d will be %d after strftime
752         if (!filename)
753             return AVERROR(ENOMEM);
754         if (replace_int_data_in_filename(oc->filename, sizeof(oc->filename),
755 #if FF_API_HLS_WRAP
756             filename, 'd', c->wrap ? c->sequence % c->wrap : c->sequence) < 1) {
757 #else
758             filename, 'd', c->sequence) < 1) {
759 #endif
760             av_log(c, AV_LOG_ERROR, "Invalid second level segment filename template '%s', "
761                     "you can try to remove second_level_segment_index flag\n",
762                    filename);
763             av_free(filename);
764             return AVERROR(EINVAL);
765         }
766         av_free(filename);
767     }
768     if (c->flags & (HLS_SECOND_LEVEL_SEGMENT_SIZE | HLS_SECOND_LEVEL_SEGMENT_DURATION)) {
769         av_strlcpy(c->current_segment_final_filename_fmt, oc->filename,
770                    sizeof(c->current_segment_final_filename_fmt));
771         if (c->flags & HLS_SECOND_LEVEL_SEGMENT_SIZE) {
772             char * filename = av_strdup(oc->filename);  // %%s will be %s after strftime
773             if (!filename)
774                 return AVERROR(ENOMEM);
775             if (replace_int_data_in_filename(oc->filename, sizeof(oc->filename), filename, 's', 0) < 1) {
776                 av_log(c, AV_LOG_ERROR, "Invalid second level segment filename template '%s', "
777                         "you can try to remove second_level_segment_size flag\n",
778                        filename);
779                 av_free(filename);
780                 return AVERROR(EINVAL);
781             }
782             av_free(filename);
783         }
784         if (c->flags & HLS_SECOND_LEVEL_SEGMENT_DURATION) {
785             char * filename = av_strdup(oc->filename);  // %%t will be %t after strftime
786             if (!filename)
787                 return AVERROR(ENOMEM);
788             if (replace_int_data_in_filename(oc->filename, sizeof(oc->filename), filename, 't', 0) < 1) {
789                 av_log(c, AV_LOG_ERROR, "Invalid second level segment filename template '%s', "
790                         "you can try to remove second_level_segment_time flag\n",
791                        filename);
792                 av_free(filename);
793                 return AVERROR(EINVAL);
794             }
795             av_free(filename);
796         }
797     }
798     return 0;
799 }
800
801 /* Create a new segment and append it to the segment list */
802 static int hls_append_segment(struct AVFormatContext *s, HLSContext *hls, double duration,
803                               int64_t pos, int64_t size)
804 {
805     HLSSegment *en = av_malloc(sizeof(*en));
806     const char  *filename;
807     int byterange_mode = (hls->flags & HLS_SINGLE_FILE) || (hls->max_seg_size > 0);
808     int ret;
809
810     if (!en)
811         return AVERROR(ENOMEM);
812
813     ret = sls_flags_filename_process(s, hls, en, duration, pos, size);
814     if (ret < 0) {
815         return ret;
816     }
817
818     filename = av_basename(hls->avf->filename);
819
820     if (hls->use_localtime_mkdir) {
821         filename = hls->avf->filename;
822     }
823     if ((find_segment_by_filename(hls->segments, filename) || find_segment_by_filename(hls->old_segments, filename))
824         && !byterange_mode) {
825         av_log(hls, AV_LOG_WARNING, "Duplicated segment filename detected: %s\n", filename);
826     }
827     av_strlcpy(en->filename, filename, sizeof(en->filename));
828
829     if(hls->has_subtitle)
830         av_strlcpy(en->sub_filename, av_basename(hls->vtt_avf->filename), sizeof(en->sub_filename));
831     else
832         en->sub_filename[0] = '\0';
833
834     en->duration = duration;
835     en->pos      = pos;
836     en->size     = size;
837     en->next     = NULL;
838     en->discont  = 0;
839
840     if (hls->discontinuity) {
841         en->discont = 1;
842         hls->discontinuity = 0;
843     }
844
845     if (hls->key_info_file || hls->encrypt) {
846         av_strlcpy(en->key_uri, hls->key_uri, sizeof(en->key_uri));
847         av_strlcpy(en->iv_string, hls->iv_string, sizeof(en->iv_string));
848     }
849
850     if (!hls->segments)
851         hls->segments = en;
852     else
853         hls->last_segment->next = en;
854
855     hls->last_segment = en;
856
857     // EVENT or VOD playlists imply sliding window cannot be used
858     if (hls->pl_type != PLAYLIST_TYPE_NONE)
859         hls->max_nb_segments = 0;
860
861     if (hls->max_nb_segments && hls->nb_entries >= hls->max_nb_segments) {
862         en = hls->segments;
863         hls->initial_prog_date_time += en->duration;
864         hls->segments = en->next;
865         if (en && hls->flags & HLS_DELETE_SEGMENTS &&
866 #if FF_API_HLS_WRAP
867                 !(hls->flags & HLS_SINGLE_FILE || hls->wrap)) {
868 #else
869                 !(hls->flags & HLS_SINGLE_FILE)) {
870 #endif
871             en->next = hls->old_segments;
872             hls->old_segments = en;
873             if ((ret = hls_delete_old_segments(s, hls)) < 0)
874                 return ret;
875         } else
876             av_free(en);
877     } else
878         hls->nb_entries++;
879
880     if (hls->max_seg_size > 0) {
881         return 0;
882     }
883     hls->sequence++;
884
885     return 0;
886 }
887
888 static int parse_playlist(AVFormatContext *s, const char *url)
889 {
890     HLSContext *hls = s->priv_data;
891     AVIOContext *in;
892     int ret = 0, is_segment = 0;
893     int64_t new_start_pos;
894     char line[1024];
895     const char *ptr;
896     const char *end;
897
898     if ((ret = ffio_open_whitelist(&in, url, AVIO_FLAG_READ,
899                                    &s->interrupt_callback, NULL,
900                                    s->protocol_whitelist, s->protocol_blacklist)) < 0)
901         return ret;
902
903     read_chomp_line(in, line, sizeof(line));
904     if (strcmp(line, "#EXTM3U")) {
905         ret = AVERROR_INVALIDDATA;
906         goto fail;
907     }
908
909     hls->discontinuity = 0;
910     while (!avio_feof(in)) {
911         read_chomp_line(in, line, sizeof(line));
912         if (av_strstart(line, "#EXT-X-MEDIA-SEQUENCE:", &ptr)) {
913             int64_t tmp_sequence = strtoll(ptr, NULL, 10);
914             if (tmp_sequence < hls->sequence)
915               av_log(hls, AV_LOG_VERBOSE,
916                      "Found playlist sequence number was smaller """
917                      "than specified start sequence number: %"PRId64" < %"PRId64", "
918                      "omitting\n", tmp_sequence, hls->start_sequence);
919             else {
920               av_log(hls, AV_LOG_DEBUG, "Found playlist sequence number: %"PRId64"\n", tmp_sequence);
921               hls->sequence = tmp_sequence;
922             }
923         } else if (av_strstart(line, "#EXT-X-DISCONTINUITY", &ptr)) {
924             is_segment = 1;
925             hls->discontinuity = 1;
926         } else if (av_strstart(line, "#EXTINF:", &ptr)) {
927             is_segment = 1;
928             hls->duration = atof(ptr);
929         } else if (av_stristart(line, "#EXT-X-KEY:", &ptr)) {
930             ptr = av_stristr(line, "URI=\"");
931             if (ptr) {
932                 ptr += strlen("URI=\"");
933                 end = av_stristr(ptr, ",");
934                 if (end) {
935                     av_strlcpy(hls->key_uri, ptr, end - ptr);
936                 } else {
937                     av_strlcpy(hls->key_uri, ptr, sizeof(hls->key_uri));
938                 }
939             }
940
941             ptr = av_stristr(line, "IV=0x");
942             if (ptr) {
943                 ptr += strlen("IV=0x");
944                 end = av_stristr(ptr, ",");
945                 if (end) {
946                     av_strlcpy(hls->iv_string, ptr, end - ptr);
947                 } else {
948                     av_strlcpy(hls->iv_string, ptr, sizeof(hls->iv_string));
949                 }
950             }
951
952         } else if (av_strstart(line, "#", NULL)) {
953             continue;
954         } else if (line[0]) {
955             if (is_segment) {
956                 is_segment = 0;
957                 new_start_pos = avio_tell(hls->avf->pb);
958                 hls->size = new_start_pos - hls->start_pos;
959                 av_strlcpy(hls->avf->filename, line, sizeof(line));
960                 ret = hls_append_segment(s, hls, hls->duration, hls->start_pos, hls->size);
961                 if (ret < 0)
962                     goto fail;
963                 hls->start_pos = new_start_pos;
964             }
965         }
966     }
967
968 fail:
969     avio_close(in);
970     return ret;
971 }
972
973 static void hls_free_segments(HLSSegment *p)
974 {
975     HLSSegment *en;
976
977     while(p) {
978         en = p;
979         p = p->next;
980         av_free(en);
981     }
982 }
983
984 static void write_m3u8_head_block(HLSContext *hls, AVIOContext *out, int version,
985                                   int target_duration, int64_t sequence)
986 {
987     avio_printf(out, "#EXTM3U\n");
988     avio_printf(out, "#EXT-X-VERSION:%d\n", version);
989     if (hls->allowcache == 0 || hls->allowcache == 1) {
990         avio_printf(out, "#EXT-X-ALLOW-CACHE:%s\n", hls->allowcache == 0 ? "NO" : "YES");
991     }
992     avio_printf(out, "#EXT-X-TARGETDURATION:%d\n", target_duration);
993     avio_printf(out, "#EXT-X-MEDIA-SEQUENCE:%"PRId64"\n", sequence);
994     av_log(hls, AV_LOG_VERBOSE, "EXT-X-MEDIA-SEQUENCE:%"PRId64"\n", sequence);
995 }
996
997 static void hls_rename_temp_file(AVFormatContext *s, AVFormatContext *oc)
998 {
999     size_t len = strlen(oc->filename);
1000     char final_filename[sizeof(oc->filename)];
1001
1002     av_strlcpy(final_filename, oc->filename, len);
1003     final_filename[len-4] = '\0';
1004     ff_rename(oc->filename, final_filename, s);
1005     oc->filename[len-4] = '\0';
1006 }
1007
1008 static int hls_window(AVFormatContext *s, int last)
1009 {
1010     HLSContext *hls = s->priv_data;
1011     HLSSegment *en;
1012     int target_duration = 0;
1013     int ret = 0;
1014     AVIOContext *out = NULL;
1015     AVIOContext *sub_out = NULL;
1016     char temp_filename[1024];
1017     int64_t sequence = FFMAX(hls->start_sequence, hls->sequence - hls->nb_entries);
1018     int version = 3;
1019     const char *proto = avio_find_protocol_name(s->filename);
1020     int use_rename = proto && !strcmp(proto, "file");
1021     static unsigned warned_non_file;
1022     char *key_uri = NULL;
1023     char *iv_string = NULL;
1024     AVDictionary *options = NULL;
1025     double prog_date_time = hls->initial_prog_date_time;
1026     int byterange_mode = (hls->flags & HLS_SINGLE_FILE) || (hls->max_seg_size > 0);
1027
1028     if (byterange_mode) {
1029         version = 4;
1030         sequence = 0;
1031     }
1032
1033     if (hls->segment_type == SEGMENT_TYPE_FMP4) {
1034         version = 7;
1035     }
1036
1037     if (!use_rename && !warned_non_file++)
1038         av_log(s, AV_LOG_ERROR, "Cannot use rename on non file protocol, this may lead to races and temporary partial files\n");
1039
1040     set_http_options(s, &options, hls);
1041     snprintf(temp_filename, sizeof(temp_filename), use_rename ? "%s.tmp" : "%s", s->filename);
1042     if ((ret = s->io_open(s, &out, temp_filename, AVIO_FLAG_WRITE, &options)) < 0)
1043         goto fail;
1044
1045     for (en = hls->segments; en; en = en->next) {
1046         if (target_duration <= en->duration)
1047             target_duration = get_int_from_double(en->duration);
1048     }
1049
1050     hls->discontinuity_set = 0;
1051     write_m3u8_head_block(hls, out, version, target_duration, sequence);
1052     if (hls->pl_type == PLAYLIST_TYPE_EVENT) {
1053         avio_printf(out, "#EXT-X-PLAYLIST-TYPE:EVENT\n");
1054     } else if (hls->pl_type == PLAYLIST_TYPE_VOD) {
1055         avio_printf(out, "#EXT-X-PLAYLIST-TYPE:VOD\n");
1056     }
1057
1058     if((hls->flags & HLS_DISCONT_START) && sequence==hls->start_sequence && hls->discontinuity_set==0 ){
1059         avio_printf(out, "#EXT-X-DISCONTINUITY\n");
1060         hls->discontinuity_set = 1;
1061     }
1062     for (en = hls->segments; en; en = en->next) {
1063         if ((hls->encrypt || hls->key_info_file) && (!key_uri || strcmp(en->key_uri, key_uri) ||
1064                                     av_strcasecmp(en->iv_string, iv_string))) {
1065             avio_printf(out, "#EXT-X-KEY:METHOD=AES-128,URI=\"%s\"", en->key_uri);
1066             if (*en->iv_string)
1067                 avio_printf(out, ",IV=0x%s", en->iv_string);
1068             avio_printf(out, "\n");
1069             key_uri = en->key_uri;
1070             iv_string = en->iv_string;
1071         }
1072
1073         if (en->discont) {
1074             avio_printf(out, "#EXT-X-DISCONTINUITY\n");
1075         }
1076
1077         if ((hls->segment_type == SEGMENT_TYPE_FMP4) && (en == hls->segments)) {
1078             avio_printf(out, "#EXT-X-MAP:URI=\"%s\"", hls->fmp4_init_filename);
1079             if (hls->flags & HLS_SINGLE_FILE) {
1080                 avio_printf(out, ",BYTERANGE=\"%"PRId64"@%"PRId64"\"", en->size, en->pos);
1081             }
1082             avio_printf(out, "\n");
1083         }
1084         if (hls->flags & HLS_ROUND_DURATIONS)
1085             avio_printf(out, "#EXTINF:%ld,\n",  lrint(en->duration));
1086         else
1087             avio_printf(out, "#EXTINF:%f,\n", en->duration);
1088         if (byterange_mode)
1089             avio_printf(out, "#EXT-X-BYTERANGE:%"PRId64"@%"PRId64"\n",
1090                         en->size, en->pos);
1091
1092         if (hls->flags & HLS_PROGRAM_DATE_TIME) {
1093             time_t tt, wrongsecs;
1094             int milli;
1095             struct tm *tm, tmpbuf;
1096             char buf0[128], buf1[128];
1097             tt = (int64_t)prog_date_time;
1098             milli = av_clip(lrint(1000*(prog_date_time - tt)), 0, 999);
1099             tm = localtime_r(&tt, &tmpbuf);
1100             strftime(buf0, sizeof(buf0), "%Y-%m-%dT%H:%M:%S", tm);
1101             if (!strftime(buf1, sizeof(buf1), "%z", tm) || buf1[1]<'0' ||buf1[1]>'2') {
1102                 int tz_min, dst = tm->tm_isdst;
1103                 tm = gmtime_r(&tt, &tmpbuf);
1104                 tm->tm_isdst = dst;
1105                 wrongsecs = mktime(tm);
1106                 tz_min = (abs(wrongsecs - tt) + 30) / 60;
1107                 snprintf(buf1, sizeof(buf1),
1108                          "%c%02d%02d",
1109                          wrongsecs <= tt ? '+' : '-',
1110                          tz_min / 60,
1111                          tz_min % 60);
1112             }
1113             avio_printf(out, "#EXT-X-PROGRAM-DATE-TIME:%s.%03d%s\n", buf0, milli, buf1);
1114             prog_date_time += en->duration;
1115         }
1116         if (hls->baseurl)
1117             avio_printf(out, "%s", hls->baseurl);
1118         avio_printf(out, "%s\n", en->filename);
1119     }
1120
1121     if (last && (hls->flags & HLS_OMIT_ENDLIST)==0)
1122         avio_printf(out, "#EXT-X-ENDLIST\n");
1123
1124     if( hls->vtt_m3u8_name ) {
1125         if ((ret = s->io_open(s, &sub_out, hls->vtt_m3u8_name, AVIO_FLAG_WRITE, &options)) < 0)
1126             goto fail;
1127         write_m3u8_head_block(hls, sub_out, version, target_duration, sequence);
1128
1129         for (en = hls->segments; en; en = en->next) {
1130             avio_printf(sub_out, "#EXTINF:%f,\n", en->duration);
1131             if (byterange_mode)
1132                  avio_printf(sub_out, "#EXT-X-BYTERANGE:%"PRIi64"@%"PRIi64"\n",
1133                          en->size, en->pos);
1134             if (hls->baseurl)
1135                 avio_printf(sub_out, "%s", hls->baseurl);
1136             avio_printf(sub_out, "%s\n", en->sub_filename);
1137         }
1138
1139         if (last)
1140             avio_printf(sub_out, "#EXT-X-ENDLIST\n");
1141
1142     }
1143
1144 fail:
1145     av_dict_free(&options);
1146     ff_format_io_close(s, &out);
1147     ff_format_io_close(s, &sub_out);
1148     if (ret >= 0 && use_rename)
1149         ff_rename(temp_filename, s->filename, s);
1150     return ret;
1151 }
1152
1153 static int hls_start(AVFormatContext *s)
1154 {
1155     HLSContext *c = s->priv_data;
1156     AVFormatContext *oc = c->avf;
1157     AVFormatContext *vtt_oc = c->vtt_avf;
1158     AVDictionary *options = NULL;
1159     char *filename, iv_string[KEYSIZE*2 + 1];
1160     int err = 0;
1161
1162     if (c->flags & HLS_SINGLE_FILE) {
1163         av_strlcpy(oc->filename, c->basename,
1164                    sizeof(oc->filename));
1165         if (c->vtt_basename)
1166             av_strlcpy(vtt_oc->filename, c->vtt_basename,
1167                   sizeof(vtt_oc->filename));
1168     } else if (c->max_seg_size > 0) {
1169         if (replace_int_data_in_filename(oc->filename, sizeof(oc->filename),
1170 #if FF_API_HLS_WRAP
1171             c->basename, 'd', c->wrap ? c->sequence % c->wrap : c->sequence) < 1) {
1172 #else
1173             c->basename, 'd', c->sequence) < 1) {
1174 #endif
1175                 av_log(oc, AV_LOG_ERROR, "Invalid segment filename template '%s', you can try to use -use_localtime 1 with it\n", c->basename);
1176                 return AVERROR(EINVAL);
1177         }
1178     } else {
1179         if (c->use_localtime) {
1180             time_t now0;
1181             struct tm *tm, tmpbuf;
1182             time(&now0);
1183             tm = localtime_r(&now0, &tmpbuf);
1184             if (!strftime(oc->filename, sizeof(oc->filename), c->basename, tm)) {
1185                 av_log(oc, AV_LOG_ERROR, "Could not get segment filename with use_localtime\n");
1186                 return AVERROR(EINVAL);
1187             }
1188
1189             err = sls_flag_use_localtime_filename(oc, c);
1190             if (err < 0) {
1191                 return AVERROR(ENOMEM);
1192             }
1193
1194             if (c->use_localtime_mkdir) {
1195                 const char *dir;
1196                 char *fn_copy = av_strdup(oc->filename);
1197                 if (!fn_copy) {
1198                     return AVERROR(ENOMEM);
1199                 }
1200                 dir = av_dirname(fn_copy);
1201                 if (mkdir_p(dir) == -1 && errno != EEXIST) {
1202                     av_log(oc, AV_LOG_ERROR, "Could not create directory %s with use_localtime_mkdir\n", dir);
1203                     av_free(fn_copy);
1204                     return AVERROR(errno);
1205                 }
1206                 av_free(fn_copy);
1207             }
1208         } else if (replace_int_data_in_filename(oc->filename, sizeof(oc->filename),
1209 #if FF_API_HLS_WRAP
1210                    c->basename, 'd', c->wrap ? c->sequence % c->wrap : c->sequence) < 1) {
1211 #else
1212                    c->basename, 'd', c->sequence) < 1) {
1213 #endif
1214             av_log(oc, AV_LOG_ERROR, "Invalid segment filename template '%s' you can try to use -use_localtime 1 with it\n", c->basename);
1215             return AVERROR(EINVAL);
1216         }
1217         if( c->vtt_basename) {
1218             if (replace_int_data_in_filename(vtt_oc->filename, sizeof(vtt_oc->filename),
1219 #if FF_API_HLS_WRAP
1220                 c->vtt_basename, 'd', c->wrap ? c->sequence % c->wrap : c->sequence) < 1) {
1221 #else
1222                 c->vtt_basename, 'd', c->sequence) < 1) {
1223 #endif
1224                 av_log(vtt_oc, AV_LOG_ERROR, "Invalid segment filename template '%s'\n", c->vtt_basename);
1225                 return AVERROR(EINVAL);
1226             }
1227        }
1228     }
1229     c->number++;
1230
1231     set_http_options(s, &options, c);
1232
1233     if (c->flags & HLS_TEMP_FILE) {
1234         av_strlcat(oc->filename, ".tmp", sizeof(oc->filename));
1235     }
1236
1237     if (c->key_info_file || c->encrypt) {
1238         if (c->key_info_file && c->encrypt) {
1239             av_log(s, AV_LOG_WARNING, "Cannot use both -hls_key_info_file and -hls_enc,"
1240                   " will use -hls_key_info_file priority\n");
1241         }
1242
1243         if (c->number <= 1 || (c->flags & HLS_PERIODIC_REKEY)) {
1244             if (c->key_info_file) {
1245                 if ((err = hls_encryption_start(s)) < 0)
1246                     goto fail;
1247             } else {
1248                 if ((err = do_encrypt(s)) < 0)
1249                     goto fail;
1250             }
1251         }
1252         if ((err = av_dict_set(&options, "encryption_key", c->key_string, 0))
1253                 < 0)
1254             goto fail;
1255         err = av_strlcpy(iv_string, c->iv_string, sizeof(iv_string));
1256         if (!err)
1257             snprintf(iv_string, sizeof(iv_string), "%032"PRIx64, c->sequence);
1258         if ((err = av_dict_set(&options, "encryption_iv", iv_string, 0)) < 0)
1259            goto fail;
1260
1261         filename = av_asprintf("crypto:%s", oc->filename);
1262         if (!filename) {
1263             err = AVERROR(ENOMEM);
1264             goto fail;
1265         }
1266         err = s->io_open(s, &oc->pb, filename, AVIO_FLAG_WRITE, &options);
1267         av_free(filename);
1268         av_dict_free(&options);
1269         if (err < 0)
1270             return err;
1271     } else
1272         if ((err = s->io_open(s, &oc->pb, oc->filename, AVIO_FLAG_WRITE, &options)) < 0)
1273             goto fail;
1274     if (c->vtt_basename) {
1275         set_http_options(s, &options, c);
1276         if ((err = s->io_open(s, &vtt_oc->pb, vtt_oc->filename, AVIO_FLAG_WRITE, &options)) < 0)
1277             goto fail;
1278     }
1279     av_dict_free(&options);
1280
1281     if (c->segment_type == SEGMENT_TYPE_FMP4 && !(c->flags & HLS_SINGLE_FILE)) {
1282             write_styp(oc->pb);
1283     } else {
1284         /* We only require one PAT/PMT per segment. */
1285         if (oc->oformat->priv_class && oc->priv_data) {
1286             char period[21];
1287
1288             snprintf(period, sizeof(period), "%d", (INT_MAX / 2) - 1);
1289
1290             av_opt_set(oc->priv_data, "mpegts_flags", "resend_headers", 0);
1291             av_opt_set(oc->priv_data, "sdt_period", period, 0);
1292             av_opt_set(oc->priv_data, "pat_period", period, 0);
1293         }
1294     }
1295
1296     if (c->vtt_basename) {
1297         err = avformat_write_header(vtt_oc,NULL);
1298         if (err < 0)
1299             return err;
1300     }
1301
1302     return 0;
1303 fail:
1304     av_dict_free(&options);
1305
1306     return err;
1307 }
1308
1309 static const char * get_default_pattern_localtime_fmt(AVFormatContext *s)
1310 {
1311     char b[21];
1312     time_t t = time(NULL);
1313     struct tm *p, tmbuf;
1314     HLSContext *hls = s->priv_data;
1315
1316     p = localtime_r(&t, &tmbuf);
1317     // no %s support when strftime returned error or left format string unchanged
1318     // also no %s support on MSVC, which invokes the invalid parameter handler on unsupported format strings, instead of returning an error
1319     if (hls->segment_type == SEGMENT_TYPE_FMP4) {
1320         return (HAVE_LIBC_MSVCRT || !strftime(b, sizeof(b), "%s", p) || !strcmp(b, "%s")) ? "-%Y%m%d%H%M%S.m4s" : "-%s.m4s";
1321     }
1322     return (HAVE_LIBC_MSVCRT || !strftime(b, sizeof(b), "%s", p) || !strcmp(b, "%s")) ? "-%Y%m%d%H%M%S.ts" : "-%s.ts";
1323 }
1324
1325 static int hls_write_header(AVFormatContext *s)
1326 {
1327     HLSContext *hls = s->priv_data;
1328     int ret, i;
1329     char *p = NULL;
1330     const char *pattern = "%d.ts";
1331     const char *pattern_localtime_fmt = get_default_pattern_localtime_fmt(s);
1332     const char *vtt_pattern = "%d.vtt";
1333     AVDictionary *options = NULL;
1334     int basename_size = 0;
1335     int vtt_basename_size = 0;
1336     int fmp4_init_filename_len = strlen(hls->fmp4_init_filename) + 1;
1337
1338     if (hls->segment_type == SEGMENT_TYPE_FMP4) {
1339         pattern = "%d.m4s";
1340     }
1341     if ((hls->start_sequence_source_type == HLS_START_SEQUENCE_AS_SECONDS_SINCE_EPOCH) ||
1342         (hls->start_sequence_source_type == HLS_START_SEQUENCE_AS_FORMATTED_DATETIME)) {
1343         time_t t = time(NULL); // we will need it in either case
1344         if (hls->start_sequence_source_type == HLS_START_SEQUENCE_AS_SECONDS_SINCE_EPOCH) {
1345             hls->start_sequence = (int64_t)t;
1346         } else if (hls->start_sequence_source_type == HLS_START_SEQUENCE_AS_FORMATTED_DATETIME) {
1347             char b[15];
1348             struct tm *p, tmbuf;
1349             if (!(p = localtime_r(&t, &tmbuf)))
1350                 return AVERROR(ENOMEM);
1351             if (!strftime(b, sizeof(b), "%Y%m%d%H%M%S", p))
1352                 return AVERROR(ENOMEM);
1353             hls->start_sequence = strtoll(b, NULL, 10);
1354         }
1355         av_log(hls, AV_LOG_DEBUG, "start_number evaluated to %"PRId64"\n", hls->start_sequence);
1356     }
1357
1358     hls->sequence       = hls->start_sequence;
1359     hls->recording_time = (hls->init_time ? hls->init_time : hls->time) * AV_TIME_BASE;
1360     hls->start_pts      = AV_NOPTS_VALUE;
1361     hls->current_segment_final_filename_fmt[0] = '\0';
1362
1363     if (hls->flags & HLS_PROGRAM_DATE_TIME) {
1364         time_t now0;
1365         time(&now0);
1366         hls->initial_prog_date_time = now0;
1367     }
1368
1369     if (hls->format_options_str) {
1370         ret = av_dict_parse_string(&hls->format_options, hls->format_options_str, "=", ":", 0);
1371         if (ret < 0) {
1372             av_log(s, AV_LOG_ERROR, "Could not parse format options list '%s'\n", hls->format_options_str);
1373             goto fail;
1374         }
1375     }
1376
1377     for (i = 0; i < s->nb_streams; i++) {
1378         hls->has_video +=
1379             s->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO;
1380         hls->has_subtitle +=
1381             s->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE;
1382     }
1383
1384     if (hls->has_video > 1)
1385         av_log(s, AV_LOG_WARNING,
1386                "More than a single video stream present, "
1387                "expect issues decoding it.\n");
1388
1389     if (hls->segment_type == SEGMENT_TYPE_FMP4) {
1390         hls->oformat = av_guess_format("mp4", NULL, NULL);
1391     } else {
1392         hls->oformat = av_guess_format("mpegts", NULL, NULL);
1393     }
1394
1395     if (!hls->oformat) {
1396         ret = AVERROR_MUXER_NOT_FOUND;
1397         goto fail;
1398     }
1399
1400     if(hls->has_subtitle) {
1401         hls->vtt_oformat = av_guess_format("webvtt", NULL, NULL);
1402         if (!hls->oformat) {
1403             ret = AVERROR_MUXER_NOT_FOUND;
1404             goto fail;
1405         }
1406     }
1407
1408     if (hls->segment_filename) {
1409         hls->basename = av_strdup(hls->segment_filename);
1410         if (!hls->basename) {
1411             ret = AVERROR(ENOMEM);
1412             goto fail;
1413         }
1414     } else {
1415         if (hls->flags & HLS_SINGLE_FILE) {
1416             if (hls->segment_type == SEGMENT_TYPE_FMP4) {
1417                 pattern = ".m4s";
1418             } else {
1419                 pattern = ".ts";
1420             }
1421         }
1422
1423         if (hls->use_localtime) {
1424             basename_size = strlen(s->filename) + strlen(pattern_localtime_fmt) + 1;
1425         } else {
1426             basename_size = strlen(s->filename) + strlen(pattern) + 1;
1427         }
1428         hls->basename = av_malloc(basename_size);
1429         if (!hls->basename) {
1430             ret = AVERROR(ENOMEM);
1431             goto fail;
1432         }
1433
1434         av_strlcpy(hls->basename, s->filename, basename_size);
1435
1436         p = strrchr(hls->basename, '.');
1437         if (p)
1438             *p = '\0';
1439         if (hls->use_localtime) {
1440             av_strlcat(hls->basename, pattern_localtime_fmt, basename_size);
1441         } else {
1442             av_strlcat(hls->basename, pattern, basename_size);
1443         }
1444     }
1445
1446     if (hls->segment_type == SEGMENT_TYPE_FMP4) {
1447         if (av_strcasecmp(hls->fmp4_init_filename, "init.mp4")) {
1448             hls->base_output_dirname = av_malloc(fmp4_init_filename_len);
1449             if (!hls->base_output_dirname) {
1450                 ret = AVERROR(ENOMEM);
1451                 goto fail;
1452             }
1453             av_strlcpy(hls->base_output_dirname, hls->fmp4_init_filename, fmp4_init_filename_len);
1454         } else {
1455             if (basename_size > 0) {
1456                 hls->base_output_dirname = av_malloc(basename_size);
1457             } else {
1458                 hls->base_output_dirname = av_malloc(strlen(hls->fmp4_init_filename));
1459             }
1460             if (!hls->base_output_dirname) {
1461                 ret = AVERROR(ENOMEM);
1462                 goto fail;
1463             }
1464
1465             if (basename_size > 0) {
1466                 av_strlcpy(hls->base_output_dirname, s->filename, basename_size);
1467                 p = strrchr(hls->base_output_dirname, '/');
1468             }
1469             if (p) {
1470                 *(p + 1) = '\0';
1471                 av_strlcat(hls->base_output_dirname, hls->fmp4_init_filename, basename_size);
1472             } else {
1473                 av_strlcpy(hls->base_output_dirname, hls->fmp4_init_filename, fmp4_init_filename_len);
1474             }
1475         }
1476     }
1477
1478     if (!hls->use_localtime) {
1479         ret = sls_flag_check_duration_size_index(hls);
1480         if (ret < 0) {
1481              goto fail;
1482         }
1483     } else {
1484         ret = sls_flag_check_duration_size(hls);
1485         if (ret < 0) {
1486              goto fail;
1487         }
1488     }
1489     if(hls->has_subtitle) {
1490
1491         if (hls->flags & HLS_SINGLE_FILE)
1492             vtt_pattern = ".vtt";
1493         vtt_basename_size = strlen(s->filename) + strlen(vtt_pattern) + 1;
1494         hls->vtt_basename = av_malloc(vtt_basename_size);
1495         if (!hls->vtt_basename) {
1496             ret = AVERROR(ENOMEM);
1497             goto fail;
1498         }
1499         hls->vtt_m3u8_name = av_malloc(vtt_basename_size);
1500         if (!hls->vtt_m3u8_name ) {
1501             ret = AVERROR(ENOMEM);
1502             goto fail;
1503         }
1504         av_strlcpy(hls->vtt_basename, s->filename, vtt_basename_size);
1505         p = strrchr(hls->vtt_basename, '.');
1506         if (p)
1507             *p = '\0';
1508
1509         if( hls->subtitle_filename ) {
1510             strcpy(hls->vtt_m3u8_name, hls->subtitle_filename);
1511         } else {
1512             strcpy(hls->vtt_m3u8_name, hls->vtt_basename);
1513             av_strlcat(hls->vtt_m3u8_name, "_vtt.m3u8", vtt_basename_size);
1514         }
1515         av_strlcat(hls->vtt_basename, vtt_pattern, vtt_basename_size);
1516     }
1517
1518     if ((hls->flags & HLS_SINGLE_FILE) && (hls->segment_type == SEGMENT_TYPE_FMP4)) {
1519         hls->fmp4_init_filename  = av_strdup(hls->basename);
1520         if (!hls->fmp4_init_filename) {
1521             ret = AVERROR(ENOMEM);
1522             goto fail;
1523         }
1524     }
1525
1526     if ((ret = hls_mux_init(s)) < 0)
1527         goto fail;
1528
1529     if (hls->flags & HLS_APPEND_LIST) {
1530         parse_playlist(s, s->filename);
1531         hls->discontinuity = 1;
1532         if (hls->init_time > 0) {
1533             av_log(s, AV_LOG_WARNING, "append_list mode does not support hls_init_time,"
1534                    " hls_init_time value will have no effect\n");
1535             hls->init_time = 0;
1536             hls->recording_time = hls->time * AV_TIME_BASE;
1537         }
1538     }
1539
1540     if (hls->segment_type != SEGMENT_TYPE_FMP4 || hls->flags & HLS_SINGLE_FILE) {
1541         if ((ret = hls_start(s)) < 0)
1542             goto fail;
1543     }
1544
1545     av_dict_copy(&options, hls->format_options, 0);
1546     ret = avformat_write_header(hls->avf, &options);
1547     if (av_dict_count(options)) {
1548         av_log(s, AV_LOG_ERROR, "Some of provided format options in '%s' are not recognized\n", hls->format_options_str);
1549         ret = AVERROR(EINVAL);
1550         goto fail;
1551     }
1552     //av_assert0(s->nb_streams == hls->avf->nb_streams);
1553     for (i = 0; i < s->nb_streams; i++) {
1554         AVStream *inner_st;
1555         AVStream *outer_st = s->streams[i];
1556
1557         if (hls->max_seg_size > 0) {
1558             if ((outer_st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) &&
1559                 (outer_st->codecpar->bit_rate > hls->max_seg_size)) {
1560                 av_log(s, AV_LOG_WARNING, "Your video bitrate is bigger than hls_segment_size, "
1561                        "(%"PRId64 " > %"PRId64 "), the result maybe not be what you want.",
1562                        outer_st->codecpar->bit_rate, hls->max_seg_size);
1563             }
1564         }
1565
1566         if (outer_st->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE)
1567             inner_st = hls->avf->streams[i];
1568         else if (hls->vtt_avf)
1569             inner_st = hls->vtt_avf->streams[0];
1570         else {
1571             /* We have a subtitle stream, when the user does not want one */
1572             inner_st = NULL;
1573             continue;
1574         }
1575         avpriv_set_pts_info(outer_st, inner_st->pts_wrap_bits, inner_st->time_base.num, inner_st->time_base.den);
1576     }
1577 fail:
1578
1579     av_dict_free(&options);
1580     if (ret < 0) {
1581         av_freep(&hls->fmp4_init_filename);
1582         av_freep(&hls->basename);
1583         av_freep(&hls->vtt_basename);
1584         av_freep(&hls->key_basename);
1585         if (hls->avf)
1586             avformat_free_context(hls->avf);
1587         if (hls->vtt_avf)
1588             avformat_free_context(hls->vtt_avf);
1589
1590     }
1591     return ret;
1592 }
1593
1594 static int hls_write_packet(AVFormatContext *s, AVPacket *pkt)
1595 {
1596     HLSContext *hls = s->priv_data;
1597     AVFormatContext *oc = NULL;
1598     AVStream *st = s->streams[pkt->stream_index];
1599     int64_t end_pts = hls->recording_time * hls->number;
1600     int is_ref_pkt = 1;
1601     int ret = 0, can_split = 1;
1602     int stream_index = 0;
1603
1604     if (hls->sequence - hls->nb_entries > hls->start_sequence && hls->init_time > 0) {
1605         /* reset end_pts, hls->recording_time at end of the init hls list */
1606         int init_list_dur = hls->init_time * hls->nb_entries * AV_TIME_BASE;
1607         int after_init_list_dur = (hls->sequence - hls->nb_entries ) * hls->time * AV_TIME_BASE;
1608         hls->recording_time = hls->time * AV_TIME_BASE;
1609         end_pts = init_list_dur + after_init_list_dur ;
1610     }
1611
1612     if( st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE ) {
1613         oc = hls->vtt_avf;
1614         stream_index = 0;
1615     } else {
1616         oc = hls->avf;
1617         stream_index = pkt->stream_index;
1618     }
1619     if (hls->start_pts == AV_NOPTS_VALUE) {
1620         hls->start_pts = pkt->pts;
1621         hls->end_pts   = pkt->pts;
1622     }
1623
1624     if (hls->has_video) {
1625         can_split = st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
1626                     ((pkt->flags & AV_PKT_FLAG_KEY) || (hls->flags & HLS_SPLIT_BY_TIME));
1627         is_ref_pkt = st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO;
1628     }
1629     if (pkt->pts == AV_NOPTS_VALUE)
1630         is_ref_pkt = can_split = 0;
1631
1632     if (is_ref_pkt) {
1633         if (hls->new_start) {
1634             hls->new_start = 0;
1635             hls->duration = (double)(pkt->pts - hls->end_pts)
1636                                        * st->time_base.num / st->time_base.den;
1637             hls->dpp = (double)(pkt->duration) * st->time_base.num / st->time_base.den;
1638         } else {
1639             if (pkt->duration) {
1640                 hls->duration += (double)(pkt->duration) * st->time_base.num / st->time_base.den;
1641             } else {
1642                 av_log(s, AV_LOG_WARNING, "pkt->duration = 0, maybe the hls segment duration will not precise\n");
1643                 hls->duration = (double)(pkt->pts - hls->end_pts) * st->time_base.num / st->time_base.den;
1644             }
1645         }
1646
1647     }
1648     if (hls->fmp4_init_mode || can_split && av_compare_ts(pkt->pts - hls->start_pts, st->time_base,
1649                                    end_pts, AV_TIME_BASE_Q) >= 0) {
1650         int64_t new_start_pos;
1651         char *old_filename = av_strdup(hls->avf->filename);
1652         int byterange_mode = (hls->flags & HLS_SINGLE_FILE) || (hls->max_seg_size > 0);
1653
1654         if (!old_filename) {
1655             return AVERROR(ENOMEM);
1656         }
1657
1658         av_write_frame(hls->avf, NULL); /* Flush any buffered data */
1659
1660         new_start_pos = avio_tell(hls->avf->pb);
1661         hls->size = new_start_pos - hls->start_pos;
1662
1663         if (!byterange_mode) {
1664             ff_format_io_close(s, &oc->pb);
1665             if (hls->vtt_avf) {
1666                 ff_format_io_close(s, &hls->vtt_avf->pb);
1667             }
1668         }
1669         if ((hls->flags & HLS_TEMP_FILE) && oc->filename[0]) {
1670             if (!(hls->flags & HLS_SINGLE_FILE) || (hls->max_seg_size <= 0))
1671                 if ((hls->avf->oformat->priv_class && hls->avf->priv_data) && hls->segment_type != SEGMENT_TYPE_FMP4)
1672                     av_opt_set(hls->avf->priv_data, "mpegts_flags", "resend_headers", 0);
1673             hls_rename_temp_file(s, oc);
1674         }
1675
1676         if (hls->fmp4_init_mode) {
1677             hls->number--;
1678         }
1679
1680         if (!hls->fmp4_init_mode || byterange_mode)
1681             ret = hls_append_segment(s, hls, hls->duration, hls->start_pos, hls->size);
1682
1683         hls->start_pos = new_start_pos;
1684         if (ret < 0) {
1685             av_free(old_filename);
1686             return ret;
1687         }
1688
1689         hls->end_pts = pkt->pts;
1690         hls->duration = 0;
1691
1692         hls->fmp4_init_mode = 0;
1693         if (hls->flags & HLS_SINGLE_FILE) {
1694             hls->number++;
1695         } else if (hls->max_seg_size > 0) {
1696             if (hls->start_pos >= hls->max_seg_size) {
1697                 hls->sequence++;
1698                 sls_flag_file_rename(hls, old_filename);
1699                 ret = hls_start(s);
1700                 hls->start_pos = 0;
1701                 /* When split segment by byte, the duration is short than hls_time,
1702                  * so it is not enough one segment duration as hls_time, */
1703                 hls->number--;
1704             }
1705             hls->number++;
1706         } else {
1707             sls_flag_file_rename(hls, old_filename);
1708             ret = hls_start(s);
1709         }
1710         av_free(old_filename);
1711
1712         if (ret < 0) {
1713             return ret;
1714         }
1715
1716         if (!hls->fmp4_init_mode || byterange_mode)
1717             if ((ret = hls_window(s, 0)) < 0) {
1718                 return ret;
1719             }
1720     }
1721
1722     ret = ff_write_chained(oc, stream_index, pkt, s, 0);
1723
1724     return ret;
1725 }
1726
1727 static int hls_write_trailer(struct AVFormatContext *s)
1728 {
1729     HLSContext *hls = s->priv_data;
1730     AVFormatContext *oc = hls->avf;
1731     AVFormatContext *vtt_oc = hls->vtt_avf;
1732     char *old_filename = av_strdup(hls->avf->filename);
1733
1734     if (!old_filename) {
1735         return AVERROR(ENOMEM);
1736     }
1737
1738
1739     av_write_trailer(oc);
1740     if (oc->pb) {
1741         hls->size = avio_tell(hls->avf->pb) - hls->start_pos;
1742         ff_format_io_close(s, &oc->pb);
1743
1744         if ((hls->flags & HLS_TEMP_FILE) && oc->filename[0]) {
1745             hls_rename_temp_file(s, oc);
1746         }
1747
1748         /* after av_write_trailer, then duration + 1 duration per packet */
1749         hls_append_segment(s, hls, hls->duration + hls->dpp, hls->start_pos, hls->size);
1750     }
1751
1752     sls_flag_file_rename(hls, old_filename);
1753
1754     if (vtt_oc) {
1755         if (vtt_oc->pb)
1756             av_write_trailer(vtt_oc);
1757         hls->size = avio_tell(hls->vtt_avf->pb) - hls->start_pos;
1758         ff_format_io_close(s, &vtt_oc->pb);
1759     }
1760     av_freep(&hls->basename);
1761     av_freep(&hls->base_output_dirname);
1762     av_freep(&hls->key_basename);
1763     avformat_free_context(oc);
1764
1765     hls->avf = NULL;
1766     hls_window(s, 1);
1767
1768     av_freep(&hls->fmp4_init_filename);
1769     if (vtt_oc) {
1770         av_freep(&hls->vtt_basename);
1771         av_freep(&hls->vtt_m3u8_name);
1772         avformat_free_context(vtt_oc);
1773     }
1774
1775     hls_free_segments(hls->segments);
1776     hls_free_segments(hls->old_segments);
1777     av_free(old_filename);
1778     return 0;
1779 }
1780
1781 #define OFFSET(x) offsetof(HLSContext, x)
1782 #define E AV_OPT_FLAG_ENCODING_PARAM
1783 static const AVOption options[] = {
1784     {"start_number",  "set first number in the sequence",        OFFSET(start_sequence),AV_OPT_TYPE_INT64,  {.i64 = 0},     0, INT64_MAX, E},
1785     {"hls_time",      "set segment length in seconds",           OFFSET(time),    AV_OPT_TYPE_FLOAT,  {.dbl = 2},     0, FLT_MAX, E},
1786     {"hls_init_time", "set segment length in seconds at init list",           OFFSET(init_time),    AV_OPT_TYPE_FLOAT,  {.dbl = 0},     0, FLT_MAX, E},
1787     {"hls_list_size", "set maximum number of playlist entries",  OFFSET(max_nb_segments),    AV_OPT_TYPE_INT,    {.i64 = 5},     0, INT_MAX, E},
1788     {"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},
1789     {"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},
1790 #if FF_API_HLS_WRAP
1791     {"hls_wrap",      "set number after which the index wraps (will be deprecated)",  OFFSET(wrap),    AV_OPT_TYPE_INT,    {.i64 = 0},     0, INT_MAX, E},
1792 #endif
1793     {"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},
1794     {"hls_base_url",  "url to prepend to each playlist entry",   OFFSET(baseurl), AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,       E},
1795     {"hls_segment_filename", "filename template for segment files", OFFSET(segment_filename),   AV_OPT_TYPE_STRING, {.str = NULL},            0,       0,         E},
1796     {"hls_segment_size", "maximum size per segment file, (in bytes)",  OFFSET(max_seg_size),    AV_OPT_TYPE_INT,    {.i64 = 0},               0,       INT_MAX,   E},
1797     {"hls_key_info_file",    "file with key URI and key file path", OFFSET(key_info_file),      AV_OPT_TYPE_STRING, {.str = NULL},            0,       0,         E},
1798     {"hls_enc",    "enable AES128 encryption support", OFFSET(encrypt),      AV_OPT_TYPE_BOOL, {.i64 = 0},            0,       1,         E},
1799     {"hls_enc_key",    "hex-coded 16 byte key to encrypt the segments", OFFSET(key),      AV_OPT_TYPE_STRING, .flags = E},
1800     {"hls_enc_key_url",    "url to access the key to decrypt the segments", OFFSET(key_url),      AV_OPT_TYPE_STRING, {.str = NULL},            0,       0,         E},
1801     {"hls_enc_iv",    "hex-coded 16 byte initialization vector", OFFSET(iv),      AV_OPT_TYPE_STRING, .flags = E},
1802     {"hls_subtitle_path",     "set path of hls subtitles", OFFSET(subtitle_filename), AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,    E},
1803     {"hls_segment_type",     "set hls segment files type", OFFSET(segment_type), AV_OPT_TYPE_INT, {.i64 = SEGMENT_TYPE_MPEGTS }, 0, SEGMENT_TYPE_FMP4, E, "segment_type"},
1804     {"mpegts",   "make segment file to mpegts files in m3u8", 0, AV_OPT_TYPE_CONST, {.i64 = SEGMENT_TYPE_MPEGTS }, 0, UINT_MAX,   E, "segment_type"},
1805     {"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"},
1806     {"hls_fmp4_init_filename", "set fragment mp4 file init filename", OFFSET(fmp4_init_filename),   AV_OPT_TYPE_STRING, {.str = "init.mp4"},            0,       0,         E},
1807     {"hls_flags",     "set flags affecting HLS playlist and media file generation", OFFSET(flags), AV_OPT_TYPE_FLAGS, {.i64 = 0 }, 0, UINT_MAX, E, "flags"},
1808     {"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"},
1809     {"temp_file", "write segment to temporary file and rename when complete", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_TEMP_FILE }, 0, UINT_MAX,   E, "flags"},
1810     {"delete_segments", "delete segment files that are no longer part of the playlist", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_DELETE_SEGMENTS }, 0, UINT_MAX,   E, "flags"},
1811     {"round_durations", "round durations in m3u8 to whole numbers", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_ROUND_DURATIONS }, 0, UINT_MAX,   E, "flags"},
1812     {"discont_start", "start the playlist with a discontinuity tag", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_DISCONT_START }, 0, UINT_MAX,   E, "flags"},
1813     {"omit_endlist", "Do not append an endlist when ending stream", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_OMIT_ENDLIST }, 0, UINT_MAX,   E, "flags"},
1814     {"split_by_time", "split the hls segment by time which user set by hls_time", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_SPLIT_BY_TIME }, 0, UINT_MAX,   E, "flags"},
1815     {"append_list", "append the new segments into old hls segment list", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_APPEND_LIST }, 0, UINT_MAX,   E, "flags"},
1816     {"program_date_time", "add EXT-X-PROGRAM-DATE-TIME", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_PROGRAM_DATE_TIME }, 0, UINT_MAX,   E, "flags"},
1817     {"second_level_segment_index", "include segment index in segment filenames when use_localtime", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_SECOND_LEVEL_SEGMENT_INDEX }, 0, UINT_MAX,   E, "flags"},
1818     {"second_level_segment_duration", "include segment duration in segment filenames when use_localtime", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_SECOND_LEVEL_SEGMENT_DURATION }, 0, UINT_MAX,   E, "flags"},
1819     {"second_level_segment_size", "include segment size in segment filenames when use_localtime", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_SECOND_LEVEL_SEGMENT_SIZE }, 0, UINT_MAX,   E, "flags"},
1820     {"periodic_rekey", "reload keyinfo file periodically for re-keying", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_PERIODIC_REKEY }, 0, UINT_MAX,   E, "flags"},
1821     {"use_localtime", "set filename expansion with strftime at segment creation", OFFSET(use_localtime), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, E },
1822     {"use_localtime_mkdir", "create last directory component in strftime-generated filename", OFFSET(use_localtime_mkdir), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, E },
1823     {"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" },
1824     {"event", "EVENT playlist", 0, AV_OPT_TYPE_CONST, {.i64 = PLAYLIST_TYPE_EVENT }, INT_MIN, INT_MAX, E, "pl_type" },
1825     {"vod", "VOD playlist", 0, AV_OPT_TYPE_CONST, {.i64 = PLAYLIST_TYPE_VOD }, INT_MIN, INT_MAX, E, "pl_type" },
1826     {"method", "set the HTTP method(default: PUT)", OFFSET(method), AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,    E},
1827     {"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" },
1828     {"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" },
1829     {"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" },
1830     {"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" },
1831     {"http_user_agent", "override User-Agent field in HTTP header", OFFSET(user_agent), AV_OPT_TYPE_STRING, {.str = NULL},  0, 0,    E},
1832     { NULL },
1833 };
1834
1835 static const AVClass hls_class = {
1836     .class_name = "hls muxer",
1837     .item_name  = av_default_item_name,
1838     .option     = options,
1839     .version    = LIBAVUTIL_VERSION_INT,
1840 };
1841
1842
1843 AVOutputFormat ff_hls_muxer = {
1844     .name           = "hls",
1845     .long_name      = NULL_IF_CONFIG_SMALL("Apple HTTP Live Streaming"),
1846     .extensions     = "m3u8",
1847     .priv_data_size = sizeof(HLSContext),
1848     .audio_codec    = AV_CODEC_ID_AAC,
1849     .video_codec    = AV_CODEC_ID_H264,
1850     .subtitle_codec = AV_CODEC_ID_WEBVTT,
1851     .flags          = AVFMT_NOFILE | AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH,
1852     .write_header   = hls_write_header,
1853     .write_packet   = hls_write_packet,
1854     .write_trailer  = hls_write_trailer,
1855     .priv_class     = &hls_class,
1856 };