2 * Apple HTTP Live Streaming segmenter
3 * Copyright (c) 2012, Luca Barbato
4 * Copyright (c) 2017 Akamai Technologies, Inc.
6 * This file is part of FFmpeg.
8 * FFmpeg is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * FFmpeg is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with FFmpeg; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
33 #include <openssl/rand.h>
36 #include "libavutil/avassert.h"
37 #include "libavutil/mathematics.h"
38 #include "libavutil/parseutils.h"
39 #include "libavutil/avstring.h"
40 #include "libavutil/intreadwrite.h"
41 #include "libavutil/random_seed.h"
42 #include "libavutil/opt.h"
43 #include "libavutil/log.h"
44 #include "libavutil/time_internal.h"
47 #include "avio_internal.h"
48 #if CONFIG_HTTP_PROTOCOL
51 #include "hlsplaylist.h"
53 #include "os_support.h"
56 HLS_START_SEQUENCE_AS_START_NUMBER = 0,
57 HLS_START_SEQUENCE_AS_SECONDS_SINCE_EPOCH = 1,
58 HLS_START_SEQUENCE_AS_FORMATTED_DATETIME = 2, // YYYYMMDDhhmmss
59 } StartSequenceSourceType;
62 CODEC_ATTRIBUTE_WRITTEN = 0,
63 CODEC_ATTRIBUTE_WILL_NOT_BE_WRITTEN,
64 } CodecAttributeStatus;
67 #define LINE_BUFFER_SIZE 1024
68 #define HLS_MICROSECOND_UNIT 1000000
69 #define POSTFIX_PATTERN "_%d"
71 typedef struct HLSSegment {
73 char sub_filename[1024];
74 double duration; /* in seconds */
79 char key_uri[LINE_BUFFER_SIZE + 1];
80 char iv_string[KEYSIZE*2 + 1];
82 struct HLSSegment *next;
85 typedef enum HLSFlags {
86 // Generate a single media file and use byte ranges in the playlist.
87 HLS_SINGLE_FILE = (1 << 0),
88 HLS_DELETE_SEGMENTS = (1 << 1),
89 HLS_ROUND_DURATIONS = (1 << 2),
90 HLS_DISCONT_START = (1 << 3),
91 HLS_OMIT_ENDLIST = (1 << 4),
92 HLS_SPLIT_BY_TIME = (1 << 5),
93 HLS_APPEND_LIST = (1 << 6),
94 HLS_PROGRAM_DATE_TIME = (1 << 7),
95 HLS_SECOND_LEVEL_SEGMENT_INDEX = (1 << 8), // include segment index in segment filenames when use_localtime e.g.: %%03d
96 HLS_SECOND_LEVEL_SEGMENT_DURATION = (1 << 9), // include segment duration (microsec) in segment filenames when use_localtime e.g.: %%09t
97 HLS_SECOND_LEVEL_SEGMENT_SIZE = (1 << 10), // include segment size (bytes) in segment filenames when use_localtime e.g.: %%014s
98 HLS_TEMP_FILE = (1 << 11),
99 HLS_PERIODIC_REKEY = (1 << 12),
100 HLS_INDEPENDENT_SEGMENTS = (1 << 13),
108 typedef struct VariantStream {
111 AVOutputFormat *oformat;
112 AVOutputFormat *vtt_oformat;
115 int init_range_length;
117 AVFormatContext *avf;
118 AVFormatContext *vtt_avf;
123 double dpp; // duration per packet
126 double duration; // last segment duration computed so far, in seconds
127 int64_t start_pos; // last segment starting position
128 int64_t size; // last segment size
130 int discontinuity_set;
133 HLSSegment *segments;
134 HLSSegment *last_segment;
135 HLSSegment *old_segments;
142 double initial_prog_date_time;
143 char current_segment_final_filename_fmt[1024]; // when renaming segments
145 char *fmp4_init_filename;
146 char *base_output_dirname;
150 char codec_attr[128];
151 CodecAttributeStatus attr_status;
152 unsigned int nb_streams;
153 int m3u8_created; /* status of media play-list creation */
154 char *agroup; /* audio group name */
155 char *ccgroup; /* closed caption group name */
159 typedef struct ClosedCaptionsStream {
160 char *ccgroup; /* closed caption group name */
161 char *instreamid; /* closed captions INSTREAM-ID */
162 char *language; /* closed captions langauge */
163 } ClosedCaptionsStream;
165 typedef struct HLSContext {
166 const AVClass *class; // Class for private options.
167 int64_t start_sequence;
168 uint32_t start_sequence_source_type; // enum StartSequenceSourceType
170 float time; // Set by a private option.
171 float init_time; // Set by a private option.
172 int max_nb_segments; // Set by a private option.
174 int wrap; // Set by a private option.
176 uint32_t flags; // enum HLSFlags
177 uint32_t pl_type; // enum PlaylistType
178 char *segment_filename;
179 char *fmp4_init_filename;
182 int use_localtime; ///< flag to expand filename with localtime
183 int use_localtime_mkdir;///< flag to mkdir dirname in timebased filename
185 int64_t recording_time;
186 int64_t max_seg_size; // every segment file max size
189 char *format_options_str;
190 char *vtt_format_options_str;
191 char *subtitle_filename;
192 AVDictionary *format_options;
202 char key_file[LINE_BUFFER_SIZE + 1];
203 char key_uri[LINE_BUFFER_SIZE + 1];
204 char key_string[KEYSIZE*2 + 1];
205 char iv_string[KEYSIZE*2 + 1];
206 AVDictionary *vtt_format_options;
211 VariantStream *var_streams;
212 unsigned int nb_varstreams;
213 ClosedCaptionsStream *cc_streams;
214 unsigned int nb_ccstreams;
216 int master_m3u8_created; /* status of master play-list creation */
217 char *master_m3u8_url; /* URL of the master m3u8 file */
218 int version; /* HLS version */
219 char *var_stream_map; /* user specified variant stream map string */
220 char *cc_stream_map; /* user specified closed caption streams map string */
221 char *master_pl_name;
222 unsigned int master_publish_rate;
224 AVIOContext *m3u8_out;
225 AVIOContext *sub_m3u8_out;
228 static int mkdir_p(const char *path) {
230 char *temp = av_strdup(path);
234 if (!path || !temp) {
238 if (!strncmp(temp, "/", 1) || !strncmp(temp, "\\", 1)) {
240 } else if (!strncmp(temp, "./", 2) || !strncmp(temp, ".\\", 2)) {
244 for ( ; *pos != '\0'; ++pos) {
245 if (*pos == '/' || *pos == '\\') {
248 ret = mkdir(temp, 0755);
253 if ((*(pos - 1) != '/') || (*(pos - 1) != '\\')) {
254 ret = mkdir(temp, 0755);
261 static int hlsenc_io_open(AVFormatContext *s, AVIOContext **pb, char *filename,
262 AVDictionary **options) {
263 HLSContext *hls = s->priv_data;
264 int http_base_proto = filename ? ff_is_http_proto(filename) : 0;
265 int err = AVERROR_MUXER_NOT_FOUND;
266 if (!*pb || !http_base_proto || !hls->http_persistent) {
267 err = s->io_open(s, pb, filename, AVIO_FLAG_WRITE, options);
268 #if CONFIG_HTTP_PROTOCOL
270 URLContext *http_url_context = ffio_geturlcontext(*pb);
271 av_assert0(http_url_context);
272 err = ff_http_do_new_request(http_url_context, filename);
278 static void hlsenc_io_close(AVFormatContext *s, AVIOContext **pb, char *filename) {
279 HLSContext *hls = s->priv_data;
280 int http_base_proto = filename ? ff_is_http_proto(filename) : 0;
281 if (!http_base_proto || !hls->http_persistent || hls->key_info_file || hls->encrypt) {
282 ff_format_io_close(s, pb);
283 #if CONFIG_HTTP_PROTOCOL
285 URLContext *http_url_context = ffio_geturlcontext(*pb);
286 av_assert0(http_url_context);
288 ffurl_shutdown(http_url_context, AVIO_FLAG_WRITE);
293 static void set_http_options(AVFormatContext *s, AVDictionary **options, HLSContext *c)
295 int http_base_proto = ff_is_http_proto(s->url);
298 av_dict_set(options, "method", c->method, 0);
299 } else if (http_base_proto) {
300 av_log(c, AV_LOG_WARNING, "No HTTP method set, hls muxer defaulting to method PUT.\n");
301 av_dict_set(options, "method", "PUT", 0);
304 av_dict_set(options, "user_agent", c->user_agent, 0);
305 if (c->http_persistent)
306 av_dict_set_int(options, "multiple_requests", 1, 0);
310 static void write_codec_attr(AVStream *st, VariantStream *vs) {
311 int codec_strlen = strlen(vs->codec_attr);
314 if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE)
316 if (vs->attr_status == CODEC_ATTRIBUTE_WILL_NOT_BE_WRITTEN)
319 if (st->codecpar->codec_id == AV_CODEC_ID_H264) {
320 uint8_t *data = st->codecpar->extradata;
321 if (data && (data[0] | data[1] | data[2]) == 0 && data[3] == 1 && (data[4] & 0x1F) == 7) {
322 snprintf(attr, sizeof(attr),
323 "avc1.%02x%02x%02x", data[5], data[6], data[7]);
327 } else if (st->codecpar->codec_id == AV_CODEC_ID_MP2) {
328 snprintf(attr, sizeof(attr), "mp4a.40.33");
329 } else if (st->codecpar->codec_id == AV_CODEC_ID_MP3) {
330 snprintf(attr, sizeof(attr), "mp4a.40.34");
331 } else if (st->codecpar->codec_id == AV_CODEC_ID_AAC) {
332 /* TODO : For HE-AAC, HE-AACv2, the last digit needs to be set to 5 and 29 respectively */
333 snprintf(attr, sizeof(attr), "mp4a.40.2");
334 } else if (st->codecpar->codec_id == AV_CODEC_ID_AC3) {
335 snprintf(attr, sizeof(attr), "ac-3");
336 } else if (st->codecpar->codec_id == AV_CODEC_ID_EAC3) {
337 snprintf(attr, sizeof(attr), "ec-3");
341 // Don't write the same attribute multiple times
342 if (!av_stristr(vs->codec_attr, attr)) {
343 snprintf(vs->codec_attr + codec_strlen,
344 sizeof(vs->codec_attr) - codec_strlen,
345 "%s%s", codec_strlen ? "," : "", attr);
350 vs->codec_attr[0] = '\0';
351 vs->attr_status = CODEC_ATTRIBUTE_WILL_NOT_BE_WRITTEN;
355 static int replace_int_data_in_filename(char **s, const char *filename, char placeholder, int64_t number)
360 int nd, addchar_count;
364 av_bprint_init(&buf, 0, AV_BPRINT_SIZE_UNLIMITED);
371 if (c == '%' && *(p+1) == '%') // %%
373 else if (c == '%' && (av_isdigit(*(p+1)) || *(p+1) == placeholder)) {
376 while (av_isdigit(*(p + addchar_count))) {
377 nd = nd * 10 + *(p + addchar_count) - '0';
381 if (*(p + addchar_count) == placeholder) {
382 av_bprintf(&buf, "%0*"PRId64, (number < 0) ? nd : nd++, number);
383 p += (addchar_count + 1);
391 av_bprint_append_data(&buf, p, addchar_count);
394 if (!av_bprint_is_complete(&buf)) {
395 av_bprint_finalize(&buf, NULL);
398 if (av_bprint_finalize(&buf, &new_filename) < 0 || !new_filename)
404 static void write_styp(AVIOContext *pb)
407 ffio_wfourcc(pb, "styp");
408 ffio_wfourcc(pb, "msdh");
409 avio_wb32(pb, 0); /* minor */
410 ffio_wfourcc(pb, "msdh");
411 ffio_wfourcc(pb, "msix");
414 static int flush_dynbuf(VariantStream *vs, int *range_length)
416 AVFormatContext *ctx = vs->avf;
420 return AVERROR(EINVAL);
424 av_write_frame(ctx, NULL);
428 *range_length = avio_close_dyn_buf(ctx->pb, &buffer);
430 avio_write(vs->out, buffer, *range_length);
434 return avio_open_dyn_buf(&ctx->pb);
437 static int hls_delete_old_segments(AVFormatContext *s, HLSContext *hls,
440 HLSSegment *segment, *previous_segment = NULL;
441 float playlist_duration = 0.0f;
442 int ret = 0, path_size, sub_path_size;
443 char *dirname = NULL, *p, *sub_path;
445 AVDictionary *options = NULL;
446 AVIOContext *out = NULL;
447 const char *proto = NULL;
449 segment = vs->segments;
451 playlist_duration += segment->duration;
452 segment = segment->next;
455 segment = vs->old_segments;
457 playlist_duration -= segment->duration;
458 previous_segment = segment;
459 segment = previous_segment->next;
460 if (playlist_duration <= -previous_segment->duration) {
461 previous_segment->next = NULL;
466 if (segment && !hls->use_localtime_mkdir) {
467 if (hls->segment_filename) {
468 dirname = av_strdup(hls->segment_filename);
470 dirname = av_strdup(vs->avf->url);
473 ret = AVERROR(ENOMEM);
476 p = (char *)av_basename(dirname);
481 av_log(hls, AV_LOG_DEBUG, "deleting old segment %s\n",
483 path_size = (hls->use_localtime_mkdir ? 0 : strlen(dirname)) + strlen(segment->filename) + 1;
484 path = av_malloc(path_size);
486 ret = AVERROR(ENOMEM);
490 if (hls->use_localtime_mkdir)
491 av_strlcpy(path, segment->filename, path_size);
492 else { // segment->filename contains basename only
493 av_strlcpy(path, dirname, path_size);
494 av_strlcat(path, segment->filename, path_size);
497 proto = avio_find_protocol_name(s->url);
498 if (hls->method || (proto && !av_strcasecmp(proto, "http"))) {
499 av_dict_set(&options, "method", "DELETE", 0);
500 if ((ret = vs->avf->io_open(vs->avf, &out, path, AVIO_FLAG_WRITE, &options)) < 0)
502 ff_format_io_close(vs->avf, &out);
503 } else if (unlink(path) < 0) {
504 av_log(hls, AV_LOG_ERROR, "failed to delete old segment %s: %s\n",
505 path, strerror(errno));
508 if ((segment->sub_filename[0] != '\0')) {
509 sub_path_size = strlen(segment->sub_filename) + 1 + (dirname ? strlen(dirname) : 0);
510 sub_path = av_malloc(sub_path_size);
512 ret = AVERROR(ENOMEM);
516 av_strlcpy(sub_path, dirname, sub_path_size);
517 av_strlcat(sub_path, segment->sub_filename, sub_path_size);
519 if (hls->method || (proto && !av_strcasecmp(proto, "http"))) {
520 av_dict_set(&options, "method", "DELETE", 0);
521 if ((ret = vs->avf->io_open(vs->avf, &out, sub_path, AVIO_FLAG_WRITE, &options)) < 0) {
525 ff_format_io_close(vs->avf, &out);
526 } else if (unlink(sub_path) < 0) {
527 av_log(hls, AV_LOG_ERROR, "failed to delete old segment %s: %s\n",
528 sub_path, strerror(errno));
533 previous_segment = segment;
534 segment = previous_segment->next;
535 av_free(previous_segment);
545 static int randomize(uint8_t *buf, int len)
548 gcry_randomize(buf, len, GCRY_VERY_STRONG_RANDOM);
551 if (RAND_bytes(buf, len))
554 return AVERROR(ENOSYS);
556 return AVERROR(EINVAL);
559 static int do_encrypt(AVFormatContext *s, VariantStream *vs)
561 HLSContext *hls = s->priv_data;
565 uint8_t key[KEYSIZE];
567 len = strlen(s->url) + 4 + 1;
568 hls->key_basename = av_mallocz(len);
569 if (!hls->key_basename)
570 return AVERROR(ENOMEM);
572 av_strlcpy(hls->key_basename, s->url, len);
573 av_strlcat(hls->key_basename, ".key", len);
576 av_strlcpy(hls->key_file, hls->key_url, sizeof(hls->key_file));
577 av_strlcpy(hls->key_uri, hls->key_url, sizeof(hls->key_uri));
579 av_strlcpy(hls->key_file, hls->key_basename, sizeof(hls->key_file));
580 av_strlcpy(hls->key_uri, hls->key_basename, sizeof(hls->key_uri));
583 if (!*hls->iv_string) {
584 uint8_t iv[16] = { 0 };
588 AV_WB64(iv + 8, vs->sequence);
590 memcpy(iv, hls->iv, sizeof(iv));
592 ff_data_to_hex(buf, iv, sizeof(iv), 0);
594 memcpy(hls->iv_string, buf, sizeof(hls->iv_string));
597 if (!*hls->key_uri) {
598 av_log(hls, AV_LOG_ERROR, "no key URI specified in key info file\n");
599 return AVERROR(EINVAL);
602 if (!*hls->key_file) {
603 av_log(hls, AV_LOG_ERROR, "no key file specified in key info file\n");
604 return AVERROR(EINVAL);
607 if (!*hls->key_string) {
609 if ((ret = randomize(key, sizeof(key))) < 0) {
610 av_log(s, AV_LOG_ERROR, "Cannot generate a strong random key\n");
614 memcpy(key, hls->key, sizeof(key));
617 ff_data_to_hex(hls->key_string, key, sizeof(key), 0);
618 if ((ret = s->io_open(s, &pb, hls->key_file, AVIO_FLAG_WRITE, NULL)) < 0)
620 avio_seek(pb, 0, SEEK_CUR);
621 avio_write(pb, key, KEYSIZE);
628 static int hls_encryption_start(AVFormatContext *s)
630 HLSContext *hls = s->priv_data;
633 uint8_t key[KEYSIZE];
635 if ((ret = s->io_open(s, &pb, hls->key_info_file, AVIO_FLAG_READ, NULL)) < 0) {
636 av_log(hls, AV_LOG_ERROR,
637 "error opening key info file %s\n", hls->key_info_file);
641 ff_get_line(pb, hls->key_uri, sizeof(hls->key_uri));
642 hls->key_uri[strcspn(hls->key_uri, "\r\n")] = '\0';
644 ff_get_line(pb, hls->key_file, sizeof(hls->key_file));
645 hls->key_file[strcspn(hls->key_file, "\r\n")] = '\0';
647 ff_get_line(pb, hls->iv_string, sizeof(hls->iv_string));
648 hls->iv_string[strcspn(hls->iv_string, "\r\n")] = '\0';
650 ff_format_io_close(s, &pb);
652 if (!*hls->key_uri) {
653 av_log(hls, AV_LOG_ERROR, "no key URI specified in key info file\n");
654 return AVERROR(EINVAL);
657 if (!*hls->key_file) {
658 av_log(hls, AV_LOG_ERROR, "no key file specified in key info file\n");
659 return AVERROR(EINVAL);
662 if ((ret = s->io_open(s, &pb, hls->key_file, AVIO_FLAG_READ, NULL)) < 0) {
663 av_log(hls, AV_LOG_ERROR, "error opening key file %s\n", hls->key_file);
667 ret = avio_read(pb, key, sizeof(key));
668 ff_format_io_close(s, &pb);
669 if (ret != sizeof(key)) {
670 av_log(hls, AV_LOG_ERROR, "error reading key file %s\n", hls->key_file);
671 if (ret >= 0 || ret == AVERROR_EOF)
672 ret = AVERROR(EINVAL);
675 ff_data_to_hex(hls->key_string, key, sizeof(key), 0);
680 static int read_chomp_line(AVIOContext *s, char *buf, int maxlen)
682 int len = ff_get_line(s, buf, maxlen);
683 while (len > 0 && av_isspace(buf[len - 1]))
688 static int hls_mux_init(AVFormatContext *s, VariantStream *vs)
690 AVDictionary *options = NULL;
691 HLSContext *hls = s->priv_data;
693 AVFormatContext *vtt_oc = NULL;
694 int byterange_mode = (hls->flags & HLS_SINGLE_FILE) || (hls->max_seg_size > 0);
697 ret = avformat_alloc_output_context2(&vs->avf, vs->oformat, NULL, NULL);
702 oc->url = av_strdup("");
704 return AVERROR(ENOMEM);
706 oc->oformat = vs->oformat;
707 oc->interrupt_callback = s->interrupt_callback;
708 oc->max_delay = s->max_delay;
709 oc->opaque = s->opaque;
710 oc->io_open = s->io_open;
711 oc->io_close = s->io_close;
712 av_dict_copy(&oc->metadata, s->metadata, 0);
714 if(vs->vtt_oformat) {
715 ret = avformat_alloc_output_context2(&vs->vtt_avf, vs->vtt_oformat, NULL, NULL);
718 vtt_oc = vs->vtt_avf;
719 vtt_oc->oformat = vs->vtt_oformat;
720 av_dict_copy(&vtt_oc->metadata, s->metadata, 0);
723 for (i = 0; i < vs->nb_streams; i++) {
725 AVFormatContext *loc;
726 if (vs->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE)
731 if (!(st = avformat_new_stream(loc, NULL)))
732 return AVERROR(ENOMEM);
733 avcodec_parameters_copy(st->codecpar, vs->streams[i]->codecpar);
734 if (!oc->oformat->codec_tag ||
735 av_codec_get_id (oc->oformat->codec_tag, vs->streams[i]->codecpar->codec_tag) == st->codecpar->codec_id ||
736 av_codec_get_tag(oc->oformat->codec_tag, vs->streams[i]->codecpar->codec_id) <= 0) {
737 st->codecpar->codec_tag = vs->streams[i]->codecpar->codec_tag;
739 st->codecpar->codec_tag = 0;
742 st->sample_aspect_ratio = vs->streams[i]->sample_aspect_ratio;
743 st->time_base = vs->streams[i]->time_base;
744 av_dict_copy(&st->metadata, vs->streams[i]->metadata, 0);
747 vs->packets_written = 1;
750 vs->fmp4_init_mode = 0;
752 if (hls->segment_type == SEGMENT_TYPE_FMP4) {
753 if (hls->max_seg_size > 0) {
754 av_log(s, AV_LOG_WARNING, "Multi-file byterange mode is currently unsupported in the HLS muxer.\n");
755 return AVERROR_PATCHWELCOME;
758 vs->packets_written = 0;
759 vs->init_range_length = 0;
760 vs->fmp4_init_mode = !byterange_mode;
761 set_http_options(s, &options, hls);
762 if ((ret = avio_open_dyn_buf(&oc->pb)) < 0)
765 ret = hlsenc_io_open(s, &vs->out, vs->base_output_dirname, &options);
766 av_dict_free(&options);
768 av_log(s, AV_LOG_ERROR, "Failed to open segment '%s'\n", vs->fmp4_init_filename);
772 if (hls->format_options_str) {
773 ret = av_dict_parse_string(&hls->format_options, hls->format_options_str, "=", ":", 0);
775 av_log(s, AV_LOG_ERROR, "Could not parse format options list '%s'\n",
776 hls->format_options_str);
781 av_dict_copy(&options, hls->format_options, 0);
782 av_dict_set(&options, "fflags", "-autobsf", 0);
783 av_dict_set(&options, "movflags", "frag_custom+dash+delay_moov", 0);
784 ret = avformat_init_output(oc, &options);
787 if (av_dict_count(options)) {
788 av_log(s, AV_LOG_ERROR, "Some of the provided format options in '%s' are not recognized\n", hls->format_options_str);
789 av_dict_free(&options);
790 return AVERROR(EINVAL);
793 av_dict_free(&options);
798 static HLSSegment *find_segment_by_filename(HLSSegment *segment, const char *filename)
801 if (!av_strcasecmp(segment->filename,filename))
803 segment = segment->next;
805 return (HLSSegment *) NULL;
808 static int sls_flags_filename_process(struct AVFormatContext *s, HLSContext *hls,
809 VariantStream *vs, HLSSegment *en,
810 double duration, int64_t pos, int64_t size)
812 if ((hls->flags & (HLS_SECOND_LEVEL_SEGMENT_SIZE | HLS_SECOND_LEVEL_SEGMENT_DURATION)) &&
813 strlen(vs->current_segment_final_filename_fmt)) {
814 char * new_url = av_strdup(vs->current_segment_final_filename_fmt);
817 return AVERROR(ENOMEM);
819 ff_format_set_url(vs->avf, new_url);
820 if (hls->flags & HLS_SECOND_LEVEL_SEGMENT_SIZE) {
821 char *filename = NULL;
822 if (replace_int_data_in_filename(&filename, vs->avf->url, 's', pos + size) < 1) {
823 av_log(hls, AV_LOG_ERROR,
824 "Invalid second level segment filename template '%s', "
825 "you can try to remove second_level_segment_size flag\n",
829 return AVERROR(EINVAL);
831 ff_format_set_url(vs->avf, filename);
833 if (hls->flags & HLS_SECOND_LEVEL_SEGMENT_DURATION) {
834 char *filename = NULL;
835 if (replace_int_data_in_filename(&filename, vs->avf->url,
836 't', (int64_t)round(duration * HLS_MICROSECOND_UNIT)) < 1) {
837 av_log(hls, AV_LOG_ERROR,
838 "Invalid second level segment filename template '%s', "
839 "you can try to remove second_level_segment_time flag\n",
843 return AVERROR(EINVAL);
845 ff_format_set_url(vs->avf, filename);
851 static int sls_flag_check_duration_size_index(HLSContext *hls)
855 if (hls->flags & HLS_SECOND_LEVEL_SEGMENT_DURATION) {
856 av_log(hls, AV_LOG_ERROR,
857 "second_level_segment_duration hls_flag requires use_localtime to be true\n");
858 ret = AVERROR(EINVAL);
860 if (hls->flags & HLS_SECOND_LEVEL_SEGMENT_SIZE) {
861 av_log(hls, AV_LOG_ERROR,
862 "second_level_segment_size hls_flag requires use_localtime to be true\n");
863 ret = AVERROR(EINVAL);
865 if (hls->flags & HLS_SECOND_LEVEL_SEGMENT_INDEX) {
866 av_log(hls, AV_LOG_ERROR,
867 "second_level_segment_index hls_flag requires use_localtime to be true\n");
868 ret = AVERROR(EINVAL);
874 static int sls_flag_check_duration_size(HLSContext *hls, VariantStream *vs)
876 const char *proto = avio_find_protocol_name(vs->basename);
877 int segment_renaming_ok = proto && !strcmp(proto, "file");
880 if ((hls->flags & HLS_SECOND_LEVEL_SEGMENT_DURATION) && !segment_renaming_ok) {
881 av_log(hls, AV_LOG_ERROR,
882 "second_level_segment_duration hls_flag works only with file protocol segment names\n");
883 ret = AVERROR(EINVAL);
885 if ((hls->flags & HLS_SECOND_LEVEL_SEGMENT_SIZE) && !segment_renaming_ok) {
886 av_log(hls, AV_LOG_ERROR,
887 "second_level_segment_size hls_flag works only with file protocol segment names\n");
888 ret = AVERROR(EINVAL);
894 static void sls_flag_file_rename(HLSContext *hls, VariantStream *vs, char *old_filename) {
895 if ((hls->flags & (HLS_SECOND_LEVEL_SEGMENT_SIZE | HLS_SECOND_LEVEL_SEGMENT_DURATION)) &&
896 strlen(vs->current_segment_final_filename_fmt)) {
897 ff_rename(old_filename, vs->avf->url, hls);
901 static int sls_flag_use_localtime_filename(AVFormatContext *oc, HLSContext *c, VariantStream *vs)
903 if (c->flags & HLS_SECOND_LEVEL_SEGMENT_INDEX) {
904 char *filename = NULL;
905 if (replace_int_data_in_filename(&filename,
907 oc->url, 'd', c->wrap ? vs->sequence % c->wrap : vs->sequence) < 1) {
909 oc->url, 'd', vs->sequence) < 1) {
911 av_log(c, AV_LOG_ERROR, "Invalid second level segment filename template '%s', "
912 "you can try to remove second_level_segment_index flag\n",
915 return AVERROR(EINVAL);
917 ff_format_set_url(oc, filename);
919 if (c->flags & (HLS_SECOND_LEVEL_SEGMENT_SIZE | HLS_SECOND_LEVEL_SEGMENT_DURATION)) {
920 av_strlcpy(vs->current_segment_final_filename_fmt, oc->url,
921 sizeof(vs->current_segment_final_filename_fmt));
922 if (c->flags & HLS_SECOND_LEVEL_SEGMENT_SIZE) {
923 char *filename = NULL;
924 if (replace_int_data_in_filename(&filename, oc->url, 's', 0) < 1) {
925 av_log(c, AV_LOG_ERROR, "Invalid second level segment filename template '%s', "
926 "you can try to remove second_level_segment_size flag\n",
929 return AVERROR(EINVAL);
931 ff_format_set_url(oc, filename);
933 if (c->flags & HLS_SECOND_LEVEL_SEGMENT_DURATION) {
934 char *filename = NULL;
935 if (replace_int_data_in_filename(&filename, oc->url, 't', 0) < 1) {
936 av_log(c, AV_LOG_ERROR, "Invalid second level segment filename template '%s', "
937 "you can try to remove second_level_segment_time flag\n",
940 return AVERROR(EINVAL);
942 ff_format_set_url(oc, filename);
948 /* Create a new segment and append it to the segment list */
949 static int hls_append_segment(struct AVFormatContext *s, HLSContext *hls,
950 VariantStream *vs, double duration, int64_t pos,
953 HLSSegment *en = av_malloc(sizeof(*en));
954 const char *filename;
955 int byterange_mode = (hls->flags & HLS_SINGLE_FILE) || (hls->max_seg_size > 0);
959 return AVERROR(ENOMEM);
961 ret = sls_flags_filename_process(s, hls, vs, en, duration, pos, size);
966 filename = av_basename(vs->avf->url);
968 if (hls->use_localtime_mkdir) {
969 filename = vs->avf->url;
971 if ((find_segment_by_filename(vs->segments, filename) || find_segment_by_filename(vs->old_segments, filename))
972 && !byterange_mode) {
973 av_log(hls, AV_LOG_WARNING, "Duplicated segment filename detected: %s\n", filename);
975 av_strlcpy(en->filename, filename, sizeof(en->filename));
978 av_strlcpy(en->sub_filename, av_basename(vs->vtt_avf->url), sizeof(en->sub_filename));
980 en->sub_filename[0] = '\0';
982 en->duration = duration;
988 if (vs->discontinuity) {
990 vs->discontinuity = 0;
993 if (hls->key_info_file || hls->encrypt) {
994 av_strlcpy(en->key_uri, hls->key_uri, sizeof(en->key_uri));
995 av_strlcpy(en->iv_string, hls->iv_string, sizeof(en->iv_string));
1001 vs->last_segment->next = en;
1003 vs->last_segment = en;
1005 // EVENT or VOD playlists imply sliding window cannot be used
1006 if (hls->pl_type != PLAYLIST_TYPE_NONE)
1007 hls->max_nb_segments = 0;
1009 if (hls->max_nb_segments && vs->nb_entries >= hls->max_nb_segments) {
1011 vs->initial_prog_date_time += en->duration;
1012 vs->segments = en->next;
1013 if (en && hls->flags & HLS_DELETE_SEGMENTS &&
1015 !(hls->flags & HLS_SINGLE_FILE || hls->wrap)) {
1017 !(hls->flags & HLS_SINGLE_FILE)) {
1019 en->next = vs->old_segments;
1020 vs->old_segments = en;
1021 if ((ret = hls_delete_old_segments(s, hls, vs)) < 0)
1028 if (hls->max_seg_size > 0) {
1036 static int parse_playlist(AVFormatContext *s, const char *url, VariantStream *vs)
1038 HLSContext *hls = s->priv_data;
1040 int ret = 0, is_segment = 0;
1041 int64_t new_start_pos;
1046 if ((ret = ffio_open_whitelist(&in, url, AVIO_FLAG_READ,
1047 &s->interrupt_callback, NULL,
1048 s->protocol_whitelist, s->protocol_blacklist)) < 0)
1051 read_chomp_line(in, line, sizeof(line));
1052 if (strcmp(line, "#EXTM3U")) {
1053 ret = AVERROR_INVALIDDATA;
1057 vs->discontinuity = 0;
1058 while (!avio_feof(in)) {
1059 read_chomp_line(in, line, sizeof(line));
1060 if (av_strstart(line, "#EXT-X-MEDIA-SEQUENCE:", &ptr)) {
1061 int64_t tmp_sequence = strtoll(ptr, NULL, 10);
1062 if (tmp_sequence < vs->sequence)
1063 av_log(hls, AV_LOG_VERBOSE,
1064 "Found playlist sequence number was smaller """
1065 "than specified start sequence number: %"PRId64" < %"PRId64", "
1066 "omitting\n", tmp_sequence, hls->start_sequence);
1068 av_log(hls, AV_LOG_DEBUG, "Found playlist sequence number: %"PRId64"\n", tmp_sequence);
1069 vs->sequence = tmp_sequence;
1071 } else if (av_strstart(line, "#EXT-X-DISCONTINUITY", &ptr)) {
1073 vs->discontinuity = 1;
1074 } else if (av_strstart(line, "#EXTINF:", &ptr)) {
1076 vs->duration = atof(ptr);
1077 } else if (av_stristart(line, "#EXT-X-KEY:", &ptr)) {
1078 ptr = av_stristr(line, "URI=\"");
1080 ptr += strlen("URI=\"");
1081 end = av_stristr(ptr, ",");
1083 av_strlcpy(hls->key_uri, ptr, end - ptr);
1085 av_strlcpy(hls->key_uri, ptr, sizeof(hls->key_uri));
1089 ptr = av_stristr(line, "IV=0x");
1091 ptr += strlen("IV=0x");
1092 end = av_stristr(ptr, ",");
1094 av_strlcpy(hls->iv_string, ptr, end - ptr);
1096 av_strlcpy(hls->iv_string, ptr, sizeof(hls->iv_string));
1100 } else if (av_strstart(line, "#", NULL)) {
1102 } else if (line[0]) {
1104 char *new_file = av_strdup(line);
1106 ret = AVERROR(ENOMEM);
1109 ff_format_set_url(vs->avf, new_file);
1111 new_start_pos = avio_tell(vs->avf->pb);
1112 vs->size = new_start_pos - vs->start_pos;
1113 ret = hls_append_segment(s, hls, vs, vs->duration, vs->start_pos, vs->size);
1116 vs->start_pos = new_start_pos;
1126 static void hls_free_segments(HLSSegment *p)
1137 static int hls_rename_temp_file(AVFormatContext *s, AVFormatContext *oc)
1139 size_t len = strlen(oc->url);
1140 char *final_filename = av_strdup(oc->url);
1143 if (!final_filename)
1144 return AVERROR(ENOMEM);
1145 final_filename[len-4] = '\0';
1146 ret = ff_rename(oc->url, final_filename, s);
1147 oc->url[len-4] = '\0';
1148 av_freep(&final_filename);
1152 static int get_relative_url(const char *master_url, const char *media_url,
1153 char *rel_url, int rel_url_buf_size)
1157 p = strrchr(master_url, '/') ? strrchr(master_url, '/') :\
1158 strrchr(master_url, '\\');
1160 base_len = FFABS(p - master_url);
1161 if (av_strncasecmp(master_url, media_url, base_len)) {
1162 av_log(NULL, AV_LOG_WARNING, "Unable to find relative url\n");
1163 return AVERROR(EINVAL);
1166 av_strlcpy(rel_url, &(media_url[base_len + 1]), rel_url_buf_size);
1170 static int create_master_playlist(AVFormatContext *s,
1171 VariantStream * const input_vs)
1173 HLSContext *hls = s->priv_data;
1174 VariantStream *vs, *temp_vs;
1175 AVStream *vid_st, *aud_st;
1176 AVDictionary *options = NULL;
1178 int m3u8_name_size, ret, bandwidth;
1179 char *m3u8_rel_name, *ccgroup;
1180 ClosedCaptionsStream *ccs;
1182 input_vs->m3u8_created = 1;
1183 if (!hls->master_m3u8_created) {
1184 /* For the first time, wait until all the media playlists are created */
1185 for (i = 0; i < hls->nb_varstreams; i++)
1186 if (!hls->var_streams[i].m3u8_created)
1189 /* Keep publishing the master playlist at the configured rate */
1190 if (&hls->var_streams[0] != input_vs || !hls->master_publish_rate ||
1191 input_vs->number % hls->master_publish_rate)
1195 set_http_options(s, &options, hls);
1197 ret = hlsenc_io_open(s, &hls->m3u8_out, hls->master_m3u8_url, &options);
1198 av_dict_free(&options);
1200 av_log(NULL, AV_LOG_ERROR, "Failed to open master play list file '%s'\n",
1201 hls->master_m3u8_url);
1205 ff_hls_write_playlist_version(hls->m3u8_out, hls->version);
1207 for (i = 0; i < hls->nb_ccstreams; i++) {
1208 ccs = &(hls->cc_streams[i]);
1209 avio_printf(hls->m3u8_out, "#EXT-X-MEDIA:TYPE=CLOSED-CAPTIONS");
1210 avio_printf(hls->m3u8_out, ",GROUP-ID=\"%s\"", ccs->ccgroup);
1211 avio_printf(hls->m3u8_out, ",NAME=\"%s\"", ccs->instreamid);
1213 avio_printf(hls->m3u8_out, ",LANGUAGE=\"%s\"", ccs->language);
1214 avio_printf(hls->m3u8_out, ",INSTREAM-ID=\"%s\"\n", ccs->instreamid);
1217 /* For audio only variant streams add #EXT-X-MEDIA tag with attributes*/
1218 for (i = 0; i < hls->nb_varstreams; i++) {
1219 vs = &(hls->var_streams[i]);
1221 if (vs->has_video || vs->has_subtitle || !vs->agroup)
1224 m3u8_name_size = strlen(vs->m3u8_name) + 1;
1225 m3u8_rel_name = av_malloc(m3u8_name_size);
1226 if (!m3u8_rel_name) {
1227 ret = AVERROR(ENOMEM);
1230 av_strlcpy(m3u8_rel_name, vs->m3u8_name, m3u8_name_size);
1231 ret = get_relative_url(hls->master_m3u8_url, vs->m3u8_name,
1232 m3u8_rel_name, m3u8_name_size);
1234 av_log(s, AV_LOG_ERROR, "Unable to find relative URL\n");
1238 ff_hls_write_audio_rendition(hls->m3u8_out, vs->agroup, m3u8_rel_name, 0, 1);
1240 av_freep(&m3u8_rel_name);
1243 /* For variant streams with video add #EXT-X-STREAM-INF tag with attributes*/
1244 for (i = 0; i < hls->nb_varstreams; i++) {
1245 vs = &(hls->var_streams[i]);
1247 m3u8_name_size = strlen(vs->m3u8_name) + 1;
1248 m3u8_rel_name = av_malloc(m3u8_name_size);
1249 if (!m3u8_rel_name) {
1250 ret = AVERROR(ENOMEM);
1253 av_strlcpy(m3u8_rel_name, vs->m3u8_name, m3u8_name_size);
1254 ret = get_relative_url(hls->master_m3u8_url, vs->m3u8_name,
1255 m3u8_rel_name, m3u8_name_size);
1257 av_log(NULL, AV_LOG_ERROR, "Unable to find relative URL\n");
1263 for (j = 0; j < vs->nb_streams; j++) {
1264 if (vs->streams[j]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
1265 vid_st = vs->streams[j];
1266 else if (vs->streams[j]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
1267 aud_st = vs->streams[j];
1270 if (!vid_st && !aud_st) {
1271 av_log(NULL, AV_LOG_WARNING, "Media stream not found\n");
1276 * Traverse through the list of audio only rendition streams and find
1277 * the rendition which has highest bitrate in the same audio group
1280 for (j = 0; j < hls->nb_varstreams; j++) {
1281 temp_vs = &(hls->var_streams[j]);
1282 if (!temp_vs->has_video && !temp_vs->has_subtitle &&
1284 !av_strcasecmp(temp_vs->agroup, vs->agroup)) {
1286 aud_st = temp_vs->streams[0];
1287 if (temp_vs->streams[0]->codecpar->bit_rate >
1288 aud_st->codecpar->bit_rate)
1289 aud_st = temp_vs->streams[0];
1296 bandwidth += vid_st->codecpar->bit_rate;
1298 bandwidth += aud_st->codecpar->bit_rate;
1299 bandwidth += bandwidth / 10;
1302 if (vid_st && vs->ccgroup) {
1303 /* check if this group name is available in the cc map string */
1304 for (j = 0; j < hls->nb_ccstreams; j++) {
1305 ccs = &(hls->cc_streams[j]);
1306 if (!av_strcasecmp(ccs->ccgroup, vs->ccgroup)) {
1307 ccgroup = vs->ccgroup;
1311 if (j == hls->nb_ccstreams)
1312 av_log(NULL, AV_LOG_WARNING, "mapping ccgroup %s not found\n",
1316 ff_hls_write_stream_info(vid_st, hls->m3u8_out, bandwidth, m3u8_rel_name,
1317 aud_st ? vs->agroup : NULL, vs->codec_attr, ccgroup);
1319 av_freep(&m3u8_rel_name);
1323 hls->master_m3u8_created = 1;
1324 av_freep(&m3u8_rel_name);
1325 hlsenc_io_close(s, &hls->m3u8_out, hls->master_m3u8_url);
1329 static int hls_window(AVFormatContext *s, int last, VariantStream *vs)
1331 HLSContext *hls = s->priv_data;
1333 int target_duration = 0;
1335 char temp_filename[1024];
1336 int64_t sequence = FFMAX(hls->start_sequence, vs->sequence - vs->nb_entries);
1337 const char *proto = avio_find_protocol_name(s->url);
1338 int use_rename = proto && !strcmp(proto, "file");
1339 static unsigned warned_non_file;
1340 char *key_uri = NULL;
1341 char *iv_string = NULL;
1342 AVDictionary *options = NULL;
1343 double prog_date_time = vs->initial_prog_date_time;
1344 double *prog_date_time_p = (hls->flags & HLS_PROGRAM_DATE_TIME) ? &prog_date_time : NULL;
1345 int byterange_mode = (hls->flags & HLS_SINGLE_FILE) || (hls->max_seg_size > 0);
1348 if (byterange_mode) {
1353 if (hls->flags & HLS_INDEPENDENT_SEGMENTS) {
1357 if (hls->segment_type == SEGMENT_TYPE_FMP4) {
1361 if (!use_rename && !warned_non_file++)
1362 av_log(s, AV_LOG_ERROR, "Cannot use rename on non file protocol, this may lead to races and temporary partial files\n");
1364 set_http_options(s, &options, hls);
1365 snprintf(temp_filename, sizeof(temp_filename), use_rename ? "%s.tmp" : "%s", vs->m3u8_name);
1366 if ((ret = hlsenc_io_open(s, &hls->m3u8_out, temp_filename, &options)) < 0)
1369 for (en = vs->segments; en; en = en->next) {
1370 if (target_duration <= en->duration)
1371 target_duration = lrint(en->duration);
1374 vs->discontinuity_set = 0;
1375 ff_hls_write_playlist_header(hls->m3u8_out, hls->version, hls->allowcache,
1376 target_duration, sequence, hls->pl_type);
1378 if((hls->flags & HLS_DISCONT_START) && sequence==hls->start_sequence && vs->discontinuity_set==0 ){
1379 avio_printf(hls->m3u8_out, "#EXT-X-DISCONTINUITY\n");
1380 vs->discontinuity_set = 1;
1382 if (vs->has_video && (hls->flags & HLS_INDEPENDENT_SEGMENTS)) {
1383 avio_printf(hls->m3u8_out, "#EXT-X-INDEPENDENT-SEGMENTS\n");
1385 for (en = vs->segments; en; en = en->next) {
1386 if ((hls->encrypt || hls->key_info_file) && (!key_uri || strcmp(en->key_uri, key_uri) ||
1387 av_strcasecmp(en->iv_string, iv_string))) {
1388 avio_printf(hls->m3u8_out, "#EXT-X-KEY:METHOD=AES-128,URI=\"%s\"", en->key_uri);
1390 avio_printf(hls->m3u8_out, ",IV=0x%s", en->iv_string);
1391 avio_printf(hls->m3u8_out, "\n");
1392 key_uri = en->key_uri;
1393 iv_string = en->iv_string;
1396 if ((hls->segment_type == SEGMENT_TYPE_FMP4) && (en == vs->segments)) {
1397 ff_hls_write_init_file(hls->m3u8_out, vs->fmp4_init_filename,
1398 hls->flags & HLS_SINGLE_FILE, en->size, en->pos);
1401 ret = ff_hls_write_file_entry(hls->m3u8_out, en->discont, byterange_mode,
1402 en->duration, hls->flags & HLS_ROUND_DURATIONS,
1403 en->size, en->pos, vs->baseurl,
1404 en->filename, prog_date_time_p);
1406 av_log(s, AV_LOG_WARNING, "ff_hls_write_file_entry get error\n");
1410 if (last && (hls->flags & HLS_OMIT_ENDLIST)==0)
1411 ff_hls_write_end_list(hls->m3u8_out);
1413 if( vs->vtt_m3u8_name ) {
1414 if ((ret = hlsenc_io_open(s, &hls->sub_m3u8_out, vs->vtt_m3u8_name, &options)) < 0)
1416 ff_hls_write_playlist_header(hls->sub_m3u8_out, hls->version, hls->allowcache,
1417 target_duration, sequence, PLAYLIST_TYPE_NONE);
1418 for (en = vs->segments; en; en = en->next) {
1419 ret = ff_hls_write_file_entry(hls->sub_m3u8_out, 0, byterange_mode,
1420 en->duration, 0, en->size, en->pos,
1421 vs->baseurl, en->sub_filename, NULL);
1423 av_log(s, AV_LOG_WARNING, "ff_hls_write_file_entry get error\n");
1428 ff_hls_write_end_list(hls->sub_m3u8_out);
1433 av_dict_free(&options);
1434 hlsenc_io_close(s, &hls->m3u8_out, temp_filename);
1435 hlsenc_io_close(s, &hls->sub_m3u8_out, vs->vtt_m3u8_name);
1436 if (ret >= 0 && use_rename)
1437 ff_rename(temp_filename, vs->m3u8_name, s);
1439 if (ret >= 0 && hls->master_pl_name)
1440 if (create_master_playlist(s, vs) < 0)
1441 av_log(s, AV_LOG_WARNING, "Master playlist creation failed\n");
1446 static int hls_start(AVFormatContext *s, VariantStream *vs)
1448 HLSContext *c = s->priv_data;
1449 AVFormatContext *oc = vs->avf;
1450 AVFormatContext *vtt_oc = vs->vtt_avf;
1451 AVDictionary *options = NULL;
1452 char *filename, iv_string[KEYSIZE*2 + 1];
1455 if (c->flags & HLS_SINGLE_FILE) {
1456 char *new_name = av_strdup(vs->basename);
1458 return AVERROR(ENOMEM);
1459 ff_format_set_url(oc, new_name);
1460 if (vs->vtt_basename) {
1461 new_name = av_strdup(vs->vtt_basename);
1463 return AVERROR(ENOMEM);
1464 ff_format_set_url(vtt_oc, new_name);
1466 } else if (c->max_seg_size > 0) {
1467 char *filename = NULL;
1468 if (replace_int_data_in_filename(&filename,
1470 vs->basename, 'd', c->wrap ? vs->sequence % c->wrap : vs->sequence) < 1) {
1472 vs->basename, 'd', vs->sequence) < 1) {
1475 av_log(oc, AV_LOG_ERROR, "Invalid segment filename template '%s', you can try to use -use_localtime 1 with it\n", vs->basename);
1476 return AVERROR(EINVAL);
1478 ff_format_set_url(oc, filename);
1480 if (c->use_localtime) {
1482 struct tm *tm, tmpbuf;
1483 int bufsize = strlen(vs->basename) + 1024;
1484 char *buf = av_mallocz(bufsize);
1486 return AVERROR(ENOMEM);
1488 tm = localtime_r(&now0, &tmpbuf);
1489 ff_format_set_url(oc, buf);
1490 if (!strftime(oc->url, bufsize, vs->basename, tm)) {
1491 av_log(oc, AV_LOG_ERROR, "Could not get segment filename with use_localtime\n");
1492 return AVERROR(EINVAL);
1495 err = sls_flag_use_localtime_filename(oc, c, vs);
1497 return AVERROR(ENOMEM);
1500 if (c->use_localtime_mkdir) {
1502 char *fn_copy = av_strdup(oc->url);
1504 return AVERROR(ENOMEM);
1506 dir = av_dirname(fn_copy);
1507 if (mkdir_p(dir) == -1 && errno != EEXIST) {
1508 av_log(oc, AV_LOG_ERROR, "Could not create directory %s with use_localtime_mkdir\n", dir);
1510 return AVERROR(errno);
1515 char *filename = NULL;
1516 if (replace_int_data_in_filename(&filename,
1518 vs->basename, 'd', c->wrap ? vs->sequence % c->wrap : vs->sequence) < 1) {
1520 vs->basename, 'd', vs->sequence) < 1) {
1523 av_log(oc, AV_LOG_ERROR, "Invalid segment filename template '%s' you can try to use -use_localtime 1 with it\n", vs->basename);
1524 return AVERROR(EINVAL);
1526 ff_format_set_url(oc, filename);
1528 if( vs->vtt_basename) {
1529 char *filename = NULL;
1530 if (replace_int_data_in_filename(&filename,
1532 vs->vtt_basename, 'd', c->wrap ? vs->sequence % c->wrap : vs->sequence) < 1) {
1534 vs->vtt_basename, 'd', vs->sequence) < 1) {
1537 av_log(vtt_oc, AV_LOG_ERROR, "Invalid segment filename template '%s'\n", vs->vtt_basename);
1538 return AVERROR(EINVAL);
1540 ff_format_set_url(vtt_oc, filename);
1545 set_http_options(s, &options, c);
1547 if (c->flags & HLS_TEMP_FILE) {
1548 char *new_name = av_asprintf("%s.tmp", oc->url);
1550 return AVERROR(ENOMEM);
1551 ff_format_set_url(oc, new_name);
1554 if (c->key_info_file || c->encrypt) {
1555 if (c->key_info_file && c->encrypt) {
1556 av_log(s, AV_LOG_WARNING, "Cannot use both -hls_key_info_file and -hls_enc,"
1557 " will use -hls_key_info_file priority\n");
1560 if (!c->encrypt_started || (c->flags & HLS_PERIODIC_REKEY)) {
1561 if (c->key_info_file) {
1562 if ((err = hls_encryption_start(s)) < 0)
1565 if ((err = do_encrypt(s, vs)) < 0)
1568 c->encrypt_started = 1;
1570 if ((err = av_dict_set(&options, "encryption_key", c->key_string, 0))
1573 err = av_strlcpy(iv_string, c->iv_string, sizeof(iv_string));
1575 snprintf(iv_string, sizeof(iv_string), "%032"PRIx64, vs->sequence);
1576 if ((err = av_dict_set(&options, "encryption_iv", iv_string, 0)) < 0)
1579 filename = av_asprintf("crypto:%s", oc->url);
1581 err = AVERROR(ENOMEM);
1584 err = hlsenc_io_open(s, &oc->pb, filename, &options);
1586 av_dict_free(&options);
1589 } else if (c->segment_type != SEGMENT_TYPE_FMP4) {
1590 if ((err = hlsenc_io_open(s, &oc->pb, oc->url, &options)) < 0)
1593 if (vs->vtt_basename) {
1594 set_http_options(s, &options, c);
1595 if ((err = hlsenc_io_open(s, &vtt_oc->pb, vtt_oc->url, &options)) < 0)
1598 av_dict_free(&options);
1600 if (c->segment_type != SEGMENT_TYPE_FMP4) {
1601 /* We only require one PAT/PMT per segment. */
1602 if (oc->oformat->priv_class && oc->priv_data) {
1605 snprintf(period, sizeof(period), "%d", (INT_MAX / 2) - 1);
1607 av_opt_set(oc->priv_data, "mpegts_flags", "resend_headers", 0);
1608 av_opt_set(oc->priv_data, "sdt_period", period, 0);
1609 av_opt_set(oc->priv_data, "pat_period", period, 0);
1613 if (vs->vtt_basename) {
1614 err = avformat_write_header(vtt_oc,NULL);
1621 av_dict_free(&options);
1626 static const char * get_default_pattern_localtime_fmt(AVFormatContext *s)
1629 time_t t = time(NULL);
1630 struct tm *p, tmbuf;
1631 HLSContext *hls = s->priv_data;
1633 p = localtime_r(&t, &tmbuf);
1634 // no %s support when strftime returned error or left format string unchanged
1635 // also no %s support on MSVC, which invokes the invalid parameter handler on unsupported format strings, instead of returning an error
1636 if (hls->segment_type == SEGMENT_TYPE_FMP4) {
1637 return (HAVE_LIBC_MSVCRT || !strftime(b, sizeof(b), "%s", p) || !strcmp(b, "%s")) ? "-%Y%m%d%H%M%S.m4s" : "-%s.m4s";
1639 return (HAVE_LIBC_MSVCRT || !strftime(b, sizeof(b), "%s", p) || !strcmp(b, "%s")) ? "-%Y%m%d%H%M%S.ts" : "-%s.ts";
1642 static int append_postfix(char *name, int name_buf_len, int i)
1645 char extension[10] = {'\0'};
1647 p = strrchr(name, '.');
1649 av_strlcpy(extension, p, sizeof(extension));
1653 snprintf(name + strlen(name), name_buf_len - strlen(name), POSTFIX_PATTERN, i);
1655 if (strlen(extension))
1656 av_strlcat(name, extension, name_buf_len);
1661 static int validate_name(int nb_vs, const char *fn)
1663 const char *filename, *subdir_name;
1664 char *fn_dup = NULL;
1668 ret = AVERROR(EINVAL);
1672 fn_dup = av_strdup(fn);
1674 ret = AVERROR(ENOMEM);
1678 filename = av_basename(fn);
1679 subdir_name = av_dirname(fn_dup);
1681 if (nb_vs > 1 && !av_stristr(filename, "%v") && !av_stristr(subdir_name, "%v")) {
1682 av_log(NULL, AV_LOG_ERROR, "More than 1 variant streams are present, %%v is expected in the filename %s\n",
1684 ret = AVERROR(EINVAL);
1688 if (av_stristr(filename, "%v") && av_stristr(subdir_name, "%v")) {
1689 av_log(NULL, AV_LOG_ERROR, "%%v is expected either in filename or in the sub-directory name of file %s\n",
1691 ret = AVERROR(EINVAL);
1700 static int format_name(char *buf, int buf_len, int index)
1702 const char *proto, *dir;
1703 char *orig_buf_dup = NULL, *mod_buf = NULL, *mod_buf_dup = NULL;
1706 if (!av_stristr(buf, "%v"))
1709 orig_buf_dup = av_strdup(buf);
1710 if (!orig_buf_dup) {
1711 ret = AVERROR(ENOMEM);
1715 if (replace_int_data_in_filename(&mod_buf, orig_buf_dup, 'v', index) < 1) {
1716 ret = AVERROR(EINVAL);
1719 av_strlcpy(buf, mod_buf, buf_len);
1721 proto = avio_find_protocol_name(orig_buf_dup);
1722 dir = av_dirname(orig_buf_dup);
1724 /* if %v is present in the file's directory, create sub-directory */
1725 if (av_stristr(dir, "%v") && proto && !strcmp(proto, "file")) {
1726 mod_buf_dup = av_strdup(buf);
1728 ret = AVERROR(ENOMEM);
1732 dir = av_dirname(mod_buf_dup);
1733 if (mkdir_p(dir) == -1 && errno != EEXIST) {
1734 ret = AVERROR(errno);
1740 av_freep(&orig_buf_dup);
1741 av_freep(&mod_buf_dup);
1746 static int get_nth_codec_stream_index(AVFormatContext *s,
1747 enum AVMediaType codec_type,
1750 unsigned int stream_index, cnt;
1751 if (stream_id < 0 || stream_id > s->nb_streams - 1)
1754 for (stream_index = 0; stream_index < s->nb_streams; stream_index++) {
1755 if (s->streams[stream_index]->codecpar->codec_type != codec_type)
1757 if (cnt == stream_id)
1758 return stream_index;
1764 static int parse_variant_stream_mapstring(AVFormatContext *s)
1766 HLSContext *hls = s->priv_data;
1769 enum AVMediaType codec_type;
1770 int nb_varstreams, nb_streams;
1771 char *p, *q, *saveptr1, *saveptr2, *varstr, *keyval;
1775 * Expected format for var_stream_map string is as below:
1777 * "a:0,agroup:a0 a:1,agroup:a1 v:0,agroup:a0 v:1,agroup:a1"
1778 * This string specifies how to group the audio, video and subtitle streams
1779 * into different variant streams. The variant stream groups are separated
1782 * a:, v:, s: are keys to specify audio, video and subtitle streams
1783 * respectively. Allowed values are 0 to 9 digits (limited just based on
1786 * agroup: is key to specify audio group. A string can be given as value.
1788 p = av_strdup(hls->var_stream_map);
1790 while(av_strtok(q, " \t", &saveptr1)) {
1792 hls->nb_varstreams++;
1796 hls->var_streams = av_mallocz(sizeof(*hls->var_streams) * hls->nb_varstreams);
1797 if (!hls->var_streams)
1798 return AVERROR(ENOMEM);
1800 p = hls->var_stream_map;
1802 while (varstr = av_strtok(p, " \t", &saveptr1)) {
1805 if (nb_varstreams < hls->nb_varstreams)
1806 vs = &(hls->var_streams[nb_varstreams++]);
1808 return AVERROR(EINVAL);
1811 while (q < varstr + strlen(varstr)) {
1812 if (!av_strncasecmp(q, "a:", 2) || !av_strncasecmp(q, "v:", 2) ||
1813 !av_strncasecmp(q, "s:", 2))
1817 vs->streams = av_mallocz(sizeof(AVStream *) * vs->nb_streams);
1819 return AVERROR(ENOMEM);
1822 while (keyval = av_strtok(varstr, ",", &saveptr2)) {
1825 if (av_strstart(keyval, "agroup:", &val)) {
1826 vs->agroup = av_strdup(val);
1828 return AVERROR(ENOMEM);
1830 } else if (av_strstart(keyval, "ccgroup:", &val)) {
1831 vs->ccgroup = av_strdup(val);
1833 return AVERROR(ENOMEM);
1835 } else if (av_strstart(keyval, "v:", &val)) {
1836 codec_type = AVMEDIA_TYPE_VIDEO;
1837 } else if (av_strstart(keyval, "a:", &val)) {
1838 codec_type = AVMEDIA_TYPE_AUDIO;
1839 } else if (av_strstart(keyval, "s:", &val)) {
1840 codec_type = AVMEDIA_TYPE_SUBTITLE;
1842 av_log(s, AV_LOG_ERROR, "Invalid keyval %s\n", keyval);
1843 return AVERROR(EINVAL);
1847 if (av_isdigit(*val))
1848 stream_index = get_nth_codec_stream_index (s, codec_type,
1851 if (stream_index >= 0 && nb_streams < vs->nb_streams) {
1852 vs->streams[nb_streams++] = s->streams[stream_index];
1854 av_log(s, AV_LOG_ERROR, "Unable to map stream at %s\n", keyval);
1855 return AVERROR(EINVAL);
1859 av_log(s, AV_LOG_DEBUG, "Number of variant streams %d\n",
1860 hls->nb_varstreams);
1865 static int parse_cc_stream_mapstring(AVFormatContext *s)
1867 HLSContext *hls = s->priv_data;
1869 char *p, *q, *saveptr1, *saveptr2, *ccstr, *keyval;
1871 ClosedCaptionsStream *ccs;
1873 p = av_strdup(hls->cc_stream_map);
1875 while(av_strtok(q, " \t", &saveptr1)) {
1877 hls->nb_ccstreams++;
1881 hls->cc_streams = av_mallocz(sizeof(*hls->cc_streams) * hls->nb_ccstreams);
1882 if (!hls->cc_streams)
1883 return AVERROR(ENOMEM);
1885 p = hls->cc_stream_map;
1887 while (ccstr = av_strtok(p, " \t", &saveptr1)) {
1890 if (nb_ccstreams < hls->nb_ccstreams)
1891 ccs = &(hls->cc_streams[nb_ccstreams++]);
1893 return AVERROR(EINVAL);
1895 while (keyval = av_strtok(ccstr, ",", &saveptr2)) {
1898 if (av_strstart(keyval, "ccgroup:", &val)) {
1899 ccs->ccgroup = av_strdup(val);
1901 return AVERROR(ENOMEM);
1902 } else if (av_strstart(keyval, "instreamid:", &val)) {
1903 ccs->instreamid = av_strdup(val);
1904 if (!ccs->instreamid)
1905 return AVERROR(ENOMEM);
1906 } else if (av_strstart(keyval, "language:", &val)) {
1907 ccs->language = av_strdup(val);
1909 return AVERROR(ENOMEM);
1911 av_log(s, AV_LOG_ERROR, "Invalid keyval %s\n", keyval);
1912 return AVERROR(EINVAL);
1916 if (!ccs->ccgroup || !ccs->instreamid) {
1917 av_log(s, AV_LOG_ERROR, "Insufficient parameters in cc stream map string\n");
1918 return AVERROR(EINVAL);
1921 if (av_strstart(ccs->instreamid, "CC", &val)) {
1922 if(atoi(val) < 1 || atoi(val) > 4) {
1923 av_log(s, AV_LOG_ERROR, "Invalid instream ID CC index %d in %s, range 1-4\n",
1924 atoi(val), ccs->instreamid);
1925 return AVERROR(EINVAL);
1927 } else if (av_strstart(ccs->instreamid, "SERVICE", &val)) {
1928 if(atoi(val) < 1 || atoi(val) > 63) {
1929 av_log(s, AV_LOG_ERROR, "Invalid instream ID SERVICE index %d in %s, range 1-63 \n",
1930 atoi(val), ccs->instreamid);
1931 return AVERROR(EINVAL);
1934 av_log(s, AV_LOG_ERROR, "Invalid instream ID %s, supported are CCn or SERIVICEn\n",
1936 return AVERROR(EINVAL);
1943 static int update_variant_stream_info(AVFormatContext *s) {
1944 HLSContext *hls = s->priv_data;
1948 if (hls->cc_stream_map) {
1949 ret = parse_cc_stream_mapstring(s);
1954 if (hls->var_stream_map) {
1955 return parse_variant_stream_mapstring(s);
1957 //By default, a single variant stream with all the codec streams is created
1958 hls->nb_varstreams = 1;
1959 hls->var_streams = av_mallocz(sizeof(*hls->var_streams) *
1960 hls->nb_varstreams);
1961 if (!hls->var_streams)
1962 return AVERROR(ENOMEM);
1964 hls->var_streams[0].nb_streams = s->nb_streams;
1965 hls->var_streams[0].streams = av_mallocz(sizeof(AVStream *) *
1966 hls->var_streams[0].nb_streams);
1967 if (!hls->var_streams[0].streams)
1968 return AVERROR(ENOMEM);
1970 //by default, the first available ccgroup is mapped to the variant stream
1971 if (hls->nb_ccstreams) {
1972 hls->var_streams[0].ccgroup = av_strdup(hls->cc_streams[0].ccgroup);
1973 if (!hls->var_streams[0].ccgroup)
1974 return AVERROR(ENOMEM);
1977 for (i = 0; i < s->nb_streams; i++)
1978 hls->var_streams[0].streams[i] = s->streams[i];
1983 static int update_master_pl_info(AVFormatContext *s) {
1984 HLSContext *hls = s->priv_data;
1986 char *fn1= NULL, *fn2 = NULL;
1989 fn1 = av_strdup(s->url);
1991 ret = AVERROR(ENOMEM);
1995 dir = av_dirname(fn1);
1998 * if output file's directory has %v, variants are created in sub-directories
1999 * then master is created at the sub-directories level
2001 if (dir && av_stristr(av_basename(dir), "%v")) {
2002 fn2 = av_strdup(dir);
2004 ret = AVERROR(ENOMEM);
2007 dir = av_dirname(fn2);
2010 if (dir && strcmp(dir, "."))
2011 hls->master_m3u8_url = av_append_path_component(dir, hls->master_pl_name);
2013 hls->master_m3u8_url = av_strdup(hls->master_pl_name);
2015 if (!hls->master_m3u8_url) {
2016 ret = AVERROR(ENOMEM);
2027 static int hls_write_header(AVFormatContext *s)
2029 HLSContext *hls = s->priv_data;
2031 AVDictionary *options = NULL;
2032 VariantStream *vs = NULL;
2034 for (i = 0; i < hls->nb_varstreams; i++) {
2035 vs = &hls->var_streams[i];
2037 av_dict_copy(&options, hls->format_options, 0);
2038 ret = avformat_write_header(vs->avf, &options);
2039 if (av_dict_count(options)) {
2040 av_log(s, AV_LOG_ERROR, "Some of provided format options in '%s' are not recognized\n", hls->format_options_str);
2041 ret = AVERROR(EINVAL);
2042 av_dict_free(&options);
2045 av_dict_free(&options);
2046 //av_assert0(s->nb_streams == hls->avf->nb_streams);
2047 for (j = 0; j < vs->nb_streams; j++) {
2049 AVStream *outer_st = vs->streams[j];
2051 if (hls->max_seg_size > 0) {
2052 if ((outer_st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) &&
2053 (outer_st->codecpar->bit_rate > hls->max_seg_size)) {
2054 av_log(s, AV_LOG_WARNING, "Your video bitrate is bigger than hls_segment_size, "
2055 "(%"PRId64 " > %"PRId64 "), the result maybe not be what you want.",
2056 outer_st->codecpar->bit_rate, hls->max_seg_size);
2060 if (outer_st->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE)
2061 inner_st = vs->avf->streams[j];
2062 else if (vs->vtt_avf)
2063 inner_st = vs->vtt_avf->streams[0];
2065 /* We have a subtitle stream, when the user does not want one */
2069 avpriv_set_pts_info(outer_st, inner_st->pts_wrap_bits, inner_st->time_base.num, inner_st->time_base.den);
2070 write_codec_attr(outer_st, vs);
2073 /* Update the Codec Attr string for the mapped audio groups */
2074 if (vs->has_video && vs->agroup) {
2075 for (j = 0; j < hls->nb_varstreams; j++) {
2076 VariantStream *vs_agroup = &(hls->var_streams[j]);
2077 if (!vs_agroup->has_video && !vs_agroup->has_subtitle &&
2078 vs_agroup->agroup &&
2079 !av_strcasecmp(vs_agroup->agroup, vs->agroup)) {
2080 write_codec_attr(vs_agroup->streams[0], vs);
2090 static int hls_write_packet(AVFormatContext *s, AVPacket *pkt)
2092 HLSContext *hls = s->priv_data;
2093 AVFormatContext *oc = NULL;
2094 AVStream *st = s->streams[pkt->stream_index];
2095 int64_t end_pts = 0;
2097 int ret = 0, can_split = 1, i, j;
2098 int stream_index = 0;
2099 int range_length = 0;
2100 uint8_t *buffer = NULL;
2101 VariantStream *vs = NULL;
2103 for (i = 0; i < hls->nb_varstreams; i++) {
2104 vs = &hls->var_streams[i];
2105 for (j = 0; j < vs->nb_streams; j++) {
2106 if (vs->streams[j] == st) {
2107 if( st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE ) {
2123 av_log(s, AV_LOG_ERROR, "Unable to find mapping variant stream\n");
2124 return AVERROR(ENOMEM);
2127 end_pts = hls->recording_time * vs->number;
2129 if (vs->sequence - vs->nb_entries > hls->start_sequence && hls->init_time > 0) {
2130 /* reset end_pts, hls->recording_time at end of the init hls list */
2131 int init_list_dur = hls->init_time * vs->nb_entries * AV_TIME_BASE;
2132 int after_init_list_dur = (vs->sequence - vs->nb_entries ) * hls->time * AV_TIME_BASE;
2133 hls->recording_time = hls->time * AV_TIME_BASE;
2134 end_pts = init_list_dur + after_init_list_dur ;
2137 if (vs->start_pts == AV_NOPTS_VALUE) {
2138 vs->start_pts = pkt->pts;
2141 if (vs->has_video) {
2142 can_split = st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
2143 ((pkt->flags & AV_PKT_FLAG_KEY) || (hls->flags & HLS_SPLIT_BY_TIME));
2144 is_ref_pkt = st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO;
2146 if (pkt->pts == AV_NOPTS_VALUE)
2147 is_ref_pkt = can_split = 0;
2150 if (vs->end_pts == AV_NOPTS_VALUE)
2151 vs->end_pts = pkt->pts;
2152 if (vs->new_start) {
2154 vs->duration = (double)(pkt->pts - vs->end_pts)
2155 * st->time_base.num / st->time_base.den;
2156 vs->dpp = (double)(pkt->duration) * st->time_base.num / st->time_base.den;
2158 if (pkt->duration) {
2159 vs->duration += (double)(pkt->duration) * st->time_base.num / st->time_base.den;
2161 av_log(s, AV_LOG_WARNING, "pkt->duration = 0, maybe the hls segment duration will not precise\n");
2162 vs->duration = (double)(pkt->pts - vs->end_pts) * st->time_base.num / st->time_base.den;
2168 if (vs->packets_written && can_split && av_compare_ts(pkt->pts - vs->start_pts, st->time_base,
2169 end_pts, AV_TIME_BASE_Q) >= 0) {
2170 int64_t new_start_pos;
2171 char *old_filename = NULL;
2172 int byterange_mode = (hls->flags & HLS_SINGLE_FILE) || (hls->max_seg_size > 0);
2174 av_write_frame(vs->avf, NULL); /* Flush any buffered data */
2176 new_start_pos = avio_tell(vs->avf->pb);
2177 vs->size = new_start_pos - vs->start_pos;
2179 if (!byterange_mode) {
2180 if (hls->segment_type == SEGMENT_TYPE_FMP4) {
2181 if (!vs->init_range_length) {
2183 range_length = avio_close_dyn_buf(oc->pb, &buffer);
2184 avio_write(vs->out, buffer, range_length);
2185 vs->init_range_length = range_length;
2186 avio_open_dyn_buf(&oc->pb);
2187 vs->packets_written = 0;
2188 ff_format_io_close(s, &vs->out);
2189 hlsenc_io_close(s, &vs->out, vs->base_output_dirname);
2192 hlsenc_io_close(s, &oc->pb, oc->url);
2195 hlsenc_io_close(s, &vs->vtt_avf->pb, vs->vtt_avf->url);
2198 if ((hls->flags & HLS_TEMP_FILE) && oc->url[0]) {
2199 if (!(hls->flags & HLS_SINGLE_FILE) || (hls->max_seg_size <= 0))
2200 if ((vs->avf->oformat->priv_class && vs->avf->priv_data) && hls->segment_type != SEGMENT_TYPE_FMP4)
2201 av_opt_set(vs->avf->priv_data, "mpegts_flags", "resend_headers", 0);
2202 hls_rename_temp_file(s, oc);
2205 if (vs->fmp4_init_mode) {
2209 if (hls->segment_type == SEGMENT_TYPE_FMP4) {
2210 ret = hlsenc_io_open(s, &vs->out, vs->avf->url, NULL);
2212 av_log(NULL, AV_LOG_ERROR, "Failed to open file '%s'\n",
2216 write_styp(vs->out);
2217 ret = flush_dynbuf(vs, &range_length);
2221 ff_format_io_close(s, &vs->out);
2224 old_filename = av_strdup(vs->avf->url);
2225 if (!old_filename) {
2226 return AVERROR(ENOMEM);
2229 ret = hls_append_segment(s, hls, vs, vs->duration, vs->start_pos, vs->size);
2230 vs->start_pos = new_start_pos;
2232 av_free(old_filename);
2236 vs->end_pts = pkt->pts;
2239 vs->fmp4_init_mode = 0;
2240 if (hls->flags & HLS_SINGLE_FILE) {
2242 } else if (hls->max_seg_size > 0) {
2243 if (vs->start_pos >= hls->max_seg_size) {
2245 sls_flag_file_rename(hls, vs, old_filename);
2246 ret = hls_start(s, vs);
2248 /* When split segment by byte, the duration is short than hls_time,
2249 * so it is not enough one segment duration as hls_time, */
2254 sls_flag_file_rename(hls, vs, old_filename);
2255 ret = hls_start(s, vs);
2257 av_free(old_filename);
2263 if (!vs->fmp4_init_mode || byterange_mode)
2264 if ((ret = hls_window(s, 0, vs)) < 0) {
2269 vs->packets_written++;
2270 ret = ff_write_chained(oc, stream_index, pkt, s, 0);
2275 static int hls_write_trailer(struct AVFormatContext *s)
2277 HLSContext *hls = s->priv_data;
2278 AVFormatContext *oc = NULL;
2279 AVFormatContext *vtt_oc = NULL;
2280 char *old_filename = NULL;
2283 VariantStream *vs = NULL;
2285 for (i = 0; i < hls->nb_varstreams; i++) {
2286 vs = &hls->var_streams[i];
2289 vtt_oc = vs->vtt_avf;
2290 old_filename = av_strdup(vs->avf->url);
2292 if (!old_filename) {
2293 return AVERROR(ENOMEM);
2295 if ( hls->segment_type == SEGMENT_TYPE_FMP4) {
2296 int range_length = 0;
2297 ret = hlsenc_io_open(s, &vs->out, vs->avf->url, NULL);
2299 av_log(NULL, AV_LOG_ERROR, "Failed to open file '%s'\n", vs->avf->url);
2302 write_styp(vs->out);
2303 ret = flush_dynbuf(vs, &range_length);
2307 ff_format_io_close(s, &vs->out);
2311 av_write_trailer(oc);
2313 vs->size = avio_tell(vs->avf->pb) - vs->start_pos;
2314 if (hls->segment_type != SEGMENT_TYPE_FMP4)
2315 ff_format_io_close(s, &oc->pb);
2317 if ((hls->flags & HLS_TEMP_FILE) && oc->url[0]) {
2318 hls_rename_temp_file(s, oc);
2319 av_free(old_filename);
2320 old_filename = av_strdup(vs->avf->url);
2322 if (!old_filename) {
2323 return AVERROR(ENOMEM);
2327 /* after av_write_trailer, then duration + 1 duration per packet */
2328 hls_append_segment(s, hls, vs, vs->duration + vs->dpp, vs->start_pos, vs->size);
2331 sls_flag_file_rename(hls, vs, old_filename);
2335 av_write_trailer(vtt_oc);
2336 vs->size = avio_tell(vs->vtt_avf->pb) - vs->start_pos;
2337 ff_format_io_close(s, &vtt_oc->pb);
2339 av_freep(&vs->basename);
2340 av_freep(&vs->base_output_dirname);
2341 avformat_free_context(oc);
2344 hls_window(s, 1, vs);
2346 av_freep(&vs->fmp4_init_filename);
2348 av_freep(&vs->vtt_basename);
2349 av_freep(&vs->vtt_m3u8_name);
2350 avformat_free_context(vtt_oc);
2353 hls_free_segments(vs->segments);
2354 hls_free_segments(vs->old_segments);
2355 av_free(old_filename);
2356 av_freep(&vs->m3u8_name);
2357 av_freep(&vs->streams);
2358 av_freep(&vs->agroup);
2359 av_freep(&vs->ccgroup);
2360 av_freep(&vs->baseurl);
2363 for (i = 0; i < hls->nb_ccstreams; i++) {
2364 ClosedCaptionsStream *ccs = &hls->cc_streams[i];
2365 av_freep(&ccs->ccgroup);
2366 av_freep(&ccs->instreamid);
2367 av_freep(&ccs->language);
2370 ff_format_io_close(s, &hls->m3u8_out);
2371 ff_format_io_close(s, &hls->sub_m3u8_out);
2372 av_freep(&hls->key_basename);
2373 av_freep(&hls->var_streams);
2374 av_freep(&hls->cc_streams);
2375 av_freep(&hls->master_m3u8_url);
2380 static int hls_init(AVFormatContext *s)
2385 HLSContext *hls = s->priv_data;
2386 const char *pattern = "%d.ts";
2387 VariantStream *vs = NULL;
2388 int basename_size = 0;
2389 const char *pattern_localtime_fmt = get_default_pattern_localtime_fmt(s);
2390 const char *vtt_pattern = "%d.vtt";
2392 int vtt_basename_size = 0;
2393 int fmp4_init_filename_len = strlen(hls->fmp4_init_filename) + 1;
2395 ret = update_variant_stream_info(s);
2397 av_log(s, AV_LOG_ERROR, "Variant stream info update failed with status %x\n",
2401 //TODO: Updates needed to encryption functionality with periodic re-key when more than one variant streams are present
2402 if (hls->nb_varstreams > 1 && hls->flags & HLS_PERIODIC_REKEY) {
2403 ret = AVERROR(EINVAL);
2404 av_log(s, AV_LOG_ERROR, "Periodic re-key not supported when more than one variant streams are present\n");
2408 ret = validate_name(hls->nb_varstreams, s->url);
2412 if (hls->segment_filename) {
2413 ret = validate_name(hls->nb_varstreams, hls->segment_filename);
2418 if (av_strcasecmp(hls->fmp4_init_filename, "init.mp4")) {
2419 ret = validate_name(hls->nb_varstreams, hls->fmp4_init_filename);
2424 if (hls->subtitle_filename) {
2425 ret = validate_name(hls->nb_varstreams, hls->subtitle_filename);
2430 if (hls->master_pl_name) {
2431 ret = update_master_pl_info(s);
2433 av_log(s, AV_LOG_ERROR, "Master stream info update failed with status %x\n",
2439 if (hls->segment_type == SEGMENT_TYPE_FMP4) {
2442 if ((hls->start_sequence_source_type == HLS_START_SEQUENCE_AS_SECONDS_SINCE_EPOCH) ||
2443 (hls->start_sequence_source_type == HLS_START_SEQUENCE_AS_FORMATTED_DATETIME)) {
2444 time_t t = time(NULL); // we will need it in either case
2445 if (hls->start_sequence_source_type == HLS_START_SEQUENCE_AS_SECONDS_SINCE_EPOCH) {
2446 hls->start_sequence = (int64_t)t;
2447 } else if (hls->start_sequence_source_type == HLS_START_SEQUENCE_AS_FORMATTED_DATETIME) {
2449 struct tm *p, tmbuf;
2450 if (!(p = localtime_r(&t, &tmbuf)))
2451 return AVERROR(ENOMEM);
2452 if (!strftime(b, sizeof(b), "%Y%m%d%H%M%S", p))
2453 return AVERROR(ENOMEM);
2454 hls->start_sequence = strtoll(b, NULL, 10);
2456 av_log(hls, AV_LOG_DEBUG, "start_number evaluated to %"PRId64"\n", hls->start_sequence);
2459 hls->recording_time = (hls->init_time ? hls->init_time : hls->time) * AV_TIME_BASE;
2460 for (i = 0; i < hls->nb_varstreams; i++) {
2461 vs = &hls->var_streams[i];
2463 vs->m3u8_name = av_strdup(s->url);
2464 if (!vs->m3u8_name ) {
2465 ret = AVERROR(ENOMEM);
2468 ret = format_name(vs->m3u8_name, strlen(s->url) + 1, i);
2472 vs->sequence = hls->start_sequence;
2473 vs->start_pts = AV_NOPTS_VALUE;
2474 vs->end_pts = AV_NOPTS_VALUE;
2475 vs->current_segment_final_filename_fmt[0] = '\0';
2477 if (hls->flags & HLS_SPLIT_BY_TIME && hls->flags & HLS_INDEPENDENT_SEGMENTS) {
2478 // Independent segments cannot be guaranteed when splitting by time
2479 hls->flags &= ~HLS_INDEPENDENT_SEGMENTS;
2480 av_log(s, AV_LOG_WARNING,
2481 "'split_by_time' and 'independent_segments' cannot be enabled together. "
2482 "Disabling 'independent_segments' flag\n");
2485 if (hls->flags & HLS_PROGRAM_DATE_TIME) {
2488 vs->initial_prog_date_time = now0;
2490 if (hls->format_options_str) {
2491 ret = av_dict_parse_string(&hls->format_options, hls->format_options_str, "=", ":", 0);
2493 av_log(s, AV_LOG_ERROR, "Could not parse format options list '%s'\n", hls->format_options_str);
2498 for (j = 0; j < vs->nb_streams; j++) {
2499 vs->has_video += vs->streams[j]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO;
2500 vs->has_subtitle += vs->streams[j]->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE;
2503 if (vs->has_video > 1)
2504 av_log(s, AV_LOG_WARNING, "More than a single video stream present, expect issues decoding it.\n");
2505 if (hls->segment_type == SEGMENT_TYPE_FMP4) {
2506 vs->oformat = av_guess_format("mp4", NULL, NULL);
2508 vs->oformat = av_guess_format("mpegts", NULL, NULL);
2512 ret = AVERROR_MUXER_NOT_FOUND;
2516 if (vs->has_subtitle) {
2517 vs->vtt_oformat = av_guess_format("webvtt", NULL, NULL);
2519 ret = AVERROR_MUXER_NOT_FOUND;
2523 if (hls->segment_filename) {
2524 basename_size = strlen(hls->segment_filename) + 1;
2525 vs->basename = av_malloc(basename_size);
2526 if (!vs->basename) {
2527 ret = AVERROR(ENOMEM);
2531 av_strlcpy(vs->basename, hls->segment_filename, basename_size);
2532 ret = format_name(vs->basename, basename_size, i);
2536 if (hls->flags & HLS_SINGLE_FILE) {
2537 if (hls->segment_type == SEGMENT_TYPE_FMP4) {
2544 if (hls->use_localtime) {
2545 basename_size = strlen(vs->m3u8_name) + strlen(pattern_localtime_fmt) + 1;
2547 basename_size = strlen(vs->m3u8_name) + strlen(pattern) + 1;
2550 vs->basename = av_malloc(basename_size);
2551 if (!vs->basename) {
2552 ret = AVERROR(ENOMEM);
2556 av_strlcpy(vs->basename, vs->m3u8_name, basename_size);
2558 p = strrchr(vs->basename, '.');
2561 if (hls->use_localtime) {
2562 av_strlcat(vs->basename, pattern_localtime_fmt, basename_size);
2564 av_strlcat(vs->basename, pattern, basename_size);
2568 if (hls->segment_type == SEGMENT_TYPE_FMP4) {
2569 if (hls->nb_varstreams > 1)
2570 fmp4_init_filename_len += strlen(POSTFIX_PATTERN);
2571 vs->fmp4_init_filename = av_malloc(fmp4_init_filename_len);
2572 if (!vs->fmp4_init_filename ) {
2573 ret = AVERROR(ENOMEM);
2576 av_strlcpy(vs->fmp4_init_filename, hls->fmp4_init_filename,
2577 fmp4_init_filename_len);
2579 if (av_strcasecmp(hls->fmp4_init_filename, "init.mp4")) {
2580 ret = format_name(vs->fmp4_init_filename, fmp4_init_filename_len, i);
2584 fmp4_init_filename_len = strlen(vs->fmp4_init_filename) + 1;
2585 vs->base_output_dirname = av_malloc(fmp4_init_filename_len);
2586 if (!vs->base_output_dirname) {
2587 ret = AVERROR(ENOMEM);
2590 av_strlcpy(vs->base_output_dirname, vs->fmp4_init_filename,
2591 fmp4_init_filename_len);
2593 if (hls->nb_varstreams > 1) {
2594 ret = append_postfix(vs->fmp4_init_filename, fmp4_init_filename_len, i);
2599 fmp4_init_filename_len = strlen(vs->m3u8_name) +
2600 strlen(vs->fmp4_init_filename) + 1;
2602 vs->base_output_dirname = av_malloc(fmp4_init_filename_len);
2603 if (!vs->base_output_dirname) {
2604 ret = AVERROR(ENOMEM);
2608 av_strlcpy(vs->base_output_dirname, vs->m3u8_name,
2609 fmp4_init_filename_len);
2610 p = strrchr(vs->base_output_dirname, '/');
2613 av_strlcat(vs->base_output_dirname, vs->fmp4_init_filename,
2614 fmp4_init_filename_len);
2616 av_strlcpy(vs->base_output_dirname, vs->fmp4_init_filename,
2617 fmp4_init_filename_len);
2622 if (!hls->use_localtime) {
2623 ret = sls_flag_check_duration_size_index(hls);
2628 ret = sls_flag_check_duration_size(hls, vs);
2633 if (vs->has_subtitle) {
2635 if (hls->flags & HLS_SINGLE_FILE)
2636 vtt_pattern = ".vtt";
2637 vtt_basename_size = strlen(vs->m3u8_name) + strlen(vtt_pattern) + 1;
2639 vs->vtt_basename = av_malloc(vtt_basename_size);
2640 if (!vs->vtt_basename) {
2641 ret = AVERROR(ENOMEM);
2644 vs->vtt_m3u8_name = av_malloc(vtt_basename_size);
2645 if (!vs->vtt_m3u8_name ) {
2646 ret = AVERROR(ENOMEM);
2649 av_strlcpy(vs->vtt_basename, vs->m3u8_name, vtt_basename_size);
2650 p = strrchr(vs->vtt_basename, '.');
2654 if ( hls->subtitle_filename ) {
2655 strcpy(vs->vtt_m3u8_name, hls->subtitle_filename);
2656 ret = format_name(vs->vtt_m3u8_name, vtt_basename_size, i);
2660 strcpy(vs->vtt_m3u8_name, vs->vtt_basename);
2661 av_strlcat(vs->vtt_m3u8_name, "_vtt.m3u8", vtt_basename_size);
2663 av_strlcat(vs->vtt_basename, vtt_pattern, vtt_basename_size);
2667 vs->baseurl = av_strdup(hls->baseurl);
2669 ret = AVERROR(ENOMEM);
2674 if ((hls->flags & HLS_SINGLE_FILE) && (hls->segment_type == SEGMENT_TYPE_FMP4)) {
2675 vs->fmp4_init_filename = av_strdup(vs->basename);
2676 if (!vs->fmp4_init_filename) {
2677 ret = AVERROR(ENOMEM);
2681 if ((ret = hls_mux_init(s, vs)) < 0)
2684 if (hls->flags & HLS_APPEND_LIST) {
2685 parse_playlist(s, vs->m3u8_name, vs);
2686 vs->discontinuity = 1;
2687 if (hls->init_time > 0) {
2688 av_log(s, AV_LOG_WARNING, "append_list mode does not support hls_init_time,"
2689 " hls_init_time value will have no effect\n");
2691 hls->recording_time = hls->time * AV_TIME_BASE;
2695 if ((ret = hls_start(s, vs)) < 0)
2701 av_freep(&hls->key_basename);
2702 for (i = 0; i < hls->nb_varstreams && hls->var_streams; i++) {
2703 vs = &hls->var_streams[i];
2704 av_freep(&vs->basename);
2705 av_freep(&vs->vtt_basename);
2706 av_freep(&vs->fmp4_init_filename);
2707 av_freep(&vs->m3u8_name);
2708 av_freep(&vs->vtt_m3u8_name);
2709 av_freep(&vs->streams);
2710 av_freep(&vs->agroup);
2711 av_freep(&vs->ccgroup);
2712 av_freep(&vs->baseurl);
2714 avformat_free_context(vs->avf);
2716 avformat_free_context(vs->vtt_avf);
2718 for (i = 0; i < hls->nb_ccstreams; i++) {
2719 ClosedCaptionsStream *ccs = &hls->cc_streams[i];
2720 av_freep(&ccs->ccgroup);
2721 av_freep(&ccs->instreamid);
2722 av_freep(&ccs->language);
2724 av_freep(&hls->var_streams);
2725 av_freep(&hls->cc_streams);
2726 av_freep(&hls->master_m3u8_url);
2732 #define OFFSET(x) offsetof(HLSContext, x)
2733 #define E AV_OPT_FLAG_ENCODING_PARAM
2734 static const AVOption options[] = {
2735 {"start_number", "set first number in the sequence", OFFSET(start_sequence),AV_OPT_TYPE_INT64, {.i64 = 0}, 0, INT64_MAX, E},
2736 {"hls_time", "set segment length in seconds", OFFSET(time), AV_OPT_TYPE_FLOAT, {.dbl = 2}, 0, FLT_MAX, E},
2737 {"hls_init_time", "set segment length in seconds at init list", OFFSET(init_time), AV_OPT_TYPE_FLOAT, {.dbl = 0}, 0, FLT_MAX, E},
2738 {"hls_list_size", "set maximum number of playlist entries", OFFSET(max_nb_segments), AV_OPT_TYPE_INT, {.i64 = 5}, 0, INT_MAX, E},
2739 {"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},
2740 {"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},
2742 {"hls_wrap", "set number after which the index wraps (will be deprecated)", OFFSET(wrap), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E},
2744 {"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},
2745 {"hls_base_url", "url to prepend to each playlist entry", OFFSET(baseurl), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
2746 {"hls_segment_filename", "filename template for segment files", OFFSET(segment_filename), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
2747 {"hls_segment_size", "maximum size per segment file, (in bytes)", OFFSET(max_seg_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E},
2748 {"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},
2749 {"hls_enc", "enable AES128 encryption support", OFFSET(encrypt), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, E},
2750 {"hls_enc_key", "hex-coded 16 byte key to encrypt the segments", OFFSET(key), AV_OPT_TYPE_STRING, .flags = E},
2751 {"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},
2752 {"hls_enc_iv", "hex-coded 16 byte initialization vector", OFFSET(iv), AV_OPT_TYPE_STRING, .flags = E},
2753 {"hls_subtitle_path", "set path of hls subtitles", OFFSET(subtitle_filename), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
2754 {"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"},
2755 {"mpegts", "make segment file to mpegts files in m3u8", 0, AV_OPT_TYPE_CONST, {.i64 = SEGMENT_TYPE_MPEGTS }, 0, UINT_MAX, E, "segment_type"},
2756 {"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"},
2757 {"hls_fmp4_init_filename", "set fragment mp4 file init filename", OFFSET(fmp4_init_filename), AV_OPT_TYPE_STRING, {.str = "init.mp4"}, 0, 0, E},
2758 {"hls_flags", "set flags affecting HLS playlist and media file generation", OFFSET(flags), AV_OPT_TYPE_FLAGS, {.i64 = 0 }, 0, UINT_MAX, E, "flags"},
2759 {"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"},
2760 {"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"},
2761 {"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"},
2762 {"round_durations", "round durations in m3u8 to whole numbers", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_ROUND_DURATIONS }, 0, UINT_MAX, E, "flags"},
2763 {"discont_start", "start the playlist with a discontinuity tag", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_DISCONT_START }, 0, UINT_MAX, E, "flags"},
2764 {"omit_endlist", "Do not append an endlist when ending stream", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_OMIT_ENDLIST }, 0, UINT_MAX, E, "flags"},
2765 {"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"},
2766 {"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"},
2767 {"program_date_time", "add EXT-X-PROGRAM-DATE-TIME", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_PROGRAM_DATE_TIME }, 0, UINT_MAX, E, "flags"},
2768 {"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"},
2769 {"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"},
2770 {"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"},
2771 {"periodic_rekey", "reload keyinfo file periodically for re-keying", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_PERIODIC_REKEY }, 0, UINT_MAX, E, "flags"},
2772 {"independent_segments", "add EXT-X-INDEPENDENT-SEGMENTS, whenever applicable", 0, AV_OPT_TYPE_CONST, { .i64 = HLS_INDEPENDENT_SEGMENTS }, 0, UINT_MAX, E, "flags"},
2773 {"use_localtime", "set filename expansion with strftime at segment creation", OFFSET(use_localtime), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, E },
2774 {"use_localtime_mkdir", "create last directory component in strftime-generated filename", OFFSET(use_localtime_mkdir), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, E },
2775 {"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" },
2776 {"event", "EVENT playlist", 0, AV_OPT_TYPE_CONST, {.i64 = PLAYLIST_TYPE_EVENT }, INT_MIN, INT_MAX, E, "pl_type" },
2777 {"vod", "VOD playlist", 0, AV_OPT_TYPE_CONST, {.i64 = PLAYLIST_TYPE_VOD }, INT_MIN, INT_MAX, E, "pl_type" },
2778 {"method", "set the HTTP method(default: PUT)", OFFSET(method), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
2779 {"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" },
2780 {"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" },
2781 {"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" },
2782 {"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" },
2783 {"http_user_agent", "override User-Agent field in HTTP header", OFFSET(user_agent), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
2784 {"var_stream_map", "Variant stream map string", OFFSET(var_stream_map), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
2785 {"cc_stream_map", "Closed captions stream map string", OFFSET(cc_stream_map), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
2786 {"master_pl_name", "Create HLS master playlist with this name", OFFSET(master_pl_name), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
2787 {"master_pl_publish_rate", "Publish master play list every after this many segment intervals", OFFSET(master_publish_rate), AV_OPT_TYPE_INT, {.i64 = 0}, 0, UINT_MAX, E},
2788 {"http_persistent", "Use persistent HTTP connections", OFFSET(http_persistent), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, E },
2792 static const AVClass hls_class = {
2793 .class_name = "hls muxer",
2794 .item_name = av_default_item_name,
2796 .version = LIBAVUTIL_VERSION_INT,
2800 AVOutputFormat ff_hls_muxer = {
2802 .long_name = NULL_IF_CONFIG_SMALL("Apple HTTP Live Streaming"),
2803 .extensions = "m3u8",
2804 .priv_data_size = sizeof(HLSContext),
2805 .audio_codec = AV_CODEC_ID_AAC,
2806 .video_codec = AV_CODEC_ID_H264,
2807 .subtitle_codec = AV_CODEC_ID_WEBVTT,
2808 .flags = AVFMT_NOFILE | AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH,
2810 .write_header = hls_write_header,
2811 .write_packet = hls_write_packet,
2812 .write_trailer = hls_write_trailer,
2813 .priv_class = &hls_class,