FFmpeg coverage


Directory: ../../../ffmpeg/
File: src/libavformat/hlsenc.c
Date: 2023-12-04 05:51:44
Exec Total Coverage
Lines: 711 1849 38.5%
Functions: 25 46 54.3%
Branches: 418 1362 30.7%

Line Branch Exec Source
1 /*
2 * Apple HTTP Live Streaming segmenter
3 * Copyright (c) 2012, Luca Barbato
4 * Copyright (c) 2017 Akamai Technologies, Inc.
5 *
6 * This file is part of FFmpeg.
7 *
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.
12 *
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.
17 *
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
21 */
22
23 #include "config.h"
24 #include "config_components.h"
25 #include <stdint.h>
26 #include <time.h>
27 #if HAVE_UNISTD_H
28 #include <unistd.h>
29 #endif
30
31 #include "libavutil/avassert.h"
32 #include "libavutil/mathematics.h"
33 #include "libavutil/avstring.h"
34 #include "libavutil/bprint.h"
35 #include "libavutil/intreadwrite.h"
36 #include "libavutil/opt.h"
37 #include "libavutil/log.h"
38 #include "libavutil/random_seed.h"
39 #include "libavutil/time.h"
40 #include "libavutil/time_internal.h"
41
42 #include "libavcodec/defs.h"
43
44 #include "avformat.h"
45 #include "avio_internal.h"
46 #include "avc.h"
47 #if CONFIG_HTTP_PROTOCOL
48 #include "http.h"
49 #endif
50 #include "hlsplaylist.h"
51 #include "internal.h"
52 #include "mux.h"
53 #include "os_support.h"
54 #include "url.h"
55
56 typedef enum {
57 HLS_START_SEQUENCE_AS_START_NUMBER = 0,
58 HLS_START_SEQUENCE_AS_SECONDS_SINCE_EPOCH = 1,
59 HLS_START_SEQUENCE_AS_FORMATTED_DATETIME = 2, // YYYYMMDDhhmmss
60 HLS_START_SEQUENCE_AS_MICROSECONDS_SINCE_EPOCH = 3,
61 HLS_START_SEQUENCE_LAST, // unused
62 } StartSequenceSourceType;
63
64 typedef enum {
65 CODEC_ATTRIBUTE_WRITTEN = 0,
66 CODEC_ATTRIBUTE_WILL_NOT_BE_WRITTEN,
67 } CodecAttributeStatus;
68
69 #define KEYSIZE 16
70 #define LINE_BUFFER_SIZE MAX_URL_SIZE
71 #define HLS_MICROSECOND_UNIT 1000000
72 #define BUFSIZE (16 * 1024)
73 #define POSTFIX_PATTERN "_%d"
74
75 typedef struct HLSSegment {
76 char filename[MAX_URL_SIZE];
77 char sub_filename[MAX_URL_SIZE];
78 double duration; /* in seconds */
79 int discont;
80 int64_t pos;
81 int64_t size;
82 int64_t keyframe_pos;
83 int64_t keyframe_size;
84 unsigned var_stream_idx;
85
86 char key_uri[LINE_BUFFER_SIZE + 1];
87 char iv_string[KEYSIZE*2 + 1];
88
89 struct HLSSegment *next;
90 double discont_program_date_time;
91 } HLSSegment;
92
93 typedef enum HLSFlags {
94 // Generate a single media file and use byte ranges in the playlist.
95 HLS_SINGLE_FILE = (1 << 0),
96 HLS_DELETE_SEGMENTS = (1 << 1),
97 HLS_ROUND_DURATIONS = (1 << 2),
98 HLS_DISCONT_START = (1 << 3),
99 HLS_OMIT_ENDLIST = (1 << 4),
100 HLS_SPLIT_BY_TIME = (1 << 5),
101 HLS_APPEND_LIST = (1 << 6),
102 HLS_PROGRAM_DATE_TIME = (1 << 7),
103 HLS_SECOND_LEVEL_SEGMENT_INDEX = (1 << 8), // include segment index in segment filenames when use_localtime e.g.: %%03d
104 HLS_SECOND_LEVEL_SEGMENT_DURATION = (1 << 9), // include segment duration (microsec) in segment filenames when use_localtime e.g.: %%09t
105 HLS_SECOND_LEVEL_SEGMENT_SIZE = (1 << 10), // include segment size (bytes) in segment filenames when use_localtime e.g.: %%014s
106 HLS_TEMP_FILE = (1 << 11),
107 HLS_PERIODIC_REKEY = (1 << 12),
108 HLS_INDEPENDENT_SEGMENTS = (1 << 13),
109 HLS_I_FRAMES_ONLY = (1 << 14),
110 } HLSFlags;
111
112 typedef enum {
113 SEGMENT_TYPE_MPEGTS,
114 SEGMENT_TYPE_FMP4,
115 } SegmentType;
116
117 typedef struct VariantStream {
118 unsigned var_stream_idx;
119 unsigned number;
120 int64_t sequence;
121 const AVOutputFormat *oformat;
122 const AVOutputFormat *vtt_oformat;
123 AVIOContext *out;
124 AVIOContext *out_single_file;
125 int packets_written;
126 int init_range_length;
127 uint8_t *temp_buffer;
128 uint8_t *init_buffer;
129
130 AVFormatContext *avf;
131 AVFormatContext *vtt_avf;
132
133 int has_video;
134 int has_subtitle;
135 int new_start;
136 int start_pts_from_audio;
137 double dpp; // duration per packet
138 int64_t start_pts;
139 int64_t end_pts;
140 int64_t video_lastpos;
141 int64_t video_keyframe_pos;
142 int64_t video_keyframe_size;
143 double duration; // last segment duration computed so far, in seconds
144 int64_t start_pos; // last segment starting position
145 int64_t size; // last segment size
146 int nb_entries;
147 int discontinuity_set;
148 int discontinuity;
149 int reference_stream_index;
150
151 HLSSegment *segments;
152 HLSSegment *last_segment;
153 HLSSegment *old_segments;
154
155 char *basename_tmp;
156 char *basename;
157 char *vtt_basename;
158 char *vtt_m3u8_name;
159 char *m3u8_name;
160
161 double initial_prog_date_time;
162 char current_segment_final_filename_fmt[MAX_URL_SIZE]; // when renaming segments
163
164 char *fmp4_init_filename;
165 char *base_output_dirname;
166
167 int encrypt_started;
168
169 char key_file[LINE_BUFFER_SIZE + 1];
170 char key_uri[LINE_BUFFER_SIZE + 1];
171 char key_string[KEYSIZE*2 + 1];
172 char iv_string[KEYSIZE*2 + 1];
173
174 AVStream **streams;
175 char codec_attr[128];
176 CodecAttributeStatus attr_status;
177 unsigned int nb_streams;
178 int m3u8_created; /* status of media play-list creation */
179 int is_default; /* default status of audio group */
180 const char *language; /* audio language name */
181 const char *agroup; /* audio group name */
182 const char *sgroup; /* subtitle group name */
183 const char *ccgroup; /* closed caption group name */
184 const char *varname; /* variant name */
185 } VariantStream;
186
187 typedef struct ClosedCaptionsStream {
188 const char *ccgroup; /* closed caption group name */
189 const char *instreamid; /* closed captions INSTREAM-ID */
190 const char *language; /* closed captions language */
191 } ClosedCaptionsStream;
192
193 typedef struct HLSContext {
194 const AVClass *class; // Class for private options.
195 int64_t start_sequence;
196 uint32_t start_sequence_source_type; // enum StartSequenceSourceType
197
198 int64_t time; // Set by a private option.
199 int64_t init_time; // Set by a private option.
200 int max_nb_segments; // Set by a private option.
201 int hls_delete_threshold; // Set by a private option.
202 uint32_t flags; // enum HLSFlags
203 uint32_t pl_type; // enum PlaylistType
204 char *segment_filename;
205 char *fmp4_init_filename;
206 int segment_type;
207 int resend_init_file; ///< resend init file into disk after refresh m3u8
208
209 int use_localtime; ///< flag to expand filename with localtime
210 int use_localtime_mkdir;///< flag to mkdir dirname in timebased filename
211 int allowcache;
212 int64_t recording_time;
213 int64_t max_seg_size; // every segment file max size
214
215 char *baseurl;
216 char *vtt_format_options_str;
217 char *subtitle_filename;
218 AVDictionary *format_options;
219
220 int encrypt;
221 char *key;
222 char *key_url;
223 char *iv;
224 char *key_basename;
225 int encrypt_started;
226
227 char *key_info_file;
228 char key_file[LINE_BUFFER_SIZE + 1];
229 char key_uri[LINE_BUFFER_SIZE + 1];
230 char key_string[KEYSIZE*2 + 1];
231 char iv_string[KEYSIZE*2 + 1];
232 AVDictionary *vtt_format_options;
233
234 char *method;
235 char *user_agent;
236
237 VariantStream *var_streams;
238 unsigned int nb_varstreams;
239 ClosedCaptionsStream *cc_streams;
240 unsigned int nb_ccstreams;
241
242 int master_m3u8_created; /* status of master play-list creation */
243 char *master_m3u8_url; /* URL of the master m3u8 file */
244 int version; /* HLS version */
245 char *var_stream_map; /* user specified variant stream map string */
246 char *cc_stream_map; /* user specified closed caption streams map string */
247 char *master_pl_name;
248 unsigned int master_publish_rate;
249 int http_persistent;
250 AVIOContext *m3u8_out;
251 AVIOContext *sub_m3u8_out;
252 AVIOContext *http_delete;
253 int64_t timeout;
254 int ignore_io_errors;
255 char *headers;
256 int has_default_key; /* has DEFAULT field of var_stream_map */
257 int has_video_m3u8; /* has video stream m3u8 list */
258 } HLSContext;
259
260 static int strftime_expand(const char *fmt, char **dest)
261 {
262 int r = 1;
263 time_t now0;
264 struct tm *tm, tmpbuf;
265 char *buf;
266
267 buf = av_mallocz(MAX_URL_SIZE);
268 if (!buf)
269 return AVERROR(ENOMEM);
270
271 time(&now0);
272 tm = localtime_r(&now0, &tmpbuf);
273 r = strftime(buf, MAX_URL_SIZE, fmt, tm);
274 if (!r) {
275 av_free(buf);
276 return AVERROR(EINVAL);
277 }
278 *dest = buf;
279
280 return r;
281 }
282
283 119 static int hlsenc_io_open(AVFormatContext *s, AVIOContext **pb, const char *filename,
284 AVDictionary **options)
285 {
286 119 HLSContext *hls = s->priv_data;
287
1/2
✓ Branch 0 taken 119 times.
✗ Branch 1 not taken.
119 int http_base_proto = filename ? ff_is_http_proto(filename) : 0;
288 119 int err = AVERROR_MUXER_NOT_FOUND;
289
1/6
✗ Branch 0 not taken.
✓ Branch 1 taken 119 times.
✗ Branch 2 not taken.
✗ Branch 3 not taken.
✗ Branch 4 not taken.
✗ Branch 5 not taken.
119 if (!*pb || !http_base_proto || !hls->http_persistent) {
290 119 err = s->io_open(s, pb, filename, AVIO_FLAG_WRITE, options);
291 #if CONFIG_HTTP_PROTOCOL
292 } else {
293 URLContext *http_url_context = ffio_geturlcontext(*pb);
294 av_assert0(http_url_context);
295 err = ff_http_do_new_request(http_url_context, filename);
296 if (err < 0)
297 ff_format_io_close(s, pb);
298
299 #endif
300 }
301 119 return err;
302 }
303
304 185 static int hlsenc_io_close(AVFormatContext *s, AVIOContext **pb, char *filename)
305 {
306 185 HLSContext *hls = s->priv_data;
307
2/2
✓ Branch 0 taken 119 times.
✓ Branch 1 taken 66 times.
185 int http_base_proto = filename ? ff_is_http_proto(filename) : 0;
308 185 int ret = 0;
309
2/2
✓ Branch 0 taken 66 times.
✓ Branch 1 taken 119 times.
185 if (!*pb)
310 66 return ret;
311
1/8
✗ Branch 0 not taken.
✓ Branch 1 taken 119 times.
✗ Branch 2 not taken.
✗ Branch 3 not taken.
✗ Branch 4 not taken.
✗ Branch 5 not taken.
✗ Branch 6 not taken.
✗ Branch 7 not taken.
119 if (!http_base_proto || !hls->http_persistent || hls->key_info_file || hls->encrypt) {
312 119 ff_format_io_close(s, pb);
313 #if CONFIG_HTTP_PROTOCOL
314 } else {
315 URLContext *http_url_context = ffio_geturlcontext(*pb);
316 av_assert0(http_url_context);
317 avio_flush(*pb);
318 ret = ffurl_shutdown(http_url_context, AVIO_FLAG_WRITE);
319 #endif
320 }
321 119 return ret;
322 }
323
324 118 static void set_http_options(AVFormatContext *s, AVDictionary **options, HLSContext *c)
325 {
326 118 int http_base_proto = ff_is_http_proto(s->url);
327
328
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 118 times.
118 if (c->method) {
329 av_dict_set(options, "method", c->method, 0);
330
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 118 times.
118 } else if (http_base_proto) {
331 av_dict_set(options, "method", "PUT", 0);
332 }
333
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 118 times.
118 if (c->user_agent)
334 av_dict_set(options, "user_agent", c->user_agent, 0);
335
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 118 times.
118 if (c->http_persistent)
336 av_dict_set_int(options, "multiple_requests", 1, 0);
337
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 118 times.
118 if (c->timeout >= 0)
338 av_dict_set_int(options, "timeout", c->timeout, 0);
339
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 118 times.
118 if (c->headers)
340 av_dict_set(options, "headers", c->headers, 0);
341 118 }
342
343 10 static void write_codec_attr(AVStream *st, VariantStream *vs)
344 {
345 10 int codec_strlen = strlen(vs->codec_attr);
346 char attr[32];
347
348
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 10 times.
10 if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE)
349 return;
350
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 10 times.
10 if (vs->attr_status == CODEC_ATTRIBUTE_WILL_NOT_BE_WRITTEN)
351 return;
352
353
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 10 times.
10 if (st->codecpar->codec_id == AV_CODEC_ID_H264) {
354 uint8_t *data = st->codecpar->extradata;
355 if (data) {
356 const uint8_t *p;
357
358 if (AV_RB32(data) == 0x01 && (data[4] & 0x1F) == 7)
359 p = &data[5];
360 else if (AV_RB24(data) == 0x01 && (data[3] & 0x1F) == 7)
361 p = &data[4];
362 else if (data[0] == 0x01) /* avcC */
363 p = &data[1];
364 else
365 goto fail;
366 snprintf(attr, sizeof(attr),
367 "avc1.%02x%02x%02x", p[0], p[1], p[2]);
368 } else {
369 goto fail;
370 }
371
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 10 times.
10 } else if (st->codecpar->codec_id == AV_CODEC_ID_HEVC) {
372 uint8_t *data = st->codecpar->extradata;
373 int profile = AV_PROFILE_UNKNOWN;
374 int level = AV_LEVEL_UNKNOWN;
375
376 if (st->codecpar->profile != AV_PROFILE_UNKNOWN)
377 profile = st->codecpar->profile;
378 if (st->codecpar->level != AV_LEVEL_UNKNOWN)
379 level = st->codecpar->level;
380
381 /* check the boundary of data which from current position is small than extradata_size */
382 while (data && (data - st->codecpar->extradata + 19) < st->codecpar->extradata_size) {
383 /* get HEVC SPS NAL and seek to profile_tier_level */
384 if (!(data[0] | data[1] | data[2]) && data[3] == 1 && ((data[4] & 0x7E) == 0x42)) {
385 uint8_t *rbsp_buf;
386 int remain_size = 0;
387 int rbsp_size = 0;
388 /* skip start code + nalu header */
389 data += 6;
390 /* process by reference General NAL unit syntax */
391 remain_size = st->codecpar->extradata_size - (data - st->codecpar->extradata);
392 rbsp_buf = ff_nal_unit_extract_rbsp(data, remain_size, &rbsp_size, 0);
393 if (!rbsp_buf)
394 return;
395 if (rbsp_size < 13) {
396 av_freep(&rbsp_buf);
397 break;
398 }
399 /* skip sps_video_parameter_set_id u(4),
400 * sps_max_sub_layers_minus1 u(3),
401 * and sps_temporal_id_nesting_flag u(1) */
402 profile = rbsp_buf[1] & 0x1f;
403 /* skip 8 + 8 + 32 + 4 + 43 + 1 bit */
404 level = rbsp_buf[12];
405 av_freep(&rbsp_buf);
406 break;
407 }
408 data++;
409 }
410 if (st->codecpar->codec_tag == MKTAG('h','v','c','1') &&
411 profile != AV_PROFILE_UNKNOWN &&
412 level != AV_LEVEL_UNKNOWN) {
413 snprintf(attr, sizeof(attr), "%s.%d.4.L%d.B01", av_fourcc2str(st->codecpar->codec_tag), profile, level);
414 } else
415 goto fail;
416
2/2
✓ Branch 0 taken 9 times.
✓ Branch 1 taken 1 times.
10 } else if (st->codecpar->codec_id == AV_CODEC_ID_MP2) {
417 9 snprintf(attr, sizeof(attr), "mp4a.40.33");
418
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 1 times.
1 } else if (st->codecpar->codec_id == AV_CODEC_ID_MP3) {
419 snprintf(attr, sizeof(attr), "mp4a.40.34");
420
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 1 times.
1 } else if (st->codecpar->codec_id == AV_CODEC_ID_AAC) {
421 /* TODO : For HE-AAC, HE-AACv2, the last digit needs to be set to 5 and 29 respectively */
422 snprintf(attr, sizeof(attr), "mp4a.40.2");
423
1/2
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
1 } else if (st->codecpar->codec_id == AV_CODEC_ID_AC3) {
424 1 snprintf(attr, sizeof(attr), "ac-3");
425 } else if (st->codecpar->codec_id == AV_CODEC_ID_EAC3) {
426 snprintf(attr, sizeof(attr), "ec-3");
427 } else {
428 goto fail;
429 }
430 // Don't write the same attribute multiple times
431
1/2
✓ Branch 1 taken 10 times.
✗ Branch 2 not taken.
10 if (!av_stristr(vs->codec_attr, attr)) {
432
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 10 times.
10 snprintf(vs->codec_attr + codec_strlen,
433 sizeof(vs->codec_attr) - codec_strlen,
434 "%s%s", codec_strlen ? "," : "", attr);
435 }
436 10 return;
437
438 fail:
439 vs->codec_attr[0] = '\0';
440 vs->attr_status = CODEC_ATTRIBUTE_WILL_NOT_BE_WRITTEN;
441 return;
442 }
443
444 static int replace_str_data_in_filename(char **s, const char *filename, char placeholder, const char *datastring)
445 {
446 const char *p;
447 char c;
448 int addchar_count;
449 int found_count = 0;
450 AVBPrint buf;
451 int ret;
452
453 av_bprint_init(&buf, 0, AV_BPRINT_SIZE_UNLIMITED);
454
455 p = filename;
456 for (;;) {
457 c = *p;
458 if (c == '\0')
459 break;
460 if (c == '%' && *(p+1) == '%') // %%
461 addchar_count = 2;
462 else if (c == '%' && *(p+1) == placeholder) {
463 av_bprintf(&buf, "%s", datastring);
464 p += 2;
465 addchar_count = 0;
466 found_count ++;
467 } else
468 addchar_count = 1;
469
470 if (addchar_count > 0) {
471 av_bprint_append_data(&buf, p, addchar_count);
472 p += addchar_count;
473 }
474 }
475 if (!av_bprint_is_complete(&buf)) {
476 av_bprint_finalize(&buf, NULL);
477 return AVERROR(ENOMEM);
478 }
479 if ((ret = av_bprint_finalize(&buf, s)) < 0)
480 return ret;
481 return found_count;
482 }
483
484 50 static int replace_int_data_in_filename(char **s, const char *filename, char placeholder, int64_t number)
485 {
486 const char *p;
487 char c;
488 int nd, addchar_count;
489 50 int found_count = 0;
490 AVBPrint buf;
491 int ret;
492
493 50 av_bprint_init(&buf, 0, AV_BPRINT_SIZE_UNLIMITED);
494
495 50 p = filename;
496 for (;;) {
497 4329 c = *p;
498
2/2
✓ Branch 0 taken 50 times.
✓ Branch 1 taken 4279 times.
4329 if (c == '\0')
499 50 break;
500
3/4
✓ Branch 0 taken 50 times.
✓ Branch 1 taken 4229 times.
✗ Branch 2 not taken.
✓ Branch 3 taken 50 times.
4279 if (c == '%' && *(p+1) == '%') // %%
501 addchar_count = 2;
502
5/6
✓ Branch 0 taken 50 times.
✓ Branch 1 taken 4229 times.
✓ Branch 2 taken 34 times.
✓ Branch 3 taken 16 times.
✓ Branch 4 taken 34 times.
✗ Branch 5 not taken.
4279 else if (c == '%' && (av_isdigit(*(p+1)) || *(p+1) == placeholder)) {
503 50 nd = 0;
504 50 addchar_count = 1;
505
2/2
✓ Branch 0 taken 32 times.
✓ Branch 1 taken 50 times.
82 while (av_isdigit(*(p + addchar_count))) {
506 32 nd = nd * 10 + *(p + addchar_count) - '0';
507 32 addchar_count++;
508 }
509
510
1/2
✓ Branch 0 taken 50 times.
✗ Branch 1 not taken.
50 if (*(p + addchar_count) == placeholder) {
511
1/2
✓ Branch 0 taken 50 times.
✗ Branch 1 not taken.
50 av_bprintf(&buf, "%0*"PRId64, (number < 0) ? nd : nd++, number);
512 50 p += (addchar_count + 1);
513 50 addchar_count = 0;
514 50 found_count++;
515 }
516
517 } else
518 4229 addchar_count = 1;
519
520 4279 av_bprint_append_data(&buf, p, addchar_count);
521 4279 p += addchar_count;
522 }
523
1/2
✗ Branch 1 not taken.
✓ Branch 2 taken 50 times.
50 if (!av_bprint_is_complete(&buf)) {
524 av_bprint_finalize(&buf, NULL);
525 return AVERROR(ENOMEM);
526 }
527
1/2
✗ Branch 1 not taken.
✓ Branch 2 taken 50 times.
50 if ((ret = av_bprint_finalize(&buf, s)) < 0)
528 return ret;
529 50 return found_count;
530 }
531
532 5 static void write_styp(AVIOContext *pb)
533 {
534 5 avio_wb32(pb, 24);
535 5 ffio_wfourcc(pb, "styp");
536 5 ffio_wfourcc(pb, "msdh");
537 5 avio_wb32(pb, 0); /* minor */
538 5 ffio_wfourcc(pb, "msdh");
539 5 ffio_wfourcc(pb, "msix");
540 5 }
541
542 60 static int flush_dynbuf(VariantStream *vs, int *range_length)
543 {
544 60 AVFormatContext *ctx = vs->avf;
545
546
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 60 times.
60 if (!ctx->pb) {
547 return AVERROR(EINVAL);
548 }
549
550 // flush
551 60 av_write_frame(ctx, NULL);
552
553 // write out to file
554 60 *range_length = avio_close_dyn_buf(ctx->pb, &vs->temp_buffer);
555 60 ctx->pb = NULL;
556 60 avio_write(vs->out, vs->temp_buffer, *range_length);
557 60 avio_flush(vs->out);
558
559 // re-open buffer
560 60 return avio_open_dyn_buf(&ctx->pb);
561 }
562
563 static void reflush_dynbuf(VariantStream *vs, int *range_length)
564 {
565 // re-open buffer
566 avio_write(vs->out, vs->temp_buffer, *range_length);
567 }
568
569 #if HAVE_DOS_PATHS
570 #define SEPARATOR '\\'
571 #else
572 #define SEPARATOR '/'
573 #endif
574
575 static int hls_delete_file(HLSContext *hls, AVFormatContext *avf,
576 char *path, const char *proto)
577 {
578 if (hls->method || (proto && !av_strcasecmp(proto, "http"))) {
579 AVDictionary *opt = NULL;
580 int ret;
581
582 set_http_options(avf, &opt, hls);
583 av_dict_set(&opt, "method", "DELETE", 0);
584
585 ret = hlsenc_io_open(avf, &hls->http_delete, path, &opt);
586 av_dict_free(&opt);
587 if (ret < 0)
588 return hls->ignore_io_errors ? 1 : ret;
589
590 //Nothing to write
591 hlsenc_io_close(avf, &hls->http_delete, path);
592 } else if (unlink(path) < 0) {
593 av_log(hls, AV_LOG_ERROR, "failed to delete old segment %s: %s\n",
594 path, strerror(errno));
595 }
596 return 0;
597 }
598
599 static int hls_delete_old_segments(AVFormatContext *s, HLSContext *hls,
600 VariantStream *vs)
601 {
602
603 HLSSegment *segment, *previous_segment = NULL;
604 float playlist_duration = 0.0f;
605 int ret = 0;
606 int segment_cnt = 0;
607 AVBPrint path;
608 const char *dirname = NULL;
609 char *dirname_r = NULL;
610 char *dirname_repl = NULL;
611 const char *vtt_dirname = NULL;
612 char *vtt_dirname_r = NULL;
613 const char *proto = NULL;
614
615 av_bprint_init(&path, 0, AV_BPRINT_SIZE_UNLIMITED);
616
617 segment = vs->segments;
618 while (segment) {
619 playlist_duration += segment->duration;
620 segment = segment->next;
621 }
622
623 segment = vs->old_segments;
624 segment_cnt = 0;
625 while (segment) {
626 playlist_duration -= segment->duration;
627 previous_segment = segment;
628 segment = previous_segment->next;
629 segment_cnt++;
630 if (playlist_duration <= -previous_segment->duration) {
631 previous_segment->next = NULL;
632 break;
633 }
634 if (segment_cnt >= hls->hls_delete_threshold) {
635 previous_segment->next = NULL;
636 break;
637 }
638 }
639
640 if (segment && !hls->use_localtime_mkdir) {
641 dirname_r = hls->segment_filename ? av_strdup(hls->segment_filename): av_strdup(vs->avf->url);
642 dirname = av_dirname(dirname_r);
643 }
644
645 /* if %v is present in the file's directory
646 * all segment belongs to the same variant, so do it only once before the loop*/
647 if (dirname && av_stristr(dirname, "%v")) {
648 if (!vs->varname) {
649 if (replace_int_data_in_filename(&dirname_repl, dirname, 'v', segment->var_stream_idx) < 1) {
650 ret = AVERROR(EINVAL);
651 goto fail;
652 }
653 } else {
654 if (replace_str_data_in_filename(&dirname_repl, dirname, 'v', vs->varname) < 1) {
655 ret = AVERROR(EINVAL);
656 goto fail;
657 }
658 }
659
660 dirname = dirname_repl;
661 }
662
663 while (segment) {
664 av_log(hls, AV_LOG_DEBUG, "deleting old segment %s\n",
665 segment->filename);
666 if (!hls->use_localtime_mkdir) // segment->filename contains basename only
667 av_bprintf(&path, "%s%c", dirname, SEPARATOR);
668 av_bprintf(&path, "%s", segment->filename);
669
670 if (!av_bprint_is_complete(&path)) {
671 ret = AVERROR(ENOMEM);
672 goto fail;
673 }
674
675 proto = avio_find_protocol_name(s->url);
676 if (ret = hls_delete_file(hls, s, path.str, proto))
677 goto fail;
678
679 if ((segment->sub_filename[0] != '\0')) {
680 vtt_dirname_r = av_strdup(vs->vtt_avf->url);
681 vtt_dirname = av_dirname(vtt_dirname_r);
682
683 av_bprint_clear(&path);
684 av_bprintf(&path, "%s%c%s", vtt_dirname, SEPARATOR,
685 segment->sub_filename);
686 av_freep(&vtt_dirname_r);
687
688 if (!av_bprint_is_complete(&path)) {
689 ret = AVERROR(ENOMEM);
690 goto fail;
691 }
692
693 if (ret = hls_delete_file(hls, s, path.str, proto))
694 goto fail;
695 }
696 av_bprint_clear(&path);
697 previous_segment = segment;
698 segment = previous_segment->next;
699 av_freep(&previous_segment);
700 }
701
702 fail:
703 av_bprint_finalize(&path, NULL);
704 av_freep(&dirname_r);
705 av_freep(&dirname_repl);
706
707 return ret;
708 }
709
710 static int do_encrypt(AVFormatContext *s, VariantStream *vs)
711 {
712 HLSContext *hls = s->priv_data;
713 int ret;
714 int len;
715 AVIOContext *pb;
716 uint8_t key[KEYSIZE];
717 char * key_basename_source = (hls->master_m3u8_url) ? hls->master_m3u8_url : s->url;
718
719 len = strlen(key_basename_source) + 4 + 1;
720 hls->key_basename = av_mallocz(len);
721 if (!hls->key_basename)
722 return AVERROR(ENOMEM);
723
724 av_strlcpy(hls->key_basename, key_basename_source, len);
725 av_strlcat(hls->key_basename, ".key", len);
726
727 if (hls->key_url) {
728 av_strlcpy(hls->key_file, hls->key_url, sizeof(hls->key_file));
729 av_strlcpy(hls->key_uri, hls->key_url, sizeof(hls->key_uri));
730 } else {
731 av_strlcpy(hls->key_file, hls->key_basename, sizeof(hls->key_file));
732 av_strlcpy(hls->key_uri, hls->key_basename, sizeof(hls->key_uri));
733 }
734
735 if (!*hls->iv_string) {
736 uint8_t iv[16] = { 0 };
737 char buf[33];
738
739 if (!hls->iv) {
740 AV_WB64(iv + 8, vs->sequence);
741 } else {
742 memcpy(iv, hls->iv, sizeof(iv));
743 }
744 ff_data_to_hex(buf, iv, sizeof(iv), 0);
745 memcpy(hls->iv_string, buf, sizeof(hls->iv_string));
746 }
747
748 if (!*hls->key_uri) {
749 av_log(hls, AV_LOG_ERROR, "no key URI specified in key info file\n");
750 return AVERROR(EINVAL);
751 }
752
753 if (!*hls->key_file) {
754 av_log(hls, AV_LOG_ERROR, "no key file specified in key info file\n");
755 return AVERROR(EINVAL);
756 }
757
758 if (!*hls->key_string) {
759 AVDictionary *options = NULL;
760 if (!hls->key) {
761 if ((ret = av_random_bytes(key, sizeof(key))) < 0) {
762 av_log(s, AV_LOG_ERROR, "Cannot generate a strong random key\n");
763 return ret;
764 }
765 } else {
766 memcpy(key, hls->key, sizeof(key));
767 }
768
769 ff_data_to_hex(hls->key_string, key, sizeof(key), 0);
770 set_http_options(s, &options, hls);
771 ret = s->io_open(s, &pb, hls->key_file, AVIO_FLAG_WRITE, &options);
772 av_dict_free(&options);
773 if (ret < 0)
774 return ret;
775 avio_seek(pb, 0, SEEK_CUR);
776 avio_write(pb, key, KEYSIZE);
777 avio_close(pb);
778 }
779 return 0;
780 }
781
782
783 static int hls_encryption_start(AVFormatContext *s, VariantStream *vs)
784 {
785 HLSContext *hls = s->priv_data;
786 int ret;
787 AVIOContext *pb;
788 uint8_t key[KEYSIZE];
789 AVDictionary *options = NULL;
790
791 set_http_options(s, &options, hls);
792 ret = s->io_open(s, &pb, hls->key_info_file, AVIO_FLAG_READ, &options);
793 av_dict_free(&options);
794 if (ret < 0) {
795 av_log(hls, AV_LOG_ERROR,
796 "error opening key info file %s\n", hls->key_info_file);
797 return ret;
798 }
799
800 ff_get_line(pb, vs->key_uri, sizeof(vs->key_uri));
801 vs->key_uri[strcspn(vs->key_uri, "\r\n")] = '\0';
802
803 ff_get_line(pb, vs->key_file, sizeof(vs->key_file));
804 vs->key_file[strcspn(vs->key_file, "\r\n")] = '\0';
805
806 ff_get_line(pb, vs->iv_string, sizeof(vs->iv_string));
807 vs->iv_string[strcspn(vs->iv_string, "\r\n")] = '\0';
808
809 ff_format_io_close(s, &pb);
810
811 if (!*vs->key_uri) {
812 av_log(hls, AV_LOG_ERROR, "no key URI specified in key info file\n");
813 return AVERROR(EINVAL);
814 }
815
816 if (!*vs->key_file) {
817 av_log(hls, AV_LOG_ERROR, "no key file specified in key info file\n");
818 return AVERROR(EINVAL);
819 }
820
821 set_http_options(s, &options, hls);
822 ret = s->io_open(s, &pb, vs->key_file, AVIO_FLAG_READ, &options);
823 av_dict_free(&options);
824 if (ret < 0) {
825 av_log(hls, AV_LOG_ERROR, "error opening key file %s\n", vs->key_file);
826 return ret;
827 }
828
829 ret = avio_read(pb, key, sizeof(key));
830 ff_format_io_close(s, &pb);
831 if (ret != sizeof(key)) {
832 av_log(hls, AV_LOG_ERROR, "error reading key file %s\n", vs->key_file);
833 if (ret >= 0 || ret == AVERROR_EOF)
834 ret = AVERROR(EINVAL);
835 return ret;
836 }
837 ff_data_to_hex(vs->key_string, key, sizeof(key), 0);
838
839 return 0;
840 }
841
842 10 static int hls_mux_init(AVFormatContext *s, VariantStream *vs)
843 {
844 10 AVDictionary *options = NULL;
845 10 HLSContext *hls = s->priv_data;
846 AVFormatContext *oc;
847 10 AVFormatContext *vtt_oc = NULL;
848
4/4
✓ Branch 0 taken 9 times.
✓ Branch 1 taken 1 times.
✓ Branch 2 taken 1 times.
✓ Branch 3 taken 8 times.
10 int byterange_mode = (hls->flags & HLS_SINGLE_FILE) || (hls->max_seg_size > 0);
849 int remaining_options;
850 int i, ret;
851
852 10 ret = avformat_alloc_output_context2(&vs->avf, vs->oformat, NULL, NULL);
853
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 10 times.
10 if (ret < 0)
854 return ret;
855 10 oc = vs->avf;
856
857 10 oc->url = av_strdup("");
858
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 10 times.
10 if (!oc->url)
859 return AVERROR(ENOMEM);
860
861 10 oc->interrupt_callback = s->interrupt_callback;
862 10 oc->max_delay = s->max_delay;
863 10 oc->opaque = s->opaque;
864 10 oc->io_open = s->io_open;
865 #if FF_API_AVFORMAT_IO_CLOSE
866 FF_DISABLE_DEPRECATION_WARNINGS
867 10 oc->io_close = s->io_close;
868 FF_ENABLE_DEPRECATION_WARNINGS
869 #endif
870 10 oc->io_close2 = s->io_close2;
871 10 oc->strict_std_compliance = s->strict_std_compliance;
872 10 av_dict_copy(&oc->metadata, s->metadata, 0);
873
874
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 10 times.
10 if (vs->vtt_oformat) {
875 ret = avformat_alloc_output_context2(&vs->vtt_avf, vs->vtt_oformat, NULL, NULL);
876 if (ret < 0)
877 return ret;
878 vtt_oc = vs->vtt_avf;
879 av_dict_copy(&vtt_oc->metadata, s->metadata, 0);
880 }
881
882
2/2
✓ Branch 0 taken 10 times.
✓ Branch 1 taken 10 times.
20 for (i = 0; i < vs->nb_streams; i++) {
883 AVStream *st;
884 AVFormatContext *loc;
885
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 10 times.
10 if (vs->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE)
886 loc = vtt_oc;
887 else
888 10 loc = oc;
889
890
1/2
✗ Branch 1 not taken.
✓ Branch 2 taken 10 times.
10 if (!(st = avformat_new_stream(loc, NULL)))
891 return AVERROR(ENOMEM);
892 10 avcodec_parameters_copy(st->codecpar, vs->streams[i]->codecpar);
893
2/2
✓ Branch 0 taken 1 times.
✓ Branch 1 taken 9 times.
10 if (!oc->oformat->codec_tag ||
894
2/4
✓ Branch 1 taken 1 times.
✗ Branch 2 not taken.
✗ Branch 3 not taken.
✓ Branch 4 taken 1 times.
2 av_codec_get_id (oc->oformat->codec_tag, vs->streams[i]->codecpar->codec_tag) == st->codecpar->codec_id ||
895 1 av_codec_get_tag(oc->oformat->codec_tag, vs->streams[i]->codecpar->codec_id) <= 0) {
896 9 st->codecpar->codec_tag = vs->streams[i]->codecpar->codec_tag;
897 } else {
898 1 st->codecpar->codec_tag = 0;
899 }
900
901 10 st->sample_aspect_ratio = vs->streams[i]->sample_aspect_ratio;
902 10 st->time_base = vs->streams[i]->time_base;
903 10 av_dict_copy(&st->metadata, vs->streams[i]->metadata, 0);
904 10 st->id = vs->streams[i]->id;
905 }
906
907 10 vs->start_pos = 0;
908 10 vs->new_start = 1;
909
910
3/4
✓ Branch 0 taken 1 times.
✓ Branch 1 taken 9 times.
✗ Branch 2 not taken.
✓ Branch 3 taken 1 times.
10 if (hls->segment_type == SEGMENT_TYPE_FMP4 && hls->max_seg_size > 0) {
911 if (hls->http_persistent > 0) {
912 //TODO: Support fragment fmp4 for http persistent in HLS muxer.
913 av_log(s, AV_LOG_WARNING, "http persistent mode is currently unsupported for fragment mp4 in the HLS muxer.\n");
914 }
915 if (hls->max_seg_size > 0) {
916 av_log(s, AV_LOG_WARNING, "Multi-file byterange mode is currently unsupported in the HLS muxer.\n");
917 return AVERROR_PATCHWELCOME;
918 }
919 }
920
921
1/2
✗ Branch 1 not taken.
✓ Branch 2 taken 10 times.
10 if ((ret = avio_open_dyn_buf(&oc->pb)) < 0)
922 return ret;
923
924
2/2
✓ Branch 0 taken 1 times.
✓ Branch 1 taken 9 times.
10 if (hls->segment_type == SEGMENT_TYPE_FMP4) {
925 1 set_http_options(s, &options, hls);
926
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 1 times.
1 if (byterange_mode) {
927 ret = hlsenc_io_open(s, &vs->out, vs->basename, &options);
928 } else {
929 1 ret = hlsenc_io_open(s, &vs->out, vs->base_output_dirname, &options);
930 }
931 1 av_dict_free(&options);
932 }
933
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 10 times.
10 if (ret < 0) {
934 av_log(s, AV_LOG_ERROR, "Failed to open segment '%s'\n", vs->fmp4_init_filename);
935 return ret;
936 }
937
938 10 av_dict_copy(&options, hls->format_options, 0);
939
2/2
✓ Branch 0 taken 1 times.
✓ Branch 1 taken 9 times.
10 if (hls->segment_type == SEGMENT_TYPE_FMP4) {
940 1 av_dict_set(&options, "fflags", "-autobsf", 0);
941 1 av_dict_set(&options, "movflags", "+frag_custom+dash+delay_moov", AV_DICT_APPEND);
942 } else {
943 /* We only require one PAT/PMT per segment. */
944 char period[21];
945 9 snprintf(period, sizeof(period), "%d", (INT_MAX / 2) - 1);
946 9 av_dict_set(&options, "sdt_period", period, AV_DICT_DONT_OVERWRITE);
947 9 av_dict_set(&options, "pat_period", period, AV_DICT_DONT_OVERWRITE);
948 }
949 10 ret = avformat_init_output(oc, &options);
950 10 remaining_options = av_dict_count(options);
951 10 av_dict_free(&options);
952
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 10 times.
10 if (ret < 0)
953 return ret;
954
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 10 times.
10 if (remaining_options) {
955 av_log(s, AV_LOG_ERROR, "Some of the provided format options are not recognized\n");
956 return AVERROR(EINVAL);
957 }
958 10 avio_flush(oc->pb);
959 10 return 0;
960 }
961
962 121 static HLSSegment *find_segment_by_filename(HLSSegment *segment, const char *filename)
963 {
964
2/2
✓ Branch 0 taken 173 times.
✓ Branch 1 taken 106 times.
279 while (segment) {
965
2/2
✓ Branch 1 taken 15 times.
✓ Branch 2 taken 158 times.
173 if (!av_strcasecmp(segment->filename,filename))
966 15 return segment;
967 158 segment = segment->next;
968 }
969 106 return (HLSSegment *) NULL;
970 }
971
972 68 static int sls_flags_filename_process(struct AVFormatContext *s, HLSContext *hls,
973 VariantStream *vs, HLSSegment *en,
974 double duration, int64_t pos, int64_t size)
975 {
976
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 68 times.
68 if ((hls->flags & (HLS_SECOND_LEVEL_SEGMENT_SIZE | HLS_SECOND_LEVEL_SEGMENT_DURATION)) &&
977 strlen(vs->current_segment_final_filename_fmt)) {
978 char * new_url = av_strdup(vs->current_segment_final_filename_fmt);
979 if (!new_url) {
980 return AVERROR(ENOMEM);
981 }
982 ff_format_set_url(vs->avf, new_url);
983 if (hls->flags & HLS_SECOND_LEVEL_SEGMENT_SIZE) {
984 char *filename = NULL;
985 if (replace_int_data_in_filename(&filename, vs->avf->url, 's', pos + size) < 1) {
986 av_log(hls, AV_LOG_ERROR,
987 "Invalid second level segment filename template '%s', "
988 "you can try to remove second_level_segment_size flag\n",
989 vs->avf->url);
990 av_freep(&filename);
991 return AVERROR(EINVAL);
992 }
993 ff_format_set_url(vs->avf, filename);
994 }
995 if (hls->flags & HLS_SECOND_LEVEL_SEGMENT_DURATION) {
996 char *filename = NULL;
997 if (replace_int_data_in_filename(&filename, vs->avf->url,
998 't', (int64_t)round(duration * HLS_MICROSECOND_UNIT)) < 1) {
999 av_log(hls, AV_LOG_ERROR,
1000 "Invalid second level segment filename template '%s', "
1001 "you can try to remove second_level_segment_duration flag\n",
1002 vs->avf->url);
1003 av_freep(&filename);
1004 return AVERROR(EINVAL);
1005 }
1006 ff_format_set_url(vs->avf, filename);
1007 }
1008 }
1009 68 return 0;
1010 }
1011
1012 10 static int sls_flag_check_duration_size_index(HLSContext *hls)
1013 {
1014 10 int ret = 0;
1015
1016
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 10 times.
10 if (hls->flags & HLS_SECOND_LEVEL_SEGMENT_DURATION) {
1017 av_log(hls, AV_LOG_ERROR,
1018 "second_level_segment_duration hls_flag requires strftime to be true\n");
1019 ret = AVERROR(EINVAL);
1020 }
1021
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 10 times.
10 if (hls->flags & HLS_SECOND_LEVEL_SEGMENT_SIZE) {
1022 av_log(hls, AV_LOG_ERROR,
1023 "second_level_segment_size hls_flag requires strfime to be true\n");
1024 ret = AVERROR(EINVAL);
1025 }
1026
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 10 times.
10 if (hls->flags & HLS_SECOND_LEVEL_SEGMENT_INDEX) {
1027 av_log(hls, AV_LOG_ERROR,
1028 "second_level_segment_index hls_flag requires strftime to be true\n");
1029 ret = AVERROR(EINVAL);
1030 }
1031
1032 10 return ret;
1033 }
1034
1035 static int sls_flag_check_duration_size(HLSContext *hls, VariantStream *vs)
1036 {
1037 const char *proto = avio_find_protocol_name(vs->basename);
1038 int segment_renaming_ok = proto && !strcmp(proto, "file");
1039 int ret = 0;
1040
1041 if ((hls->flags & HLS_SECOND_LEVEL_SEGMENT_DURATION) && !segment_renaming_ok) {
1042 av_log(hls, AV_LOG_ERROR,
1043 "second_level_segment_duration hls_flag works only with file protocol segment names\n");
1044 ret = AVERROR(EINVAL);
1045 }
1046 if ((hls->flags & HLS_SECOND_LEVEL_SEGMENT_SIZE) && !segment_renaming_ok) {
1047 av_log(hls, AV_LOG_ERROR,
1048 "second_level_segment_size hls_flag works only with file protocol segment names\n");
1049 ret = AVERROR(EINVAL);
1050 }
1051
1052 return ret;
1053 }
1054
1055 51 static void sls_flag_file_rename(HLSContext *hls, VariantStream *vs, char *old_filename) {
1056
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 51 times.
51 if ((hls->flags & (HLS_SECOND_LEVEL_SEGMENT_SIZE | HLS_SECOND_LEVEL_SEGMENT_DURATION)) &&
1057 strlen(vs->current_segment_final_filename_fmt)) {
1058 ff_rename(old_filename, vs->avf->url, hls);
1059 }
1060 51 }
1061
1062 static int sls_flag_use_localtime_filename(AVFormatContext *oc, HLSContext *c, VariantStream *vs)
1063 {
1064 if (c->flags & HLS_SECOND_LEVEL_SEGMENT_INDEX) {
1065 char *filename = NULL;
1066 if (replace_int_data_in_filename(&filename,
1067 oc->url, 'd', vs->sequence) < 1) {
1068 av_log(c, AV_LOG_ERROR, "Invalid second level segment filename template '%s', "
1069 "you can try to remove second_level_segment_index flag\n",
1070 oc->url);
1071 av_freep(&filename);
1072 return AVERROR(EINVAL);
1073 }
1074 ff_format_set_url(oc, filename);
1075 }
1076 if (c->flags & (HLS_SECOND_LEVEL_SEGMENT_SIZE | HLS_SECOND_LEVEL_SEGMENT_DURATION)) {
1077 av_strlcpy(vs->current_segment_final_filename_fmt, oc->url,
1078 sizeof(vs->current_segment_final_filename_fmt));
1079 if (c->flags & HLS_SECOND_LEVEL_SEGMENT_SIZE) {
1080 char *filename = NULL;
1081 if (replace_int_data_in_filename(&filename, oc->url, 's', 0) < 1) {
1082 av_log(c, AV_LOG_ERROR, "Invalid second level segment filename template '%s', "
1083 "you can try to remove second_level_segment_size flag\n",
1084 oc->url);
1085 av_freep(&filename);
1086 return AVERROR(EINVAL);
1087 }
1088 ff_format_set_url(oc, filename);
1089 }
1090 if (c->flags & HLS_SECOND_LEVEL_SEGMENT_DURATION) {
1091 char *filename = NULL;
1092 if (replace_int_data_in_filename(&filename, oc->url, 't', 0) < 1) {
1093 av_log(c, AV_LOG_ERROR, "Invalid second level segment filename template '%s', "
1094 "you can try to remove second_level_segment_duration flag\n",
1095 oc->url);
1096 av_freep(&filename);
1097 return AVERROR(EINVAL);
1098 }
1099 ff_format_set_url(oc, filename);
1100 }
1101 }
1102 return 0;
1103 }
1104
1105 /* Create a new segment and append it to the segment list */
1106 68 static int hls_append_segment(struct AVFormatContext *s, HLSContext *hls,
1107 VariantStream *vs, double duration, int64_t pos,
1108 int64_t size)
1109 {
1110 68 HLSSegment *en = av_malloc(sizeof(*en));
1111 const char *filename;
1112
4/4
✓ Branch 0 taken 58 times.
✓ Branch 1 taken 10 times.
✓ Branch 2 taken 10 times.
✓ Branch 3 taken 48 times.
68 int byterange_mode = (hls->flags & HLS_SINGLE_FILE) || (hls->max_seg_size > 0);
1113 int ret;
1114
1115
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 68 times.
68 if (!en)
1116 return AVERROR(ENOMEM);
1117
1118 68 en->var_stream_idx = vs->var_stream_idx;
1119 68 ret = sls_flags_filename_process(s, hls, vs, en, duration, pos, size);
1120
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 68 times.
68 if (ret < 0) {
1121 av_freep(&en);
1122 return ret;
1123 }
1124
1125 68 filename = av_basename(vs->avf->url);
1126
1127
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 68 times.
68 if (hls->use_localtime_mkdir) {
1128 filename = vs->avf->url;
1129 }
1130
3/4
✓ Branch 1 taken 53 times.
✓ Branch 2 taken 15 times.
✗ Branch 4 not taken.
✓ Branch 5 taken 53 times.
68 if ((find_segment_by_filename(vs->segments, filename) || find_segment_by_filename(vs->old_segments, filename))
1131
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 15 times.
15 && !byterange_mode) {
1132 av_log(hls, AV_LOG_WARNING, "Duplicated segment filename detected: %s\n", filename);
1133 }
1134 68 av_strlcpy(en->filename, filename, sizeof(en->filename));
1135
1136
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 68 times.
68 if (vs->has_subtitle)
1137 av_strlcpy(en->sub_filename, av_basename(vs->vtt_avf->url), sizeof(en->sub_filename));
1138 else
1139 68 en->sub_filename[0] = '\0';
1140
1141 68 en->duration = duration;
1142 68 en->pos = pos;
1143 68 en->size = size;
1144 68 en->keyframe_pos = vs->video_keyframe_pos;
1145 68 en->keyframe_size = vs->video_keyframe_size;
1146 68 en->next = NULL;
1147 68 en->discont = 0;
1148 68 en->discont_program_date_time = 0;
1149
1150
2/2
✓ Branch 0 taken 1 times.
✓ Branch 1 taken 67 times.
68 if (vs->discontinuity) {
1151 1 en->discont = 1;
1152 1 vs->discontinuity = 0;
1153 }
1154
1155
2/4
✓ Branch 0 taken 68 times.
✗ Branch 1 not taken.
✗ Branch 2 not taken.
✓ Branch 3 taken 68 times.
68 if (hls->key_info_file || hls->encrypt) {
1156 av_strlcpy(en->key_uri, vs->key_uri, sizeof(en->key_uri));
1157 av_strlcpy(en->iv_string, vs->iv_string, sizeof(en->iv_string));
1158 }
1159
1160
2/2
✓ Branch 0 taken 10 times.
✓ Branch 1 taken 58 times.
68 if (!vs->segments)
1161 10 vs->segments = en;
1162 else
1163 58 vs->last_segment->next = en;
1164
1165 68 vs->last_segment = en;
1166
1167 // EVENT or VOD playlists imply sliding window cannot be used
1168
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 68 times.
68 if (hls->pl_type != PLAYLIST_TYPE_NONE)
1169 hls->max_nb_segments = 0;
1170
1171
4/4
✓ Branch 0 taken 31 times.
✓ Branch 1 taken 37 times.
✓ Branch 2 taken 8 times.
✓ Branch 3 taken 23 times.
68 if (hls->max_nb_segments && vs->nb_entries >= hls->max_nb_segments) {
1172 8 en = vs->segments;
1173
2/4
✓ Branch 0 taken 8 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 8 times.
✗ Branch 3 not taken.
8 if (!en->next->discont_program_date_time && !en->discont_program_date_time)
1174 8 vs->initial_prog_date_time += en->duration;
1175 8 vs->segments = en->next;
1176
2/4
✓ Branch 0 taken 8 times.
✗ Branch 1 not taken.
✗ Branch 2 not taken.
✓ Branch 3 taken 8 times.
8 if (en && hls->flags & HLS_DELETE_SEGMENTS &&
1177 !(hls->flags & HLS_SINGLE_FILE)) {
1178 en->next = vs->old_segments;
1179 vs->old_segments = en;
1180 if ((ret = hls_delete_old_segments(s, hls, vs)) < 0)
1181 return ret;
1182 } else
1183 8 av_freep(&en);
1184 } else
1185 60 vs->nb_entries++;
1186
1187
2/2
✓ Branch 0 taken 10 times.
✓ Branch 1 taken 58 times.
68 if (hls->max_seg_size > 0) {
1188 10 return 0;
1189 }
1190 58 vs->sequence++;
1191
1192 58 return 0;
1193 }
1194
1195 1 static int parse_playlist(AVFormatContext *s, const char *url, VariantStream *vs)
1196 {
1197 1 HLSContext *hls = s->priv_data;
1198 AVIOContext *in;
1199 1 int ret = 0, is_segment = 0;
1200 int64_t new_start_pos;
1201 char line[MAX_URL_SIZE];
1202 const char *ptr;
1203 const char *end;
1204 1 double discont_program_date_time = 0;
1205
1206
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 1 times.
1 if ((ret = ffio_open_whitelist(&in, url, AVIO_FLAG_READ,
1207 1 &s->interrupt_callback, NULL,
1208 1 s->protocol_whitelist, s->protocol_blacklist)) < 0)
1209 return ret;
1210
1211 1 ff_get_chomp_line(in, line, sizeof(line));
1212
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 1 times.
1 if (strcmp(line, "#EXTM3U")) {
1213 ret = AVERROR_INVALIDDATA;
1214 goto fail;
1215 }
1216
1217 1 vs->discontinuity = 0;
1218
2/2
✓ Branch 1 taken 10 times.
✓ Branch 2 taken 1 times.
11 while (!avio_feof(in)) {
1219 10 ff_get_chomp_line(in, line, sizeof(line));
1220
2/2
✓ Branch 1 taken 1 times.
✓ Branch 2 taken 9 times.
10 if (av_strstart(line, "#EXT-X-MEDIA-SEQUENCE:", &ptr)) {
1221 1 int64_t tmp_sequence = strtoll(ptr, NULL, 10);
1222
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 1 times.
1 if (tmp_sequence < vs->sequence)
1223 av_log(hls, AV_LOG_VERBOSE,
1224 "Found playlist sequence number was smaller """
1225 "than specified start sequence number: %"PRId64" < %"PRId64", "
1226 "omitting\n", tmp_sequence, hls->start_sequence);
1227 else {
1228 1 av_log(hls, AV_LOG_DEBUG, "Found playlist sequence number: %"PRId64"\n", tmp_sequence);
1229 1 vs->sequence = tmp_sequence;
1230 }
1231
1/2
✗ Branch 1 not taken.
✓ Branch 2 taken 9 times.
9 } else if (av_strstart(line, "#EXT-X-DISCONTINUITY", &ptr)) {
1232 is_segment = 1;
1233 vs->discontinuity = 1;
1234
2/2
✓ Branch 1 taken 2 times.
✓ Branch 2 taken 7 times.
9 } else if (av_strstart(line, "#EXTINF:", &ptr)) {
1235 2 is_segment = 1;
1236 2 vs->duration = atof(ptr);
1237
1/2
✗ Branch 1 not taken.
✓ Branch 2 taken 7 times.
7 } else if (av_stristart(line, "#EXT-X-KEY:", &ptr)) {
1238 ptr = av_stristr(line, "URI=\"");
1239 if (ptr) {
1240 ptr += strlen("URI=\"");
1241 end = av_stristr(ptr, ",");
1242 if (end) {
1243 av_strlcpy(vs->key_uri, ptr, end - ptr);
1244 } else {
1245 av_strlcpy(vs->key_uri, ptr, sizeof(vs->key_uri));
1246 }
1247 }
1248
1249 ptr = av_stristr(line, "IV=0x");
1250 if (ptr) {
1251 ptr += strlen("IV=0x");
1252 end = av_stristr(ptr, ",");
1253 if (end) {
1254 av_strlcpy(vs->iv_string, ptr, end - ptr);
1255 } else {
1256 av_strlcpy(vs->iv_string, ptr, sizeof(vs->iv_string));
1257 }
1258 }
1259
1/2
✗ Branch 1 not taken.
✓ Branch 2 taken 7 times.
7 } else if (av_strstart(line, "#EXT-X-PROGRAM-DATE-TIME:", &ptr)) {
1260 struct tm program_date_time;
1261 int y,M,d,h,m,s;
1262 double ms;
1263 if (sscanf(ptr, "%d-%d-%dT%d:%d:%d.%lf", &y, &M, &d, &h, &m, &s, &ms) != 7) {
1264 ret = AVERROR_INVALIDDATA;
1265 goto fail;
1266 }
1267
1268 program_date_time.tm_year = y - 1900;
1269 program_date_time.tm_mon = M - 1;
1270 program_date_time.tm_mday = d;
1271 program_date_time.tm_hour = h;
1272 program_date_time.tm_min = m;
1273 program_date_time.tm_sec = s;
1274 program_date_time.tm_isdst = -1;
1275
1276 discont_program_date_time = mktime(&program_date_time);
1277 discont_program_date_time += (double)(ms / 1000);
1278
2/2
✓ Branch 1 taken 4 times.
✓ Branch 2 taken 3 times.
7 } else if (av_strstart(line, "#", NULL)) {
1279 4 continue;
1280
2/2
✓ Branch 0 taken 2 times.
✓ Branch 1 taken 1 times.
3 } else if (line[0]) {
1281
1/2
✓ Branch 0 taken 2 times.
✗ Branch 1 not taken.
2 if (is_segment) {
1282 2 char *new_file = av_strdup(line);
1283
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 2 times.
2 if (!new_file) {
1284 ret = AVERROR(ENOMEM);
1285 goto fail;
1286 }
1287 2 ff_format_set_url(vs->avf, new_file);
1288 2 is_segment = 0;
1289 2 new_start_pos = avio_tell(vs->avf->pb);
1290 2 vs->size = new_start_pos - vs->start_pos;
1291 2 ret = hls_append_segment(s, hls, vs, vs->duration, vs->start_pos, vs->size);
1292
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 2 times.
2 if (discont_program_date_time) {
1293 vs->last_segment->discont_program_date_time = discont_program_date_time;
1294 discont_program_date_time += vs->duration;
1295 }
1296
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 2 times.
2 if (ret < 0)
1297 goto fail;
1298 2 vs->start_pos = new_start_pos;
1299 }
1300 }
1301 }
1302
1303 1 fail:
1304 1 avio_close(in);
1305 1 return ret;
1306 }
1307
1308 20 static void hls_free_segments(HLSSegment *p)
1309 {
1310 HLSSegment *en;
1311
1312
2/2
✓ Branch 0 taken 60 times.
✓ Branch 1 taken 20 times.
80 while (p) {
1313 60 en = p;
1314 60 p = p->next;
1315 60 av_freep(&en);
1316 }
1317 20 }
1318
1319 static int hls_rename_temp_file(AVFormatContext *s, AVFormatContext *oc)
1320 {
1321 size_t len = strlen(oc->url);
1322 char *final_filename = av_strdup(oc->url);
1323 int ret;
1324
1325 if (!final_filename)
1326 return AVERROR(ENOMEM);
1327 final_filename[len-4] = '\0';
1328 ret = ff_rename(oc->url, final_filename, s);
1329 oc->url[len-4] = '\0';
1330 av_freep(&final_filename);
1331 return ret;
1332 }
1333
1334 static const char* get_relative_url(const char *master_url, const char *media_url)
1335 {
1336 const char *p = strrchr(master_url, '/');
1337 size_t base_len = 0;
1338
1339 if (!p) p = strrchr(master_url, '\\');
1340
1341 if (p) {
1342 base_len = p - master_url;
1343 if (av_strncasecmp(master_url, media_url, base_len)) {
1344 av_log(NULL, AV_LOG_WARNING, "Unable to find relative url\n");
1345 return NULL;
1346 }
1347 } else {
1348 return media_url;
1349 }
1350
1351 return media_url + base_len + 1;
1352 }
1353
1354 static int64_t get_stream_bit_rate(AVStream *stream)
1355 {
1356 const AVPacketSideData *sd = av_packet_side_data_get(
1357 stream->codecpar->coded_side_data, stream->codecpar->nb_coded_side_data,
1358 AV_PKT_DATA_CPB_PROPERTIES
1359 );
1360
1361 if (stream->codecpar->bit_rate)
1362 return stream->codecpar->bit_rate;
1363 else if (sd) {
1364 AVCPBProperties *props = (AVCPBProperties*)sd->data;
1365 return props->max_bitrate;
1366 }
1367
1368 return 0;
1369 }
1370
1371 static int create_master_playlist(AVFormatContext *s,
1372 VariantStream * const input_vs)
1373 {
1374 HLSContext *hls = s->priv_data;
1375 VariantStream *vs, *temp_vs;
1376 AVStream *vid_st, *aud_st;
1377 AVDictionary *options = NULL;
1378 unsigned int i, j;
1379 int ret, bandwidth;
1380 const char *m3u8_rel_name = NULL;
1381 const char *vtt_m3u8_rel_name = NULL;
1382 const char *ccgroup;
1383 const char *sgroup = NULL;
1384 ClosedCaptionsStream *ccs;
1385 const char *proto = avio_find_protocol_name(hls->master_m3u8_url);
1386 int is_file_proto = proto && !strcmp(proto, "file");
1387 int use_temp_file = is_file_proto && ((hls->flags & HLS_TEMP_FILE) || hls->master_publish_rate);
1388 char temp_filename[MAX_URL_SIZE];
1389 int nb_channels;
1390
1391 input_vs->m3u8_created = 1;
1392 if (!hls->master_m3u8_created) {
1393 /* For the first time, wait until all the media playlists are created */
1394 for (i = 0; i < hls->nb_varstreams; i++)
1395 if (!hls->var_streams[i].m3u8_created)
1396 return 0;
1397 } else {
1398 /* Keep publishing the master playlist at the configured rate */
1399 if (&hls->var_streams[0] != input_vs || !hls->master_publish_rate ||
1400 input_vs->number % hls->master_publish_rate)
1401 return 0;
1402 }
1403
1404 set_http_options(s, &options, hls);
1405 snprintf(temp_filename, sizeof(temp_filename), use_temp_file ? "%s.tmp" : "%s", hls->master_m3u8_url);
1406 ret = hlsenc_io_open(s, &hls->m3u8_out, temp_filename, &options);
1407 av_dict_free(&options);
1408 if (ret < 0) {
1409 av_log(s, AV_LOG_ERROR, "Failed to open master play list file '%s'\n",
1410 temp_filename);
1411 goto fail;
1412 }
1413
1414 ff_hls_write_playlist_version(hls->m3u8_out, hls->version);
1415
1416 for (i = 0; i < hls->nb_ccstreams; i++) {
1417 ccs = &(hls->cc_streams[i]);
1418 avio_printf(hls->m3u8_out, "#EXT-X-MEDIA:TYPE=CLOSED-CAPTIONS");
1419 avio_printf(hls->m3u8_out, ",GROUP-ID=\"%s\"", ccs->ccgroup);
1420 avio_printf(hls->m3u8_out, ",NAME=\"%s\"", ccs->instreamid);
1421 if (ccs->language)
1422 avio_printf(hls->m3u8_out, ",LANGUAGE=\"%s\"", ccs->language);
1423 avio_printf(hls->m3u8_out, ",INSTREAM-ID=\"%s\"\n", ccs->instreamid);
1424 }
1425
1426 /* For audio only variant streams add #EXT-X-MEDIA tag with attributes*/
1427 for (i = 0; i < hls->nb_varstreams; i++) {
1428 vs = &(hls->var_streams[i]);
1429
1430 if (vs->has_video || vs->has_subtitle || !vs->agroup)
1431 continue;
1432
1433 m3u8_rel_name = get_relative_url(hls->master_m3u8_url, vs->m3u8_name);
1434 if (!m3u8_rel_name) {
1435 av_log(s, AV_LOG_ERROR, "Unable to find relative URL\n");
1436 goto fail;
1437 }
1438 nb_channels = 0;
1439 for (j = 0; j < vs->nb_streams; j++)
1440 if (vs->streams[j]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
1441 if (vs->streams[j]->codecpar->ch_layout.nb_channels > nb_channels)
1442 nb_channels = vs->streams[j]->codecpar->ch_layout.nb_channels;
1443
1444 ff_hls_write_audio_rendition(hls->m3u8_out, vs->agroup, m3u8_rel_name, vs->language, i, hls->has_default_key ? vs->is_default : 1, nb_channels);
1445 }
1446
1447 /* For variant streams with video add #EXT-X-STREAM-INF tag with attributes*/
1448 for (i = 0; i < hls->nb_varstreams; i++) {
1449 vs = &(hls->var_streams[i]);
1450
1451 m3u8_rel_name = get_relative_url(hls->master_m3u8_url, vs->m3u8_name);
1452 if (!m3u8_rel_name) {
1453 av_log(s, AV_LOG_ERROR, "Unable to find relative URL\n");
1454 goto fail;
1455 }
1456
1457 vid_st = NULL;
1458 aud_st = NULL;
1459 for (j = 0; j < vs->nb_streams; j++) {
1460 if (vs->streams[j]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
1461 vid_st = vs->streams[j];
1462 else if (vs->streams[j]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
1463 aud_st = vs->streams[j];
1464 }
1465
1466 if (!vid_st && !aud_st) {
1467 av_log(s, AV_LOG_WARNING, "Media stream not found\n");
1468 continue;
1469 }
1470
1471 /**
1472 * Traverse through the list of audio only rendition streams and find
1473 * the rendition which has highest bitrate in the same audio group
1474 */
1475 if (vs->agroup) {
1476 for (j = 0; j < hls->nb_varstreams; j++) {
1477 temp_vs = &(hls->var_streams[j]);
1478 if (!temp_vs->has_video && !temp_vs->has_subtitle &&
1479 temp_vs->agroup &&
1480 !av_strcasecmp(temp_vs->agroup, vs->agroup)) {
1481 if (!aud_st)
1482 aud_st = temp_vs->streams[0];
1483 if (temp_vs->streams[0]->codecpar->bit_rate >
1484 aud_st->codecpar->bit_rate)
1485 aud_st = temp_vs->streams[0];
1486 }
1487 }
1488 }
1489
1490 bandwidth = 0;
1491 if (vid_st)
1492 bandwidth += get_stream_bit_rate(vid_st);
1493 if (aud_st)
1494 bandwidth += get_stream_bit_rate(aud_st);
1495 bandwidth += bandwidth / 10;
1496
1497 ccgroup = NULL;
1498 if (vid_st && vs->ccgroup) {
1499 /* check if this group name is available in the cc map string */
1500 for (j = 0; j < hls->nb_ccstreams; j++) {
1501 ccs = &(hls->cc_streams[j]);
1502 if (!av_strcasecmp(ccs->ccgroup, vs->ccgroup)) {
1503 ccgroup = vs->ccgroup;
1504 break;
1505 }
1506 }
1507 if (j == hls->nb_ccstreams)
1508 av_log(s, AV_LOG_WARNING, "mapping ccgroup %s not found\n",
1509 vs->ccgroup);
1510 }
1511
1512 if (vid_st && vs->sgroup) {
1513 sgroup = vs->sgroup;
1514 vtt_m3u8_rel_name = get_relative_url(hls->master_m3u8_url, vs->vtt_m3u8_name);
1515 if (!vtt_m3u8_rel_name) {
1516 av_log(s, AV_LOG_WARNING, "Unable to find relative subtitle URL\n");
1517 break;
1518 }
1519
1520 ff_hls_write_subtitle_rendition(hls->m3u8_out, sgroup, vtt_m3u8_rel_name, vs->language, i, hls->has_default_key ? vs->is_default : 1);
1521 }
1522
1523 if (!hls->has_default_key || !hls->has_video_m3u8) {
1524 ff_hls_write_stream_info(vid_st, hls->m3u8_out, bandwidth, m3u8_rel_name,
1525 aud_st ? vs->agroup : NULL, vs->codec_attr, ccgroup, sgroup);
1526 } else {
1527 if (vid_st) {
1528 ff_hls_write_stream_info(vid_st, hls->m3u8_out, bandwidth, m3u8_rel_name,
1529 aud_st ? vs->agroup : NULL, vs->codec_attr, ccgroup, sgroup);
1530 }
1531 }
1532 }
1533 fail:
1534 if (ret >=0)
1535 hls->master_m3u8_created = 1;
1536 hlsenc_io_close(s, &hls->m3u8_out, temp_filename);
1537 if (use_temp_file)
1538 ff_rename(temp_filename, hls->master_m3u8_url, s);
1539
1540 return ret;
1541 }
1542
1543 66 static int hls_window(AVFormatContext *s, int last, VariantStream *vs)
1544 {
1545 66 HLSContext *hls = s->priv_data;
1546 HLSSegment *en;
1547 66 int target_duration = 0;
1548 66 int ret = 0;
1549 char temp_filename[MAX_URL_SIZE];
1550 char temp_vtt_filename[MAX_URL_SIZE];
1551 66 int64_t sequence = FFMAX(hls->start_sequence, vs->sequence - vs->nb_entries);
1552 66 const char *proto = avio_find_protocol_name(vs->m3u8_name);
1553
2/4
✓ Branch 0 taken 66 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 66 times.
✗ Branch 3 not taken.
66 int is_file_proto = proto && !strcmp(proto, "file");
1554
3/6
✓ Branch 0 taken 66 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 66 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 66 times.
✗ Branch 5 not taken.
66 int use_temp_file = is_file_proto && ((hls->flags & HLS_TEMP_FILE) || !(hls->pl_type == PLAYLIST_TYPE_VOD));
1555 static unsigned warned_non_file;
1556 66 char *key_uri = NULL;
1557 66 char *iv_string = NULL;
1558 66 AVDictionary *options = NULL;
1559 66 double prog_date_time = vs->initial_prog_date_time;
1560
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 66 times.
66 double *prog_date_time_p = (hls->flags & HLS_PROGRAM_DATE_TIME) ? &prog_date_time : NULL;
1561
4/4
✓ Branch 0 taken 56 times.
✓ Branch 1 taken 10 times.
✓ Branch 2 taken 10 times.
✓ Branch 3 taken 46 times.
66 int byterange_mode = (hls->flags & HLS_SINGLE_FILE) || (hls->max_seg_size > 0);
1562
1563 66 hls->version = 2;
1564
1/2
✓ Branch 0 taken 66 times.
✗ Branch 1 not taken.
66 if (!(hls->flags & HLS_ROUND_DURATIONS)) {
1565 66 hls->version = 3;
1566 }
1567
1568
2/2
✓ Branch 0 taken 20 times.
✓ Branch 1 taken 46 times.
66 if (byterange_mode) {
1569 20 hls->version = 4;
1570 20 sequence = 0;
1571 }
1572
1573
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 66 times.
66 if (hls->flags & HLS_I_FRAMES_ONLY) {
1574 hls->version = 4;
1575 }
1576
1577
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 66 times.
66 if (hls->flags & HLS_INDEPENDENT_SEGMENTS) {
1578 hls->version = 6;
1579 }
1580
1581
2/2
✓ Branch 0 taken 5 times.
✓ Branch 1 taken 61 times.
66 if (hls->segment_type == SEGMENT_TYPE_FMP4) {
1582 5 hls->version = 7;
1583 }
1584
1585
1/6
✗ Branch 0 not taken.
✓ Branch 1 taken 66 times.
✗ Branch 2 not taken.
✗ Branch 3 not taken.
✗ Branch 4 not taken.
✗ Branch 5 not taken.
66 if (!is_file_proto && (hls->flags & HLS_TEMP_FILE) && !warned_non_file++)
1586 av_log(s, AV_LOG_ERROR, "Cannot use rename on non file protocol, this may lead to races and temporary partial files\n");
1587
1588 66 set_http_options(s, &options, hls);
1589
1/2
✓ Branch 0 taken 66 times.
✗ Branch 1 not taken.
66 snprintf(temp_filename, sizeof(temp_filename), use_temp_file ? "%s.tmp" : "%s", vs->m3u8_name);
1590
2/2
✓ Branch 0 taken 20 times.
✓ Branch 1 taken 46 times.
66 ret = hlsenc_io_open(s, byterange_mode ? &hls->m3u8_out : &vs->out, temp_filename, &options);
1591 66 av_dict_free(&options);
1592
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 66 times.
66 if (ret < 0) {
1593 if (hls->ignore_io_errors)
1594 ret = 0;
1595 goto fail;
1596 }
1597
1598
2/2
✓ Branch 0 taken 269 times.
✓ Branch 1 taken 66 times.
335 for (en = vs->segments; en; en = en->next) {
1599
2/2
✓ Branch 0 taken 186 times.
✓ Branch 1 taken 83 times.
269 if (target_duration <= en->duration)
1600 186 target_duration = lrint(en->duration);
1601 }
1602
1603 66 vs->discontinuity_set = 0;
1604 66 ff_hls_write_playlist_header(byterange_mode ? hls->m3u8_out : vs->out, hls->version, hls->allowcache,
1605
2/2
✓ Branch 0 taken 20 times.
✓ Branch 1 taken 46 times.
66 target_duration, sequence, hls->pl_type, hls->flags & HLS_I_FRAMES_ONLY);
1606
1607
1/6
✗ Branch 0 not taken.
✓ Branch 1 taken 66 times.
✗ Branch 2 not taken.
✗ Branch 3 not taken.
✗ Branch 4 not taken.
✗ Branch 5 not taken.
66 if ((hls->flags & HLS_DISCONT_START) && sequence==hls->start_sequence && vs->discontinuity_set==0) {
1608 avio_printf(byterange_mode ? hls->m3u8_out : vs->out, "#EXT-X-DISCONTINUITY\n");
1609 vs->discontinuity_set = 1;
1610 }
1611
1/4
✗ Branch 0 not taken.
✓ Branch 1 taken 66 times.
✗ Branch 2 not taken.
✗ Branch 3 not taken.
66 if (vs->has_video && (hls->flags & HLS_INDEPENDENT_SEGMENTS)) {
1612 avio_printf(byterange_mode ? hls->m3u8_out : vs->out, "#EXT-X-INDEPENDENT-SEGMENTS\n");
1613 }
1614
2/2
✓ Branch 0 taken 269 times.
✓ Branch 1 taken 66 times.
335 for (en = vs->segments; en; en = en->next) {
1615
2/10
✓ Branch 0 taken 269 times.
✗ Branch 1 not taken.
✗ Branch 2 not taken.
✓ Branch 3 taken 269 times.
✗ Branch 4 not taken.
✗ Branch 5 not taken.
✗ Branch 6 not taken.
✗ Branch 7 not taken.
✗ Branch 8 not taken.
✗ Branch 9 not taken.
269 if ((hls->encrypt || hls->key_info_file) && (!key_uri || strcmp(en->key_uri, key_uri) ||
1616 av_strcasecmp(en->iv_string, iv_string))) {
1617 avio_printf(byterange_mode ? hls->m3u8_out : vs->out, "#EXT-X-KEY:METHOD=AES-128,URI=\"%s\"", en->key_uri);
1618 if (*en->iv_string)
1619 avio_printf(byterange_mode ? hls->m3u8_out : vs->out, ",IV=0x%s", en->iv_string);
1620 avio_printf(byterange_mode ? hls->m3u8_out : vs->out, "\n");
1621 key_uri = en->key_uri;
1622 iv_string = en->iv_string;
1623 }
1624
1625
4/4
✓ Branch 0 taken 15 times.
✓ Branch 1 taken 254 times.
✓ Branch 2 taken 5 times.
✓ Branch 3 taken 10 times.
269 if ((hls->segment_type == SEGMENT_TYPE_FMP4) && (en == vs->segments)) {
1626
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 5 times.
5 ff_hls_write_init_file(byterange_mode ? hls->m3u8_out : vs->out, (hls->flags & HLS_SINGLE_FILE) ? en->filename : vs->fmp4_init_filename,
1627
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 5 times.
5 hls->flags & HLS_SINGLE_FILE, vs->init_range_length, 0);
1628 }
1629
1630 538 ret = ff_hls_write_file_entry(byterange_mode ? hls->m3u8_out : vs->out, en->discont, byterange_mode,
1631 269 en->duration, hls->flags & HLS_ROUND_DURATIONS,
1632 269 en->size, en->pos, hls->baseurl,
1633
2/2
✓ Branch 0 taken 110 times.
✓ Branch 1 taken 159 times.
269 en->filename,
1634 269 en->discont_program_date_time ? &en->discont_program_date_time : prog_date_time_p,
1635
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 269 times.
269 en->keyframe_size, en->keyframe_pos, hls->flags & HLS_I_FRAMES_ONLY);
1636
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 269 times.
269 if (en->discont_program_date_time)
1637 en->discont_program_date_time -= en->duration;
1638
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 269 times.
269 if (ret < 0) {
1639 av_log(s, AV_LOG_WARNING, "ff_hls_write_file_entry get error\n");
1640 }
1641 }
1642
1643
4/4
✓ Branch 0 taken 10 times.
✓ Branch 1 taken 56 times.
✓ Branch 2 taken 9 times.
✓ Branch 3 taken 1 times.
66 if (last && (hls->flags & HLS_OMIT_ENDLIST)==0)
1644
2/2
✓ Branch 0 taken 2 times.
✓ Branch 1 taken 7 times.
9 ff_hls_write_end_list(byterange_mode ? hls->m3u8_out : vs->out);
1645
1646
1/2
✓ Branch 0 taken 66 times.
✗ Branch 1 not taken.
66 if (vs->vtt_m3u8_name) {
1647 set_http_options(vs->vtt_avf, &options, hls);
1648 snprintf(temp_vtt_filename, sizeof(temp_vtt_filename), use_temp_file ? "%s.tmp" : "%s", vs->vtt_m3u8_name);
1649 ret = hlsenc_io_open(s, &hls->sub_m3u8_out, temp_vtt_filename, &options);
1650 av_dict_free(&options);
1651 if (ret < 0) {
1652 if (hls->ignore_io_errors)
1653 ret = 0;
1654 goto fail;
1655 }
1656 ff_hls_write_playlist_header(hls->sub_m3u8_out, hls->version, hls->allowcache,
1657 target_duration, sequence, PLAYLIST_TYPE_NONE, 0);
1658 for (en = vs->segments; en; en = en->next) {
1659 ret = ff_hls_write_file_entry(hls->sub_m3u8_out, 0, byterange_mode,
1660 en->duration, 0, en->size, en->pos,
1661 hls->baseurl, en->sub_filename, NULL, 0, 0, 0);
1662 if (ret < 0) {
1663 av_log(s, AV_LOG_WARNING, "ff_hls_write_file_entry get error\n");
1664 }
1665 }
1666
1667 if (last)
1668 ff_hls_write_end_list(hls->sub_m3u8_out);
1669
1670 }
1671
1672 66 fail:
1673 66 av_dict_free(&options);
1674
2/2
✓ Branch 0 taken 20 times.
✓ Branch 1 taken 46 times.
66 ret = hlsenc_io_close(s, byterange_mode ? &hls->m3u8_out : &vs->out, temp_filename);
1675
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 66 times.
66 if (ret < 0) {
1676 return ret;
1677 }
1678 66 hlsenc_io_close(s, &hls->sub_m3u8_out, vs->vtt_m3u8_name);
1679
1/2
✓ Branch 0 taken 66 times.
✗ Branch 1 not taken.
66 if (use_temp_file) {
1680 66 ff_rename(temp_filename, vs->m3u8_name, s);
1681
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 66 times.
66 if (vs->vtt_m3u8_name)
1682 ff_rename(temp_vtt_filename, vs->vtt_m3u8_name, s);
1683 }
1684
2/4
✓ Branch 0 taken 66 times.
✗ Branch 1 not taken.
✗ Branch 2 not taken.
✓ Branch 3 taken 66 times.
66 if (ret >= 0 && hls->master_pl_name)
1685 if (create_master_playlist(s, vs) < 0)
1686 av_log(s, AV_LOG_WARNING, "Master playlist creation failed\n");
1687
1688 66 return ret;
1689 }
1690
1691 51 static int hls_start(AVFormatContext *s, VariantStream *vs)
1692 {
1693 51 HLSContext *c = s->priv_data;
1694 51 AVFormatContext *oc = vs->avf;
1695 51 AVFormatContext *vtt_oc = vs->vtt_avf;
1696 51 AVDictionary *options = NULL;
1697 51 const char *proto = NULL;
1698 51 int use_temp_file = 0;
1699 char iv_string[KEYSIZE*2 + 1];
1700 51 int err = 0;
1701
1702
2/2
✓ Branch 0 taken 1 times.
✓ Branch 1 taken 50 times.
51 if (c->flags & HLS_SINGLE_FILE) {
1703 1 char *new_name = av_strdup(vs->basename);
1704
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 1 times.
1 if (!new_name)
1705 return AVERROR(ENOMEM);
1706 1 ff_format_set_url(oc, new_name);
1707
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 1 times.
1 if (vs->vtt_basename) {
1708 new_name = av_strdup(vs->vtt_basename);
1709 if (!new_name)
1710 return AVERROR(ENOMEM);
1711 ff_format_set_url(vtt_oc, new_name);
1712 }
1713
2/2
✓ Branch 0 taken 4 times.
✓ Branch 1 taken 46 times.
50 } else if (c->max_seg_size > 0) {
1714 4 char *filename = NULL;
1715
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 4 times.
4 if (replace_int_data_in_filename(&filename,
1716 4 vs->basename, 'd', vs->sequence) < 1) {
1717 av_freep(&filename);
1718 av_log(oc, AV_LOG_ERROR, "Invalid segment filename template '%s', you can try to use -strftime 1 with it\n", vs->basename);
1719 return AVERROR(EINVAL);
1720 }
1721 4 ff_format_set_url(oc, filename);
1722 } else {
1723
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 46 times.
46 if (c->use_localtime) {
1724 int r;
1725 char *expanded = NULL;
1726
1727 r = strftime_expand(vs->basename, &expanded);
1728 if (r < 0) {
1729 av_log(oc, AV_LOG_ERROR, "Could not get segment filename with strftime\n");
1730 return r;
1731 }
1732 ff_format_set_url(oc, expanded);
1733
1734 err = sls_flag_use_localtime_filename(oc, c, vs);
1735 if (err < 0) {
1736 return AVERROR(ENOMEM);
1737 }
1738
1739 if (c->use_localtime_mkdir) {
1740 const char *dir;
1741 char *fn_copy = av_strdup(oc->url);
1742 if (!fn_copy)
1743 return AVERROR(ENOMEM);
1744 dir = av_dirname(fn_copy);
1745 if (ff_mkdir_p(dir) == -1 && errno != EEXIST) {
1746 av_log(oc, AV_LOG_ERROR, "Could not create directory %s with use_localtime_mkdir\n", dir);
1747 av_freep(&fn_copy);
1748 return AVERROR(errno);
1749 }
1750 av_freep(&fn_copy);
1751 }
1752 } else {
1753 46 char *filename = NULL;
1754
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 46 times.
46 if (replace_int_data_in_filename(&filename,
1755 46 vs->basename, 'd', vs->sequence) < 1) {
1756 av_freep(&filename);
1757 av_log(oc, AV_LOG_ERROR, "Invalid segment filename template '%s' you can try to use -strftime 1 with it\n", vs->basename);
1758 return AVERROR(EINVAL);
1759 }
1760 46 ff_format_set_url(oc, filename);
1761 }
1762
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 46 times.
46 if (vs->vtt_basename) {
1763 char *filename = NULL;
1764 if (replace_int_data_in_filename(&filename,
1765 vs->vtt_basename, 'd', vs->sequence) < 1) {
1766 av_freep(&filename);
1767 av_log(vtt_oc, AV_LOG_ERROR, "Invalid segment filename template '%s'\n", vs->vtt_basename);
1768 return AVERROR(EINVAL);
1769 }
1770 ff_format_set_url(vtt_oc, filename);
1771 }
1772 }
1773
1774 51 proto = avio_find_protocol_name(oc->url);
1775
3/6
✓ Branch 0 taken 51 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 51 times.
✗ Branch 3 not taken.
✗ Branch 4 not taken.
✓ Branch 5 taken 51 times.
51 use_temp_file = proto && !strcmp(proto, "file") && (c->flags & HLS_TEMP_FILE);
1776
1777
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 51 times.
51 if (use_temp_file) {
1778 char *new_name = av_asprintf("%s.tmp", oc->url);
1779 if (!new_name)
1780 return AVERROR(ENOMEM);
1781 ff_format_set_url(oc, new_name);
1782 }
1783
1784
2/4
✓ Branch 0 taken 51 times.
✗ Branch 1 not taken.
✗ Branch 2 not taken.
✓ Branch 3 taken 51 times.
51 if (c->key_info_file || c->encrypt) {
1785 if (c->segment_type == SEGMENT_TYPE_FMP4) {
1786 av_log(s, AV_LOG_ERROR, "Encrypted fmp4 not yet supported\n");
1787 return AVERROR_PATCHWELCOME;
1788 }
1789
1790 if (c->key_info_file && c->encrypt) {
1791 av_log(s, AV_LOG_WARNING, "Cannot use both -hls_key_info_file and -hls_enc,"
1792 " ignoring -hls_enc\n");
1793 }
1794
1795 if (!vs->encrypt_started || (c->flags & HLS_PERIODIC_REKEY)) {
1796 if (c->key_info_file) {
1797 if ((err = hls_encryption_start(s, vs)) < 0)
1798 goto fail;
1799 } else {
1800 if (!c->encrypt_started) {
1801 if ((err = do_encrypt(s, vs)) < 0)
1802 goto fail;
1803 c->encrypt_started = 1;
1804 }
1805 av_strlcpy(vs->key_uri, c->key_uri, sizeof(vs->key_uri));
1806 av_strlcpy(vs->key_string, c->key_string, sizeof(vs->key_string));
1807 av_strlcpy(vs->iv_string, c->iv_string, sizeof(vs->iv_string));
1808 }
1809 vs->encrypt_started = 1;
1810 }
1811 err = av_strlcpy(iv_string, vs->iv_string, sizeof(iv_string));
1812 if (!err) {
1813 snprintf(iv_string, sizeof(iv_string), "%032"PRIx64, vs->sequence);
1814 memset(vs->iv_string, 0, sizeof(vs->iv_string));
1815 memcpy(vs->iv_string, iv_string, sizeof(iv_string));
1816 }
1817 }
1818
2/2
✓ Branch 0 taken 46 times.
✓ Branch 1 taken 5 times.
51 if (c->segment_type != SEGMENT_TYPE_FMP4) {
1819
2/4
✓ Branch 0 taken 46 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 46 times.
✗ Branch 3 not taken.
46 if (oc->oformat->priv_class && oc->priv_data) {
1820 46 av_opt_set(oc->priv_data, "mpegts_flags", "resend_headers", 0);
1821 }
1822
2/2
✓ Branch 0 taken 1 times.
✓ Branch 1 taken 45 times.
46 if (c->flags & HLS_SINGLE_FILE) {
1823
2/4
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
✗ Branch 2 not taken.
✓ Branch 3 taken 1 times.
1 if (c->key_info_file || c->encrypt) {
1824 av_dict_set(&options, "encryption_key", vs->key_string, 0);
1825 av_dict_set(&options, "encryption_iv", vs->iv_string, 0);
1826
1827 /* Write temp file with cryption content */
1828 av_freep(&vs->basename_tmp);
1829 vs->basename_tmp = av_asprintf("crypto:%s.tmp", oc->url);
1830
1831 /* append temp file content into single file */
1832 av_freep(&vs->basename);
1833 vs->basename = av_asprintf("%s", oc->url);
1834 } else {
1835 1 vs->basename_tmp = vs->basename;
1836 }
1837 1 set_http_options(s, &options, c);
1838
1/2
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
1 if (!vs->out_single_file)
1839
1/2
✗ Branch 1 not taken.
✓ Branch 2 taken 1 times.
1 if ((err = hlsenc_io_open(s, &vs->out_single_file, vs->basename, &options)) < 0) {
1840 if (c->ignore_io_errors)
1841 err = 0;
1842 goto fail;
1843 }
1844
1845
1/2
✗ Branch 1 not taken.
✓ Branch 2 taken 1 times.
1 if ((err = hlsenc_io_open(s, &vs->out, vs->basename_tmp, &options)) < 0) {
1846 if (c->ignore_io_errors)
1847 err = 0;
1848 goto fail;
1849 }
1850
1851 }
1852 }
1853
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 51 times.
51 if (vs->vtt_basename) {
1854 set_http_options(s, &options, c);
1855 if ((err = hlsenc_io_open(s, &vtt_oc->pb, vtt_oc->url, &options)) < 0) {
1856 if (c->ignore_io_errors)
1857 err = 0;
1858 goto fail;
1859 }
1860 }
1861 51 av_dict_free(&options);
1862
1863
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 51 times.
51 if (vs->vtt_basename) {
1864 err = avformat_write_header(vtt_oc,NULL);
1865 if (err < 0)
1866 return err;
1867 }
1868
1869 51 return 0;
1870 fail:
1871 av_dict_free(&options);
1872
1873 return err;
1874 }
1875
1876 static const char * get_default_pattern_localtime_fmt(AVFormatContext *s)
1877 {
1878 char b[21];
1879 time_t t = time(NULL);
1880 struct tm *p, tmbuf;
1881 HLSContext *hls = s->priv_data;
1882
1883 p = localtime_r(&t, &tmbuf);
1884 // no %s support when strftime returned error or left format string unchanged
1885 // also no %s support on MSVC, which invokes the invalid parameter handler on unsupported format strings, instead of returning an error
1886 if (hls->segment_type == SEGMENT_TYPE_FMP4) {
1887 return (HAVE_LIBC_MSVCRT || !strftime(b, sizeof(b), "%s", p) || !strcmp(b, "%s")) ? "-%Y%m%d%H%M%S.m4s" : "-%s.m4s";
1888 }
1889 return (HAVE_LIBC_MSVCRT || !strftime(b, sizeof(b), "%s", p) || !strcmp(b, "%s")) ? "-%Y%m%d%H%M%S.ts" : "-%s.ts";
1890 }
1891
1892 static int append_postfix(char *name, int name_buf_len, int i)
1893 {
1894 char *p;
1895 char extension[10] = {'\0'};
1896
1897 p = strrchr(name, '.');
1898 if (p) {
1899 av_strlcpy(extension, p, sizeof(extension));
1900 *p = '\0';
1901 }
1902
1903 snprintf(name + strlen(name), name_buf_len - strlen(name), POSTFIX_PATTERN, i);
1904
1905 if (strlen(extension))
1906 av_strlcat(name, extension, name_buf_len);
1907
1908 return 0;
1909 }
1910
1911 22 static int validate_name(int nb_vs, const char *fn)
1912 {
1913 const char *filename, *subdir_name;
1914 22 char *fn_dup = NULL;
1915 22 int ret = 0;
1916
1917
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 22 times.
22 if (!fn)
1918 return AVERROR(EINVAL);
1919
1920 22 fn_dup = av_strdup(fn);
1921
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 22 times.
22 if (!fn_dup)
1922 return AVERROR(ENOMEM);
1923 22 filename = av_basename(fn);
1924 22 subdir_name = av_dirname(fn_dup);
1925
1926
1/6
✗ Branch 0 not taken.
✓ Branch 1 taken 22 times.
✗ Branch 3 not taken.
✗ Branch 4 not taken.
✗ Branch 6 not taken.
✗ Branch 7 not taken.
22 if (nb_vs > 1 && !av_stristr(filename, "%v") && !av_stristr(subdir_name, "%v")) {
1927 av_log(NULL, AV_LOG_ERROR, "More than 1 variant streams are present, %%v is expected "
1928 "either in the filename or in the sub-directory name of file %s\n", fn);
1929 ret = AVERROR(EINVAL);
1930 goto fail;
1931 }
1932
1933
1/4
✓ Branch 1 taken 22 times.
✗ Branch 2 not taken.
✗ Branch 4 not taken.
✗ Branch 5 not taken.
22 if (av_stristr(filename, "%v") && av_stristr(subdir_name, "%v")) {
1934 av_log(NULL, AV_LOG_ERROR, "%%v is expected either in the filename or "
1935 "in the sub-directory name of file %s, but only in one of them\n", fn);
1936 ret = AVERROR(EINVAL);
1937 goto fail;
1938 }
1939
1940 22 fail:
1941 22 av_freep(&fn_dup);
1942 22 return ret;
1943 }
1944
1945 20 static int format_name(const char *buf, char **s, int index, const char *varname)
1946 {
1947 const char *proto, *dir;
1948 20 char *orig_buf_dup = NULL, *mod_buf_dup = NULL;
1949 20 int ret = 0;
1950
1951 20 orig_buf_dup = av_strdup(buf);
1952
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 20 times.
20 if (!orig_buf_dup)
1953 return AVERROR(ENOMEM);
1954
1955
1/2
✓ Branch 1 taken 20 times.
✗ Branch 2 not taken.
20 if (!av_stristr(buf, "%v")) {
1956 20 *s = orig_buf_dup;
1957 20 return 0;
1958 }
1959
1960 if (!varname) {
1961 if (replace_int_data_in_filename(s, orig_buf_dup, 'v', index) < 1) {
1962 ret = AVERROR(EINVAL);
1963 goto fail;
1964 }
1965 } else {
1966 if (replace_str_data_in_filename(s, orig_buf_dup, 'v', varname) < 1) {
1967 ret = AVERROR(EINVAL);
1968 goto fail;
1969 }
1970 }
1971
1972 proto = avio_find_protocol_name(orig_buf_dup);
1973 dir = av_dirname(orig_buf_dup);
1974
1975 /* if %v is present in the file's directory, create sub-directory */
1976 if (av_stristr(dir, "%v") && proto && !strcmp(proto, "file")) {
1977 mod_buf_dup = av_strdup(*s);
1978 dir = av_dirname(mod_buf_dup);
1979 if (ff_mkdir_p(dir) == -1 && errno != EEXIST) {
1980 ret = AVERROR(errno);
1981 goto fail;
1982 }
1983 }
1984
1985 fail:
1986 av_freep(&orig_buf_dup);
1987 av_freep(&mod_buf_dup);
1988 return ret;
1989 }
1990
1991 static int get_nth_codec_stream_index(AVFormatContext *s,
1992 enum AVMediaType codec_type,
1993 int64_t stream_id)
1994 {
1995 unsigned int stream_index, cnt;
1996 if (stream_id < 0 || stream_id > s->nb_streams - 1)
1997 return -1;
1998 cnt = 0;
1999 for (stream_index = 0; stream_index < s->nb_streams; stream_index++) {
2000 if (s->streams[stream_index]->codecpar->codec_type != codec_type)
2001 continue;
2002 if (cnt == stream_id)
2003 return stream_index;
2004 cnt++;
2005 }
2006 return -1;
2007 }
2008
2009 static int parse_variant_stream_mapstring(AVFormatContext *s)
2010 {
2011 HLSContext *hls = s->priv_data;
2012 VariantStream *vs;
2013 int stream_index, i, j;
2014 enum AVMediaType codec_type;
2015 int nb_varstreams = 0, nb_streams;
2016 char *p, *q, *saveptr1, *saveptr2, *varstr, *keyval;
2017 const char *val;
2018
2019 /**
2020 * Expected format for var_stream_map string is as below:
2021 * "a:0,v:0 a:1,v:1"
2022 * "a:0,agroup:a0,default:1,language:ENG a:1,agroup:a1,default:0 v:0,agroup:a0 v:1,agroup:a1"
2023 * This string specifies how to group the audio, video and subtitle streams
2024 * into different variant streams. The variant stream groups are separated
2025 * by space.
2026 *
2027 * a:, v:, s: are keys to specify audio, video and subtitle streams
2028 * respectively. Allowed values are 0 to 9 digits (limited just based on
2029 * practical usage)
2030 *
2031 * agroup: is key to specify audio group. A string can be given as value.
2032 * sgroup: is key to specify subtitle group. A string can be given as value.
2033 */
2034 p = av_strdup(hls->var_stream_map);
2035 if (!p)
2036 return AVERROR(ENOMEM);
2037
2038 q = p;
2039 while (av_strtok(q, " \t", &saveptr1)) {
2040 q = NULL;
2041 nb_varstreams++;
2042 }
2043 av_freep(&p);
2044
2045 hls->var_streams = av_mallocz(sizeof(*hls->var_streams) * nb_varstreams);
2046 if (!hls->var_streams)
2047 return AVERROR(ENOMEM);
2048 hls->nb_varstreams = nb_varstreams;
2049
2050 p = hls->var_stream_map;
2051 nb_varstreams = 0;
2052 while (varstr = av_strtok(p, " \t", &saveptr1)) {
2053 p = NULL;
2054
2055 if (nb_varstreams < hls->nb_varstreams) {
2056 vs = &(hls->var_streams[nb_varstreams]);
2057 vs->var_stream_idx = nb_varstreams;
2058 vs->is_default = 0;
2059 nb_varstreams++;
2060 } else
2061 return AVERROR(EINVAL);
2062
2063 q = varstr;
2064 while (1) {
2065 if (!av_strncasecmp(q, "a:", 2) || !av_strncasecmp(q, "v:", 2) ||
2066 !av_strncasecmp(q, "s:", 2))
2067 vs->nb_streams++;
2068 q = strchr(q, ',');
2069 if (!q)
2070 break;
2071 q++;
2072 }
2073 vs->streams = av_mallocz(sizeof(AVStream *) * vs->nb_streams);
2074 if (!vs->streams)
2075 return AVERROR(ENOMEM);
2076
2077 nb_streams = 0;
2078 while (keyval = av_strtok(varstr, ",", &saveptr2)) {
2079 int64_t num;
2080 char *end;
2081 varstr = NULL;
2082 if (av_strstart(keyval, "language:", &val)) {
2083 vs->language = val;
2084 continue;
2085 } else if (av_strstart(keyval, "default:", &val)) {
2086 vs->is_default = (!av_strncasecmp(val, "YES", strlen("YES")) ||
2087 (!av_strncasecmp(val, "1", strlen("1"))));
2088 hls->has_default_key = 1;
2089 continue;
2090 } else if (av_strstart(keyval, "name:", &val)) {
2091 vs->varname = val;
2092 continue;
2093 } else if (av_strstart(keyval, "agroup:", &val)) {
2094 vs->agroup = val;
2095 continue;
2096 } else if (av_strstart(keyval, "sgroup:", &val)) {
2097 vs->sgroup = val;
2098 continue;
2099 } else if (av_strstart(keyval, "ccgroup:", &val)) {
2100 vs->ccgroup = val;
2101 continue;
2102 } else if (av_strstart(keyval, "v:", &val)) {
2103 codec_type = AVMEDIA_TYPE_VIDEO;
2104 hls->has_video_m3u8 = 1;
2105 } else if (av_strstart(keyval, "a:", &val)) {
2106 codec_type = AVMEDIA_TYPE_AUDIO;
2107 } else if (av_strstart(keyval, "s:", &val)) {
2108 codec_type = AVMEDIA_TYPE_SUBTITLE;
2109 } else {
2110 av_log(s, AV_LOG_ERROR, "Invalid keyval %s\n", keyval);
2111 return AVERROR(EINVAL);
2112 }
2113
2114 num = strtoll(val, &end, 10);
2115 if (!av_isdigit(*val) || *end != '\0') {
2116 av_log(s, AV_LOG_ERROR, "Invalid stream number: '%s'\n", val);
2117 return AVERROR(EINVAL);
2118 }
2119 stream_index = get_nth_codec_stream_index(s, codec_type, num);
2120
2121 if (stream_index >= 0 && nb_streams < vs->nb_streams) {
2122 for (i = 0; nb_streams > 0 && i < nb_streams; i++) {
2123 if (vs->streams[i] == s->streams[stream_index]) {
2124 av_log(s, AV_LOG_ERROR, "Same elementary stream found more than once inside "
2125 "variant definition #%d\n", nb_varstreams - 1);
2126 return AVERROR(EINVAL);
2127 }
2128 }
2129 for (j = 0; nb_varstreams > 1 && j < nb_varstreams - 1; j++) {
2130 for (i = 0; i < hls->var_streams[j].nb_streams; i++) {
2131 if (hls->var_streams[j].streams[i] == s->streams[stream_index]) {
2132 av_log(s, AV_LOG_ERROR, "Same elementary stream found more than once "
2133 "in two different variant definitions #%d and #%d\n",
2134 j, nb_varstreams - 1);
2135 return AVERROR(EINVAL);
2136 }
2137 }
2138 }
2139 vs->streams[nb_streams++] = s->streams[stream_index];
2140 } else {
2141 av_log(s, AV_LOG_ERROR, "Unable to map stream at %s\n", keyval);
2142 return AVERROR(EINVAL);
2143 }
2144 }
2145 }
2146 av_log(s, AV_LOG_DEBUG, "Number of variant streams %d\n",
2147 hls->nb_varstreams);
2148
2149 return 0;
2150 }
2151
2152 static int parse_cc_stream_mapstring(AVFormatContext *s)
2153 {
2154 HLSContext *hls = s->priv_data;
2155 int nb_ccstreams = 0;
2156 char *p, *q, *ccstr, *keyval;
2157 char *saveptr1 = NULL, *saveptr2 = NULL;
2158 const char *val;
2159 ClosedCaptionsStream *ccs;
2160
2161 p = av_strdup(hls->cc_stream_map);
2162 if(!p)
2163 return AVERROR(ENOMEM);
2164