2 * Apple HTTP Live Streaming segmenter
3 * Copyright (c) 2012, Luca Barbato
5 * This file is part of FFmpeg.
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.
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.
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
32 #include <openssl/rand.h>
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"
46 #include "avio_internal.h"
48 #include "os_support.h"
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;
57 #define LINE_BUFFER_SIZE 1024
58 #define HLS_MICROSECOND_UNIT 1000000
60 typedef struct HLSSegment {
62 char sub_filename[1024];
63 double duration; /* in seconds */
68 char key_uri[LINE_BUFFER_SIZE + 1];
69 char iv_string[KEYSIZE*2 + 1];
71 struct HLSSegment *next;
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),
103 typedef struct HLSContext {
104 const AVClass *class; // Class for private options.
107 int64_t start_sequence;
108 uint32_t start_sequence_source_type; // enum StartSequenceSourceType
109 AVOutputFormat *oformat;
110 AVOutputFormat *vtt_oformat;
112 AVFormatContext *avf;
113 AVFormatContext *vtt_avf;
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.
119 int wrap; // Set by a private option.
121 uint32_t flags; // enum HLSFlags
122 uint32_t pl_type; // enum PlaylistType
123 char *segment_filename;
124 char *fmp4_init_filename;
128 int use_localtime; ///< flag to expand filename with localtime
129 int use_localtime_mkdir;///< flag to mkdir dirname in timebased filename
131 int64_t recording_time;
135 double dpp; // duration per packet
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
143 int discontinuity_set;
146 HLSSegment *segments;
147 HLSSegment *last_segment;
148 HLSSegment *old_segments;
151 char *base_output_dirname;
155 char *format_options_str;
156 char *vtt_format_options_str;
157 char *subtitle_filename;
158 AVDictionary *format_options;
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;
175 double initial_prog_date_time;
176 char current_segment_final_filename_fmt[1024]; // when renaming segments
180 static int get_int_from_double(double val)
182 return (int)((val - (int)val) >= 0.001) ? (int)(val + 1) : (int)val;
185 static int mkdir_p(const char *path) {
187 char *temp = av_strdup(path);
191 if (!path || !temp) {
195 if (!strncmp(temp, "/", 1) || !strncmp(temp, "\\", 1)) {
197 } else if (!strncmp(temp, "./", 2) || !strncmp(temp, ".\\", 2)) {
201 for ( ; *pos != '\0'; ++pos) {
202 if (*pos == '/' || *pos == '\\') {
205 ret = mkdir(temp, 0755);
210 if ((*(pos - 1) != '/') || (*(pos - 1) != '\\')) {
211 ret = mkdir(temp, 0755);
218 static void set_http_options(AVFormatContext *s, AVDictionary **options, HLSContext *c)
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;
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);
230 av_dict_set(options, "user_agent", c->user_agent, 0);
234 static int replace_int_data_in_filename(char *buf, int buf_size, const char *filename, char placeholder, int64_t number)
237 char *q, buf1[20], c;
238 int nd, len, addchar_count;
247 if (c == '%' && *(p+1) == '%') // %%
249 else if (c == '%' && (av_isdigit(*(p+1)) || *(p+1) == placeholder)) {
252 while (av_isdigit(*(p + addchar_count))) {
253 nd = nd * 10 + *(p + addchar_count) - '0';
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
261 if ((q - buf + len) > buf_size - 1)
263 memcpy(q, buf1, len);
265 p += (addchar_count + 1);
273 while (addchar_count--)
274 if ((q - buf) < buf_size - 1)
286 static void write_styp(AVIOContext *pb)
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");
296 static int hls_delete_old_segments(AVFormatContext *s, HLSContext *hls) {
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;
303 AVDictionary *options = NULL;
304 AVIOContext *out = NULL;
305 const char *proto = NULL;
307 segment = hls->segments;
309 playlist_duration += segment->duration;
310 segment = segment->next;
313 segment = hls->old_segments;
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;
324 if (segment && !hls->use_localtime_mkdir) {
325 if (hls->segment_filename) {
326 dirname = av_strdup(hls->segment_filename);
328 dirname = av_strdup(hls->avf->filename);
331 ret = AVERROR(ENOMEM);
334 p = (char *)av_basename(dirname);
339 av_log(hls, AV_LOG_DEBUG, "deleting old segment %s\n",
341 path_size = (hls->use_localtime_mkdir ? 0 : strlen(dirname)) + strlen(segment->filename) + 1;
342 path = av_malloc(path_size);
344 ret = AVERROR(ENOMEM);
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);
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)
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));
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);
370 ret = AVERROR(ENOMEM);
374 av_strlcpy(sub_path, dirname, sub_path_size);
375 av_strlcat(sub_path, segment->sub_filename, sub_path_size);
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) {
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));
391 previous_segment = segment;
392 segment = previous_segment->next;
393 av_free(previous_segment);
403 static int randomize(uint8_t *buf, int len)
406 gcry_randomize(buf, len, GCRY_VERY_STRONG_RANDOM);
409 if (RAND_bytes(buf, len))
412 return AVERROR(ENOSYS);
414 return AVERROR(EINVAL);
417 static int do_encrypt(AVFormatContext *s)
419 HLSContext *hls = s->priv_data;
423 uint8_t key[KEYSIZE];
425 len = strlen(hls->basename) + 4 + 1;
426 hls->key_basename = av_mallocz(len);
427 if (!hls->key_basename)
428 return AVERROR(ENOMEM);
430 av_strlcpy(hls->key_basename, s->filename, len);
431 av_strlcat(hls->key_basename, ".key", len);
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));
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));
441 if (!*hls->iv_string) {
442 uint8_t iv[16] = { 0 };
446 AV_WB64(iv + 8, hls->sequence);
448 memcpy(iv, hls->iv, sizeof(iv));
450 ff_data_to_hex(buf, iv, sizeof(iv), 0);
452 memcpy(hls->iv_string, buf, sizeof(hls->iv_string));
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);
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);
465 if (!*hls->key_string) {
467 if ((ret = randomize(key, sizeof(key))) < 0) {
468 av_log(s, AV_LOG_ERROR, "Cannot generate a strong random key\n");
472 memcpy(key, hls->key, sizeof(key));
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)
478 avio_seek(pb, 0, SEEK_CUR);
479 avio_write(pb, key, KEYSIZE);
486 static int hls_encryption_start(AVFormatContext *s)
488 HLSContext *hls = s->priv_data;
491 uint8_t key[KEYSIZE];
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);
499 ff_get_line(pb, hls->key_uri, sizeof(hls->key_uri));
500 hls->key_uri[strcspn(hls->key_uri, "\r\n")] = '\0';
502 ff_get_line(pb, hls->key_file, sizeof(hls->key_file));
503 hls->key_file[strcspn(hls->key_file, "\r\n")] = '\0';
505 ff_get_line(pb, hls->iv_string, sizeof(hls->iv_string));
506 hls->iv_string[strcspn(hls->iv_string, "\r\n")] = '\0';
508 ff_format_io_close(s, &pb);
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);
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);
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);
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);
533 ff_data_to_hex(hls->key_string, key, sizeof(key), 0);
538 static int read_chomp_line(AVIOContext *s, char *buf, int maxlen)
540 int len = ff_get_line(s, buf, maxlen);
541 while (len > 0 && av_isspace(buf[len - 1]))
546 static int hls_mux_init(AVFormatContext *s)
548 AVDictionary *options = NULL;
549 HLSContext *hls = s->priv_data;
551 AVFormatContext *vtt_oc = NULL;
552 int byterange_mode = (hls->flags & HLS_SINGLE_FILE) || (hls->max_seg_size > 0);
555 ret = avformat_alloc_output_context2(&hls->avf, hls->oformat, NULL, NULL);
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);
569 if(hls->vtt_oformat) {
570 ret = avformat_alloc_output_context2(&hls->vtt_avf, hls->vtt_oformat, NULL, NULL);
573 vtt_oc = hls->vtt_avf;
574 vtt_oc->oformat = hls->vtt_oformat;
575 av_dict_copy(&vtt_oc->metadata, s->metadata, 0);
578 for (i = 0; i < s->nb_streams; i++) {
580 AVFormatContext *loc;
581 if (s->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE)
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;
594 st->codecpar->codec_tag = 0;
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);
603 hls->fmp4_init_mode = 0;
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;
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);
617 if (hls->format_options_str) {
618 ret = av_dict_parse_string(&hls->format_options, hls->format_options_str, "=", ":", 0);
620 av_log(s, AV_LOG_ERROR, "Could not parse format options list '%s'\n",
621 hls->format_options_str);
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);
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);
637 av_dict_free(&options);
642 static HLSSegment *find_segment_by_filename(HLSSegment *segment, const char *filename)
645 if (!av_strcasecmp(segment->filename,filename))
647 segment = segment->next;
649 return (HLSSegment *) NULL;
652 static int sls_flags_filename_process(struct AVFormatContext *s, HLSContext *hls, HLSSegment *en, double duration,
653 int64_t pos, int64_t size)
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
662 return AVERROR(ENOMEM);
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",
672 return AVERROR(EINVAL);
676 if (hls->flags & HLS_SECOND_LEVEL_SEGMENT_DURATION) {
677 char * filename = av_strdup(hls->avf->filename); // %%t will be %t after strftime
680 return AVERROR(ENOMEM);
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",
690 return AVERROR(EINVAL);
698 static int sls_flag_check_duration_size_index(HLSContext *hls)
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);
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);
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);
721 static int sls_flag_check_duration_size(HLSContext *hls)
723 const char *proto = avio_find_protocol_name(hls->basename);
724 int segment_renaming_ok = proto && !strcmp(proto, "file");
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);
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);
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);
748 static int sls_flag_use_localtime_filename(AVFormatContext *oc, HLSContext *c)
750 if (c->flags & HLS_SECOND_LEVEL_SEGMENT_INDEX) {
751 char * filename = av_strdup(oc->filename); // %%d will be %d after strftime
753 return AVERROR(ENOMEM);
754 if (replace_int_data_in_filename(oc->filename, sizeof(oc->filename),
756 filename, 'd', c->wrap ? c->sequence % c->wrap : c->sequence) < 1) {
758 filename, 'd', c->sequence) < 1) {
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",
764 return AVERROR(EINVAL);
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
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",
780 return AVERROR(EINVAL);
784 if (c->flags & HLS_SECOND_LEVEL_SEGMENT_DURATION) {
785 char * filename = av_strdup(oc->filename); // %%t will be %t after strftime
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",
793 return AVERROR(EINVAL);
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)
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);
811 return AVERROR(ENOMEM);
813 ret = sls_flags_filename_process(s, hls, en, duration, pos, size);
818 filename = av_basename(hls->avf->filename);
820 if (hls->use_localtime_mkdir) {
821 filename = hls->avf->filename;
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);
827 av_strlcpy(en->filename, filename, sizeof(en->filename));
829 if(hls->has_subtitle)
830 av_strlcpy(en->sub_filename, av_basename(hls->vtt_avf->filename), sizeof(en->sub_filename));
832 en->sub_filename[0] = '\0';
834 en->duration = duration;
840 if (hls->discontinuity) {
842 hls->discontinuity = 0;
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));
853 hls->last_segment->next = en;
855 hls->last_segment = en;
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;
861 if (hls->max_nb_segments && hls->nb_entries >= hls->max_nb_segments) {
863 hls->initial_prog_date_time += en->duration;
864 hls->segments = en->next;
865 if (en && hls->flags & HLS_DELETE_SEGMENTS &&
867 !(hls->flags & HLS_SINGLE_FILE || hls->wrap)) {
869 !(hls->flags & HLS_SINGLE_FILE)) {
871 en->next = hls->old_segments;
872 hls->old_segments = en;
873 if ((ret = hls_delete_old_segments(s, hls)) < 0)
880 if (hls->max_seg_size > 0) {
888 static int parse_playlist(AVFormatContext *s, const char *url)
890 HLSContext *hls = s->priv_data;
892 int ret = 0, is_segment = 0;
893 int64_t new_start_pos;
898 if ((ret = ffio_open_whitelist(&in, url, AVIO_FLAG_READ,
899 &s->interrupt_callback, NULL,
900 s->protocol_whitelist, s->protocol_blacklist)) < 0)
903 read_chomp_line(in, line, sizeof(line));
904 if (strcmp(line, "#EXTM3U")) {
905 ret = AVERROR_INVALIDDATA;
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);
920 av_log(hls, AV_LOG_DEBUG, "Found playlist sequence number: %"PRId64"\n", tmp_sequence);
921 hls->sequence = tmp_sequence;
923 } else if (av_strstart(line, "#EXT-X-DISCONTINUITY", &ptr)) {
925 hls->discontinuity = 1;
926 } else if (av_strstart(line, "#EXTINF:", &ptr)) {
928 hls->duration = atof(ptr);
929 } else if (av_stristart(line, "#EXT-X-KEY:", &ptr)) {
930 ptr = av_stristr(line, "URI=\"");
932 ptr += strlen("URI=\"");
933 end = av_stristr(ptr, ",");
935 av_strlcpy(hls->key_uri, ptr, end - ptr);
937 av_strlcpy(hls->key_uri, ptr, sizeof(hls->key_uri));
941 ptr = av_stristr(line, "IV=0x");
943 ptr += strlen("IV=0x");
944 end = av_stristr(ptr, ",");
946 av_strlcpy(hls->iv_string, ptr, end - ptr);
948 av_strlcpy(hls->iv_string, ptr, sizeof(hls->iv_string));
952 } else if (av_strstart(line, "#", NULL)) {
954 } else if (line[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);
963 hls->start_pos = new_start_pos;
973 static void hls_free_segments(HLSSegment *p)
984 static void write_m3u8_head_block(HLSContext *hls, AVIOContext *out, int version,
985 int target_duration, int64_t sequence)
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");
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);
997 static void hls_rename_temp_file(AVFormatContext *s, AVFormatContext *oc)
999 size_t len = strlen(oc->filename);
1000 char final_filename[sizeof(oc->filename)];
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';
1008 static int hls_window(AVFormatContext *s, int last)
1010 HLSContext *hls = s->priv_data;
1012 int target_duration = 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);
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);
1028 if (byterange_mode) {
1033 if (hls->segment_type == SEGMENT_TYPE_FMP4) {
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");
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)
1045 for (en = hls->segments; en; en = en->next) {
1046 if (target_duration <= en->duration)
1047 target_duration = get_int_from_double(en->duration);
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");
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;
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);
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;
1074 avio_printf(out, "#EXT-X-DISCONTINUITY\n");
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);
1082 avio_printf(out, "\n");
1084 if (hls->flags & HLS_ROUND_DURATIONS)
1085 avio_printf(out, "#EXTINF:%ld,\n", lrint(en->duration));
1087 avio_printf(out, "#EXTINF:%f,\n", en->duration);
1089 avio_printf(out, "#EXT-X-BYTERANGE:%"PRId64"@%"PRId64"\n",
1092 if (hls->flags & HLS_PROGRAM_DATE_TIME) {
1093 time_t tt, wrongsecs;
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);
1105 wrongsecs = mktime(tm);
1106 tz_min = (abs(wrongsecs - tt) + 30) / 60;
1107 snprintf(buf1, sizeof(buf1),
1109 wrongsecs <= tt ? '+' : '-',
1113 avio_printf(out, "#EXT-X-PROGRAM-DATE-TIME:%s.%03d%s\n", buf0, milli, buf1);
1114 prog_date_time += en->duration;
1117 avio_printf(out, "%s", hls->baseurl);
1118 avio_printf(out, "%s\n", en->filename);
1121 if (last && (hls->flags & HLS_OMIT_ENDLIST)==0)
1122 avio_printf(out, "#EXT-X-ENDLIST\n");
1124 if( hls->vtt_m3u8_name ) {
1125 if ((ret = s->io_open(s, &sub_out, hls->vtt_m3u8_name, AVIO_FLAG_WRITE, &options)) < 0)
1127 write_m3u8_head_block(hls, sub_out, version, target_duration, sequence);
1129 for (en = hls->segments; en; en = en->next) {
1130 avio_printf(sub_out, "#EXTINF:%f,\n", en->duration);
1132 avio_printf(sub_out, "#EXT-X-BYTERANGE:%"PRIi64"@%"PRIi64"\n",
1135 avio_printf(sub_out, "%s", hls->baseurl);
1136 avio_printf(sub_out, "%s\n", en->sub_filename);
1140 avio_printf(sub_out, "#EXT-X-ENDLIST\n");
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);
1153 static int hls_start(AVFormatContext *s)
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];
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),
1171 c->basename, 'd', c->wrap ? c->sequence % c->wrap : c->sequence) < 1) {
1173 c->basename, 'd', c->sequence) < 1) {
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);
1179 if (c->use_localtime) {
1181 struct tm *tm, tmpbuf;
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);
1189 err = sls_flag_use_localtime_filename(oc, c);
1191 return AVERROR(ENOMEM);
1194 if (c->use_localtime_mkdir) {
1196 char *fn_copy = av_strdup(oc->filename);
1198 return AVERROR(ENOMEM);
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);
1204 return AVERROR(errno);
1208 } else if (replace_int_data_in_filename(oc->filename, sizeof(oc->filename),
1210 c->basename, 'd', c->wrap ? c->sequence % c->wrap : c->sequence) < 1) {
1212 c->basename, 'd', c->sequence) < 1) {
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);
1217 if( c->vtt_basename) {
1218 if (replace_int_data_in_filename(vtt_oc->filename, sizeof(vtt_oc->filename),
1220 c->vtt_basename, 'd', c->wrap ? c->sequence % c->wrap : c->sequence) < 1) {
1222 c->vtt_basename, 'd', c->sequence) < 1) {
1224 av_log(vtt_oc, AV_LOG_ERROR, "Invalid segment filename template '%s'\n", c->vtt_basename);
1225 return AVERROR(EINVAL);
1231 set_http_options(s, &options, c);
1233 if (c->flags & HLS_TEMP_FILE) {
1234 av_strlcat(oc->filename, ".tmp", sizeof(oc->filename));
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");
1243 if (c->number <= 1 || (c->flags & HLS_PERIODIC_REKEY)) {
1244 if (c->key_info_file) {
1245 if ((err = hls_encryption_start(s)) < 0)
1248 if ((err = do_encrypt(s)) < 0)
1252 if ((err = av_dict_set(&options, "encryption_key", c->key_string, 0))
1255 err = av_strlcpy(iv_string, c->iv_string, sizeof(iv_string));
1257 snprintf(iv_string, sizeof(iv_string), "%032"PRIx64, c->sequence);
1258 if ((err = av_dict_set(&options, "encryption_iv", iv_string, 0)) < 0)
1261 filename = av_asprintf("crypto:%s", oc->filename);
1263 err = AVERROR(ENOMEM);
1266 err = s->io_open(s, &oc->pb, filename, AVIO_FLAG_WRITE, &options);
1268 av_dict_free(&options);
1272 if ((err = s->io_open(s, &oc->pb, oc->filename, AVIO_FLAG_WRITE, &options)) < 0)
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)
1279 av_dict_free(&options);
1281 if (c->segment_type == SEGMENT_TYPE_FMP4 && !(c->flags & HLS_SINGLE_FILE)) {
1284 /* We only require one PAT/PMT per segment. */
1285 if (oc->oformat->priv_class && oc->priv_data) {
1288 snprintf(period, sizeof(period), "%d", (INT_MAX / 2) - 1);
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);
1296 if (c->vtt_basename) {
1297 err = avformat_write_header(vtt_oc,NULL);
1304 av_dict_free(&options);
1309 static const char * get_default_pattern_localtime_fmt(AVFormatContext *s)
1312 time_t t = time(NULL);
1313 struct tm *p, tmbuf;
1314 HLSContext *hls = s->priv_data;
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";
1322 return (HAVE_LIBC_MSVCRT || !strftime(b, sizeof(b), "%s", p) || !strcmp(b, "%s")) ? "-%Y%m%d%H%M%S.ts" : "-%s.ts";
1325 static int hls_write_header(AVFormatContext *s)
1327 HLSContext *hls = s->priv_data;
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;
1338 if (hls->segment_type == SEGMENT_TYPE_FMP4) {
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) {
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);
1355 av_log(hls, AV_LOG_DEBUG, "start_number evaluated to %"PRId64"\n", hls->start_sequence);
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';
1363 if (hls->flags & HLS_PROGRAM_DATE_TIME) {
1366 hls->initial_prog_date_time = now0;
1369 if (hls->format_options_str) {
1370 ret = av_dict_parse_string(&hls->format_options, hls->format_options_str, "=", ":", 0);
1372 av_log(s, AV_LOG_ERROR, "Could not parse format options list '%s'\n", hls->format_options_str);
1377 for (i = 0; i < s->nb_streams; i++) {
1379 s->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO;
1380 hls->has_subtitle +=
1381 s->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE;
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");
1389 if (hls->segment_type == SEGMENT_TYPE_FMP4) {
1390 hls->oformat = av_guess_format("mp4", NULL, NULL);
1392 hls->oformat = av_guess_format("mpegts", NULL, NULL);
1395 if (!hls->oformat) {
1396 ret = AVERROR_MUXER_NOT_FOUND;
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;
1408 if (hls->segment_filename) {
1409 hls->basename = av_strdup(hls->segment_filename);
1410 if (!hls->basename) {
1411 ret = AVERROR(ENOMEM);
1415 if (hls->flags & HLS_SINGLE_FILE) {
1416 if (hls->segment_type == SEGMENT_TYPE_FMP4) {
1423 if (hls->use_localtime) {
1424 basename_size = strlen(s->filename) + strlen(pattern_localtime_fmt) + 1;
1426 basename_size = strlen(s->filename) + strlen(pattern) + 1;
1428 hls->basename = av_malloc(basename_size);
1429 if (!hls->basename) {
1430 ret = AVERROR(ENOMEM);
1434 av_strlcpy(hls->basename, s->filename, basename_size);
1436 p = strrchr(hls->basename, '.');
1439 if (hls->use_localtime) {
1440 av_strlcat(hls->basename, pattern_localtime_fmt, basename_size);
1442 av_strlcat(hls->basename, pattern, basename_size);
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);
1453 av_strlcpy(hls->base_output_dirname, hls->fmp4_init_filename, fmp4_init_filename_len);
1455 if (basename_size > 0) {
1456 hls->base_output_dirname = av_malloc(basename_size);
1458 hls->base_output_dirname = av_malloc(strlen(hls->fmp4_init_filename));
1460 if (!hls->base_output_dirname) {
1461 ret = AVERROR(ENOMEM);
1465 if (basename_size > 0) {
1466 av_strlcpy(hls->base_output_dirname, s->filename, basename_size);
1467 p = strrchr(hls->base_output_dirname, '/');
1471 av_strlcat(hls->base_output_dirname, hls->fmp4_init_filename, basename_size);
1473 av_strlcpy(hls->base_output_dirname, hls->fmp4_init_filename, fmp4_init_filename_len);
1478 if (!hls->use_localtime) {
1479 ret = sls_flag_check_duration_size_index(hls);
1484 ret = sls_flag_check_duration_size(hls);
1489 if(hls->has_subtitle) {
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);
1499 hls->vtt_m3u8_name = av_malloc(vtt_basename_size);
1500 if (!hls->vtt_m3u8_name ) {
1501 ret = AVERROR(ENOMEM);
1504 av_strlcpy(hls->vtt_basename, s->filename, vtt_basename_size);
1505 p = strrchr(hls->vtt_basename, '.');
1509 if( hls->subtitle_filename ) {
1510 strcpy(hls->vtt_m3u8_name, hls->subtitle_filename);
1512 strcpy(hls->vtt_m3u8_name, hls->vtt_basename);
1513 av_strlcat(hls->vtt_m3u8_name, "_vtt.m3u8", vtt_basename_size);
1515 av_strlcat(hls->vtt_basename, vtt_pattern, vtt_basename_size);
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);
1526 if ((ret = hls_mux_init(s)) < 0)
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");
1536 hls->recording_time = hls->time * AV_TIME_BASE;
1540 if (hls->segment_type != SEGMENT_TYPE_FMP4 || hls->flags & HLS_SINGLE_FILE) {
1541 if ((ret = hls_start(s)) < 0)
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);
1552 //av_assert0(s->nb_streams == hls->avf->nb_streams);
1553 for (i = 0; i < s->nb_streams; i++) {
1555 AVStream *outer_st = s->streams[i];
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);
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];
1571 /* We have a subtitle stream, when the user does not want one */
1575 avpriv_set_pts_info(outer_st, inner_st->pts_wrap_bits, inner_st->time_base.num, inner_st->time_base.den);
1579 av_dict_free(&options);
1581 av_freep(&hls->fmp4_init_filename);
1582 av_freep(&hls->basename);
1583 av_freep(&hls->vtt_basename);
1584 av_freep(&hls->key_basename);
1586 avformat_free_context(hls->avf);
1588 avformat_free_context(hls->vtt_avf);
1594 static int hls_write_packet(AVFormatContext *s, AVPacket *pkt)
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;
1601 int ret = 0, can_split = 1;
1602 int stream_index = 0;
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 ;
1612 if( st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE ) {
1617 stream_index = pkt->stream_index;
1619 if (hls->start_pts == AV_NOPTS_VALUE) {
1620 hls->start_pts = pkt->pts;
1621 hls->end_pts = pkt->pts;
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;
1629 if (pkt->pts == AV_NOPTS_VALUE)
1630 is_ref_pkt = can_split = 0;
1633 if (hls->new_start) {
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;
1639 if (pkt->duration) {
1640 hls->duration += (double)(pkt->duration) * st->time_base.num / st->time_base.den;
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;
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);
1654 if (!old_filename) {
1655 return AVERROR(ENOMEM);
1658 av_write_frame(hls->avf, NULL); /* Flush any buffered data */
1660 new_start_pos = avio_tell(hls->avf->pb);
1661 hls->size = new_start_pos - hls->start_pos;
1663 if (!byterange_mode) {
1664 ff_format_io_close(s, &oc->pb);
1666 ff_format_io_close(s, &hls->vtt_avf->pb);
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);
1676 if (hls->fmp4_init_mode) {
1680 if (!hls->fmp4_init_mode || byterange_mode)
1681 ret = hls_append_segment(s, hls, hls->duration, hls->start_pos, hls->size);
1683 hls->start_pos = new_start_pos;
1685 av_free(old_filename);
1689 hls->end_pts = pkt->pts;
1692 hls->fmp4_init_mode = 0;
1693 if (hls->flags & HLS_SINGLE_FILE) {
1695 } else if (hls->max_seg_size > 0) {
1696 if (hls->start_pos >= hls->max_seg_size) {
1698 sls_flag_file_rename(hls, old_filename);
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, */
1707 sls_flag_file_rename(hls, old_filename);
1710 av_free(old_filename);
1716 if (!hls->fmp4_init_mode || byterange_mode)
1717 if ((ret = hls_window(s, 0)) < 0) {
1722 ret = ff_write_chained(oc, stream_index, pkt, s, 0);
1727 static int hls_write_trailer(struct AVFormatContext *s)
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);
1734 if (!old_filename) {
1735 return AVERROR(ENOMEM);
1739 av_write_trailer(oc);
1741 hls->size = avio_tell(hls->avf->pb) - hls->start_pos;
1742 ff_format_io_close(s, &oc->pb);
1744 if ((hls->flags & HLS_TEMP_FILE) && oc->filename[0]) {
1745 hls_rename_temp_file(s, oc);
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);
1752 sls_flag_file_rename(hls, old_filename);
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);
1760 av_freep(&hls->basename);
1761 av_freep(&hls->base_output_dirname);
1762 av_freep(&hls->key_basename);
1763 avformat_free_context(oc);
1768 av_freep(&hls->fmp4_init_filename);
1770 av_freep(&hls->vtt_basename);
1771 av_freep(&hls->vtt_m3u8_name);
1772 avformat_free_context(vtt_oc);
1775 hls_free_segments(hls->segments);
1776 hls_free_segments(hls->old_segments);
1777 av_free(old_filename);
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},
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},
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},
1835 static const AVClass hls_class = {
1836 .class_name = "hls muxer",
1837 .item_name = av_default_item_name,
1839 .version = LIBAVUTIL_VERSION_INT,
1843 AVOutputFormat ff_hls_muxer = {
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,