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 MAX_URL_SIZE
68 #define HLS_MICROSECOND_UNIT 1000000
69 #define POSTFIX_PATTERN "_%d"
71 typedef struct HLSSegment {
72 char filename[MAX_URL_SIZE];
73 char sub_filename[MAX_URL_SIZE];
74 double duration; /* in seconds */
79 int64_t keyframe_size;
80 unsigned var_stream_idx;
82 char key_uri[LINE_BUFFER_SIZE + 1];
83 char iv_string[KEYSIZE*2 + 1];
85 struct HLSSegment *next;
88 typedef enum HLSFlags {
89 // Generate a single media file and use byte ranges in the playlist.
90 HLS_SINGLE_FILE = (1 << 0),
91 HLS_DELETE_SEGMENTS = (1 << 1),
92 HLS_ROUND_DURATIONS = (1 << 2),
93 HLS_DISCONT_START = (1 << 3),
94 HLS_OMIT_ENDLIST = (1 << 4),
95 HLS_SPLIT_BY_TIME = (1 << 5),
96 HLS_APPEND_LIST = (1 << 6),
97 HLS_PROGRAM_DATE_TIME = (1 << 7),
98 HLS_SECOND_LEVEL_SEGMENT_INDEX = (1 << 8), // include segment index in segment filenames when use_localtime e.g.: %%03d
99 HLS_SECOND_LEVEL_SEGMENT_DURATION = (1 << 9), // include segment duration (microsec) in segment filenames when use_localtime e.g.: %%09t
100 HLS_SECOND_LEVEL_SEGMENT_SIZE = (1 << 10), // include segment size (bytes) in segment filenames when use_localtime e.g.: %%014s
101 HLS_TEMP_FILE = (1 << 11),
102 HLS_PERIODIC_REKEY = (1 << 12),
103 HLS_INDEPENDENT_SEGMENTS = (1 << 13),
104 HLS_I_FRAMES_ONLY = (1 << 14),
112 typedef struct VariantStream {
113 unsigned var_stream_idx;
116 ff_const59 AVOutputFormat *oformat;
117 ff_const59 AVOutputFormat *vtt_oformat;
120 int init_range_length;
122 AVFormatContext *avf;
123 AVFormatContext *vtt_avf;
128 double dpp; // duration per packet
131 int64_t video_lastpos;
132 int64_t video_keyframe_pos;
133 int64_t video_keyframe_size;
134 double duration; // last segment duration computed so far, in seconds
135 int64_t start_pos; // last segment starting position
136 int64_t size; // last segment size
138 int discontinuity_set;
140 int reference_stream_index;
142 HLSSegment *segments;
143 HLSSegment *last_segment;
144 HLSSegment *old_segments;
151 double initial_prog_date_time;
152 char current_segment_final_filename_fmt[MAX_URL_SIZE]; // when renaming segments
154 char *fmp4_init_filename;
155 char *base_output_dirname;
158 char codec_attr[128];
159 CodecAttributeStatus attr_status;
160 unsigned int nb_streams;
161 int m3u8_created; /* status of media play-list creation */
162 int is_default; /* default status of audio group */
163 char *language; /* audio lauguage name */
164 char *agroup; /* audio group name */
165 char *ccgroup; /* closed caption group name */
167 char *varname; // variant name
170 typedef struct ClosedCaptionsStream {
171 char *ccgroup; /* closed caption group name */
172 char *instreamid; /* closed captions INSTREAM-ID */
173 char *language; /* closed captions langauge */
174 } ClosedCaptionsStream;
176 typedef struct HLSContext {
177 const AVClass *class; // Class for private options.
178 int64_t start_sequence;
179 uint32_t start_sequence_source_type; // enum StartSequenceSourceType
181 float time; // Set by a private option.
182 float init_time; // Set by a private option.
183 int max_nb_segments; // Set by a private option.
184 int hls_delete_threshold; // Set by a private option.
186 int wrap; // Set by a private option.
188 uint32_t flags; // enum HLSFlags
189 uint32_t pl_type; // enum PlaylistType
190 char *segment_filename;
191 char *fmp4_init_filename;
194 int use_localtime; ///< flag to expand filename with localtime
195 int use_localtime_mkdir;///< flag to mkdir dirname in timebased filename
197 int64_t recording_time;
198 int64_t max_seg_size; // every segment file max size
201 char *format_options_str;
202 char *vtt_format_options_str;
203 char *subtitle_filename;
204 AVDictionary *format_options;
214 char key_file[LINE_BUFFER_SIZE + 1];
215 char key_uri[LINE_BUFFER_SIZE + 1];
216 char key_string[KEYSIZE*2 + 1];
217 char iv_string[KEYSIZE*2 + 1];
218 AVDictionary *vtt_format_options;
223 VariantStream *var_streams;
224 unsigned int nb_varstreams;
225 ClosedCaptionsStream *cc_streams;
226 unsigned int nb_ccstreams;
228 int master_m3u8_created; /* status of master play-list creation */
229 char *master_m3u8_url; /* URL of the master m3u8 file */
230 int version; /* HLS version */
231 char *var_stream_map; /* user specified variant stream map string */
232 char *cc_stream_map; /* user specified closed caption streams map string */
233 char *master_pl_name;
234 unsigned int master_publish_rate;
236 AVIOContext *m3u8_out;
237 AVIOContext *sub_m3u8_out;
239 int ignore_io_errors;
241 int has_default_key; /* has DEFAULT field of var_stream_map */
242 int has_video_m3u8; /* has video stream m3u8 list */
245 static int hlsenc_io_open(AVFormatContext *s, AVIOContext **pb, char *filename,
246 AVDictionary **options) {
247 HLSContext *hls = s->priv_data;
248 int http_base_proto = filename ? ff_is_http_proto(filename) : 0;
249 int err = AVERROR_MUXER_NOT_FOUND;
250 if (!*pb || !http_base_proto || !hls->http_persistent) {
251 err = s->io_open(s, pb, filename, AVIO_FLAG_WRITE, options);
252 #if CONFIG_HTTP_PROTOCOL
254 URLContext *http_url_context = ffio_geturlcontext(*pb);
255 av_assert0(http_url_context);
256 err = ff_http_do_new_request(http_url_context, filename);
258 ff_format_io_close(s, pb);
265 static void hlsenc_io_close(AVFormatContext *s, AVIOContext **pb, char *filename) {
266 HLSContext *hls = s->priv_data;
267 int http_base_proto = filename ? ff_is_http_proto(filename) : 0;
270 if (!http_base_proto || !hls->http_persistent || hls->key_info_file || hls->encrypt) {
271 ff_format_io_close(s, pb);
272 #if CONFIG_HTTP_PROTOCOL
274 URLContext *http_url_context = ffio_geturlcontext(*pb);
275 av_assert0(http_url_context);
277 ffurl_shutdown(http_url_context, AVIO_FLAG_WRITE);
282 static void set_http_options(AVFormatContext *s, AVDictionary **options, HLSContext *c)
284 int http_base_proto = ff_is_http_proto(s->url);
287 av_dict_set(options, "method", c->method, 0);
288 } else if (http_base_proto) {
289 av_log(c, AV_LOG_WARNING, "No HTTP method set, hls muxer defaulting to method PUT.\n");
290 av_dict_set(options, "method", "PUT", 0);
293 av_dict_set(options, "user_agent", c->user_agent, 0);
294 if (c->http_persistent)
295 av_dict_set_int(options, "multiple_requests", 1, 0);
297 av_dict_set_int(options, "timeout", c->timeout, 0);
299 av_dict_set(options, "headers", c->headers, 0);
302 static void write_codec_attr(AVStream *st, VariantStream *vs) {
303 int codec_strlen = strlen(vs->codec_attr);
306 if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE)
308 if (vs->attr_status == CODEC_ATTRIBUTE_WILL_NOT_BE_WRITTEN)
311 if (st->codecpar->codec_id == AV_CODEC_ID_H264) {
312 uint8_t *data = st->codecpar->extradata;
313 if (data && (data[0] | data[1] | data[2]) == 0 && data[3] == 1 && (data[4] & 0x1F) == 7) {
314 snprintf(attr, sizeof(attr),
315 "avc1.%02x%02x%02x", data[5], data[6], data[7]);
319 } else if (st->codecpar->codec_id == AV_CODEC_ID_MP2) {
320 snprintf(attr, sizeof(attr), "mp4a.40.33");
321 } else if (st->codecpar->codec_id == AV_CODEC_ID_MP3) {
322 snprintf(attr, sizeof(attr), "mp4a.40.34");
323 } else if (st->codecpar->codec_id == AV_CODEC_ID_AAC) {
324 /* TODO : For HE-AAC, HE-AACv2, the last digit needs to be set to 5 and 29 respectively */
325 snprintf(attr, sizeof(attr), "mp4a.40.2");
326 } else if (st->codecpar->codec_id == AV_CODEC_ID_AC3) {
327 snprintf(attr, sizeof(attr), "ac-3");
328 } else if (st->codecpar->codec_id == AV_CODEC_ID_EAC3) {
329 snprintf(attr, sizeof(attr), "ec-3");
333 // Don't write the same attribute multiple times
334 if (!av_stristr(vs->codec_attr, attr)) {
335 snprintf(vs->codec_attr + codec_strlen,
336 sizeof(vs->codec_attr) - codec_strlen,
337 "%s%s", codec_strlen ? "," : "", attr);
342 vs->codec_attr[0] = '\0';
343 vs->attr_status = CODEC_ATTRIBUTE_WILL_NOT_BE_WRITTEN;
347 static int replace_str_data_in_filename(char **s, const char *filename, char placeholder, const char *datastring)
356 av_bprint_init(&buf, 0, AV_BPRINT_SIZE_UNLIMITED);
363 if (c == '%' && *(p+1) == '%') // %%
365 else if (c == '%' && *(p+1) == placeholder) {
366 av_bprintf(&buf, "%s", datastring);
373 if (addchar_count > 0) {
374 av_bprint_append_data(&buf, p, addchar_count);
378 if (!av_bprint_is_complete(&buf)) {
379 av_bprint_finalize(&buf, NULL);
382 if (av_bprint_finalize(&buf, &new_filename) < 0 || !new_filename)
388 static int replace_int_data_in_filename(char **s, const char *filename, char placeholder, int64_t number)
393 int nd, addchar_count;
397 av_bprint_init(&buf, 0, AV_BPRINT_SIZE_UNLIMITED);
404 if (c == '%' && *(p+1) == '%') // %%
406 else if (c == '%' && (av_isdigit(*(p+1)) || *(p+1) == placeholder)) {
409 while (av_isdigit(*(p + addchar_count))) {
410 nd = nd * 10 + *(p + addchar_count) - '0';
414 if (*(p + addchar_count) == placeholder) {
415 av_bprintf(&buf, "%0*"PRId64, (number < 0) ? nd : nd++, number);
416 p += (addchar_count + 1);
424 av_bprint_append_data(&buf, p, addchar_count);
427 if (!av_bprint_is_complete(&buf)) {
428 av_bprint_finalize(&buf, NULL);
431 if (av_bprint_finalize(&buf, &new_filename) < 0 || !new_filename)
437 static void write_styp(AVIOContext *pb)
440 ffio_wfourcc(pb, "styp");
441 ffio_wfourcc(pb, "msdh");
442 avio_wb32(pb, 0); /* minor */
443 ffio_wfourcc(pb, "msdh");
444 ffio_wfourcc(pb, "msix");
447 static int flush_dynbuf(VariantStream *vs, int *range_length)
449 AVFormatContext *ctx = vs->avf;
453 return AVERROR(EINVAL);
457 av_write_frame(ctx, NULL);
461 *range_length = avio_close_dyn_buf(ctx->pb, &buffer);
463 avio_write(vs->out, buffer, *range_length);
467 return avio_open_dyn_buf(&ctx->pb);
470 static int hls_delete_old_segments(AVFormatContext *s, HLSContext *hls,
473 HLSSegment *segment, *previous_segment = NULL;
474 float playlist_duration = 0.0f;
475 int ret = 0, path_size, sub_path_size;
477 char *dirname = NULL, *p, *sub_path;
479 char *vtt_dirname = NULL;
480 AVDictionary *options = NULL;
481 AVIOContext *out = NULL;
482 const char *proto = NULL;
484 segment = vs->segments;
486 playlist_duration += segment->duration;
487 segment = segment->next;
490 segment = vs->old_segments;
493 playlist_duration -= segment->duration;
494 previous_segment = segment;
495 segment = previous_segment->next;
497 if (playlist_duration <= -previous_segment->duration) {
498 previous_segment->next = NULL;
501 if (segment_cnt >= hls->hls_delete_threshold) {
502 previous_segment->next = NULL;
507 if (segment && !hls->use_localtime_mkdir) {
508 dirname = hls->segment_filename ? av_strdup(hls->segment_filename): av_strdup(vs->avf->url);
510 ret = AVERROR(ENOMEM);
513 p = (char *)av_basename(dirname);
517 /* if %v is present in the file's directory
518 * all segment belongs to the same variant, so do it only once before the loop*/
519 if (dirname && av_stristr(dirname, "%v")) {
520 char * r_dirname = dirname;
522 if (replace_int_data_in_filename(&r_dirname, dirname, 'v', segment->var_stream_idx) < 1) {
523 ret = AVERROR(EINVAL);
527 if (replace_str_data_in_filename(&r_dirname, dirname, 'v', vs->varname) < 1) {
528 ret = AVERROR(EINVAL);
538 av_log(hls, AV_LOG_DEBUG, "deleting old segment %s\n",
540 path_size = (hls->use_localtime_mkdir ? 0 : strlen(dirname)) + strlen(segment->filename) + 1;
541 path = av_malloc(path_size);
543 ret = AVERROR(ENOMEM);
547 if (hls->use_localtime_mkdir)
548 av_strlcpy(path, segment->filename, path_size);
549 else { // segment->filename contains basename only
550 av_strlcpy(path, dirname, path_size);
551 av_strlcat(path, segment->filename, path_size);
554 proto = avio_find_protocol_name(s->url);
555 if (hls->method || (proto && !av_strcasecmp(proto, "http"))) {
556 av_dict_set(&options, "method", "DELETE", 0);
557 if ((ret = vs->avf->io_open(vs->avf, &out, path, AVIO_FLAG_WRITE, &options)) < 0) {
558 if (hls->ignore_io_errors)
562 ff_format_io_close(vs->avf, &out);
563 } else if (unlink(path) < 0) {
564 av_log(hls, AV_LOG_ERROR, "failed to delete old segment %s: %s\n",
565 path, strerror(errno));
568 if ((segment->sub_filename[0] != '\0')) {
569 vtt_dirname = av_strdup(vs->vtt_avf->url);
571 ret = AVERROR(ENOMEM);
574 p = (char *)av_basename(vtt_dirname);
576 sub_path_size = strlen(segment->sub_filename) + 1 + strlen(vtt_dirname);
577 sub_path = av_malloc(sub_path_size);
579 ret = AVERROR(ENOMEM);
583 av_strlcpy(sub_path, vtt_dirname, sub_path_size);
584 av_strlcat(sub_path, segment->sub_filename, sub_path_size);
586 if (hls->method || (proto && !av_strcasecmp(proto, "http"))) {
587 av_dict_set(&options, "method", "DELETE", 0);
588 if ((ret = vs->vtt_avf->io_open(vs->vtt_avf, &out, sub_path, AVIO_FLAG_WRITE, &options)) < 0) {
589 if (hls->ignore_io_errors)
594 ff_format_io_close(vs->vtt_avf, &out);
595 } else if (unlink(sub_path) < 0) {
596 av_log(hls, AV_LOG_ERROR, "failed to delete old segment %s: %s\n",
597 sub_path, strerror(errno));
602 previous_segment = segment;
603 segment = previous_segment->next;
604 av_free(previous_segment);
610 av_free(vtt_dirname);
615 static int randomize(uint8_t *buf, int len)
618 gcry_randomize(buf, len, GCRY_VERY_STRONG_RANDOM);
621 if (RAND_bytes(buf, len))
624 return AVERROR(ENOSYS);
626 return AVERROR(EINVAL);
629 static int do_encrypt(AVFormatContext *s, VariantStream *vs)
631 HLSContext *hls = s->priv_data;
635 uint8_t key[KEYSIZE];
637 len = strlen(s->url) + 4 + 1;
638 hls->key_basename = av_mallocz(len);
639 if (!hls->key_basename)
640 return AVERROR(ENOMEM);
642 av_strlcpy(hls->key_basename, s->url, len);
643 av_strlcat(hls->key_basename, ".key", len);
646 av_strlcpy(hls->key_file, hls->key_url, sizeof(hls->key_file));
647 av_strlcpy(hls->key_uri, hls->key_url, sizeof(hls->key_uri));
649 av_strlcpy(hls->key_file, hls->key_basename, sizeof(hls->key_file));
650 av_strlcpy(hls->key_uri, hls->key_basename, sizeof(hls->key_uri));
653 if (!*hls->iv_string) {
654 uint8_t iv[16] = { 0 };
658 AV_WB64(iv + 8, vs->sequence);
660 memcpy(iv, hls->iv, sizeof(iv));
662 ff_data_to_hex(buf, iv, sizeof(iv), 0);
664 memcpy(hls->iv_string, buf, sizeof(hls->iv_string));
667 if (!*hls->key_uri) {
668 av_log(hls, AV_LOG_ERROR, "no key URI specified in key info file\n");
669 return AVERROR(EINVAL);
672 if (!*hls->key_file) {
673 av_log(hls, AV_LOG_ERROR, "no key file specified in key info file\n");
674 return AVERROR(EINVAL);
677 if (!*hls->key_string) {
679 if ((ret = randomize(key, sizeof(key))) < 0) {
680 av_log(s, AV_LOG_ERROR, "Cannot generate a strong random key\n");
684 memcpy(key, hls->key, sizeof(key));
687 ff_data_to_hex(hls->key_string, key, sizeof(key), 0);
688 if ((ret = s->io_open(s, &pb, hls->key_file, AVIO_FLAG_WRITE, NULL)) < 0)
690 avio_seek(pb, 0, SEEK_CUR);
691 avio_write(pb, key, KEYSIZE);
698 static int hls_encryption_start(AVFormatContext *s)
700 HLSContext *hls = s->priv_data;
703 uint8_t key[KEYSIZE];
705 if ((ret = s->io_open(s, &pb, hls->key_info_file, AVIO_FLAG_READ, NULL)) < 0) {
706 av_log(hls, AV_LOG_ERROR,
707 "error opening key info file %s\n", hls->key_info_file);
711 ff_get_line(pb, hls->key_uri, sizeof(hls->key_uri));
712 hls->key_uri[strcspn(hls->key_uri, "\r\n")] = '\0';
714 ff_get_line(pb, hls->key_file, sizeof(hls->key_file));
715 hls->key_file[strcspn(hls->key_file, "\r\n")] = '\0';
717 ff_get_line(pb, hls->iv_string, sizeof(hls->iv_string));
718 hls->iv_string[strcspn(hls->iv_string, "\r\n")] = '\0';
720 ff_format_io_close(s, &pb);
722 if (!*hls->key_uri) {
723 av_log(hls, AV_LOG_ERROR, "no key URI specified in key info file\n");
724 return AVERROR(EINVAL);
727 if (!*hls->key_file) {
728 av_log(hls, AV_LOG_ERROR, "no key file specified in key info file\n");
729 return AVERROR(EINVAL);
732 if ((ret = s->io_open(s, &pb, hls->key_file, AVIO_FLAG_READ, NULL)) < 0) {
733 av_log(hls, AV_LOG_ERROR, "error opening key file %s\n", hls->key_file);
737 ret = avio_read(pb, key, sizeof(key));
738 ff_format_io_close(s, &pb);
739 if (ret != sizeof(key)) {
740 av_log(hls, AV_LOG_ERROR, "error reading key file %s\n", hls->key_file);
741 if (ret >= 0 || ret == AVERROR_EOF)
742 ret = AVERROR(EINVAL);
745 ff_data_to_hex(hls->key_string, key, sizeof(key), 0);
750 static int hls_mux_init(AVFormatContext *s, VariantStream *vs)
752 AVDictionary *options = NULL;
753 HLSContext *hls = s->priv_data;
755 AVFormatContext *vtt_oc = NULL;
756 int byterange_mode = (hls->flags & HLS_SINGLE_FILE) || (hls->max_seg_size > 0);
759 ret = avformat_alloc_output_context2(&vs->avf, vs->oformat, NULL, NULL);
764 oc->url = av_strdup("");
766 return AVERROR(ENOMEM);
768 oc->oformat = vs->oformat;
769 oc->interrupt_callback = s->interrupt_callback;
770 oc->max_delay = s->max_delay;
771 oc->opaque = s->opaque;
772 oc->io_open = s->io_open;
773 oc->io_close = s->io_close;
774 av_dict_copy(&oc->metadata, s->metadata, 0);
776 if(vs->vtt_oformat) {
777 ret = avformat_alloc_output_context2(&vs->vtt_avf, vs->vtt_oformat, NULL, NULL);
780 vtt_oc = vs->vtt_avf;
781 vtt_oc->oformat = vs->vtt_oformat;
782 av_dict_copy(&vtt_oc->metadata, s->metadata, 0);
785 for (i = 0; i < vs->nb_streams; i++) {
787 AVFormatContext *loc;
788 if (vs->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE)
793 if (!(st = avformat_new_stream(loc, NULL)))
794 return AVERROR(ENOMEM);
795 avcodec_parameters_copy(st->codecpar, vs->streams[i]->codecpar);
796 if (!oc->oformat->codec_tag ||
797 av_codec_get_id (oc->oformat->codec_tag, vs->streams[i]->codecpar->codec_tag) == st->codecpar->codec_id ||
798 av_codec_get_tag(oc->oformat->codec_tag, vs->streams[i]->codecpar->codec_id) <= 0) {
799 st->codecpar->codec_tag = vs->streams[i]->codecpar->codec_tag;
801 st->codecpar->codec_tag = 0;
804 st->sample_aspect_ratio = vs->streams[i]->sample_aspect_ratio;
805 st->time_base = vs->streams[i]->time_base;
806 av_dict_copy(&st->metadata, vs->streams[i]->metadata, 0);
809 vs->packets_written = 1;
813 if (hls->segment_type == SEGMENT_TYPE_FMP4 && hls->max_seg_size > 0) {
814 if (hls->http_persistent > 0) {
815 //TODO: Support fragment fmp4 for http persistent in HLS muxer.
816 av_log(s, AV_LOG_WARNING, "http persistent mode is currently unsupported for fragment mp4 in the HLS muxer.\n");
818 if (hls->max_seg_size > 0) {
819 av_log(s, AV_LOG_WARNING, "Multi-file byterange mode is currently unsupported in the HLS muxer.\n");
820 return AVERROR_PATCHWELCOME;
824 vs->packets_written = 0;
825 vs->init_range_length = 0;
826 set_http_options(s, &options, hls);
827 if ((ret = avio_open_dyn_buf(&oc->pb)) < 0)
830 if (hls->segment_type == SEGMENT_TYPE_FMP4) {
831 if (byterange_mode) {
832 ret = hlsenc_io_open(s, &vs->out, vs->basename, &options);
834 ret = hlsenc_io_open(s, &vs->out, vs->base_output_dirname, &options);
837 av_dict_free(&options);
839 av_log(s, AV_LOG_ERROR, "Failed to open segment '%s'\n", vs->fmp4_init_filename);
843 if (hls->format_options_str) {
844 ret = av_dict_parse_string(&hls->format_options, hls->format_options_str, "=", ":", 0);
846 av_log(s, AV_LOG_ERROR, "Could not parse format options list '%s'\n",
847 hls->format_options_str);
852 av_dict_copy(&options, hls->format_options, 0);
853 if (hls->segment_type == SEGMENT_TYPE_FMP4) {
854 av_dict_set(&options, "fflags", "-autobsf", 0);
855 av_dict_set(&options, "movflags", "+frag_custom+dash+delay_moov", AV_DICT_APPEND);
856 ret = avformat_init_output(oc, &options);
859 if (av_dict_count(options)) {
860 av_log(s, AV_LOG_ERROR, "Some of the provided format options in '%s' are not recognized\n", hls->format_options_str);
861 av_dict_free(&options);
862 return AVERROR(EINVAL);
866 av_dict_free(&options);
870 static HLSSegment *find_segment_by_filename(HLSSegment *segment, const char *filename)
873 if (!av_strcasecmp(segment->filename,filename))
875 segment = segment->next;
877 return (HLSSegment *) NULL;
880 static int sls_flags_filename_process(struct AVFormatContext *s, HLSContext *hls,
881 VariantStream *vs, HLSSegment *en,
882 double duration, int64_t pos, int64_t size)
884 if ((hls->flags & (HLS_SECOND_LEVEL_SEGMENT_SIZE | HLS_SECOND_LEVEL_SEGMENT_DURATION)) &&
885 strlen(vs->current_segment_final_filename_fmt)) {
886 char * new_url = av_strdup(vs->current_segment_final_filename_fmt);
889 return AVERROR(ENOMEM);
891 ff_format_set_url(vs->avf, new_url);
892 if (hls->flags & HLS_SECOND_LEVEL_SEGMENT_SIZE) {
893 char *filename = NULL;
894 if (replace_int_data_in_filename(&filename, vs->avf->url, 's', pos + size) < 1) {
895 av_log(hls, AV_LOG_ERROR,
896 "Invalid second level segment filename template '%s', "
897 "you can try to remove second_level_segment_size flag\n",
901 return AVERROR(EINVAL);
903 ff_format_set_url(vs->avf, filename);
905 if (hls->flags & HLS_SECOND_LEVEL_SEGMENT_DURATION) {
906 char *filename = NULL;
907 if (replace_int_data_in_filename(&filename, vs->avf->url,
908 't', (int64_t)round(duration * HLS_MICROSECOND_UNIT)) < 1) {
909 av_log(hls, AV_LOG_ERROR,
910 "Invalid second level segment filename template '%s', "
911 "you can try to remove second_level_segment_time flag\n",
915 return AVERROR(EINVAL);
917 ff_format_set_url(vs->avf, filename);
923 static int sls_flag_check_duration_size_index(HLSContext *hls)
927 if (hls->flags & HLS_SECOND_LEVEL_SEGMENT_DURATION) {
928 av_log(hls, AV_LOG_ERROR,
929 "second_level_segment_duration hls_flag requires strftime to be true\n");
930 ret = AVERROR(EINVAL);
932 if (hls->flags & HLS_SECOND_LEVEL_SEGMENT_SIZE) {
933 av_log(hls, AV_LOG_ERROR,
934 "second_level_segment_size hls_flag requires strfime to be true\n");
935 ret = AVERROR(EINVAL);
937 if (hls->flags & HLS_SECOND_LEVEL_SEGMENT_INDEX) {
938 av_log(hls, AV_LOG_ERROR,
939 "second_level_segment_index hls_flag requires strftime to be true\n");
940 ret = AVERROR(EINVAL);
946 static int sls_flag_check_duration_size(HLSContext *hls, VariantStream *vs)
948 const char *proto = avio_find_protocol_name(vs->basename);
949 int segment_renaming_ok = proto && !strcmp(proto, "file");
952 if ((hls->flags & HLS_SECOND_LEVEL_SEGMENT_DURATION) && !segment_renaming_ok) {
953 av_log(hls, AV_LOG_ERROR,
954 "second_level_segment_duration hls_flag works only with file protocol segment names\n");
955 ret = AVERROR(EINVAL);
957 if ((hls->flags & HLS_SECOND_LEVEL_SEGMENT_SIZE) && !segment_renaming_ok) {
958 av_log(hls, AV_LOG_ERROR,
959 "second_level_segment_size hls_flag works only with file protocol segment names\n");
960 ret = AVERROR(EINVAL);
966 static void sls_flag_file_rename(HLSContext *hls, VariantStream *vs, char *old_filename) {
967 if ((hls->flags & (HLS_SECOND_LEVEL_SEGMENT_SIZE | HLS_SECOND_LEVEL_SEGMENT_DURATION)) &&
968 strlen(vs->current_segment_final_filename_fmt)) {
969 ff_rename(old_filename, vs->avf->url, hls);
973 static int sls_flag_use_localtime_filename(AVFormatContext *oc, HLSContext *c, VariantStream *vs)
975 if (c->flags & HLS_SECOND_LEVEL_SEGMENT_INDEX) {
976 char *filename = NULL;
977 if (replace_int_data_in_filename(&filename,
979 oc->url, 'd', c->wrap ? vs->sequence % c->wrap : vs->sequence) < 1) {
981 oc->url, 'd', vs->sequence) < 1) {
983 av_log(c, AV_LOG_ERROR, "Invalid second level segment filename template '%s', "
984 "you can try to remove second_level_segment_index flag\n",
987 return AVERROR(EINVAL);
989 ff_format_set_url(oc, filename);
991 if (c->flags & (HLS_SECOND_LEVEL_SEGMENT_SIZE | HLS_SECOND_LEVEL_SEGMENT_DURATION)) {
992 av_strlcpy(vs->current_segment_final_filename_fmt, oc->url,
993 sizeof(vs->current_segment_final_filename_fmt));
994 if (c->flags & HLS_SECOND_LEVEL_SEGMENT_SIZE) {
995 char *filename = NULL;
996 if (replace_int_data_in_filename(&filename, oc->url, 's', 0) < 1) {
997 av_log(c, AV_LOG_ERROR, "Invalid second level segment filename template '%s', "
998 "you can try to remove second_level_segment_size flag\n",
1001 return AVERROR(EINVAL);
1003 ff_format_set_url(oc, filename);
1005 if (c->flags & HLS_SECOND_LEVEL_SEGMENT_DURATION) {
1006 char *filename = NULL;
1007 if (replace_int_data_in_filename(&filename, oc->url, 't', 0) < 1) {
1008 av_log(c, AV_LOG_ERROR, "Invalid second level segment filename template '%s', "
1009 "you can try to remove second_level_segment_time flag\n",
1012 return AVERROR(EINVAL);
1014 ff_format_set_url(oc, filename);
1020 /* Create a new segment and append it to the segment list */
1021 static int hls_append_segment(struct AVFormatContext *s, HLSContext *hls,
1022 VariantStream *vs, double duration, int64_t pos,
1025 HLSSegment *en = av_malloc(sizeof(*en));
1026 const char *filename;
1027 int byterange_mode = (hls->flags & HLS_SINGLE_FILE) || (hls->max_seg_size > 0);
1031 return AVERROR(ENOMEM);
1033 en->var_stream_idx = vs->var_stream_idx;
1034 ret = sls_flags_filename_process(s, hls, vs, en, duration, pos, size);
1039 filename = av_basename(vs->avf->url);
1041 if (hls->use_localtime_mkdir) {
1042 filename = vs->avf->url;
1044 if ((find_segment_by_filename(vs->segments, filename) || find_segment_by_filename(vs->old_segments, filename))
1045 && !byterange_mode) {
1046 av_log(hls, AV_LOG_WARNING, "Duplicated segment filename detected: %s\n", filename);
1048 av_strlcpy(en->filename, filename, sizeof(en->filename));
1050 if(vs->has_subtitle)
1051 av_strlcpy(en->sub_filename, av_basename(vs->vtt_avf->url), sizeof(en->sub_filename));
1053 en->sub_filename[0] = '\0';
1055 en->duration = duration;
1058 en->keyframe_pos = vs->video_keyframe_pos;
1059 en->keyframe_size = vs->video_keyframe_size;
1063 if (vs->discontinuity) {
1065 vs->discontinuity = 0;
1068 if (hls->key_info_file || hls->encrypt) {
1069 av_strlcpy(en->key_uri, hls->key_uri, sizeof(en->key_uri));
1070 av_strlcpy(en->iv_string, hls->iv_string, sizeof(en->iv_string));
1076 vs->last_segment->next = en;
1078 vs->last_segment = en;
1080 // EVENT or VOD playlists imply sliding window cannot be used
1081 if (hls->pl_type != PLAYLIST_TYPE_NONE)
1082 hls->max_nb_segments = 0;
1084 if (hls->max_nb_segments && vs->nb_entries >= hls->max_nb_segments) {
1086 vs->initial_prog_date_time += en->duration;
1087 vs->segments = en->next;
1088 if (en && hls->flags & HLS_DELETE_SEGMENTS &&
1090 !(hls->flags & HLS_SINGLE_FILE || hls->wrap)) {
1092 !(hls->flags & HLS_SINGLE_FILE)) {
1094 en->next = vs->old_segments;
1095 vs->old_segments = en;
1096 if ((ret = hls_delete_old_segments(s, hls, vs)) < 0)
1103 if (hls->max_seg_size > 0) {
1111 static int parse_playlist(AVFormatContext *s, const char *url, VariantStream *vs)
1113 HLSContext *hls = s->priv_data;
1115 int ret = 0, is_segment = 0;
1116 int64_t new_start_pos;
1117 char line[MAX_URL_SIZE];
1121 if ((ret = ffio_open_whitelist(&in, url, AVIO_FLAG_READ,
1122 &s->interrupt_callback, NULL,
1123 s->protocol_whitelist, s->protocol_blacklist)) < 0)
1126 ff_get_chomp_line(in, line, sizeof(line));
1127 if (strcmp(line, "#EXTM3U")) {
1128 ret = AVERROR_INVALIDDATA;
1132 vs->discontinuity = 0;
1133 while (!avio_feof(in)) {
1134 ff_get_chomp_line(in, line, sizeof(line));
1135 if (av_strstart(line, "#EXT-X-MEDIA-SEQUENCE:", &ptr)) {
1136 int64_t tmp_sequence = strtoll(ptr, NULL, 10);
1137 if (tmp_sequence < vs->sequence)
1138 av_log(hls, AV_LOG_VERBOSE,
1139 "Found playlist sequence number was smaller """
1140 "than specified start sequence number: %"PRId64" < %"PRId64", "
1141 "omitting\n", tmp_sequence, hls->start_sequence);
1143 av_log(hls, AV_LOG_DEBUG, "Found playlist sequence number: %"PRId64"\n", tmp_sequence);
1144 vs->sequence = tmp_sequence;
1146 } else if (av_strstart(line, "#EXT-X-DISCONTINUITY", &ptr)) {
1148 vs->discontinuity = 1;
1149 } else if (av_strstart(line, "#EXTINF:", &ptr)) {
1151 vs->duration = atof(ptr);
1152 } else if (av_stristart(line, "#EXT-X-KEY:", &ptr)) {
1153 ptr = av_stristr(line, "URI=\"");
1155 ptr += strlen("URI=\"");
1156 end = av_stristr(ptr, ",");
1158 av_strlcpy(hls->key_uri, ptr, end - ptr);
1160 av_strlcpy(hls->key_uri, ptr, sizeof(hls->key_uri));
1164 ptr = av_stristr(line, "IV=0x");
1166 ptr += strlen("IV=0x");
1167 end = av_stristr(ptr, ",");
1169 av_strlcpy(hls->iv_string, ptr, end - ptr);
1171 av_strlcpy(hls->iv_string, ptr, sizeof(hls->iv_string));
1175 } else if (av_strstart(line, "#", NULL)) {
1177 } else if (line[0]) {
1179 char *new_file = av_strdup(line);
1181 ret = AVERROR(ENOMEM);
1184 ff_format_set_url(vs->avf, new_file);
1186 new_start_pos = avio_tell(vs->avf->pb);
1187 vs->size = new_start_pos - vs->start_pos;
1188 ret = hls_append_segment(s, hls, vs, vs->duration, vs->start_pos, vs->size);
1191 vs->start_pos = new_start_pos;
1201 static void hls_free_segments(HLSSegment *p)
1212 static int hls_rename_temp_file(AVFormatContext *s, AVFormatContext *oc)
1214 size_t len = strlen(oc->url);
1215 char *final_filename = av_strdup(oc->url);
1218 if (!final_filename)
1219 return AVERROR(ENOMEM);
1220 final_filename[len-4] = '\0';
1221 ret = ff_rename(oc->url, final_filename, s);
1222 oc->url[len-4] = '\0';
1223 av_freep(&final_filename);
1227 static int get_relative_url(const char *master_url, const char *media_url,
1228 char *rel_url, int rel_url_buf_size)
1232 p = strrchr(master_url, '/') ? strrchr(master_url, '/') :\
1233 strrchr(master_url, '\\');
1235 base_len = FFABS(p - master_url);
1236 if (av_strncasecmp(master_url, media_url, base_len)) {
1237 av_log(NULL, AV_LOG_WARNING, "Unable to find relative url\n");
1238 return AVERROR(EINVAL);
1241 av_strlcpy(rel_url, &(media_url[base_len + 1]), rel_url_buf_size);
1245 static int64_t get_stream_bit_rate(AVStream *stream) {
1246 AVCPBProperties *props = (AVCPBProperties*)av_stream_get_side_data(
1248 AV_PKT_DATA_CPB_PROPERTIES,
1252 if (stream->codecpar->bit_rate)
1253 return stream->codecpar->bit_rate;
1255 return props->max_bitrate;
1260 static int create_master_playlist(AVFormatContext *s,
1261 VariantStream * const input_vs)
1263 HLSContext *hls = s->priv_data;
1264 VariantStream *vs, *temp_vs;
1265 AVStream *vid_st, *aud_st;
1266 AVDictionary *options = NULL;
1268 int m3u8_name_size, ret, bandwidth;
1269 char *m3u8_rel_name = NULL, *ccgroup;
1270 ClosedCaptionsStream *ccs;
1271 const char *proto = avio_find_protocol_name(hls->master_m3u8_url);
1272 int is_file_proto = proto && !strcmp(proto, "file");
1273 int use_temp_file = is_file_proto && ((hls->flags & HLS_TEMP_FILE) || hls->master_publish_rate);
1274 char temp_filename[MAX_URL_SIZE];
1276 input_vs->m3u8_created = 1;
1277 if (!hls->master_m3u8_created) {
1278 /* For the first time, wait until all the media playlists are created */
1279 for (i = 0; i < hls->nb_varstreams; i++)
1280 if (!hls->var_streams[i].m3u8_created)
1283 /* Keep publishing the master playlist at the configured rate */
1284 if (&hls->var_streams[0] != input_vs || !hls->master_publish_rate ||
1285 input_vs->number % hls->master_publish_rate)
1289 set_http_options(s, &options, hls);
1290 snprintf(temp_filename, sizeof(temp_filename), use_temp_file ? "%s.tmp" : "%s", hls->master_m3u8_url);
1291 ret = hlsenc_io_open(s, &hls->m3u8_out, temp_filename, &options);
1292 av_dict_free(&options);
1294 av_log(NULL, AV_LOG_ERROR, "Failed to open master play list file '%s'\n",
1299 ff_hls_write_playlist_version(hls->m3u8_out, hls->version);
1301 for (i = 0; i < hls->nb_ccstreams; i++) {
1302 ccs = &(hls->cc_streams[i]);
1303 avio_printf(hls->m3u8_out, "#EXT-X-MEDIA:TYPE=CLOSED-CAPTIONS");
1304 avio_printf(hls->m3u8_out, ",GROUP-ID=\"%s\"", ccs->ccgroup);
1305 avio_printf(hls->m3u8_out, ",NAME=\"%s\"", ccs->instreamid);
1307 avio_printf(hls->m3u8_out, ",LANGUAGE=\"%s\"", ccs->language);
1308 avio_printf(hls->m3u8_out, ",INSTREAM-ID=\"%s\"\n", ccs->instreamid);
1311 /* For audio only variant streams add #EXT-X-MEDIA tag with attributes*/
1312 for (i = 0; i < hls->nb_varstreams; i++) {
1313 vs = &(hls->var_streams[i]);
1315 if (vs->has_video || vs->has_subtitle || !vs->agroup)
1318 m3u8_name_size = strlen(vs->m3u8_name) + 1;
1319 m3u8_rel_name = av_malloc(m3u8_name_size);
1320 if (!m3u8_rel_name) {
1321 ret = AVERROR(ENOMEM);
1324 av_strlcpy(m3u8_rel_name, vs->m3u8_name, m3u8_name_size);
1325 ret = get_relative_url(hls->master_m3u8_url, vs->m3u8_name,
1326 m3u8_rel_name, m3u8_name_size);
1328 av_log(s, AV_LOG_ERROR, "Unable to find relative URL\n");
1332 ff_hls_write_audio_rendition(hls->m3u8_out, vs->agroup, m3u8_rel_name, vs->language, i, hls->has_default_key ? vs->is_default : 1);
1334 av_freep(&m3u8_rel_name);
1337 /* For variant streams with video add #EXT-X-STREAM-INF tag with attributes*/
1338 for (i = 0; i < hls->nb_varstreams; i++) {
1339 vs = &(hls->var_streams[i]);
1341 m3u8_name_size = strlen(vs->m3u8_name) + 1;
1342 m3u8_rel_name = av_malloc(m3u8_name_size);
1343 if (!m3u8_rel_name) {
1344 ret = AVERROR(ENOMEM);
1347 av_strlcpy(m3u8_rel_name, vs->m3u8_name, m3u8_name_size);
1348 ret = get_relative_url(hls->master_m3u8_url, vs->m3u8_name,
1349 m3u8_rel_name, m3u8_name_size);
1351 av_log(NULL, AV_LOG_ERROR, "Unable to find relative URL\n");
1357 for (j = 0; j < vs->nb_streams; j++) {
1358 if (vs->streams[j]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
1359 vid_st = vs->streams[j];
1360 else if (vs->streams[j]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
1361 aud_st = vs->streams[j];
1364 if (!vid_st && !aud_st) {
1365 av_log(NULL, AV_LOG_WARNING, "Media stream not found\n");
1370 * Traverse through the list of audio only rendition streams and find
1371 * the rendition which has highest bitrate in the same audio group
1374 for (j = 0; j < hls->nb_varstreams; j++) {
1375 temp_vs = &(hls->var_streams[j]);
1376 if (!temp_vs->has_video && !temp_vs->has_subtitle &&
1378 !av_strcasecmp(temp_vs->agroup, vs->agroup)) {
1380 aud_st = temp_vs->streams[0];
1381 if (temp_vs->streams[0]->codecpar->bit_rate >
1382 aud_st->codecpar->bit_rate)
1383 aud_st = temp_vs->streams[0];
1390 bandwidth += get_stream_bit_rate(vid_st);
1392 bandwidth += get_stream_bit_rate(aud_st);
1393 bandwidth += bandwidth / 10;
1396 if (vid_st && vs->ccgroup) {
1397 /* check if this group name is available in the cc map string */
1398 for (j = 0; j < hls->nb_ccstreams; j++) {
1399 ccs = &(hls->cc_streams[j]);
1400 if (!av_strcasecmp(ccs->ccgroup, vs->ccgroup)) {
1401 ccgroup = vs->ccgroup;
1405 if (j == hls->nb_ccstreams)
1406 av_log(NULL, AV_LOG_WARNING, "mapping ccgroup %s not found\n",
1410 if (!hls->has_default_key || !hls->has_video_m3u8) {
1411 ff_hls_write_stream_info(vid_st, hls->m3u8_out, bandwidth, m3u8_rel_name,
1412 aud_st ? vs->agroup : NULL, vs->codec_attr, ccgroup);
1415 ff_hls_write_stream_info(vid_st, hls->m3u8_out, bandwidth, m3u8_rel_name,
1416 aud_st ? vs->agroup : NULL, vs->codec_attr, ccgroup);
1420 av_freep(&m3u8_rel_name);
1424 hls->master_m3u8_created = 1;
1425 av_freep(&m3u8_rel_name);
1426 hlsenc_io_close(s, &hls->m3u8_out, temp_filename);
1428 ff_rename(temp_filename, hls->master_m3u8_url, s);
1433 static int hls_window(AVFormatContext *s, int last, VariantStream *vs)
1435 HLSContext *hls = s->priv_data;
1437 int target_duration = 0;
1439 char temp_filename[MAX_URL_SIZE];
1440 char temp_vtt_filename[MAX_URL_SIZE];
1441 int64_t sequence = FFMAX(hls->start_sequence, vs->sequence - vs->nb_entries);
1442 const char *proto = avio_find_protocol_name(vs->m3u8_name);
1443 int is_file_proto = proto && !strcmp(proto, "file");
1444 int use_temp_file = is_file_proto && ((hls->flags & HLS_TEMP_FILE) || !(hls->pl_type == PLAYLIST_TYPE_VOD));
1445 static unsigned warned_non_file;
1446 char *key_uri = NULL;
1447 char *iv_string = NULL;
1448 AVDictionary *options = NULL;
1449 double prog_date_time = vs->initial_prog_date_time;
1450 double *prog_date_time_p = (hls->flags & HLS_PROGRAM_DATE_TIME) ? &prog_date_time : NULL;
1451 int byterange_mode = (hls->flags & HLS_SINGLE_FILE) || (hls->max_seg_size > 0);
1454 if (byterange_mode) {
1459 if (hls->flags & HLS_INDEPENDENT_SEGMENTS) {
1463 if (hls->segment_type == SEGMENT_TYPE_FMP4) {
1467 if (!is_file_proto && (hls->flags & HLS_TEMP_FILE) && !warned_non_file++)
1468 av_log(s, AV_LOG_ERROR, "Cannot use rename on non file protocol, this may lead to races and temporary partial files\n");
1470 set_http_options(s, &options, hls);
1471 snprintf(temp_filename, sizeof(temp_filename), use_temp_file ? "%s.tmp" : "%s", vs->m3u8_name);
1472 if ((ret = hlsenc_io_open(s, (byterange_mode || hls->segment_type == SEGMENT_TYPE_FMP4) ? &hls->m3u8_out : &vs->out, temp_filename, &options)) < 0) {
1473 if (hls->ignore_io_errors)
1478 for (en = vs->segments; en; en = en->next) {
1479 if (target_duration <= en->duration)
1480 target_duration = lrint(en->duration);
1483 vs->discontinuity_set = 0;
1484 ff_hls_write_playlist_header((byterange_mode || hls->segment_type == SEGMENT_TYPE_FMP4) ? hls->m3u8_out : vs->out, hls->version, hls->allowcache,
1485 target_duration, sequence, hls->pl_type, hls->flags & HLS_I_FRAMES_ONLY);
1487 if((hls->flags & HLS_DISCONT_START) && sequence==hls->start_sequence && vs->discontinuity_set==0 ){
1488 avio_printf((byterange_mode || hls->segment_type == SEGMENT_TYPE_FMP4) ? hls->m3u8_out : vs->out, "#EXT-X-DISCONTINUITY\n");
1489 vs->discontinuity_set = 1;
1491 if (vs->has_video && (hls->flags & HLS_INDEPENDENT_SEGMENTS)) {
1492 avio_printf((byterange_mode || hls->segment_type == SEGMENT_TYPE_FMP4) ? hls->m3u8_out : vs->out, "#EXT-X-INDEPENDENT-SEGMENTS\n");
1494 for (en = vs->segments; en; en = en->next) {
1495 if ((hls->encrypt || hls->key_info_file) && (!key_uri || strcmp(en->key_uri, key_uri) ||
1496 av_strcasecmp(en->iv_string, iv_string))) {
1497 avio_printf((byterange_mode || hls->segment_type == SEGMENT_TYPE_FMP4) ? hls->m3u8_out : vs->out, "#EXT-X-KEY:METHOD=AES-128,URI=\"%s\"", en->key_uri);
1499 avio_printf((byterange_mode || hls->segment_type == SEGMENT_TYPE_FMP4) ? hls->m3u8_out : vs->out, ",IV=0x%s", en->iv_string);
1500 avio_printf((byterange_mode || hls->segment_type == SEGMENT_TYPE_FMP4) ? hls->m3u8_out : vs->out, "\n");
1501 key_uri = en->key_uri;
1502 iv_string = en->iv_string;
1505 if ((hls->segment_type == SEGMENT_TYPE_FMP4) && (en == vs->segments)) {
1506 ff_hls_write_init_file((byterange_mode || hls->segment_type == SEGMENT_TYPE_FMP4) ? hls->m3u8_out : vs->out, (hls->flags & HLS_SINGLE_FILE) ? en->filename : vs->fmp4_init_filename,
1507 hls->flags & HLS_SINGLE_FILE, vs->init_range_length, 0);
1510 ret = ff_hls_write_file_entry((byterange_mode || hls->segment_type == SEGMENT_TYPE_FMP4) ? hls->m3u8_out : vs->out, en->discont, byterange_mode,
1511 en->duration, hls->flags & HLS_ROUND_DURATIONS,
1512 en->size, en->pos, vs->baseurl,
1513 en->filename, prog_date_time_p, en->keyframe_size, en->keyframe_pos, hls->flags & HLS_I_FRAMES_ONLY);
1515 av_log(s, AV_LOG_WARNING, "ff_hls_write_file_entry get error\n");
1519 if (last && (hls->flags & HLS_OMIT_ENDLIST)==0)
1520 ff_hls_write_end_list((byterange_mode || hls->segment_type == SEGMENT_TYPE_FMP4) ? hls->m3u8_out : vs->out);
1522 if (vs->vtt_m3u8_name) {
1523 snprintf(temp_vtt_filename, sizeof(temp_vtt_filename), use_temp_file ? "%s.tmp" : "%s", vs->vtt_m3u8_name);
1524 if ((ret = hlsenc_io_open(s, &hls->sub_m3u8_out, temp_vtt_filename, &options)) < 0) {
1525 if (hls->ignore_io_errors)
1529 ff_hls_write_playlist_header(hls->sub_m3u8_out, hls->version, hls->allowcache,
1530 target_duration, sequence, PLAYLIST_TYPE_NONE, 0);
1531 for (en = vs->segments; en; en = en->next) {
1532 ret = ff_hls_write_file_entry(hls->sub_m3u8_out, 0, byterange_mode,
1533 en->duration, 0, en->size, en->pos,
1534 vs->baseurl, en->sub_filename, NULL, 0, 0, 0);
1536 av_log(s, AV_LOG_WARNING, "ff_hls_write_file_entry get error\n");
1541 ff_hls_write_end_list(hls->sub_m3u8_out);
1546 av_dict_free(&options);
1547 hlsenc_io_close(s, (byterange_mode || hls->segment_type == SEGMENT_TYPE_FMP4) ? &hls->m3u8_out : &vs->out, temp_filename);
1548 hlsenc_io_close(s, &hls->sub_m3u8_out, vs->vtt_m3u8_name);
1549 if (use_temp_file) {
1550 ff_rename(temp_filename, vs->m3u8_name, s);
1551 if (vs->vtt_m3u8_name)
1552 ff_rename(temp_vtt_filename, vs->vtt_m3u8_name, s);
1554 if (ret >= 0 && hls->master_pl_name)
1555 if (create_master_playlist(s, vs) < 0)
1556 av_log(s, AV_LOG_WARNING, "Master playlist creation failed\n");
1561 static int hls_start(AVFormatContext *s, VariantStream *vs)
1563 HLSContext *c = s->priv_data;
1564 AVFormatContext *oc = vs->avf;
1565 AVFormatContext *vtt_oc = vs->vtt_avf;
1566 AVDictionary *options = NULL;
1567 const char *proto = NULL;
1568 int use_temp_file = 0;
1569 char iv_string[KEYSIZE*2 + 1];
1572 if (c->flags & HLS_SINGLE_FILE) {
1573 char *new_name = av_strdup(vs->basename);
1575 return AVERROR(ENOMEM);
1576 ff_format_set_url(oc, new_name);
1577 if (vs->vtt_basename) {
1578 new_name = av_strdup(vs->vtt_basename);
1580 return AVERROR(ENOMEM);
1581 ff_format_set_url(vtt_oc, new_name);
1583 } else if (c->max_seg_size > 0) {
1584 char *filename = NULL;
1585 if (replace_int_data_in_filename(&filename,
1587 vs->basename, 'd', c->wrap ? vs->sequence % c->wrap : vs->sequence) < 1) {
1589 vs->basename, 'd', vs->sequence) < 1) {
1592 av_log(oc, AV_LOG_ERROR, "Invalid segment filename template '%s', you can try to use -strftime 1 with it\n", vs->basename);
1593 return AVERROR(EINVAL);
1595 ff_format_set_url(oc, filename);
1597 if (c->use_localtime) {
1599 struct tm *tm, tmpbuf;
1600 int bufsize = strlen(vs->basename) + MAX_URL_SIZE;
1601 char *buf = av_mallocz(bufsize);
1603 return AVERROR(ENOMEM);
1605 tm = localtime_r(&now0, &tmpbuf);
1606 ff_format_set_url(oc, buf);
1607 if (!strftime(oc->url, bufsize, vs->basename, tm)) {
1608 av_log(oc, AV_LOG_ERROR, "Could not get segment filename with strftime\n");
1609 return AVERROR(EINVAL);
1612 err = sls_flag_use_localtime_filename(oc, c, vs);
1614 return AVERROR(ENOMEM);
1617 if (c->use_localtime_mkdir) {
1619 char *fn_copy = av_strdup(oc->url);
1621 return AVERROR(ENOMEM);
1623 dir = av_dirname(fn_copy);
1624 if (ff_mkdir_p(dir) == -1 && errno != EEXIST) {
1625 av_log(oc, AV_LOG_ERROR, "Could not create directory %s with use_localtime_mkdir\n", dir);
1627 return AVERROR(errno);
1632 char *filename = NULL;
1633 if (replace_int_data_in_filename(&filename,
1635 vs->basename, 'd', c->wrap ? vs->sequence % c->wrap : vs->sequence) < 1) {
1637 vs->basename, 'd', vs->sequence) < 1) {
1640 av_log(oc, AV_LOG_ERROR, "Invalid segment filename template '%s' you can try to use -strftime 1 with it\n", vs->basename);
1641 return AVERROR(EINVAL);
1643 ff_format_set_url(oc, filename);
1645 if( vs->vtt_basename) {
1646 char *filename = NULL;
1647 if (replace_int_data_in_filename(&filename,
1649 vs->vtt_basename, 'd', c->wrap ? vs->sequence % c->wrap : vs->sequence) < 1) {
1651 vs->vtt_basename, 'd', vs->sequence) < 1) {
1654 av_log(vtt_oc, AV_LOG_ERROR, "Invalid segment filename template '%s'\n", vs->vtt_basename);
1655 return AVERROR(EINVAL);
1657 ff_format_set_url(vtt_oc, filename);
1662 set_http_options(s, &options, c);
1664 proto = avio_find_protocol_name(oc->url);
1665 use_temp_file = proto && !strcmp(proto, "file") && (c->flags & HLS_TEMP_FILE);
1667 if (use_temp_file) {
1668 char *new_name = av_asprintf("%s.tmp", oc->url);
1670 return AVERROR(ENOMEM);
1671 ff_format_set_url(oc, new_name);
1674 if (c->key_info_file || c->encrypt) {
1675 if (c->segment_type == SEGMENT_TYPE_FMP4) {
1676 av_log(s, AV_LOG_ERROR, "Encrypted fmp4 not yet supported\n");
1677 return AVERROR_PATCHWELCOME;
1680 if (c->key_info_file && c->encrypt) {
1681 av_log(s, AV_LOG_WARNING, "Cannot use both -hls_key_info_file and -hls_enc,"
1682 " ignoring -hls_enc\n");
1685 if (!c->encrypt_started || (c->flags & HLS_PERIODIC_REKEY)) {
1686 if (c->key_info_file) {
1687 if ((err = hls_encryption_start(s)) < 0)
1690 if ((err = do_encrypt(s, vs)) < 0)
1693 c->encrypt_started = 1;
1695 err = av_strlcpy(iv_string, c->iv_string, sizeof(iv_string));
1697 snprintf(iv_string, sizeof(iv_string), "%032"PRIx64, vs->sequence);
1698 memset(c->iv_string, 0, sizeof(c->iv_string));
1699 memcpy(c->iv_string, iv_string, sizeof(iv_string));
1702 if (c->segment_type != SEGMENT_TYPE_FMP4) {
1703 /* We only require one PAT/PMT per segment. */
1704 if (oc->oformat->priv_class && oc->priv_data) {
1707 snprintf(period, sizeof(period), "%d", (INT_MAX / 2) - 1);
1709 av_opt_set(oc->priv_data, "mpegts_flags", "resend_headers", 0);
1710 av_opt_set(oc->priv_data, "sdt_period", period, 0);
1711 av_opt_set(oc->priv_data, "pat_period", period, 0);
1713 if (c->flags & HLS_SINGLE_FILE) {
1714 if ((err = hlsenc_io_open(s, &vs->out, oc->url, &options)) < 0) {
1715 if (c->ignore_io_errors)
1721 if (vs->vtt_basename) {
1722 set_http_options(s, &options, c);
1723 if ((err = hlsenc_io_open(s, &vtt_oc->pb, vtt_oc->url, &options)) < 0) {
1724 if (c->ignore_io_errors)
1729 av_dict_free(&options);
1731 if (vs->vtt_basename) {
1732 err = avformat_write_header(vtt_oc,NULL);
1739 av_dict_free(&options);
1744 static const char * get_default_pattern_localtime_fmt(AVFormatContext *s)
1747 time_t t = time(NULL);
1748 struct tm *p, tmbuf;
1749 HLSContext *hls = s->priv_data;
1751 p = localtime_r(&t, &tmbuf);
1752 // no %s support when strftime returned error or left format string unchanged
1753 // also no %s support on MSVC, which invokes the invalid parameter handler on unsupported format strings, instead of returning an error
1754 if (hls->segment_type == SEGMENT_TYPE_FMP4) {
1755 return (HAVE_LIBC_MSVCRT || !strftime(b, sizeof(b), "%s", p) || !strcmp(b, "%s")) ? "-%Y%m%d%H%M%S.m4s" : "-%s.m4s";
1757 return (HAVE_LIBC_MSVCRT || !strftime(b, sizeof(b), "%s", p) || !strcmp(b, "%s")) ? "-%Y%m%d%H%M%S.ts" : "-%s.ts";
1760 static int append_postfix(char *name, int name_buf_len, int i)
1763 char extension[10] = {'\0'};
1765 p = strrchr(name, '.');
1767 av_strlcpy(extension, p, sizeof(extension));
1771 snprintf(name + strlen(name), name_buf_len - strlen(name), POSTFIX_PATTERN, i);
1773 if (strlen(extension))
1774 av_strlcat(name, extension, name_buf_len);
1779 static int validate_name(int nb_vs, const char *fn)
1781 const char *filename, *subdir_name;
1782 char *fn_dup = NULL;
1786 ret = AVERROR(EINVAL);
1790 fn_dup = av_strdup(fn);
1792 ret = AVERROR(ENOMEM);
1796 filename = av_basename(fn);
1797 subdir_name = av_dirname(fn_dup);
1799 if (nb_vs > 1 && !av_stristr(filename, "%v") && !av_stristr(subdir_name, "%v")) {
1800 av_log(NULL, AV_LOG_ERROR, "More than 1 variant streams are present, %%v is expected "
1801 "either in the filename or in the sub-directory name of file %s\n", fn);
1802 ret = AVERROR(EINVAL);
1806 if (av_stristr(filename, "%v") && av_stristr(subdir_name, "%v")) {
1807 av_log(NULL, AV_LOG_ERROR, "%%v is expected either in the filename or "
1808 "in the sub-directory name of file %s, but only in one of them\n", fn);
1809 ret = AVERROR(EINVAL);
1818 static int format_name(const char *buf, char **s, int index, const char *varname)
1820 const char *proto, *dir;
1821 char *orig_buf_dup = NULL, *mod_buf_dup = NULL;
1824 orig_buf_dup = av_strdup(buf);
1825 if (!orig_buf_dup) {
1826 ret = AVERROR(ENOMEM);
1830 if (!av_stristr(buf, "%v")) {
1836 if (replace_int_data_in_filename(s, orig_buf_dup, 'v', index) < 1) {
1837 ret = AVERROR(EINVAL);
1841 if (replace_str_data_in_filename(s, orig_buf_dup, 'v', varname) < 1) {
1842 ret = AVERROR(EINVAL);
1847 proto = avio_find_protocol_name(orig_buf_dup);
1848 dir = av_dirname(orig_buf_dup);
1850 /* if %v is present in the file's directory, create sub-directory */
1851 if (av_stristr(dir, "%v") && proto && !strcmp(proto, "file")) {
1852 mod_buf_dup = av_strdup(*s);
1854 ret = AVERROR(ENOMEM);
1858 dir = av_dirname(mod_buf_dup);
1859 if (ff_mkdir_p(dir) == -1 && errno != EEXIST) {
1860 ret = AVERROR(errno);
1866 av_freep(&orig_buf_dup);
1867 av_freep(&mod_buf_dup);
1871 static int get_nth_codec_stream_index(AVFormatContext *s,
1872 enum AVMediaType codec_type,
1875 unsigned int stream_index, cnt;
1876 if (stream_id < 0 || stream_id > s->nb_streams - 1)
1879 for (stream_index = 0; stream_index < s->nb_streams; stream_index++) {
1880 if (s->streams[stream_index]->codecpar->codec_type != codec_type)
1882 if (cnt == stream_id)
1883 return stream_index;
1889 static int parse_variant_stream_mapstring(AVFormatContext *s)
1891 HLSContext *hls = s->priv_data;
1893 int stream_index, i, j;
1894 enum AVMediaType codec_type;
1895 int nb_varstreams, nb_streams;
1896 char *p, *q, *saveptr1, *saveptr2, *varstr, *keyval;
1900 * Expected format for var_stream_map string is as below:
1902 * "a:0,agroup:a0,default:1,language:ENG a:1,agroup:a1,default:0 v:0,agroup:a0 v:1,agroup:a1"
1903 * This string specifies how to group the audio, video and subtitle streams
1904 * into different variant streams. The variant stream groups are separated
1907 * a:, v:, s: are keys to specify audio, video and subtitle streams
1908 * respectively. Allowed values are 0 to 9 digits (limited just based on
1911 * agroup: is key to specify audio group. A string can be given as value.
1913 p = av_strdup(hls->var_stream_map);
1915 while(av_strtok(q, " \t", &saveptr1)) {
1917 hls->nb_varstreams++;
1921 hls->var_streams = av_mallocz(sizeof(*hls->var_streams) * hls->nb_varstreams);
1922 if (!hls->var_streams)
1923 return AVERROR(ENOMEM);
1925 p = hls->var_stream_map;
1927 while (varstr = av_strtok(p, " \t", &saveptr1)) {
1930 if (nb_varstreams < hls->nb_varstreams) {
1931 vs = &(hls->var_streams[nb_varstreams]);
1932 vs->var_stream_idx = nb_varstreams;
1936 return AVERROR(EINVAL);
1939 while (q < varstr + strlen(varstr)) {
1940 if (!av_strncasecmp(q, "a:", 2) || !av_strncasecmp(q, "v:", 2) ||
1941 !av_strncasecmp(q, "s:", 2))
1945 vs->streams = av_mallocz(sizeof(AVStream *) * vs->nb_streams);
1947 return AVERROR(ENOMEM);
1950 while (keyval = av_strtok(varstr, ",", &saveptr2)) {
1952 if (av_strstart(keyval, "language:", &val)) {
1953 vs->language = av_strdup(val);
1955 return AVERROR(ENOMEM);
1957 } else if (av_strstart(keyval, "default:", &val)) {
1958 vs->is_default = (!av_strncasecmp(val, "YES", strlen("YES")) ||
1959 (!av_strncasecmp(val, "1", strlen("1"))));
1960 hls->has_default_key = 1;
1962 } else if (av_strstart(keyval, "name:", &val)) {
1963 vs->varname = av_strdup(val);
1965 return AVERROR(ENOMEM);
1967 } else if (av_strstart(keyval, "agroup:", &val)) {
1968 vs->agroup = av_strdup(val);
1970 return AVERROR(ENOMEM);
1972 } else if (av_strstart(keyval, "ccgroup:", &val)) {
1973 vs->ccgroup = av_strdup(val);
1975 return AVERROR(ENOMEM);
1977 } else if (av_strstart(keyval, "v:", &val)) {
1978 codec_type = AVMEDIA_TYPE_VIDEO;
1979 hls->has_video_m3u8 = 1;
1980 } else if (av_strstart(keyval, "a:", &val)) {
1981 codec_type = AVMEDIA_TYPE_AUDIO;
1982 } else if (av_strstart(keyval, "s:", &val)) {
1983 codec_type = AVMEDIA_TYPE_SUBTITLE;
1985 av_log(s, AV_LOG_ERROR, "Invalid keyval %s\n", keyval);
1986 return AVERROR(EINVAL);
1990 if (av_isdigit(*val))
1991 stream_index = get_nth_codec_stream_index (s, codec_type,
1994 if (stream_index >= 0 && nb_streams < vs->nb_streams) {
1995 for(i = 0; nb_streams > 0 && i < nb_streams; i++) {
1996 if (vs->streams[i] == s->streams[stream_index]) {
1997 av_log(s, AV_LOG_ERROR, "Same elementary stream found more than once inside "
1998 "variant definition #%d\n", nb_varstreams - 1);
1999 return AVERROR(EINVAL);
2002 for(j = 0; nb_varstreams > 1 && j < nb_varstreams - 1; j++) {
2003 for(i = 0; i < hls->var_streams[j].nb_streams; i++) {
2004 if (hls->var_streams[j].streams[i] == s->streams[stream_index]) {
2005 av_log(s, AV_LOG_ERROR, "Same elementary stream found more than once "
2006 "in two different variant definitions #%d and #%d\n",
2007 j, nb_varstreams - 1);
2008 return AVERROR(EINVAL);
2012 vs->streams[nb_streams++] = s->streams[stream_index];
2014 av_log(s, AV_LOG_ERROR, "Unable to map stream at %s\n", keyval);
2015 return AVERROR(EINVAL);
2019 av_log(s, AV_LOG_DEBUG, "Number of variant streams %d\n",
2020 hls->nb_varstreams);
2025 static int parse_cc_stream_mapstring(AVFormatContext *s)
2027 HLSContext *hls = s->priv_data;
2029 char *p, *q, *ccstr, *keyval;
2030 char *saveptr1 = NULL, *saveptr2 = NULL;
2032 ClosedCaptionsStream *ccs;
2034 p = av_strdup(hls->cc_stream_map);
2036 while(av_strtok(q, " \t", &saveptr1)) {
2038 hls->nb_ccstreams++;
2042 hls->cc_streams = av_mallocz(sizeof(*hls->cc_streams) * hls->nb_ccstreams);
2043 if (!hls->cc_streams)
2044 return AVERROR(ENOMEM);
2046 p = hls->cc_stream_map;
2048 while (ccstr = av_strtok(p, " \t", &saveptr1)) {
2051 if (nb_ccstreams < hls->nb_ccstreams)
2052 ccs = &(hls->cc_streams[nb_ccstreams++]);
2054 return AVERROR(EINVAL);
2056 while (keyval = av_strtok(ccstr, ",", &saveptr2)) {
2059 if (av_strstart(keyval, "ccgroup:", &val)) {
2060 ccs->ccgroup = av_strdup(val);
2062 return AVERROR(ENOMEM);
2063 } else if (av_strstart(keyval, "instreamid:", &val)) {
2064 ccs->instreamid = av_strdup(val);
2065 if (!ccs->instreamid)
2066 return AVERROR(ENOMEM);
2067 } else if (av_strstart(keyval, "language:", &val)) {
2068 ccs->language = av_strdup(val);
2070 return AVERROR(ENOMEM);
2072 av_log(s, AV_LOG_ERROR, "Invalid keyval %s\n", keyval);
2073 return AVERROR(EINVAL);
2077 if (!ccs->ccgroup || !ccs->instreamid) {
2078 av_log(s, AV_LOG_ERROR, "Insufficient parameters in cc stream map string\n");
2079 return AVERROR(EINVAL);
2082 if (av_strstart(ccs->instreamid, "CC", &val)) {
2083 if(atoi(val) < 1 || atoi(val) > 4) {
2084 av_log(s, AV_LOG_ERROR, "Invalid instream ID CC index %d in %s, range 1-4\n",
2085 atoi(val), ccs->instreamid);
2086 return AVERROR(EINVAL);
2088 } else if (av_strstart(ccs->instreamid, "SERVICE", &val)) {
2089 if(atoi(val) < 1 || atoi(val) > 63) {
2090 av_log(s, AV_LOG_ERROR, "Invalid instream ID SERVICE index %d in %s, range 1-63 \n",
2091 atoi(val), ccs->instreamid);
2092 return AVERROR(EINVAL);
2095 av_log(s, AV_LOG_ERROR, "Invalid instream ID %s, supported are CCn or SERIVICEn\n",
2097 return AVERROR(EINVAL);
2104 static int update_variant_stream_info(AVFormatContext *s) {
2105 HLSContext *hls = s->priv_data;
2109 if (hls->cc_stream_map) {
2110 ret = parse_cc_stream_mapstring(s);
2115 if (hls->var_stream_map) {
2116 return parse_variant_stream_mapstring(s);
2118 //By default, a single variant stream with all the codec streams is created
2119 hls->nb_varstreams = 1;
2120 hls->var_streams = av_mallocz(sizeof(*hls->var_streams) *
2121 hls->nb_varstreams);
2122 if (!hls->var_streams)
2123 return AVERROR(ENOMEM);
2125 hls->var_streams[0].var_stream_idx = 0;
2126 hls->var_streams[0].nb_streams = s->nb_streams;
2127 hls->var_streams[0].streams = av_mallocz(sizeof(AVStream *) *
2128 hls->var_streams[0].nb_streams);
2129 if (!hls->var_streams[0].streams) {
2130 av_free(hls->var_streams);
2131 return AVERROR(ENOMEM);
2134 //by default, the first available ccgroup is mapped to the variant stream
2135 if (hls->nb_ccstreams) {
2136 hls->var_streams[0].ccgroup = av_strdup(hls->cc_streams[0].ccgroup);
2137 if (!hls->var_streams[0].ccgroup) {
2138 av_free(hls->var_streams);
2139 return AVERROR(ENOMEM);
2143 for (i = 0; i < s->nb_streams; i++)
2144 hls->var_streams[0].streams[i] = s->streams[i];
2149 static int update_master_pl_info(AVFormatContext *s) {
2150 HLSContext *hls = s->priv_data;
2152 char *fn1= NULL, *fn2 = NULL;
2155 fn1 = av_strdup(s->url);
2157 ret = AVERROR(ENOMEM);
2161 dir = av_dirname(fn1);
2164 * if output file's directory has %v, variants are created in sub-directories
2165 * then master is created at the sub-directories level
2167 if (dir && av_stristr(av_basename(dir), "%v")) {
2168 fn2 = av_strdup(dir);
2170 ret = AVERROR(ENOMEM);
2173 dir = av_dirname(fn2);
2176 if (dir && strcmp(dir, "."))
2177 hls->master_m3u8_url = av_append_path_component(dir, hls->master_pl_name);
2179 hls->master_m3u8_url = av_strdup(hls->master_pl_name);
2181 if (!hls->master_m3u8_url) {
2182 ret = AVERROR(ENOMEM);
2193 static int hls_write_header(AVFormatContext *s)
2195 HLSContext *hls = s->priv_data;
2197 VariantStream *vs = NULL;
2199 for (i = 0; i < hls->nb_varstreams; i++) {
2200 vs = &hls->var_streams[i];
2202 ret = avformat_write_header(vs->avf, NULL);
2205 //av_assert0(s->nb_streams == hls->avf->nb_streams);
2206 for (j = 0; j < vs->nb_streams; j++) {
2208 AVStream *outer_st = vs->streams[j];
2210 if (hls->max_seg_size > 0) {
2211 if ((outer_st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) &&
2212 (outer_st->codecpar->bit_rate > hls->max_seg_size)) {
2213 av_log(s, AV_LOG_WARNING, "Your video bitrate is bigger than hls_segment_size, "
2214 "(%"PRId64 " > %"PRId64 "), the result maybe not be what you want.",
2215 outer_st->codecpar->bit_rate, hls->max_seg_size);
2219 if (outer_st->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE)
2220 inner_st = vs->avf->streams[j];
2221 else if (vs->vtt_avf)
2222 inner_st = vs->vtt_avf->streams[0];
2224 /* We have a subtitle stream, when the user does not want one */
2228 avpriv_set_pts_info(outer_st, inner_st->pts_wrap_bits, inner_st->time_base.num, inner_st->time_base.den);
2229 write_codec_attr(outer_st, vs);
2232 /* Update the Codec Attr string for the mapped audio groups */
2233 if (vs->has_video && vs->agroup) {
2234 for (j = 0; j < hls->nb_varstreams; j++) {
2235 VariantStream *vs_agroup = &(hls->var_streams[j]);
2236 if (!vs_agroup->has_video && !vs_agroup->has_subtitle &&
2237 vs_agroup->agroup &&
2238 !av_strcasecmp(vs_agroup->agroup, vs->agroup)) {
2239 write_codec_attr(vs_agroup->streams[0], vs);
2248 static int hls_write_packet(AVFormatContext *s, AVPacket *pkt)
2250 HLSContext *hls = s->priv_data;
2251 AVFormatContext *oc = NULL;
2252 AVStream *st = s->streams[pkt->stream_index];
2253 int64_t end_pts = 0;
2255 int ret = 0, can_split = 1, i, j;
2256 int stream_index = 0;
2257 int range_length = 0;
2258 const char *proto = NULL;
2259 int use_temp_file = 0;
2260 uint8_t *buffer = NULL;
2261 VariantStream *vs = NULL;
2262 AVDictionary *options = NULL;
2263 char *old_filename = NULL;
2265 for (i = 0; i < hls->nb_varstreams; i++) {
2266 vs = &hls->var_streams[i];
2267 for (j = 0; j < vs->nb_streams; j++) {
2268 if (vs->streams[j] == st) {
2269 if( st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE ) {
2285 av_log(s, AV_LOG_ERROR, "Unable to find mapping variant stream\n");
2286 return AVERROR(ENOMEM);
2289 end_pts = hls->recording_time * vs->number;
2291 if (vs->sequence - vs->nb_entries > hls->start_sequence && hls->init_time > 0) {
2292 /* reset end_pts, hls->recording_time at end of the init hls list */
2293 int64_t init_list_dur = hls->init_time * vs->nb_entries * AV_TIME_BASE;
2294 int64_t after_init_list_dur = (vs->sequence - hls->start_sequence - vs->nb_entries ) * (hls->time * AV_TIME_BASE);
2295 hls->recording_time = hls->time * AV_TIME_BASE;
2296 end_pts = init_list_dur + after_init_list_dur ;
2299 if (vs->start_pts == AV_NOPTS_VALUE) {
2300 vs->start_pts = pkt->pts;
2303 if (vs->has_video) {
2304 can_split = st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
2305 ((pkt->flags & AV_PKT_FLAG_KEY) || (hls->flags & HLS_SPLIT_BY_TIME));
2306 is_ref_pkt = (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) && (pkt->stream_index == vs->reference_stream_index);
2308 if (pkt->pts == AV_NOPTS_VALUE)
2309 is_ref_pkt = can_split = 0;
2312 if (vs->end_pts == AV_NOPTS_VALUE)
2313 vs->end_pts = pkt->pts;
2314 if (vs->new_start) {
2316 vs->duration = (double)(pkt->pts - vs->end_pts)
2317 * st->time_base.num / st->time_base.den;
2318 vs->dpp = (double)(pkt->duration) * st->time_base.num / st->time_base.den;
2320 if (pkt->duration) {
2321 vs->duration += (double)(pkt->duration) * st->time_base.num / st->time_base.den;
2323 av_log(s, AV_LOG_WARNING, "pkt->duration = 0, maybe the hls segment duration will not precise\n");
2324 vs->duration = (double)(pkt->pts - vs->end_pts) * st->time_base.num / st->time_base.den;
2330 if (vs->packets_written && can_split && av_compare_ts(pkt->pts - vs->start_pts, st->time_base,
2331 end_pts, AV_TIME_BASE_Q) >= 0) {
2332 int64_t new_start_pos;
2333 int byterange_mode = (hls->flags & HLS_SINGLE_FILE) || (hls->max_seg_size > 0);
2335 av_write_frame(oc, NULL); /* Flush any buffered data */
2336 new_start_pos = avio_tell(oc->pb);
2337 vs->size = new_start_pos - vs->start_pos;
2339 if (hls->segment_type == SEGMENT_TYPE_FMP4) {
2340 if (!vs->init_range_length) {
2341 range_length = avio_close_dyn_buf(oc->pb, &buffer);
2342 avio_write(vs->out, buffer, range_length);
2344 vs->init_range_length = range_length;
2345 avio_open_dyn_buf(&oc->pb);
2346 vs->packets_written = 0;
2347 vs->start_pos = range_length;
2348 if (!byterange_mode) {
2349 hlsenc_io_close(s, &vs->out, vs->base_output_dirname);
2353 if (!byterange_mode) {
2355 hlsenc_io_close(s, &vs->vtt_avf->pb, vs->vtt_avf->url);
2360 proto = avio_find_protocol_name(oc->url);
2361 use_temp_file = proto && !strcmp(proto, "file") && (hls->flags & HLS_TEMP_FILE);
2364 // look to rename the asset name
2365 if (use_temp_file) {
2366 av_dict_set(&options, "mpegts_flags", "resend_headers", 0);
2369 if (hls->flags & HLS_SINGLE_FILE) {
2370 ret = flush_dynbuf(vs, &range_length);
2374 vs->size = range_length;
2376 set_http_options(s, &options, hls);
2377 if ((hls->max_seg_size > 0 && (vs->size >= hls->max_seg_size)) || !byterange_mode) {
2378 char *filename = NULL;
2379 if (hls->key_info_file || hls->encrypt) {
2380 av_dict_set(&options, "encryption_key", hls->key_string, 0);
2381 av_dict_set(&options, "encryption_iv", hls->iv_string, 0);
2382 filename = av_asprintf("crypto:%s", oc->url);
2384 filename = av_asprintf("%s", oc->url);
2387 return AVERROR(ENOMEM);
2389 ret = hlsenc_io_open(s, &vs->out, filename, &options);
2391 av_log(s, hls->ignore_io_errors ? AV_LOG_WARNING : AV_LOG_ERROR,
2392 "Failed to open file '%s'\n", filename);
2393 return hls->ignore_io_errors ? 0 : ret;
2395 if (hls->segment_type == SEGMENT_TYPE_FMP4) {
2396 write_styp(vs->out);
2398 ret = flush_dynbuf(vs, &range_length);
2402 hlsenc_io_close(s, &vs->out, filename);
2407 if (use_temp_file && !(hls->flags & HLS_SINGLE_FILE)) {
2408 hls_rename_temp_file(s, oc);
2411 old_filename = av_strdup(oc->url);
2412 if (!old_filename) {
2413 return AVERROR(ENOMEM);
2416 if (vs->start_pos || hls->segment_type != SEGMENT_TYPE_FMP4) {
2417 ret = hls_append_segment(s, hls, vs, vs->duration, vs->start_pos, vs->size);
2418 vs->end_pts = pkt->pts;
2421 av_free(old_filename);
2426 // if we're building a VOD playlist, skip writing the manifest multiple times, and just wait until the end
2427 if (hls->pl_type != PLAYLIST_TYPE_VOD) {
2428 if ((ret = hls_window(s, 0, vs)) < 0) {
2429 av_free(old_filename);
2434 if (hls->flags & HLS_SINGLE_FILE) {
2436 vs->start_pos += vs->size;
2437 } else if (hls->max_seg_size > 0) {
2438 vs->start_pos = new_start_pos;
2439 if (vs->size >= hls->max_seg_size) {
2441 sls_flag_file_rename(hls, vs, old_filename);
2442 ret = hls_start(s, vs);
2444 /* When split segment by byte, the duration is short than hls_time,
2445 * so it is not enough one segment duration as hls_time, */
2450 vs->start_pos = new_start_pos;
2451 sls_flag_file_rename(hls, vs, old_filename);
2452 ret = hls_start(s, vs);
2454 av_free(old_filename);
2462 vs->packets_written++;
2464 ret = ff_write_chained(oc, stream_index, pkt, s, 0);
2465 vs->video_keyframe_size += pkt->size;
2466 if ((st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) && (pkt->flags & AV_PKT_FLAG_KEY)) {
2467 vs->video_keyframe_size = avio_tell(oc->pb);
2469 vs->video_keyframe_pos = avio_tell(vs->out);
2471 if (hls->ignore_io_errors)
2478 static void hls_free_variant_streams(struct HLSContext *hls)
2481 AVFormatContext *vtt_oc = NULL;
2482 VariantStream *vs = NULL;
2484 for (i = 0; i < hls->nb_varstreams; i++) {
2485 vs = &hls->var_streams[i];
2486 vtt_oc = vs->vtt_avf;
2488 av_freep(&vs->basename);
2489 av_freep(&vs->base_output_dirname);
2490 av_freep(&vs->fmp4_init_filename);
2492 av_freep(&vs->vtt_basename);
2493 av_freep(&vs->vtt_m3u8_name);
2496 hls_free_segments(vs->segments);
2497 hls_free_segments(vs->old_segments);
2498 av_freep(&vs->m3u8_name);
2499 av_freep(&vs->streams);
2500 av_freep(&vs->agroup);
2501 av_freep(&vs->language);
2502 av_freep(&vs->ccgroup);
2503 av_freep(&vs->baseurl);
2504 av_freep(&vs->varname);
2508 static int hls_write_trailer(struct AVFormatContext *s)
2510 HLSContext *hls = s->priv_data;
2511 AVFormatContext *oc = NULL;
2512 AVFormatContext *vtt_oc = NULL;
2513 char *old_filename = NULL;
2514 const char *proto = NULL;
2515 int use_temp_file = 0;
2518 VariantStream *vs = NULL;
2519 AVDictionary *options = NULL;
2520 int range_length, byterange_mode;
2522 for (i = 0; i < hls->nb_varstreams; i++) {
2523 char *filename = NULL;
2524 vs = &hls->var_streams[i];
2526 vtt_oc = vs->vtt_avf;
2527 old_filename = av_strdup(vs->avf->url);
2530 if (!old_filename) {
2531 return AVERROR(ENOMEM);
2533 if (hls->key_info_file || hls->encrypt) {
2534 av_dict_set(&options, "encryption_key", hls->key_string, 0);
2535 av_dict_set(&options, "encryption_iv", hls->iv_string, 0);
2536 filename = av_asprintf("crypto:%s", vs->avf->url);
2538 filename = av_asprintf("%s", vs->avf->url);
2541 av_free(old_filename);
2542 return AVERROR(ENOMEM);
2545 if ( hls->segment_type == SEGMENT_TYPE_FMP4) {
2546 int range_length = 0;
2547 if (!vs->init_range_length) {
2548 uint8_t *buffer = NULL;
2549 av_write_frame(vs->avf, NULL); /* Flush any buffered data */
2552 range_length = avio_close_dyn_buf(oc->pb, &buffer);
2553 avio_write(vs->out, buffer, range_length);
2555 vs->init_range_length = range_length;
2556 avio_open_dyn_buf(&oc->pb);
2557 vs->packets_written = 0;
2558 vs->start_pos = range_length;
2559 byterange_mode = (hls->flags & HLS_SINGLE_FILE) || (hls->max_seg_size > 0);
2560 if (!byterange_mode) {
2561 ff_format_io_close(s, &vs->out);
2562 hlsenc_io_close(s, &vs->out, vs->base_output_dirname);
2566 if (!(hls->flags & HLS_SINGLE_FILE)) {
2567 set_http_options(s, &options, hls);
2568 ret = hlsenc_io_open(s, &vs->out, filename, &options);
2570 av_log(s, AV_LOG_ERROR, "Failed to open file '%s'\n", vs->avf->url);
2573 if (hls->segment_type == SEGMENT_TYPE_FMP4)
2574 write_styp(vs->out);
2576 ret = flush_dynbuf(vs, &range_length);
2580 vs->size = range_length;
2581 hlsenc_io_close(s, &vs->out, filename);
2585 av_write_trailer(oc);
2587 proto = avio_find_protocol_name(oc->url);
2588 use_temp_file = proto && !strcmp(proto, "file") && (hls->flags & HLS_TEMP_FILE);
2591 // rename that segment from .tmp to the real one
2592 if (use_temp_file && !(hls->flags & HLS_SINGLE_FILE)) {
2593 hls_rename_temp_file(s, oc);
2594 av_free(old_filename);
2595 old_filename = av_strdup(vs->avf->url);
2597 if (!old_filename) {
2598 return AVERROR(ENOMEM);
2602 /* after av_write_trailer, then duration + 1 duration per packet */
2603 hls_append_segment(s, hls, vs, vs->duration + vs->dpp, vs->start_pos, vs->size);
2605 sls_flag_file_rename(hls, vs, old_filename);
2609 av_write_trailer(vtt_oc);
2610 vs->size = avio_tell(vs->vtt_avf->pb) - vs->start_pos;
2611 ff_format_io_close(s, &vtt_oc->pb);
2612 avformat_free_context(vtt_oc);
2614 hls_window(s, 1, vs);
2615 avformat_free_context(oc);
2618 av_free(old_filename);
2621 hls_free_variant_streams(hls);
2623 for (i = 0; i < hls->nb_ccstreams; i++) {
2624 ClosedCaptionsStream *ccs = &hls->cc_streams[i];
2625 av_freep(&ccs->ccgroup);
2626 av_freep(&ccs->instreamid);
2627 av_freep(&ccs->language);
2630 ff_format_io_close(s, &hls->m3u8_out);
2631 ff_format_io_close(s, &hls->sub_m3u8_out);
2632 av_freep(&hls->key_basename);
2633 av_freep(&hls->var_streams);
2634 av_freep(&hls->cc_streams);
2635 av_freep(&hls->master_m3u8_url);
2640 static int hls_init(AVFormatContext *s)
2645 HLSContext *hls = s->priv_data;
2646 const char *pattern = "%d.ts";
2647 VariantStream *vs = NULL;
2648 int basename_size = 0;
2649 const char *pattern_localtime_fmt = get_default_pattern_localtime_fmt(s);
2650 const char *vtt_pattern = "%d.vtt";
2652 int vtt_basename_size = 0;
2653 int fmp4_init_filename_len = strlen(hls->fmp4_init_filename) + 1;
2655 hls->has_default_key = 0;
2656 hls->has_video_m3u8 = 0;
2657 ret = update_variant_stream_info(s);
2659 av_log(s, AV_LOG_ERROR, "Variant stream info update failed with status %x\n",
2663 //TODO: Updates needed to encryption functionality with periodic re-key when more than one variant streams are present
2664 if (hls->nb_varstreams > 1 && hls->flags & HLS_PERIODIC_REKEY) {
2665 ret = AVERROR(EINVAL);
2666 av_log(s, AV_LOG_ERROR, "Periodic re-key not supported when more than one variant streams are present\n");
2670 ret = validate_name(hls->nb_varstreams, s->url);
2674 if (hls->segment_filename) {
2675 ret = validate_name(hls->nb_varstreams, hls->segment_filename);
2680 if (av_strcasecmp(hls->fmp4_init_filename, "init.mp4")) {
2681 ret = validate_name(hls->nb_varstreams, hls->fmp4_init_filename);
2686 if (hls->subtitle_filename) {
2687 ret = validate_name(hls->nb_varstreams, hls->subtitle_filename);
2692 if (hls->master_pl_name) {
2693 ret = update_master_pl_info(s);
2695 av_log(s, AV_LOG_ERROR, "Master stream info update failed with status %x\n",
2701 if (hls->segment_type == SEGMENT_TYPE_FMP4) {
2704 if ((hls->start_sequence_source_type == HLS_START_SEQUENCE_AS_SECONDS_SINCE_EPOCH) ||
2705 (hls->start_sequence_source_type == HLS_START_SEQUENCE_AS_FORMATTED_DATETIME)) {
2706 time_t t = time(NULL); // we will need it in either case
2707 if (hls->start_sequence_source_type == HLS_START_SEQUENCE_AS_SECONDS_SINCE_EPOCH) {
2708 hls->start_sequence = (int64_t)t;
2709 } else if (hls->start_sequence_source_type == HLS_START_SEQUENCE_AS_FORMATTED_DATETIME) {
2711 struct tm *p, tmbuf;
2712 if (!(p = localtime_r(&t, &tmbuf)))
2713 return AVERROR(ENOMEM);
2714 if (!strftime(b, sizeof(b), "%Y%m%d%H%M%S", p))
2715 return AVERROR(ENOMEM);
2716 hls->start_sequence = strtoll(b, NULL, 10);
2718 av_log(hls, AV_LOG_DEBUG, "start_number evaluated to %"PRId64"\n", hls->start_sequence);
2721 hls->recording_time = (hls->init_time ? hls->init_time : hls->time) * AV_TIME_BASE;
2722 for (i = 0; i < hls->nb_varstreams; i++) {
2723 vs = &hls->var_streams[i];
2725 ret = format_name(s->url, &vs->m3u8_name, i, vs->varname);
2729 vs->sequence = hls->start_sequence;
2730 vs->start_pts = AV_NOPTS_VALUE;
2731 vs->end_pts = AV_NOPTS_VALUE;
2732 vs->current_segment_final_filename_fmt[0] = '\0';
2734 if (hls->flags & HLS_SPLIT_BY_TIME && hls->flags & HLS_INDEPENDENT_SEGMENTS) {
2735 // Independent segments cannot be guaranteed when splitting by time
2736 hls->flags &= ~HLS_INDEPENDENT_SEGMENTS;
2737 av_log(s, AV_LOG_WARNING,
2738 "'split_by_time' and 'independent_segments' cannot be enabled together. "
2739 "Disabling 'independent_segments' flag\n");
2742 if (hls->flags & HLS_PROGRAM_DATE_TIME) {
2745 vs->initial_prog_date_time = now0;
2747 if (hls->format_options_str) {
2748 ret = av_dict_parse_string(&hls->format_options, hls->format_options_str, "=", ":", 0);
2750 av_log(s, AV_LOG_ERROR, "Could not parse format options list '%s'\n", hls->format_options_str);
2755 for (j = 0; j < vs->nb_streams; j++) {
2756 vs->has_video += vs->streams[j]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO;
2757 /* Get one video stream to reference for split segments
2758 * so use the first video stream index. */
2759 if ((vs->has_video == 1) && (vs->streams[j]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)) {
2760 vs->reference_stream_index = vs->streams[j]->index;
2762 vs->has_subtitle += vs->streams[j]->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE;
2765 if (vs->has_video > 1)
2766 av_log(s, AV_LOG_WARNING, "More than a single video stream present, expect issues decoding it.\n");
2767 if (hls->segment_type == SEGMENT_TYPE_FMP4) {
2768 vs->oformat = av_guess_format("mp4", NULL, NULL);
2770 vs->oformat = av_guess_format("mpegts", NULL, NULL);
2774 ret = AVERROR_MUXER_NOT_FOUND;
2778 if (vs->has_subtitle) {
2779 vs->vtt_oformat = av_guess_format("webvtt", NULL, NULL);
2781 ret = AVERROR_MUXER_NOT_FOUND;
2785 if (hls->segment_filename) {
2786 ret = format_name(hls->segment_filename, &vs->basename, i, vs->varname);
2789 basename_size = strlen(vs->basename) + 1;
2791 if (hls->flags & HLS_SINGLE_FILE) {
2792 if (hls->segment_type == SEGMENT_TYPE_FMP4) {
2799 if (hls->use_localtime) {
2800 basename_size = strlen(vs->m3u8_name) + strlen(pattern_localtime_fmt) + 1;
2802 basename_size = strlen(vs->m3u8_name) + strlen(pattern) + 1;
2805 vs->basename = av_malloc(basename_size);
2806 if (!vs->basename) {
2807 ret = AVERROR(ENOMEM);
2811 av_strlcpy(vs->basename, vs->m3u8_name, basename_size);
2813 p = strrchr(vs->basename, '.');
2816 if (hls->use_localtime) {
2817 av_strlcat(vs->basename, pattern_localtime_fmt, basename_size);
2819 av_strlcat(vs->basename, pattern, basename_size);
2823 if (hls->segment_type == SEGMENT_TYPE_FMP4) {
2824 if (hls->nb_varstreams > 1)
2825 fmp4_init_filename_len += strlen(POSTFIX_PATTERN);
2826 if (hls->flags & HLS_SINGLE_FILE) {
2827 vs->fmp4_init_filename = av_strdup(vs->basename);
2828 if (!vs->fmp4_init_filename) {
2829 ret = AVERROR(ENOMEM);
2833 vs->fmp4_init_filename = av_malloc(fmp4_init_filename_len);
2834 if (!vs->fmp4_init_filename ) {
2835 ret = AVERROR(ENOMEM);
2838 av_strlcpy(vs->fmp4_init_filename, hls->fmp4_init_filename,
2839 fmp4_init_filename_len);
2840 if (hls->nb_varstreams > 1) {
2841 if (av_stristr(vs->fmp4_init_filename, "%v")) {
2842 av_freep(&vs->fmp4_init_filename);
2843 format_name(hls->fmp4_init_filename, &vs->fmp4_init_filename, i, vs->varname);
2845 ret = append_postfix(vs->fmp4_init_filename, fmp4_init_filename_len, i);
2851 fmp4_init_filename_len = strlen(vs->m3u8_name) +
2852 strlen(vs->fmp4_init_filename) + 1;
2854 vs->base_output_dirname = av_malloc(fmp4_init_filename_len);
2855 if (!vs->base_output_dirname) {
2856 ret = AVERROR(ENOMEM);
2860 av_strlcpy(vs->base_output_dirname, vs->m3u8_name,
2861 fmp4_init_filename_len);
2862 p = strrchr(vs->base_output_dirname, '/');
2865 av_strlcat(vs->base_output_dirname, vs->fmp4_init_filename,
2866 fmp4_init_filename_len);
2868 av_strlcpy(vs->base_output_dirname, vs->fmp4_init_filename,
2869 fmp4_init_filename_len);
2874 ret = hls->use_localtime ? sls_flag_check_duration_size(hls, vs) : sls_flag_check_duration_size_index(hls);
2878 if (vs->has_subtitle) {
2880 if (hls->flags & HLS_SINGLE_FILE)
2881 vtt_pattern = ".vtt";
2882 vtt_basename_size = strlen(vs->m3u8_name) + strlen(vtt_pattern) + 1;
2884 vs->vtt_basename = av_malloc(vtt_basename_size);
2885 if (!vs->vtt_basename) {
2886 ret = AVERROR(ENOMEM);
2889 vs->vtt_m3u8_name = av_malloc(vtt_basename_size);
2890 if (!vs->vtt_m3u8_name ) {
2891 ret = AVERROR(ENOMEM);
2894 av_strlcpy(vs->vtt_basename, vs->m3u8_name, vtt_basename_size);
2895 p = strrchr(vs->vtt_basename, '.');
2899 if ( hls->subtitle_filename ) {
2900 av_freep(&vs->vtt_m3u8_name);
2901 ret = format_name(hls->subtitle_filename, &vs->vtt_m3u8_name, i, vs->varname);
2905 strcpy(vs->vtt_m3u8_name, vs->vtt_basename);
2906 av_strlcat(vs->vtt_m3u8_name, "_vtt.m3u8", vtt_basename_size);
2908 av_strlcat(vs->vtt_basename, vtt_pattern, vtt_basename_size);
2912 vs->baseurl = av_strdup(hls->baseurl);
2914 ret = AVERROR(ENOMEM);
2919 if ((ret = hls_mux_init(s, vs)) < 0)
2922 if (hls->flags & HLS_APPEND_LIST) {
2923 parse_playlist(s, vs->m3u8_name, vs);
2924 vs->discontinuity = 1;
2925 if (hls->init_time > 0) {
2926 av_log(s, AV_LOG_WARNING, "append_list mode does not support hls_init_time,"
2927 " hls_init_time value will have no effect\n");
2929 hls->recording_time = hls->time * AV_TIME_BASE;
2933 if ((ret = hls_start(s, vs)) < 0)
2939 av_freep(&hls->key_basename);
2940 for (i = 0; i < hls->nb_varstreams && hls->var_streams; i++) {
2941 vs = &hls->var_streams[i];
2942 av_freep(&vs->basename);
2943 av_freep(&vs->vtt_basename);
2944 av_freep(&vs->fmp4_init_filename);
2945 av_freep(&vs->m3u8_name);
2946 av_freep(&vs->vtt_m3u8_name);
2947 av_freep(&vs->streams);
2948 av_freep(&vs->language);
2949 av_freep(&vs->agroup);
2950 av_freep(&vs->ccgroup);
2951 av_freep(&vs->baseurl);
2952 av_freep(&vs->varname);
2954 avformat_free_context(vs->avf);
2956 avformat_free_context(vs->vtt_avf);
2958 for (i = 0; i < hls->nb_ccstreams; i++) {
2959 ClosedCaptionsStream *ccs = &hls->cc_streams[i];
2960 av_freep(&ccs->ccgroup);
2961 av_freep(&ccs->instreamid);
2962 av_freep(&ccs->language);
2964 av_freep(&hls->var_streams);
2965 av_freep(&hls->cc_streams);
2966 av_freep(&hls->master_m3u8_url);
2972 #define OFFSET(x) offsetof(HLSContext, x)
2973 #define E AV_OPT_FLAG_ENCODING_PARAM
2974 static const AVOption options[] = {
2975 {"start_number", "set first number in the sequence", OFFSET(start_sequence),AV_OPT_TYPE_INT64, {.i64 = 0}, 0, INT64_MAX, E},
2976 {"hls_time", "set segment length in seconds", OFFSET(time), AV_OPT_TYPE_FLOAT, {.dbl = 2}, 0, FLT_MAX, E},
2977 {"hls_init_time", "set segment length in seconds at init list", OFFSET(init_time), AV_OPT_TYPE_FLOAT, {.dbl = 0}, 0, FLT_MAX, E},
2978 {"hls_list_size", "set maximum number of playlist entries", OFFSET(max_nb_segments), AV_OPT_TYPE_INT, {.i64 = 5}, 0, INT_MAX, E},
2979 {"hls_delete_threshold", "set number of unreferenced segments to keep before deleting", OFFSET(hls_delete_threshold), AV_OPT_TYPE_INT, {.i64 = 1}, 1, INT_MAX, E},
2980 {"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},
2981 {"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},
2983 {"hls_wrap", "set number after which the index wraps (will be deprecated)", OFFSET(wrap), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E},
2985 {"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},
2986 {"hls_base_url", "url to prepend to each playlist entry", OFFSET(baseurl), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
2987 {"hls_segment_filename", "filename template for segment files", OFFSET(segment_filename), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
2988 {"hls_segment_size", "maximum size per segment file, (in bytes)", OFFSET(max_seg_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E},
2989 {"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},
2990 {"hls_enc", "enable AES128 encryption support", OFFSET(encrypt), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, E},
2991 {"hls_enc_key", "hex-coded 16 byte key to encrypt the segments", OFFSET(key), AV_OPT_TYPE_STRING, .flags = E},
2992 {"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},
2993 {"hls_enc_iv", "hex-coded 16 byte initialization vector", OFFSET(iv), AV_OPT_TYPE_STRING, .flags = E},
2994 {"hls_subtitle_path", "set path of hls subtitles", OFFSET(subtitle_filename), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
2995 {"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"},
2996 {"mpegts", "make segment file to mpegts files in m3u8", 0, AV_OPT_TYPE_CONST, {.i64 = SEGMENT_TYPE_MPEGTS }, 0, UINT_MAX, E, "segment_type"},
2997 {"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"},
2998 {"hls_fmp4_init_filename", "set fragment mp4 file init filename", OFFSET(fmp4_init_filename), AV_OPT_TYPE_STRING, {.str = "init.mp4"}, 0, 0, E},
2999 {"hls_flags", "set flags affecting HLS playlist and media file generation", OFFSET(flags), AV_OPT_TYPE_FLAGS, {.i64 = 0 }, 0, UINT_MAX, E, "flags"},
3000 {"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"},
3001 {"temp_file", "write segment and playlist to temporary file and rename when complete", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_TEMP_FILE }, 0, UINT_MAX, E, "flags"},
3002 {"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"},
3003 {"round_durations", "round durations in m3u8 to whole numbers", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_ROUND_DURATIONS }, 0, UINT_MAX, E, "flags"},
3004 {"discont_start", "start the playlist with a discontinuity tag", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_DISCONT_START }, 0, UINT_MAX, E, "flags"},
3005 {"omit_endlist", "Do not append an endlist when ending stream", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_OMIT_ENDLIST }, 0, UINT_MAX, E, "flags"},
3006 {"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"},
3007 {"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"},
3008 {"program_date_time", "add EXT-X-PROGRAM-DATE-TIME", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_PROGRAM_DATE_TIME }, 0, UINT_MAX, E, "flags"},
3009 {"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"},
3010 {"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"},
3011 {"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"},
3012 {"periodic_rekey", "reload keyinfo file periodically for re-keying", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_PERIODIC_REKEY }, 0, UINT_MAX, E, "flags"},
3013 {"independent_segments", "add EXT-X-INDEPENDENT-SEGMENTS, whenever applicable", 0, AV_OPT_TYPE_CONST, { .i64 = HLS_INDEPENDENT_SEGMENTS }, 0, UINT_MAX, E, "flags"},
3014 {"iframes_only", "add EXT-X-I-FRAMES-ONLY, whenever applicable", 0, AV_OPT_TYPE_CONST, { .i64 = HLS_I_FRAMES_ONLY }, 0, UINT_MAX, E, "flags"},
3015 #if FF_API_HLS_USE_LOCALTIME
3016 {"use_localtime", "set filename expansion with strftime at segment creation(will be deprecated )", OFFSET(use_localtime), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, E },
3018 {"strftime", "set filename expansion with strftime at segment creation", OFFSET(use_localtime), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, E },
3019 #if FF_API_HLS_USE_LOCALTIME
3020 {"use_localtime_mkdir", "create last directory component in strftime-generated filename(will be deprecated)", OFFSET(use_localtime_mkdir), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, E },
3022 {"strftime_mkdir", "create last directory component in strftime-generated filename", OFFSET(use_localtime_mkdir), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, E },
3023 {"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" },
3024 {"event", "EVENT playlist", 0, AV_OPT_TYPE_CONST, {.i64 = PLAYLIST_TYPE_EVENT }, INT_MIN, INT_MAX, E, "pl_type" },
3025 {"vod", "VOD playlist", 0, AV_OPT_TYPE_CONST, {.i64 = PLAYLIST_TYPE_VOD }, INT_MIN, INT_MAX, E, "pl_type" },
3026 {"method", "set the HTTP method(default: PUT)", OFFSET(method), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
3027 {"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" },
3028 {"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" },
3029 {"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" },
3030 {"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" },
3031 {"http_user_agent", "override User-Agent field in HTTP header", OFFSET(user_agent), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
3032 {"var_stream_map", "Variant stream map string", OFFSET(var_stream_map), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
3033 {"cc_stream_map", "Closed captions stream map string", OFFSET(cc_stream_map), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
3034 {"master_pl_name", "Create HLS master playlist with this name", OFFSET(master_pl_name), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
3035 {"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},
3036 {"http_persistent", "Use persistent HTTP connections", OFFSET(http_persistent), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, E },
3037 {"timeout", "set timeout for socket I/O operations", OFFSET(timeout), AV_OPT_TYPE_DURATION, { .i64 = -1 }, -1, INT_MAX, .flags = E },
3038 {"ignore_io_errors", "Ignore IO errors for stable long-duration runs with network output", OFFSET(ignore_io_errors), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
3039 {"headers", "set custom HTTP headers, can override built in default headers", OFFSET(headers), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, E },
3043 static const AVClass hls_class = {
3044 .class_name = "hls muxer",
3045 .item_name = av_default_item_name,
3047 .version = LIBAVUTIL_VERSION_INT,
3051 AVOutputFormat ff_hls_muxer = {
3053 .long_name = NULL_IF_CONFIG_SMALL("Apple HTTP Live Streaming"),
3054 .extensions = "m3u8",
3055 .priv_data_size = sizeof(HLSContext),
3056 .audio_codec = AV_CODEC_ID_AAC,
3057 .video_codec = AV_CODEC_ID_H264,
3058 .subtitle_codec = AV_CODEC_ID_WEBVTT,
3059 .flags = AVFMT_NOFILE | AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_NODIMENSIONS,
3061 .write_header = hls_write_header,
3062 .write_packet = hls_write_packet,
3063 .write_trailer = hls_write_trailer,
3064 .priv_class = &hls_class,