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