FFmpeg
Loading...
Searching...
No Matches
hlsenc.c
Go to the documentation of this file.
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
32#include "libavutil/avassert.h"
33#include "libavutil/macros.h"
35#include "libavutil/avstring.h"
36#include "libavutil/bprint.h"
38#include "libavutil/mem.h"
39#include "libavutil/opt.h"
41#include "libavutil/log.h"
43#include "libavutil/time.h"
45
46#include "libavcodec/defs.h"
47
48#include "avformat.h"
49#include "avio_internal.h"
50#if CONFIG_HTTP_PROTOCOL
51#include "http.h"
52#endif
53#include "hlsplaylist.h"
54#include "internal.h"
55#include "mux.h"
56#include "movenc.h"
57#include "os_support.h"
58#include "url.h"
59
67
72
73#define KEYSIZE 16
74#define LINE_BUFFER_SIZE MAX_URL_SIZE
75#define HLS_MICROSECOND_UNIT 1000000
76#define BUFSIZE (16 * 1024)
77#define POSTFIX_PATTERN "_%d"
78
79typedef struct HLSSegment {
80 const char *filename;
81 const char *sub_filename;
82 double duration; /* in seconds */
87
88 const char *key_uri;
89 char iv_string[KEYSIZE*2 + 1];
90
93
94 char buf[]; /* for filename, sub_filename and key_uri */
96
97typedef enum HLSFlags {
98 // Generate a single media file and use byte ranges in the playlist.
99 HLS_SINGLE_FILE = (1 << 0),
105 HLS_APPEND_LIST = (1 << 6),
107 HLS_SECOND_LEVEL_SEGMENT_INDEX = (1 << 8), // include segment index in segment filenames when use_localtime e.g.: %%03d
108 HLS_SECOND_LEVEL_SEGMENT_DURATION = (1 << 9), // include segment duration (microsec) in segment filenames when use_localtime e.g.: %%09t
109 HLS_SECOND_LEVEL_SEGMENT_SIZE = (1 << 10), // include segment size (bytes) in segment filenames when use_localtime e.g.: %%014s
110 HLS_TEMP_FILE = (1 << 11),
113 HLS_I_FRAMES_ONLY = (1 << 14),
114} HLSFlags;
115
120
121typedef struct VariantStream {
123 unsigned number;
131 uint8_t *temp_buffer;
132 uint8_t *init_buffer;
133
136
141 double dpp; // duration per packet
145 double duration; // last segment duration computed so far, in seconds
146 int64_t start_pos; // last segment starting position
147 int64_t size; // last segment size
155
160
164
166 char *basename;
170
172 char current_segment_final_filename_fmt[MAX_URL_SIZE]; // when renaming segments
173
176
178
181 char key_string[KEYSIZE*2 + 1];
182 char iv_string[KEYSIZE*2 + 1];
183
185 char codec_attr[128];
187 unsigned int nb_streams;
188 int m3u8_created; /* status of media play-list creation */
189 int is_default; /* default status of audio group */
190 const char *language; /* audio language name */
191 const char *agroup; /* audio group name */
192 const char *sgroup; /* subtitle group name */
193 const char *ccgroup; /* closed caption group name */
194 const char *varname; /* variant name */
195 const char *subtitle_varname; /* subtitle variant name */
197
198typedef struct ClosedCaptionsStream {
199 const char *ccgroup; /* closed caption group name */
200 const char *instreamid; /* closed captions INSTREAM-ID */
201 const char *language; /* closed captions language */
203
204typedef struct HLSContext {
205 const AVClass *class; // Class for private options.
207 uint32_t start_sequence_source_type; // enum StartSequenceSourceType
208
209 int64_t time; // Set by a private option.
210 int64_t init_time; // Set by a private option.
211 int max_nb_segments; // Set by a private option.
212 int hls_delete_threshold; // Set by a private option.
213 uint32_t flags; // enum HLSFlags
214 uint32_t pl_type; // enum PlaylistType
218 int resend_init_file; ///< resend init file into disk after refresh m3u8
219
220 int use_localtime; ///< flag to expand filename with localtime
221 int use_localtime_mkdir;///< flag to mkdir dirname in timebased filename
224 int64_t max_seg_size; // every segment file max size
225
226 char *baseurl;
230
232 char *key;
233 char *key_url;
234 char *iv;
237
241 char key_string[KEYSIZE*2 + 1];
242 char iv_string[KEYSIZE*2 + 1];
244
245 char *method;
247
249 unsigned int nb_varstreams;
251 unsigned int nb_ccstreams;
252
253 int master_m3u8_created; /* status of master play-list creation */
254 char *master_m3u8_url; /* URL of the master m3u8 file */
255 int version; /* HLS version */
256 char *var_stream_map; /* user specified variant stream map string */
257 char *cc_stream_map; /* user specified closed caption streams map string */
260 int http_persistent;
266 char *headers;
267 int has_default_key; /* has DEFAULT field of var_stream_map */
268 int has_video_m3u8; /* has video stream m3u8 list */
269} HLSContext;
270
271static int strftime_expand(const char *fmt, char **dest)
272{
273 int r = 1;
274 time_t now0;
275 struct tm *tm, tmpbuf;
276 char *buf;
277
279 if (!buf)
280 return AVERROR(ENOMEM);
281
282 time(&now0);
283 tm = localtime_r(&now0, &tmpbuf);
284 r = strftime(buf, MAX_URL_SIZE, fmt, tm);
285 if (!r) {
286 av_free(buf);
287 return AVERROR(EINVAL);
288 }
289 *dest = buf;
290
291 return r;
292}
293
294static int hlsenc_io_open(AVFormatContext *s, AVIOContext **pb, const char *filename,
296{
297 HLSContext *hls = s->priv_data;
298 int http_base_proto = filename ? ff_is_http_proto(filename) : 0;
299 int err = AVERROR_MUXER_NOT_FOUND;
300 if (!*pb || !http_base_proto || !hls->http_persistent) {
301 err = s->io_open(s, pb, filename, AVIO_FLAG_WRITE, options);
302#if CONFIG_HTTP_PROTOCOL
303 } else {
304 URLContext *http_url_context = ffio_geturlcontext(*pb);
305 av_assert0(http_url_context);
306 err = ff_http_do_new_request(http_url_context, filename);
307 if (err < 0)
309
310#endif
311 }
312 return err;
313}
314
315static int hlsenc_io_close(AVFormatContext *s, AVIOContext **pb, char *filename)
316{
317 HLSContext *hls = s->priv_data;
318 int http_base_proto = filename ? ff_is_http_proto(filename) : 0;
319 int ret = 0;
320 if (!*pb)
321 return ret;
322 if (!http_base_proto || !hls->http_persistent || hls->key_info_file || hls->encrypt) {
324#if CONFIG_HTTP_PROTOCOL
325 } else {
326 URLContext *http_url_context = ffio_geturlcontext(*pb);
327 av_assert0(http_url_context);
328 avio_flush(*pb);
329 ret = ffurl_shutdown(http_url_context, AVIO_FLAG_WRITE);
330#endif
331 }
332 return ret;
333}
334
336{
337 int http_base_proto = ff_is_http_proto(s->url);
338
339 if (c->method) {
340 av_dict_set(options, "method", c->method, 0);
341 } else if (http_base_proto) {
342 av_dict_set(options, "method", "PUT", 0);
343 }
344 if (c->user_agent)
345 av_dict_set(options, "user_agent", c->user_agent, 0);
346 if (c->http_persistent)
347 av_dict_set_int(options, "multiple_requests", 1, 0);
348 if (c->timeout >= 0)
349 av_dict_set_int(options, "timeout", c->timeout, 0);
350 if (c->headers)
351 av_dict_set(options, "headers", c->headers, 0);
352}
353
355{
356 int codec_strlen = strlen(vs->codec_attr);
357 char attr[64];
358 AVBPrint buffer;
359
361 return;
363 return;
364
365 av_bprint_init_for_buffer(&buffer, attr, sizeof(attr));
366 if (ff_make_codec_str(vs->avf, st->codecpar, &st->avg_frame_rate,
367 &buffer) < 0 ||
369 goto fail;
370
371 // Don't write the same attribute multiple times
372 if (!av_stristr(vs->codec_attr, attr)) {
373 snprintf(vs->codec_attr + codec_strlen,
374 sizeof(vs->codec_attr) - codec_strlen,
375 "%s%s", codec_strlen ? "," : "", attr);
376 }
377 return;
378
379fail:
380 vs->codec_attr[0] = '\0';
382 return;
383}
384
385static int replace_str_data_in_filename(char **s, const char *filename, char placeholder, const char *datastring)
386{
387 const char *p;
388 char c;
389 int addchar_count;
390 int found_count = 0;
391 AVBPrint buf;
392 int ret;
393
395
396 p = filename;
397 for (;;) {
398 c = *p;
399 if (c == '\0')
400 break;
401 if (c == '%' && *(p+1) == '%') // %%
402 addchar_count = 2;
403 else if (c == '%' && *(p+1) == placeholder) {
404 av_bprintf(&buf, "%s", datastring);
405 p += 2;
406 addchar_count = 0;
407 found_count ++;
408 } else
409 addchar_count = 1;
410
411 if (addchar_count > 0) {
412 av_bprint_append_data(&buf, p, addchar_count);
413 p += addchar_count;
414 }
415 }
416 if (!av_bprint_is_complete(&buf)) {
418 return AVERROR(ENOMEM);
419 }
420 if ((ret = av_bprint_finalize(&buf, s)) < 0)
421 return ret;
422 return found_count;
423}
424
425static int replace_int_data_in_filename(char **s, const char *filename, char placeholder, int64_t number)
426{
427 const char *p;
428 char c;
429 int nd, addchar_count;
430 int found_count = 0;
431 AVBPrint buf;
432 int ret;
433
435
436 p = filename;
437 for (;;) {
438 c = *p;
439 if (c == '\0')
440 break;
441 if (c == '%' && *(p+1) == '%') // %%
442 addchar_count = 2;
443 else if (c == '%' && (av_isdigit(*(p+1)) || *(p+1) == placeholder)) {
444 nd = 0;
445 addchar_count = 1;
446 while (av_isdigit(*(p + addchar_count))) {
447 nd = nd * 10 + *(p + addchar_count) - '0';
448 addchar_count++;
449 }
450
451 if (*(p + addchar_count) == placeholder) {
452 av_bprintf(&buf, "%0*"PRId64, (number < 0) ? nd : nd++, number);
453 p += (addchar_count + 1);
454 addchar_count = 0;
455 found_count++;
456 }
457
458 } else
459 addchar_count = 1;
460
461 av_bprint_append_data(&buf, p, addchar_count);
462 p += addchar_count;
463 }
464 if (!av_bprint_is_complete(&buf)) {
466 return AVERROR(ENOMEM);
467 }
468 if ((ret = av_bprint_finalize(&buf, s)) < 0)
469 return ret;
470 return found_count;
471}
472
473static void write_styp(AVIOContext *pb)
474{
475 avio_wb32(pb, 24);
476 ffio_wfourcc(pb, "styp");
477 ffio_wfourcc(pb, "msdh");
478 avio_wb32(pb, 0); /* minor */
479 ffio_wfourcc(pb, "msdh");
480 ffio_wfourcc(pb, "msix");
481}
482
483static int flush_dynbuf(VariantStream *vs, int *range_length)
484{
485 AVFormatContext *ctx = vs->avf;
486
487 if (!ctx->pb) {
488 return AVERROR(EINVAL);
489 }
490
491 // flush
493
494 // write out to file
495 *range_length = avio_close_dyn_buf(ctx->pb, &vs->temp_buffer);
496 ctx->pb = NULL;
497 avio_write(vs->out, vs->temp_buffer, *range_length);
498 avio_flush(vs->out);
499
500 // re-open buffer
501 return avio_open_dyn_buf(&ctx->pb);
502}
503
504static void reflush_dynbuf(VariantStream *vs, int *range_length)
505{
506 // re-open buffer
507 avio_write(vs->out, vs->temp_buffer, *range_length);
508}
509
511{
512 HLSContext *hls = s->priv_data;
513 AVFormatContext *oc = vs->avf;
514 const MOVMuxContext *mov = oc->priv_data;
515 int64_t init_size = mov->moov_end;
516 AVIOContext *media_pb;
517 uint8_t *buffer, *init_buffer = NULL;
518 int buffer_size, ret;
519
520 buffer_size = avio_get_dyn_buf(oc->pb, &buffer);
521 if (oc->pb->error < 0)
522 return oc->pb->error;
523 if (init_size <= 0 || init_size > buffer_size)
524 return AVERROR_INVALIDDATA;
525
526 /* Automatic fragment cuts may have already written media after moov.
527 * Preserve the original buffer until all split allocations succeed. */
528 if ((ret = avio_open_dyn_buf(&media_pb)) < 0)
529 return ret;
530 avio_write(media_pb, buffer + init_size, buffer_size - init_size);
531 avio_flush(media_pb);
532 if (media_pb->error < 0) {
533 ret = media_pb->error;
534 goto fail;
535 }
536 if (hls->resend_init_file) {
537 init_buffer = av_memdup(buffer, init_size);
538 if (!init_buffer) {
539 ret = AVERROR(ENOMEM);
540 goto fail;
541 }
542 }
543
544 avio_write(vs->out, buffer, init_size);
545 ffio_free_dyn_buf(&oc->pb);
546 oc->pb = media_pb;
548 vs->init_range_length = init_size;
549 vs->start_pos = init_size;
550 return 0;
551
552fail:
553 ffio_free_dyn_buf(&media_pb);
554 return ret;
555}
556
558 char *path, const char *proto)
559{
560 if (hls->method || (proto && !av_strcasecmp(proto, "http"))) {
561 AVDictionary *opt = NULL;
562 int ret;
563
564 set_http_options(avf, &opt, hls);
565 av_dict_set(&opt, "method", "DELETE", 0);
566
567 ret = hlsenc_io_open(avf, &hls->http_delete, path, &opt);
568 av_dict_free(&opt);
569 if (ret < 0)
570 return hls->ignore_io_errors ? 1 : ret;
571
572 //Nothing to write
573 hlsenc_io_close(avf, &hls->http_delete, path);
574 } else if (unlink(path) < 0) {
575 av_log(hls, AV_LOG_ERROR, "failed to delete old segment %s: %s\n",
576 path, strerror(errno));
577 }
578 return 0;
579}
580
582 VariantStream *vs)
583{
584
585 HLSSegment *segment, *previous_segment = NULL;
586 float playlist_duration = 0.0f;
587 int ret = 0;
588 int segment_cnt = 0;
589 AVBPrint path;
590 const char *dirname = NULL;
591 char *dirname_r = NULL;
592 char *dirname_repl = NULL;
593 const char *vtt_dirname = NULL;
594 char *vtt_dirname_r = NULL;
595 const char *proto = NULL;
596
598
599 segment = vs->segments;
600 while (segment) {
601 playlist_duration += segment->duration;
602 segment = segment->next;
603 }
604
605 segment = vs->old_segments;
606 segment_cnt = 0;
607 while (segment) {
608 playlist_duration -= segment->duration;
609 previous_segment = segment;
610 segment = previous_segment->next;
611 segment_cnt++;
612 if (playlist_duration <= -previous_segment->duration) {
613 previous_segment->next = NULL;
614 break;
615 }
616 if (segment_cnt >= hls->hls_delete_threshold) {
617 previous_segment->next = NULL;
618 break;
619 }
620 }
621
622 if (segment && !hls->use_localtime_mkdir) {
623 dirname_r = hls->segment_filename ? av_strdup(hls->segment_filename): av_strdup(vs->avf->url);
624 dirname = av_dirname(dirname_r);
625 }
626
627 /* if %v is present in the file's directory
628 * all segment belongs to the same variant, so do it only once before the loop*/
629 if (dirname && av_stristr(dirname, "%v")) {
630 if (!vs->varname) {
631 if (replace_int_data_in_filename(&dirname_repl, dirname, 'v', segment->var_stream_idx) < 1) {
632 ret = AVERROR(EINVAL);
633 goto fail;
634 }
635 } else {
636 if (replace_str_data_in_filename(&dirname_repl, dirname, 'v', vs->varname) < 1) {
637 ret = AVERROR(EINVAL);
638 goto fail;
639 }
640 }
641
642 dirname = dirname_repl;
643 }
644
645 while (segment) {
646 av_log(hls, AV_LOG_DEBUG, "deleting old segment %s\n",
647 segment->filename);
648 if (!hls->use_localtime_mkdir) // segment->filename contains basename only
649 av_bprintf(&path, "%s/", dirname);
650 av_bprintf(&path, "%s", segment->filename);
651
653 ret = AVERROR(ENOMEM);
654 goto fail;
655 }
656
657 proto = avio_find_protocol_name(s->url);
658 if (ret = hls_delete_file(hls, s, path.str, proto))
659 goto fail;
660
661 if ((segment->sub_filename[0] != '\0')) {
662 vtt_dirname_r = av_strdup(vs->vtt_avf->url);
663 vtt_dirname = av_dirname(vtt_dirname_r);
664
666 av_bprintf(&path, "%s/%s", vtt_dirname, segment->sub_filename);
667 av_freep(&vtt_dirname_r);
668
670 ret = AVERROR(ENOMEM);
671 goto fail;
672 }
673
674 if (ret = hls_delete_file(hls, s, path.str, proto))
675 goto fail;
676 }
678 previous_segment = segment;
679 segment = previous_segment->next;
680 av_freep(&previous_segment);
681 }
682
683fail:
685 av_freep(&dirname_r);
686 av_freep(&dirname_repl);
687
688 return ret;
689}
690
692{
693 HLSContext *hls = s->priv_data;
694 int ret;
695 int len;
696 AVIOContext *pb;
697 uint8_t key[KEYSIZE];
698 char * key_basename_source = (hls->master_m3u8_url) ? hls->master_m3u8_url : s->url;
699
700 len = strlen(key_basename_source) + 4 + 1;
702 if (!hls->key_basename)
703 return AVERROR(ENOMEM);
704
705 av_strlcpy(hls->key_basename, key_basename_source, len);
706 av_strlcat(hls->key_basename, ".key", len);
707
708 if (hls->key_url) {
709 av_strlcpy(hls->key_file, hls->key_url, sizeof(hls->key_file));
710 av_strlcpy(hls->key_uri, hls->key_url, sizeof(hls->key_uri));
711 } else {
712 av_strlcpy(hls->key_file, hls->key_basename, sizeof(hls->key_file));
713 av_strlcpy(hls->key_uri, hls->key_basename, sizeof(hls->key_uri));
714 }
715
716 if (!*hls->iv_string) {
717 uint8_t iv[16] = { 0 };
718 char buf[33];
719
720 if (!hls->iv) {
721 AV_WB64(iv + 8, vs->sequence);
722 } else if (strlen(hls->iv) < sizeof(iv)) {
723 av_log(hls, AV_LOG_ERROR, "hls_enc_iv is shorter than %zu bytes\n", sizeof(iv));
724 return AVERROR(EINVAL);
725 } else {
726 memcpy(iv, hls->iv, sizeof(iv));
727 }
728 ff_data_to_hex(buf, iv, sizeof(iv), 0);
729 memcpy(hls->iv_string, buf, sizeof(hls->iv_string));
730 }
731
732 if (!*hls->key_uri) {
733 av_log(hls, AV_LOG_ERROR, "no key URI specified in key info file\n");
734 return AVERROR(EINVAL);
735 }
736
737 if (!*hls->key_file) {
738 av_log(hls, AV_LOG_ERROR, "no key file specified in key info file\n");
739 return AVERROR(EINVAL);
740 }
741
742 if (!*hls->key_string) {
744 if (!hls->key) {
745 if ((ret = av_random_bytes(key, sizeof(key))) < 0) {
746 av_log(s, AV_LOG_ERROR, "Cannot generate a strong random key\n");
747 return ret;
748 }
749 } else if (strlen(hls->key) < sizeof(key)) {
750 av_log(hls, AV_LOG_ERROR, "hls_enc_key is shorter than %zu bytes\n", sizeof(key));
751 return AVERROR(EINVAL);
752 } else {
753 memcpy(key, hls->key, sizeof(key));
754 }
755
756 ff_data_to_hex(hls->key_string, key, sizeof(key), 0);
757 set_http_options(s, &options, hls);
758 ret = s->io_open(s, &pb, hls->key_file, AVIO_FLAG_WRITE, &options);
760 if (ret < 0)
761 return ret;
762 avio_seek(pb, 0, SEEK_CUR);
763 avio_write(pb, key, KEYSIZE);
764 ff_format_io_close(s, &pb);
765 }
766 return 0;
767}
768
769
771{
772 HLSContext *hls = s->priv_data;
773 int ret;
774 AVIOContext *pb;
775 uint8_t key[KEYSIZE];
777
778 set_http_options(s, &options, hls);
779 ret = s->io_open(s, &pb, hls->key_info_file, AVIO_FLAG_READ, &options);
781 if (ret < 0) {
782 av_log(hls, AV_LOG_ERROR,
783 "error opening key info file %s\n", hls->key_info_file);
784 return ret;
785 }
786
787 ff_get_line(pb, vs->key_uri, sizeof(vs->key_uri));
788 vs->key_uri[strcspn(vs->key_uri, "\r\n")] = '\0';
789
790 ff_get_line(pb, vs->key_file, sizeof(vs->key_file));
791 vs->key_file[strcspn(vs->key_file, "\r\n")] = '\0';
792
793 ff_get_line(pb, vs->iv_string, sizeof(vs->iv_string));
794 vs->iv_string[strcspn(vs->iv_string, "\r\n")] = '\0';
795
796 ff_format_io_close(s, &pb);
797
798 if (!*vs->key_uri) {
799 av_log(hls, AV_LOG_ERROR, "no key URI specified in key info file\n");
800 return AVERROR(EINVAL);
801 }
802
803 if (!*vs->key_file) {
804 av_log(hls, AV_LOG_ERROR, "no key file specified in key info file\n");
805 return AVERROR(EINVAL);
806 }
807
808 set_http_options(s, &options, hls);
809 ret = s->io_open(s, &pb, vs->key_file, AVIO_FLAG_READ, &options);
811 if (ret < 0) {
812 av_log(hls, AV_LOG_ERROR, "error opening key file %s\n", vs->key_file);
813 return ret;
814 }
815
816 ret = avio_read(pb, key, sizeof(key));
817 ff_format_io_close(s, &pb);
818 if (ret != sizeof(key)) {
819 av_log(hls, AV_LOG_ERROR, "error reading key file %s\n", vs->key_file);
820 if (ret >= 0 || ret == AVERROR_EOF)
821 ret = AVERROR(EINVAL);
822 return ret;
823 }
824 ff_data_to_hex(vs->key_string, key, sizeof(key), 0);
825
826 return 0;
827}
828
830{
832 HLSContext *hls = s->priv_data;
833 AVFormatContext *oc;
834 AVFormatContext *vtt_oc = NULL;
835 int byterange_mode = (hls->flags & HLS_SINGLE_FILE) || (hls->max_seg_size > 0);
836 int remaining_options;
837 int i, ret;
838
840 if (ret < 0)
841 return ret;
842 oc = vs->avf;
843
844 oc->url = av_strdup("");
845 if (!oc->url)
846 return AVERROR(ENOMEM);
847
848 oc->interrupt_callback = s->interrupt_callback;
849 oc->max_delay = s->max_delay;
850 oc->opaque = s->opaque;
851 oc->io_open = s->io_open;
852 oc->io_close2 = s->io_close2;
853 oc->strict_std_compliance = s->strict_std_compliance;
854 oc->flags = s->flags;
855 av_dict_copy(&oc->metadata, s->metadata, 0);
856
857 if (vs->vtt_oformat) {
859 if (ret < 0)
860 return ret;
861 vtt_oc = vs->vtt_avf;
862 vtt_oc->flags = s->flags;
863 av_dict_copy(&vtt_oc->metadata, s->metadata, 0);
864 }
865
866 for (i = 0; i < vs->nb_streams; i++) {
867 AVStream *st;
868 AVFormatContext *loc;
870 loc = vtt_oc;
871 else
872 loc = oc;
873
874 if (!(st = avformat_new_stream(loc, NULL)))
875 return AVERROR(ENOMEM);
877 if (ret < 0)
878 return ret;
879 if (!oc->oformat->codec_tag ||
883 } else {
884 st->codecpar->codec_tag = 0;
885 }
886
888 st->time_base = vs->streams[i]->time_base;
889 av_dict_copy(&st->metadata, vs->streams[i]->metadata, 0);
890 st->id = vs->streams[i]->id;
891 }
892
893 for (i = 0; i < s->nb_programs; i++) {
894 ret = av_program_copy(oc, (const AVFormatContext *)s, s->programs[i]->id, 0);
895 if (ret < 0) {
896 av_log(s, AV_LOG_ERROR, "unable to transfer program %d to child muxer\n", s->programs[i]->id);
897 return ret;
898 }
899 }
900
901 vs->start_pos = 0;
902 vs->new_start = 1;
903
904 if (hls->segment_type == SEGMENT_TYPE_FMP4 && hls->max_seg_size > 0) {
905 if (hls->http_persistent > 0) {
906 //TODO: Support fragment fmp4 for http persistent in HLS muxer.
907 av_log(s, AV_LOG_WARNING, "http persistent mode is currently unsupported for fragment mp4 in the HLS muxer.\n");
908 }
909 if (hls->max_seg_size > 0) {
910 av_log(s, AV_LOG_WARNING, "Multi-file byterange mode is currently unsupported in the HLS muxer.\n");
912 }
913 }
914
915 if ((ret = avio_open_dyn_buf(&oc->pb)) < 0)
916 return ret;
917
918 if (hls->segment_type == SEGMENT_TYPE_FMP4) {
919 set_http_options(s, &options, hls);
920 if (byterange_mode) {
921 ret = hlsenc_io_open(s, &vs->out, vs->basename, &options);
922 } else {
924 }
926 }
927 if (ret < 0) {
928 av_log(s, AV_LOG_ERROR, "Failed to open segment '%s'\n", vs->fmp4_init_filename);
929 return ret;
930 }
931
933 if (hls->segment_type == SEGMENT_TYPE_FMP4) {
934 av_dict_set(&options, "fflags", "-autobsf", 0);
935 av_dict_set(&options, "movflags", "+frag_custom+dash+delay_moov", AV_DICT_APPEND);
936 } else {
937 /* We only require one PAT/PMT per segment. */
938 char period[21];
939 snprintf(period, sizeof(period), "%d", (INT_MAX / 2) - 1);
940 av_dict_set(&options, "sdt_period", period, AV_DICT_DONT_OVERWRITE);
941 av_dict_set(&options, "pat_period", period, AV_DICT_DONT_OVERWRITE);
942 }
944 remaining_options = av_dict_count(options);
946 if (ret < 0)
947 return ret;
948 if (remaining_options) {
949 av_log(s, AV_LOG_ERROR, "Some of the provided format options are not recognized\n");
950 return AVERROR(EINVAL);
951 }
952 avio_flush(oc->pb);
953 return 0;
954}
955
957{
958 while (segment) {
959 if (!av_strcasecmp(segment->filename,filename))
960 return segment;
961 segment = segment->next;
962 }
963 return (HLSSegment *) NULL;
964}
965
967 VariantStream *vs,
969{
972 char * new_url = av_strdup(vs->current_segment_final_filename_fmt);
973 if (!new_url) {
974 return AVERROR(ENOMEM);
975 }
976 ff_format_set_url(vs->avf, new_url);
978 char *filename = NULL;
979 if (replace_int_data_in_filename(&filename, vs->avf->url, 's', pos + size) < 1) {
980 av_log(hls, AV_LOG_ERROR,
981 "Invalid second level segment filename template '%s', "
982 "you can try to remove second_level_segment_size flag\n",
983 vs->avf->url);
984 av_freep(&filename);
985 return AVERROR(EINVAL);
986 }
987 ff_format_set_url(vs->avf, filename);
988 }
990 char *filename = NULL;
991 if (replace_int_data_in_filename(&filename, vs->avf->url,
992 't', (int64_t)round(duration * HLS_MICROSECOND_UNIT)) < 1) {
993 av_log(hls, AV_LOG_ERROR,
994 "Invalid second level segment filename template '%s', "
995 "you can try to remove second_level_segment_duration flag\n",
996 vs->avf->url);
997 av_freep(&filename);
998 return AVERROR(EINVAL);
999 }
1000 ff_format_set_url(vs->avf, filename);
1001 }
1002 }
1003 return 0;
1004}
1005
1007{
1008 int ret = 0;
1009
1011 av_log(hls, AV_LOG_ERROR,
1012 "second_level_segment_duration hls_flag requires strftime to be true\n");
1013 ret = AVERROR(EINVAL);
1014 }
1016 av_log(hls, AV_LOG_ERROR,
1017 "second_level_segment_size hls_flag requires strfime to be true\n");
1018 ret = AVERROR(EINVAL);
1019 }
1021 av_log(hls, AV_LOG_ERROR,
1022 "second_level_segment_index hls_flag requires strftime to be true\n");
1023 ret = AVERROR(EINVAL);
1024 }
1025
1026 return ret;
1027}
1028
1030{
1031 const char *proto = avio_find_protocol_name(vs->basename);
1032 int segment_renaming_ok = proto && !strcmp(proto, "file");
1033 int ret = 0;
1034
1035 if ((hls->flags & HLS_SECOND_LEVEL_SEGMENT_DURATION) && !segment_renaming_ok) {
1036 av_log(hls, AV_LOG_ERROR,
1037 "second_level_segment_duration hls_flag works only with file protocol segment names\n");
1038 ret = AVERROR(EINVAL);
1039 }
1040 if ((hls->flags & HLS_SECOND_LEVEL_SEGMENT_SIZE) && !segment_renaming_ok) {
1041 av_log(hls, AV_LOG_ERROR,
1042 "second_level_segment_size hls_flag works only with file protocol segment names\n");
1043 ret = AVERROR(EINVAL);
1044 }
1045
1046 return ret;
1047}
1048
1049static void sls_flag_file_rename(HLSContext *hls, VariantStream *vs, char *old_filename) {
1052 ff_rename(old_filename, vs->avf->url, hls);
1053 }
1054}
1055
1057{
1058 if (c->flags & HLS_SECOND_LEVEL_SEGMENT_INDEX) {
1059 char *filename = NULL;
1060 if (replace_int_data_in_filename(&filename,
1061 oc->url, 'd', vs->sequence) < 1) {
1062 av_log(c, AV_LOG_ERROR, "Invalid second level segment filename template '%s', "
1063 "you can try to remove second_level_segment_index flag\n",
1064 oc->url);
1065 av_freep(&filename);
1066 return AVERROR(EINVAL);
1067 }
1068 ff_format_set_url(oc, filename);
1069 }
1073 if (c->flags & HLS_SECOND_LEVEL_SEGMENT_SIZE) {
1074 char *filename = NULL;
1075 if (replace_int_data_in_filename(&filename, oc->url, 's', 0) < 1) {
1076 av_log(c, AV_LOG_ERROR, "Invalid second level segment filename template '%s', "
1077 "you can try to remove second_level_segment_size flag\n",
1078 oc->url);
1079 av_freep(&filename);
1080 return AVERROR(EINVAL);
1081 }
1082 ff_format_set_url(oc, filename);
1083 }
1084 if (c->flags & HLS_SECOND_LEVEL_SEGMENT_DURATION) {
1085 char *filename = NULL;
1086 if (replace_int_data_in_filename(&filename, oc->url, 't', 0) < 1) {
1087 av_log(c, AV_LOG_ERROR, "Invalid second level segment filename template '%s', "
1088 "you can try to remove second_level_segment_duration flag\n",
1089 oc->url);
1090 av_freep(&filename);
1091 return AVERROR(EINVAL);
1092 }
1093 ff_format_set_url(oc, filename);
1094 }
1095 }
1096 return 0;
1097}
1098
1100{
1101 if (vs->discontinuity_sequence < INT64_MAX)
1103}
1104
1106 const HLSSegment *segment)
1107{
1108 if (vs->discont_start_in_playlist) {
1111 }
1112
1113 if (segment && segment->discont)
1115}
1116
1117/* Create a new segment and append it to the segment list */
1119 VariantStream *vs, double duration, int64_t pos,
1120 int64_t size)
1121{
1122 HLSSegment en0 = {0};
1123 HLSSegment *en = &en0;
1124 const char *filename;
1125 int byterange_mode = (hls->flags & HLS_SINGLE_FILE) || (hls->max_seg_size > 0);
1126 int ret;
1127 AVBPrint bp;
1128
1129 vs->total_size += size;
1130 vs->total_duration += duration;
1131 if (duration > 0.5) {
1132 // Don't include the final, possibly very short segment in the
1133 // calculation of the max bitrate.
1134 int cur_bitrate = (int)(8 * size / duration);
1135 if (cur_bitrate > vs->max_bitrate)
1136 vs->max_bitrate = cur_bitrate;
1137 }
1138 if (vs->total_duration > 0)
1139 vs->avg_bitrate = (int)(8 * vs->total_size / vs->total_duration);
1140
1143 if (ret < 0)
1144 return ret;
1145
1146 filename = av_basename(vs->avf->url);
1147
1148 if (hls->use_localtime_mkdir) {
1149 filename = vs->avf->url;
1150 }
1151 if (vs->nb_entries <= 5000 && (find_segment_by_filename(vs->segments, filename) || find_segment_by_filename(vs->old_segments, filename))
1152 && !byterange_mode) {
1153 av_log(hls, AV_LOG_WARNING, "Duplicated segment filename detected: %s\n", filename);
1154 }
1155
1157 av_bprintf(&bp, "%s%c", filename, 0);
1158 av_bprintf(&bp, "%s%c", vs->has_subtitle ? av_basename(vs->vtt_avf->url) : "", 0);
1159
1160 en->duration = duration;
1161 en->pos = pos;
1162 en->size = size;
1163
1164 if (vs->discontinuity) {
1165 en->discont = 1;
1166 vs->discontinuity = 0;
1167 }
1168
1169 if (hls->key_info_file || hls->encrypt) {
1170 av_bprintf(&bp, "%s%c", vs->key_uri, 0);
1171 av_strlcpy(en->iv_string, vs->iv_string, sizeof(en->iv_string));
1172 } else {
1173 av_bprint_chars(&bp, 0, 1);
1174 }
1175
1176 en = ff_bprint_finalize_as_fam(&bp, &en0, offsetof(HLSSegment, buf));
1177 if (!en)
1178 return AVERROR(ENOMEM);
1179#define NEXT(s) ((s) + strlen(s) + 1)
1180 en->filename = en->buf;
1181 en->sub_filename = NEXT(en->filename);
1182 en->key_uri = NEXT(en->sub_filename);
1183#undef NEXT
1184
1185 if (!vs->segments)
1186 vs->segments = en;
1187 else
1188 vs->last_segment->next = en;
1189
1190 vs->last_segment = en;
1191
1192 // EVENT or VOD playlists imply sliding window cannot be used
1193 if (hls->pl_type != PLAYLIST_TYPE_NONE)
1194 hls->max_nb_segments = 0;
1195
1196 if (hls->max_nb_segments && vs->nb_entries >= hls->max_nb_segments) {
1197 en = vs->segments;
1201 vs->segments = en->next;
1202 if (en && hls->flags & HLS_DELETE_SEGMENTS &&
1203 !(hls->flags & HLS_SINGLE_FILE)) {
1204 en->next = vs->old_segments;
1205 vs->old_segments = en;
1206 if ((ret = hls_delete_old_segments(s, hls, vs)) < 0)
1207 return ret;
1208 } else
1209 av_freep(&en);
1210 } else
1211 vs->nb_entries++;
1212
1213 if (hls->max_seg_size > 0) {
1214 return 0;
1215 }
1216 vs->sequence++;
1217
1218 return 0;
1219}
1220
1221static int extract_segment_number(const char *filename)
1222{
1223 const char *dot = strrchr(filename, '.');
1224 const char *num_start;
1225 char *end;
1226 long value;
1227
1228 if (!dot)
1229 return -1;
1230 if (dot == filename)
1231 return -1;
1232
1233 num_start = dot;
1234 while (num_start > filename &&
1235 num_start[-1] >= '0' && num_start[-1] <= '9')
1236 num_start--;
1237 if (num_start == dot)
1238 return -1;
1239
1240 errno = 0;
1241 value = strtol(num_start, &end, 10);
1242 if (errno == ERANGE || end != dot || value > INT_MAX)
1243 return -1;
1244
1245 return (int)value;
1246}
1247
1248static int parse_playlist(AVFormatContext *s, const char *url, VariantStream *vs)
1249{
1250 HLSContext *hls = s->priv_data;
1251 AVIOContext *in;
1252 int ret = 0, is_segment = 0;
1253 int64_t new_start_pos;
1254 char line[MAX_URL_SIZE];
1255 const char *ptr;
1256 const char *end;
1257 double discont_program_date_time = 0;
1258
1259 if ((ret = s->io_open(s, &in, url, AVIO_FLAG_READ, NULL)) < 0)
1260 return ret;
1261
1262 ff_get_chomp_line(in, line, sizeof(line));
1263 if (strcmp(line, "#EXTM3U")) {
1265 goto fail;
1266 }
1267
1268 vs->discontinuity = 0;
1269 while (!avio_feof(in)) {
1270 ff_get_chomp_line(in, line, sizeof(line));
1271 if (av_strstart(line, "#EXT-X-MEDIA-SEQUENCE:", &ptr)) {
1272 int64_t tmp_sequence = strtoll(ptr, NULL, 10);
1273 if (tmp_sequence < vs->sequence)
1275 "Found playlist sequence number was smaller """
1276 "than specified start sequence number: %"PRId64" < %"PRId64", "
1277 "omitting\n", tmp_sequence, hls->start_sequence);
1278 else {
1279 av_log(hls, AV_LOG_DEBUG, "Found playlist sequence number: %"PRId64"\n", tmp_sequence);
1280 vs->sequence = tmp_sequence;
1281 }
1282 } else if (av_strstart(line, "#EXT-X-DISCONTINUITY-SEQUENCE:", &ptr)) {
1283 int64_t tmp_sequence = strtoll(ptr, NULL, 10);
1284 if (tmp_sequence < 0) {
1286 "Found playlist discontinuity sequence number was negative: %"PRId64", omitting\n",
1287 tmp_sequence);
1288 } else {
1289 av_log(hls, AV_LOG_DEBUG,
1290 "Found playlist discontinuity sequence number: %"PRId64"\n",
1291 tmp_sequence);
1292 vs->discontinuity_sequence = tmp_sequence;
1294 }
1295 } else if (av_strstart(line, "#EXT-X-DISCONTINUITY", &ptr)) {
1296 is_segment = 1;
1297 vs->discontinuity = 1;
1298 } else if (av_strstart(line, "#EXTINF:", &ptr)) {
1299 is_segment = 1;
1300 vs->duration = atof(ptr);
1301 } else if (av_stristart(line, "#EXT-X-KEY:", &ptr)) {
1302 ptr = av_stristr(line, "URI=\"");
1303 if (ptr) {
1304 ptr += strlen("URI=\"");
1305 end = strchr(ptr, '"');
1306 if (end) {
1307 av_strlcpy(vs->key_uri, ptr,
1308 FFMIN(end - ptr + 1, sizeof(vs->key_uri)));
1309 } else {
1311 goto fail;
1312 }
1313 }
1314
1315 ptr = av_stristr(line, "IV=0x");
1316 if (ptr) {
1317 ptr += strlen("IV=0x");
1318 end = av_stristr(ptr, ",");
1319 if (end) {
1320 av_strlcpy(vs->iv_string, ptr, FFMIN(end - ptr + 1, sizeof(vs->iv_string)));
1321 } else {
1322 av_strlcpy(vs->iv_string, ptr, sizeof(vs->iv_string));
1323 }
1324 }
1325 } else if (av_strstart(line, "#EXT-X-PROGRAM-DATE-TIME:", &ptr)) {
1326 struct tm program_date_time = { 0 };
1327 double ms = 0;
1328 char *q = av_small_strptime(ptr, "%Y-%m-%dT%H:%M:%S", &program_date_time);
1329
1330 if (!q) {
1332 goto fail;
1333 }
1334 if (*q == '.')
1335 ms = atof(q + 1);
1336 program_date_time.tm_isdst = -1;
1337
1338 errno = 0;
1339 time_t t = mktime(&program_date_time);
1340 if (t == (time_t)-1 && errno == EOVERFLOW) {
1342 goto fail;
1343 }
1344 discont_program_date_time = t;
1345
1346 discont_program_date_time += (double)(ms / 1000);
1347 } else if (av_strstart(line, "#", NULL)) {
1348 continue;
1349 } else if (line[0]) {
1350 if (is_segment) {
1351 char *new_file = av_strdup(line);
1352 if (!new_file) {
1353 ret = AVERROR(ENOMEM);
1354 goto fail;
1355 }
1356 ff_format_set_url(vs->avf, new_file);
1357
1358 if (vs->has_subtitle) {
1359 int vtt_index = extract_segment_number(line);
1360 const char *vtt_basename = av_basename(vs->vtt_basename);
1361 char *vtt_file = NULL;
1362 ret = replace_int_data_in_filename(&vtt_file, vtt_basename, 'd', vtt_index);
1363 if (ret < 0 || !vtt_file) {
1364 ret = AVERROR(ENOMEM);
1365 goto fail;
1366 }
1367
1368 ff_format_set_url(vs->vtt_avf, vtt_file);
1369 }
1370
1371 is_segment = 0;
1372 new_start_pos = avio_tell(vs->avf->pb);
1373 vs->size = new_start_pos - vs->start_pos;
1374 ret = hls_append_segment(s, hls, vs, vs->duration, vs->start_pos, vs->size);
1375 if (discont_program_date_time) {
1376 vs->last_segment->discont_program_date_time = discont_program_date_time;
1377 discont_program_date_time += vs->duration;
1378 }
1379 if (ret < 0)
1380 goto fail;
1381 vs->start_pos = new_start_pos;
1382 }
1383 }
1384 }
1385
1386fail:
1387 ff_format_io_close(s, &in);
1388 return ret;
1389}
1390
1392{
1393 HLSSegment *en;
1394
1395 while (p) {
1396 en = p;
1397 p = p->next;
1398 av_freep(&en);
1399 }
1400}
1401
1403{
1404 size_t len = strlen(oc->url);
1405 char *final_filename = av_strdup(oc->url);
1406 int ret;
1407
1408 if (!final_filename)
1409 return AVERROR(ENOMEM);
1410 final_filename[len-4] = '\0';
1411 ret = ff_rename(oc->url, final_filename, s);
1412 oc->url[len-4] = '\0';
1413 av_freep(&final_filename);
1414 return ret;
1415}
1416
1417static const char* get_relative_url(const char *master_url, const char *media_url)
1418{
1419 const char *p = strrchr(master_url, '/');
1420 size_t base_len = 0;
1421
1422 if (!p) p = strrchr(master_url, '\\');
1423
1424 if (p) {
1425 base_len = p - master_url;
1426 if (av_strncasecmp(master_url, media_url, base_len)) {
1427 av_log(NULL, AV_LOG_WARNING, "Unable to find relative url\n");
1428 return NULL;
1429 }
1430 } else {
1431 return media_url;
1432 }
1433
1434 return media_url + base_len + 1;
1435}
1436
1438{
1442 );
1443
1444 if (stream->codecpar->bit_rate)
1445 return stream->codecpar->bit_rate;
1446 else if (sd) {
1447 AVCPBProperties *props = (AVCPBProperties*)sd->data;
1448 return props->max_bitrate;
1449 }
1450
1451 return 0;
1452}
1453
1455 VariantStream * const input_vs,
1456 int final)
1457{
1458 HLSContext *hls = s->priv_data;
1459 VariantStream *vs, *temp_vs;
1460 AVStream *vid_st, *aud_st;
1462 unsigned int i, j;
1463 int ret, bandwidth, avg_bandwidth;
1464 const char *m3u8_rel_name = NULL;
1465 const char *vtt_m3u8_rel_name = NULL;
1466 const char *ccgroup;
1467 const char *sgroup = NULL;
1469 const char *proto = avio_find_protocol_name(hls->master_m3u8_url);
1470 int is_file_proto = proto && !strcmp(proto, "file");
1471 int use_temp_file = is_file_proto && ((hls->flags & HLS_TEMP_FILE) || hls->master_publish_rate);
1472 char temp_filename[MAX_URL_SIZE];
1473 int nb_channels;
1474
1475 input_vs->m3u8_created = 1;
1476 if (!hls->master_m3u8_created) {
1477 /* For the first time, wait until all the media playlists are created */
1478 for (i = 0; i < hls->nb_varstreams; i++)
1479 if (!hls->var_streams[i].m3u8_created)
1480 return 0;
1481 } else {
1482 /* Keep publishing the master playlist at the configured rate */
1483 if ((&hls->var_streams[0] != input_vs || !hls->master_publish_rate ||
1484 input_vs->number % hls->master_publish_rate) && !final)
1485 return 0;
1486 }
1487
1488 set_http_options(s, &options, hls);
1489 snprintf(temp_filename, sizeof(temp_filename), use_temp_file ? "%s.tmp" : "%s", hls->master_m3u8_url);
1490 ret = hlsenc_io_open(s, &hls->m3u8_out, temp_filename, &options);
1492 if (ret < 0) {
1493 av_log(s, AV_LOG_ERROR, "Failed to open master play list file '%s'\n",
1494 temp_filename);
1495 goto fail;
1496 }
1497
1499
1500 for (i = 0; i < hls->nb_ccstreams; i++) {
1501 ccs = &(hls->cc_streams[i]);
1502 avio_printf(hls->m3u8_out, "#EXT-X-MEDIA:TYPE=CLOSED-CAPTIONS");
1503 avio_printf(hls->m3u8_out, ",GROUP-ID=\"%s\"", ccs->ccgroup);
1504 avio_printf(hls->m3u8_out, ",NAME=\"%s\"", ccs->instreamid);
1505 if (ccs->language)
1506 avio_printf(hls->m3u8_out, ",LANGUAGE=\"%s\"", ccs->language);
1507 avio_printf(hls->m3u8_out, ",INSTREAM-ID=\"%s\"\n", ccs->instreamid);
1508 }
1509
1510 /* For audio only variant streams add #EXT-X-MEDIA tag with attributes*/
1511 for (i = 0; i < hls->nb_varstreams; i++) {
1512 vs = &(hls->var_streams[i]);
1513
1514 if (vs->has_video || vs->has_subtitle || !vs->agroup)
1515 continue;
1516
1517 m3u8_rel_name = get_relative_url(hls->master_m3u8_url, vs->m3u8_name);
1518 if (!m3u8_rel_name) {
1519 av_log(s, AV_LOG_ERROR, "Unable to find relative URL\n");
1520 goto fail;
1521 }
1522 nb_channels = 0;
1523 for (j = 0; j < vs->nb_streams; j++)
1525 if (vs->streams[j]->codecpar->ch_layout.nb_channels > nb_channels)
1526 nb_channels = vs->streams[j]->codecpar->ch_layout.nb_channels;
1527
1528 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);
1529 }
1530
1531 /* For variant streams with video add #EXT-X-STREAM-INF tag with attributes*/
1532 for (i = 0; i < hls->nb_varstreams; i++) {
1533 vs = &(hls->var_streams[i]);
1534
1535 m3u8_rel_name = get_relative_url(hls->master_m3u8_url, vs->m3u8_name);
1536 if (!m3u8_rel_name) {
1537 av_log(s, AV_LOG_ERROR, "Unable to find relative URL\n");
1538 goto fail;
1539 }
1540
1541 vid_st = NULL;
1542 aud_st = NULL;
1543 for (j = 0; j < vs->nb_streams; j++) {
1545 vid_st = vs->streams[j];
1546 else if (vs->streams[j]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
1547 aud_st = vs->streams[j];
1548 }
1549
1550 if (!vid_st && !aud_st) {
1551 av_log(s, AV_LOG_WARNING, "Media stream not found\n");
1552 continue;
1553 }
1554
1555 /**
1556 * Traverse through the list of audio only rendition streams and find
1557 * the rendition which has highest bitrate in the same audio group
1558 */
1559 if (vs->agroup) {
1560 for (j = 0; j < hls->nb_varstreams; j++) {
1561 temp_vs = &(hls->var_streams[j]);
1562 if (!temp_vs->has_video && !temp_vs->has_subtitle &&
1563 temp_vs->agroup &&
1564 !av_strcasecmp(temp_vs->agroup, vs->agroup)) {
1565 if (!aud_st)
1566 aud_st = temp_vs->streams[0];
1567 if (temp_vs->streams[0]->codecpar->bit_rate >
1568 aud_st->codecpar->bit_rate)
1569 aud_st = temp_vs->streams[0];
1570 }
1571 }
1572 }
1573
1574 if (final) {
1575 bandwidth = vs->max_bitrate;
1576 avg_bandwidth = vs->avg_bitrate;
1577 } else {
1578 bandwidth = 0;
1579 avg_bandwidth = 0;
1580 if (vid_st)
1581 bandwidth += get_stream_bit_rate(vid_st);
1582 if (aud_st)
1583 bandwidth += get_stream_bit_rate(aud_st);
1584 bandwidth += bandwidth / 10;
1585 }
1586
1587 ccgroup = NULL;
1588 if (vid_st && vs->ccgroup) {
1589 /* check if this group name is available in the cc map string */
1590 for (j = 0; j < hls->nb_ccstreams; j++) {
1591 ccs = &(hls->cc_streams[j]);
1592 if (!av_strcasecmp(ccs->ccgroup, vs->ccgroup)) {
1593 ccgroup = vs->ccgroup;
1594 break;
1595 }
1596 }
1597 if (j == hls->nb_ccstreams)
1598 av_log(s, AV_LOG_WARNING, "mapping ccgroup %s not found\n",
1599 vs->ccgroup);
1600 }
1601
1602 if (vid_st && vs->sgroup) {
1603 sgroup = vs->sgroup;
1604 vtt_m3u8_rel_name = get_relative_url(hls->master_m3u8_url, vs->vtt_m3u8_name);
1605 if (!vtt_m3u8_rel_name) {
1606 av_log(s, AV_LOG_WARNING, "Unable to find relative subtitle URL\n");
1607 break;
1608 }
1609
1610 ff_hls_write_subtitle_rendition(hls->m3u8_out, sgroup, vtt_m3u8_rel_name, vs->language,
1611 vs->subtitle_varname, i, hls->has_default_key ? vs->is_default : 1);
1612 }
1613
1614 if (!hls->has_default_key || !hls->has_video_m3u8) {
1615 ff_hls_write_stream_info(vid_st, hls->m3u8_out, bandwidth, avg_bandwidth, m3u8_rel_name,
1616 aud_st ? vs->agroup : NULL, vs->codec_attr, ccgroup, sgroup);
1617 } else {
1618 if (vid_st) {
1619 ff_hls_write_stream_info(vid_st, hls->m3u8_out, bandwidth, avg_bandwidth, m3u8_rel_name,
1620 aud_st ? vs->agroup : NULL, vs->codec_attr, ccgroup, sgroup);
1621 }
1622 }
1623 }
1624fail:
1625 if (ret >=0)
1626 hls->master_m3u8_created = 1;
1627 hlsenc_io_close(s, &hls->m3u8_out, temp_filename);
1628 if (use_temp_file)
1629 ff_rename(temp_filename, hls->master_m3u8_url, s);
1630
1631 return ret;
1632}
1633
1634static int hls_window(AVFormatContext *s, int last, VariantStream *vs)
1635{
1636 HLSContext *hls = s->priv_data;
1637 HLSSegment *en;
1638 int target_duration = 0;
1639 int ret = 0;
1640 char temp_filename[MAX_URL_SIZE];
1641 char temp_vtt_filename[MAX_URL_SIZE];
1643 const char *proto = avio_find_protocol_name(vs->m3u8_name);
1644 int is_file_proto = proto && !strcmp(proto, "file");
1645 int use_temp_file = is_file_proto && ((hls->flags & HLS_TEMP_FILE) || !(hls->pl_type == PLAYLIST_TYPE_VOD));
1646 static unsigned warned_non_file;
1647 const char *key_uri = NULL;
1648 char *iv_string = NULL;
1650 double prog_date_time = vs->initial_prog_date_time;
1651 double *prog_date_time_p = (hls->flags & HLS_PROGRAM_DATE_TIME) ? &prog_date_time : NULL;
1652 int byterange_mode = (hls->flags & HLS_SINGLE_FILE) || (hls->max_seg_size > 0);
1653 int write_discontinuity_sequence = (hls->flags & HLS_APPEND_LIST) || (hls->flags & HLS_DISCONT_START) || vs->discontinuity_sequence_set;
1654 int discont_start_written = 0;
1655
1656 hls->version = 2;
1657 if (!(hls->flags & HLS_ROUND_DURATIONS)) {
1658 hls->version = 3;
1659 }
1660
1661 if (byterange_mode) {
1662 hls->version = 4;
1663 sequence = 0;
1664 }
1665
1666 if (hls->flags & HLS_I_FRAMES_ONLY) {
1667 hls->version = 4;
1668 }
1669
1670 if (hls->flags & HLS_INDEPENDENT_SEGMENTS) {
1671 hls->version = 6;
1672 }
1673
1674 if (hls->segment_type == SEGMENT_TYPE_FMP4) {
1675 hls->version = 7;
1676 }
1677
1678 if (!is_file_proto && (hls->flags & HLS_TEMP_FILE) && !warned_non_file++)
1679 av_log(s, AV_LOG_ERROR, "Cannot use rename on non file protocol, this may lead to races and temporary partial files\n");
1680
1681 set_http_options(s, &options, hls);
1682 snprintf(temp_filename, sizeof(temp_filename), use_temp_file ? "%s.tmp" : "%s", vs->m3u8_name);
1683 ret = hlsenc_io_open(s, byterange_mode ? &hls->m3u8_out : &vs->out, temp_filename, &options);
1685 if (ret < 0) {
1686 goto fail;
1687 }
1688
1689 for (en = vs->segments; en; en = en->next) {
1690 if (target_duration <= en->duration)
1691 target_duration = lrint(en->duration);
1692 }
1693
1694 vs->discontinuity_set = 0;
1695 ff_hls_write_playlist_header(byterange_mode ? hls->m3u8_out : vs->out, hls->version, hls->allowcache,
1696 target_duration, sequence, hls->pl_type, hls->flags & HLS_I_FRAMES_ONLY);
1697
1698 if (write_discontinuity_sequence) {
1700 }
1701
1702 if ((hls->flags & HLS_DISCONT_START) && sequence==hls->start_sequence && vs->discontinuity_set==0) {
1703 avio_printf(byterange_mode ? hls->m3u8_out : vs->out, "#EXT-X-DISCONTINUITY\n");
1704 vs->discontinuity_set = 1;
1706
1707 discont_start_written = 1;
1708 }
1709 if (vs->has_video && (hls->flags & HLS_INDEPENDENT_SEGMENTS)) {
1710 avio_printf(byterange_mode ? hls->m3u8_out : vs->out, "#EXT-X-INDEPENDENT-SEGMENTS\n");
1711 }
1712 for (en = vs->segments; en; en = en->next) {
1713 if ((hls->encrypt || hls->key_info_file) && (!key_uri || strcmp(en->key_uri, key_uri) ||
1714 av_strcasecmp(en->iv_string, iv_string))) {
1715 avio_printf(byterange_mode ? hls->m3u8_out : vs->out, "#EXT-X-KEY:METHOD=AES-128,URI=\"%s\"", en->key_uri);
1716 if (*en->iv_string)
1717 avio_printf(byterange_mode ? hls->m3u8_out : vs->out, ",IV=0x%s", en->iv_string);
1718 avio_printf(byterange_mode ? hls->m3u8_out : vs->out, "\n");
1719 key_uri = en->key_uri;
1720 iv_string = en->iv_string;
1721 }
1722
1723 if ((hls->segment_type == SEGMENT_TYPE_FMP4) && (en == vs->segments)) {
1724 ff_hls_write_init_file(byterange_mode ? hls->m3u8_out : vs->out, (hls->flags & HLS_SINGLE_FILE) ? en->filename : vs->fmp4_init_filename,
1725 hls->flags & HLS_SINGLE_FILE, vs->init_range_length, 0);
1726 }
1727
1728 ret = ff_hls_write_file_entry(byterange_mode ? hls->m3u8_out : vs->out, en->discont, byterange_mode,
1730 en->size, en->pos, hls->baseurl,
1731 en->filename,
1732 en->discont_program_date_time ? &en->discont_program_date_time : prog_date_time_p,
1733 hls->flags & HLS_I_FRAMES_ONLY);
1736 if (ret < 0) {
1737 av_log(s, AV_LOG_WARNING, "ff_hls_write_file_entry get error\n");
1738 }
1739 }
1740
1741 if (last && (hls->flags & HLS_OMIT_ENDLIST)==0)
1742 ff_hls_write_end_list(byterange_mode ? hls->m3u8_out : vs->out);
1743
1744 if (vs->vtt_m3u8_name) {
1745 set_http_options(vs->vtt_avf, &options, hls);
1746 snprintf(temp_vtt_filename, sizeof(temp_vtt_filename), use_temp_file ? "%s.tmp" : "%s", vs->vtt_m3u8_name);
1747 ret = hlsenc_io_open(s, &hls->sub_m3u8_out, temp_vtt_filename, &options);
1749 if (ret < 0) {
1750 goto fail;
1751 }
1753 target_duration, sequence, PLAYLIST_TYPE_NONE, 0);
1754
1755 if (write_discontinuity_sequence) {
1758 }
1759
1760 // To sync discontinuity sequence between main and sub playlists
1761 if (write_discontinuity_sequence && discont_start_written) {
1762 avio_printf(hls->sub_m3u8_out, "#EXT-X-DISCONTINUITY\n");
1763 }
1764
1765 for (en = vs->segments; en; en = en->next) {
1766 ret = ff_hls_write_file_entry(hls->sub_m3u8_out, en->discont, byterange_mode,
1767 en->duration, 0, en->size, en->pos,
1768 hls->baseurl, en->sub_filename, NULL, 0);
1769 if (ret < 0) {
1770 av_log(s, AV_LOG_WARNING, "ff_hls_write_file_entry get error\n");
1771 }
1772 }
1773
1774 if (last && !(hls->flags & HLS_OMIT_ENDLIST))
1776
1777 }
1778
1779fail:
1781 ret = hlsenc_io_close(s, byterange_mode ? &hls->m3u8_out : &vs->out, temp_filename);
1782 if (ret < 0) {
1783 return ret;
1784 }
1786 if (use_temp_file) {
1787 ff_rename(temp_filename, vs->m3u8_name, s);
1788 if (vs->vtt_m3u8_name)
1789 ff_rename(temp_vtt_filename, vs->vtt_m3u8_name, s);
1790 }
1791 if (ret >= 0 && hls->master_pl_name)
1792 if (create_master_playlist(s, vs, last) < 0)
1793 av_log(s, AV_LOG_WARNING, "Master playlist creation failed\n");
1794
1795 return ret;
1796}
1797
1799{
1800 HLSContext *c = s->priv_data;
1801 AVFormatContext *oc = vs->avf;
1802 AVFormatContext *vtt_oc = vs->vtt_avf;
1804 const char *proto = NULL;
1805 int use_temp_file = 0;
1806 char iv_string[KEYSIZE*2 + 1];
1807 int err = 0;
1808
1809 if (c->flags & HLS_SINGLE_FILE) {
1810 char *new_name = av_strdup(vs->basename);
1811 if (!new_name)
1812 return AVERROR(ENOMEM);
1813 ff_format_set_url(oc, new_name);
1814 if (vs->vtt_basename) {
1815 new_name = av_strdup(vs->vtt_basename);
1816 if (!new_name)
1817 return AVERROR(ENOMEM);
1818 ff_format_set_url(vtt_oc, new_name);
1819 }
1820 } else if (c->max_seg_size > 0) {
1821 char *filename = NULL;
1822 if (replace_int_data_in_filename(&filename,
1823 vs->basename, 'd', vs->sequence) < 1) {
1824 av_freep(&filename);
1825 av_log(oc, AV_LOG_ERROR, "Invalid segment filename template '%s', you can try to use -strftime 1 with it\n", vs->basename);
1826 return AVERROR(EINVAL);
1827 }
1828 ff_format_set_url(oc, filename);
1829 } else {
1830 if (c->use_localtime) {
1831 int r;
1832 char *expanded = NULL;
1833
1834 r = strftime_expand(vs->basename, &expanded);
1835 if (r < 0) {
1836 av_log(oc, AV_LOG_ERROR, "Could not get segment filename with strftime\n");
1837 return r;
1838 }
1839 ff_format_set_url(oc, expanded);
1840
1841 err = sls_flag_use_localtime_filename(oc, c, vs);
1842 if (err < 0) {
1843 return AVERROR(ENOMEM);
1844 }
1845
1846 if (c->use_localtime_mkdir) {
1847 const char *dir;
1848 char *fn_copy = av_strdup(oc->url);
1849 if (!fn_copy)
1850 return AVERROR(ENOMEM);
1851 dir = av_dirname(fn_copy);
1852 if (ff_mkdir_p(dir) == -1 && errno != EEXIST) {
1853 av_log(oc, AV_LOG_ERROR, "Could not create directory %s with use_localtime_mkdir\n", dir);
1854 av_freep(&fn_copy);
1855 return AVERROR(errno);
1856 }
1857 av_freep(&fn_copy);
1858 }
1859 } else {
1860 char *filename = NULL;
1861 if (replace_int_data_in_filename(&filename,
1862 vs->basename, 'd', vs->sequence) < 1) {
1863 av_freep(&filename);
1864 av_log(oc, AV_LOG_ERROR, "Invalid segment filename template '%s' you can try to use -strftime 1 with it\n", vs->basename);
1865 return AVERROR(EINVAL);
1866 }
1867 ff_format_set_url(oc, filename);
1868 }
1869 if (vs->vtt_basename) {
1870 char *filename = NULL;
1871 if (replace_int_data_in_filename(&filename,
1872 vs->vtt_basename, 'd', vs->sequence) < 1) {
1873 av_freep(&filename);
1874 av_log(vtt_oc, AV_LOG_ERROR, "Invalid segment filename template '%s'\n", vs->vtt_basename);
1875 return AVERROR(EINVAL);
1876 }
1877 ff_format_set_url(vtt_oc, filename);
1878 }
1879 }
1880
1881 proto = avio_find_protocol_name(oc->url);
1882 use_temp_file = proto && !strcmp(proto, "file") && (c->flags & HLS_TEMP_FILE);
1883
1884 if (use_temp_file) {
1885 char *new_name = av_asprintf("%s.tmp", oc->url);
1886 if (!new_name)
1887 return AVERROR(ENOMEM);
1888 ff_format_set_url(oc, new_name);
1889 }
1890
1891 if (c->key_info_file || c->encrypt) {
1892 if (c->segment_type == SEGMENT_TYPE_FMP4) {
1893 av_log(s, AV_LOG_ERROR, "Encrypted fmp4 not yet supported\n");
1894 return AVERROR_PATCHWELCOME;
1895 }
1896
1897 if (c->key_info_file && c->encrypt) {
1898 av_log(s, AV_LOG_WARNING, "Cannot use both -hls_key_info_file and -hls_enc,"
1899 " ignoring -hls_enc\n");
1900 }
1901
1902 if (!vs->encrypt_started || (c->flags & HLS_PERIODIC_REKEY)) {
1903 if (c->key_info_file) {
1904 if ((err = hls_encryption_start(s, vs)) < 0)
1905 goto fail;
1906 } else {
1907 if (!c->encrypt_started) {
1908 if ((err = do_encrypt(s, vs)) < 0)
1909 goto fail;
1910 c->encrypt_started = 1;
1911 }
1912 av_strlcpy(vs->key_uri, c->key_uri, sizeof(vs->key_uri));
1913 av_strlcpy(vs->key_string, c->key_string, sizeof(vs->key_string));
1914 av_strlcpy(vs->iv_string, c->iv_string, sizeof(vs->iv_string));
1915 }
1916 vs->encrypt_started = 1;
1917 }
1918 err = av_strlcpy(iv_string, vs->iv_string, sizeof(iv_string));
1919 if (!err) {
1920 snprintf(iv_string, sizeof(iv_string), "%032"PRIx64, vs->sequence);
1921 memset(vs->iv_string, 0, sizeof(vs->iv_string));
1922 memcpy(vs->iv_string, iv_string, sizeof(iv_string));
1923 }
1924 }
1925 if (c->segment_type != SEGMENT_TYPE_FMP4) {
1926 if (oc->oformat->priv_class && oc->priv_data) {
1927 av_opt_set(oc->priv_data, "mpegts_flags", "resend_headers", 0);
1928 }
1929 if (c->flags & HLS_SINGLE_FILE) {
1930 if (c->key_info_file || c->encrypt) {
1931 av_dict_set(&options, "encryption_key", vs->key_string, 0);
1932 av_dict_set(&options, "encryption_iv", vs->iv_string, 0);
1933
1934 /* Write temp file with cryption content */
1935 av_freep(&vs->basename_tmp);
1936 vs->basename_tmp = av_asprintf("crypto:%s.tmp", oc->url);
1937
1938 /* append temp file content into single file */
1939 av_freep(&vs->basename);
1940 vs->basename = av_asprintf("%s", oc->url);
1941 } else {
1942 vs->basename_tmp = vs->basename;
1943 }
1945 if (!vs->out_single_file)
1946 if ((err = hlsenc_io_open(s, &vs->out_single_file, vs->basename, &options)) < 0) {
1947 if (c->ignore_io_errors)
1948 err = 0;
1949 goto fail;
1950 }
1951
1952 if ((err = hlsenc_io_open(s, &vs->out, vs->basename_tmp, &options)) < 0) {
1953 if (c->ignore_io_errors)
1954 err = 0;
1955 goto fail;
1956 }
1957
1958 }
1959 }
1960 if (vs->vtt_basename) {
1962 if ((err = hlsenc_io_open(s, &vtt_oc->pb, vtt_oc->url, &options)) < 0) {
1963 if (c->ignore_io_errors)
1964 err = 0;
1965 goto fail;
1966 }
1967 }
1969
1970 if (vs->vtt_basename) {
1971 err = avformat_write_header(vtt_oc,NULL);
1972 if (err < 0)
1973 return err;
1974 }
1975
1976 return 0;
1977fail:
1979
1980 return err;
1981}
1982
1984{
1985 HLSContext *hls = s->priv_data;
1986#if HAVE_LIBC_MSVCRT
1987 // no %s support on MSVC, which invokes the invalid parameter handler
1988 // on unsupported format strings, instead of returning an error
1989 int strftime_s_supported = 0;
1990#else
1991 char b[21];
1992 time_t t = time(NULL);
1993 struct tm tmbuf, *p = localtime_r(&t, &tmbuf);
1994 // no %s support when strftime returned error or left format string unchanged
1995 int strftime_s_supported = strftime(b, sizeof(b), "%s", p) && strcmp(b, "%s");
1996#endif
1997
1998 if (hls->segment_type == SEGMENT_TYPE_FMP4) {
1999 return strftime_s_supported ? "-%s.m4s" : "-%Y%m%d%H%M%S.m4s";
2000 }
2001 return strftime_s_supported ? "-%s.ts" : "-%Y%m%d%H%M%S.ts";
2002}
2003
2004static int append_postfix(char *name, int name_buf_len, int i)
2005{
2006 char *p;
2007 char extension[10] = {'\0'};
2008
2009 p = strrchr(name, '.');
2010 if (p) {
2011 av_strlcpy(extension, p, sizeof(extension));
2012 *p = '\0';
2013 }
2014
2015 snprintf(name + strlen(name), name_buf_len - strlen(name), POSTFIX_PATTERN, i);
2016
2017 if (strlen(extension))
2018 av_strlcat(name, extension, name_buf_len);
2019
2020 return 0;
2021}
2022
2023static int validate_name(int nb_vs, const char *fn)
2024{
2025 const char *filename, *subdir_name;
2026 char *fn_dup = NULL;
2027 int ret = 0;
2028
2029 if (!fn)
2030 return AVERROR(EINVAL);
2031
2032 fn_dup = av_strdup(fn);
2033 if (!fn_dup)
2034 return AVERROR(ENOMEM);
2035 filename = av_basename(fn);
2036 subdir_name = av_dirname(fn_dup);
2037
2038 if (nb_vs > 1 && !av_stristr(filename, "%v") && !av_stristr(subdir_name, "%v")) {
2039 av_log(NULL, AV_LOG_ERROR, "More than 1 variant streams are present, %%v is expected "
2040 "either in the filename or in the sub-directory name of file %s\n", fn);
2041 ret = AVERROR(EINVAL);
2042 goto fail;
2043 }
2044
2045 if (av_stristr(filename, "%v") && av_stristr(subdir_name, "%v")) {
2046 av_log(NULL, AV_LOG_ERROR, "%%v is expected either in the filename or "
2047 "in the sub-directory name of file %s, but only in one of them\n", fn);
2048 ret = AVERROR(EINVAL);
2049 goto fail;
2050 }
2051
2052fail:
2053 av_freep(&fn_dup);
2054 return ret;
2055}
2056
2057static int format_name(const char *buf, char **s, int index, const char *varname)
2058{
2059 const char *proto, *dir;
2060 char *orig_buf_dup = NULL, *mod_buf_dup = NULL;
2061 int ret = 0;
2062
2063 orig_buf_dup = av_strdup(buf);
2064 if (!orig_buf_dup)
2065 return AVERROR(ENOMEM);
2066
2067 if (!av_stristr(buf, "%v")) {
2068 *s = orig_buf_dup;
2069 return 0;
2070 }
2071
2072 if (!varname) {
2073 if (replace_int_data_in_filename(s, orig_buf_dup, 'v', index) < 1) {
2074 ret = AVERROR(EINVAL);
2075 goto fail;
2076 }
2077 } else {
2078 if (replace_str_data_in_filename(s, orig_buf_dup, 'v', varname) < 1) {
2079 ret = AVERROR(EINVAL);
2080 goto fail;
2081 }
2082 }
2083
2084 proto = avio_find_protocol_name(orig_buf_dup);
2085 dir = av_dirname(orig_buf_dup);
2086
2087 /* if %v is present in the file's directory, create sub-directory */
2088 if (av_stristr(dir, "%v") && proto && !strcmp(proto, "file")) {
2089 mod_buf_dup = av_strdup(*s);
2090 dir = av_dirname(mod_buf_dup);
2091 if (ff_mkdir_p(dir) == -1 && errno != EEXIST) {
2092 ret = AVERROR(errno);
2093 goto fail;
2094 }
2095 }
2096
2097fail:
2098 av_freep(&orig_buf_dup);
2099 av_freep(&mod_buf_dup);
2100 return ret;
2101}
2102
2103static int hls_append_segment_pattern(const char *url, const char *pattern,
2104 char **filename)
2105{
2106 URLComponents uc;
2107 const char *name = url;
2108 const char *proto;
2109 const char *extension = NULL;
2110 const char *path_end;
2111 const char *path;
2112 const char *p;
2113 int add_slash = 0;
2114 int is_file;
2115 int ret;
2116
2117 /* Classify the underlying protocol before applying URL syntax. */
2118 while (av_strstart(name, "crypto:", &name) ||
2119 av_strstart(name, "crypto+", &name))
2120 ;
2122 is_file = (proto && !strcmp(proto, "file")) || is_dos_path(name) ||
2123 av_strstart(name, "file:", NULL);
2124 if (!is_file) {
2125 ret = ff_url_decompose(&uc, name, NULL);
2126 if (ret < 0)
2127 return ret;
2128 is_file = !URL_COMPONENT_HAVE(uc, scheme);
2129 }
2130
2131 path_end = url + strlen(url);
2132 if (is_file) {
2133 /* Preserve file naming, including literal '?' and '#' characters. */
2134 extension = strrchr(url, '.');
2135 } else {
2136 path = uc.path;
2137 path_end = uc.url_component_end_path;
2138 add_slash = path == path_end && URL_COMPONENT_HAVE(uc, authority);
2139 for (p = path_end; p > path; p--)
2140 if (p[-1] == '/' || (HAVE_DOS_PATHS && p[-1] == '\\'))
2141 break;
2142 path = p;
2143
2144 for (p = path; p < path_end; p++)
2145 if (*p == '.')
2146 extension = p;
2147 }
2148
2149 if (!extension)
2150 extension = path_end;
2151
2152 *filename = av_asprintf("%.*s%s%s%s", (int)(extension - url), url,
2153 add_slash ? "/" : "", pattern, path_end);
2154 return *filename ? 0 : AVERROR(ENOMEM);
2155}
2156
2159 int64_t stream_id)
2160{
2161 unsigned int stream_index, cnt;
2162 if (stream_id < 0 || stream_id > s->nb_streams - 1)
2163 return -1;
2164 cnt = 0;
2165 for (stream_index = 0; stream_index < s->nb_streams; stream_index++) {
2166 if (s->streams[stream_index]->codecpar->codec_type != codec_type)
2167 continue;
2168 if (cnt == stream_id)
2169 return stream_index;
2170 cnt++;
2171 }
2172 return -1;
2173}
2174
2176{
2177 HLSContext *hls = s->priv_data;
2178 VariantStream *vs;
2179 int stream_index, i, j;
2181 int nb_varstreams = 0, nb_streams;
2182 char *p, *q, *saveptr1, *saveptr2, *varstr, *keyval;
2183 const char *val;
2184
2185 /**
2186 * Expected format for var_stream_map string is as below:
2187 * "a:0,v:0 a:1,v:1"
2188 * "a:0,agroup:a0,default:1,language:ENG a:1,agroup:a1,default:0 v:0,agroup:a0 v:1,agroup:a1"
2189 * This string specifies how to group the audio, video and subtitle streams
2190 * into different variant streams. The variant stream groups are separated
2191 * by space.
2192 *
2193 * a:, v:, s: are keys to specify audio, video and subtitle streams
2194 * respectively. Allowed values are 0 to 9 digits (limited just based on
2195 * practical usage)
2196 *
2197 * agroup: is key to specify audio group. A string can be given as value.
2198 * sgroup: is key to specify subtitle group. A string can be given as value.
2199 */
2200 p = av_strdup(hls->var_stream_map);
2201 if (!p)
2202 return AVERROR(ENOMEM);
2203
2204 q = p;
2205 while (av_strtok(q, " \t", &saveptr1)) {
2206 q = NULL;
2207 nb_varstreams++;
2208 }
2209 av_freep(&p);
2210
2211 hls->var_streams = av_mallocz(sizeof(*hls->var_streams) * nb_varstreams);
2212 if (!hls->var_streams)
2213 return AVERROR(ENOMEM);
2214 hls->nb_varstreams = nb_varstreams;
2215
2216 p = hls->var_stream_map;
2217 nb_varstreams = 0;
2218 while (varstr = av_strtok(p, " \t", &saveptr1)) {
2219 p = NULL;
2220
2221 if (nb_varstreams < hls->nb_varstreams) {
2222 vs = &(hls->var_streams[nb_varstreams]);
2223 vs->var_stream_idx = nb_varstreams;
2224 vs->is_default = 0;
2225 nb_varstreams++;
2226 } else
2227 return AVERROR(EINVAL);
2228
2229 q = varstr;
2230 while (1) {
2231 if (!av_strncasecmp(q, "a:", 2) || !av_strncasecmp(q, "v:", 2) ||
2232 !av_strncasecmp(q, "s:", 2))
2233 vs->nb_streams++;
2234 q = strchr(q, ',');
2235 if (!q)
2236 break;
2237 q++;
2238 }
2239 vs->streams = av_mallocz(sizeof(AVStream *) * vs->nb_streams);
2240 if (!vs->streams)
2241 return AVERROR(ENOMEM);
2242
2243 nb_streams = 0;
2244 while (keyval = av_strtok(varstr, ",", &saveptr2)) {
2245 int64_t num;
2246 char *end;
2247 varstr = NULL;
2248 if (av_strstart(keyval, "language:", &val)) {
2249 vs->language = val;
2250 continue;
2251 } else if (av_strstart(keyval, "default:", &val)) {
2252 vs->is_default = (!av_strncasecmp(val, "YES", strlen("YES")) ||
2253 (!av_strncasecmp(val, "1", strlen("1"))));
2254 hls->has_default_key = 1;
2255 continue;
2256 } else if (av_strstart(keyval, "name:", &val)) {
2257 vs->varname = val;
2258 continue;
2259 } else if (av_strstart(keyval, "sname:", &val)) {
2260 vs->subtitle_varname = val;
2261 continue;
2262 } else if (av_strstart(keyval, "agroup:", &val)) {
2263 vs->agroup = val;
2264 continue;
2265 } else if (av_strstart(keyval, "sgroup:", &val)) {
2266 vs->sgroup = val;
2267 continue;
2268 } else if (av_strstart(keyval, "ccgroup:", &val)) {
2269 vs->ccgroup = val;
2270 continue;
2271 } else if (av_strstart(keyval, "v:", &val)) {
2273 hls->has_video_m3u8 = 1;
2274 } else if (av_strstart(keyval, "a:", &val)) {
2276 } else if (av_strstart(keyval, "s:", &val)) {
2278 } else {
2279 av_log(s, AV_LOG_ERROR, "Invalid keyval %s\n", keyval);
2280 return AVERROR(EINVAL);
2281 }
2282
2283 num = strtoll(val, &end, 10);
2284 if (!av_isdigit(*val) || *end != '\0') {
2285 av_log(s, AV_LOG_ERROR, "Invalid stream number: '%s'\n", val);
2286 return AVERROR(EINVAL);
2287 }
2288 stream_index = get_nth_codec_stream_index(s, codec_type, num);
2289
2290 if (stream_index >= 0 && nb_streams < vs->nb_streams) {
2291 for (i = 0; nb_streams > 0 && i < nb_streams; i++) {
2292 if (vs->streams[i] == s->streams[stream_index]) {
2293 av_log(s, AV_LOG_ERROR, "Same elementary stream found more than once inside "
2294 "variant definition #%d\n", nb_varstreams - 1);
2295 return AVERROR(EINVAL);
2296 }
2297 }
2298 for (j = 0; nb_varstreams > 1 && j < nb_varstreams - 1; j++) {
2299 for (i = 0; i < hls->var_streams[j].nb_streams; i++) {
2300 if (hls->var_streams[j].streams[i] == s->streams[stream_index]) {
2301 av_log(s, AV_LOG_ERROR, "Same elementary stream found more than once "
2302 "in two different variant definitions #%d and #%d\n",
2303 j, nb_varstreams - 1);
2304 return AVERROR(EINVAL);
2305 }
2306 }
2307 }
2308 vs->streams[nb_streams++] = s->streams[stream_index];
2309 } else {
2310 av_log(s, AV_LOG_ERROR, "Unable to map stream at %s\n", keyval);
2311 return AVERROR(EINVAL);
2312 }
2313 }
2314 }
2315 av_log(s, AV_LOG_DEBUG, "Number of variant streams %d\n",
2316 hls->nb_varstreams);
2317
2318 return 0;
2319}
2320
2322{
2323 HLSContext *hls = s->priv_data;
2324 int nb_ccstreams = 0;
2325 char *p, *q, *ccstr, *keyval;
2326 char *saveptr1 = NULL, *saveptr2 = NULL;
2327 const char *val;
2329
2330 p = av_strdup(hls->cc_stream_map);
2331 if(!p)
2332 return AVERROR(ENOMEM);
2333
2334 q = p;
2335 while (av_strtok(q, " \t", &saveptr1)) {
2336 q = NULL;
2337 nb_ccstreams++;
2338 }
2339 av_freep(&p);
2340
2341 hls->cc_streams = av_mallocz(sizeof(*hls->cc_streams) * nb_ccstreams);
2342 if (!hls->cc_streams)
2343 return AVERROR(ENOMEM);
2344 hls->nb_ccstreams = nb_ccstreams;
2345
2346 p = hls->cc_stream_map;
2347 nb_ccstreams = 0;
2348 while (ccstr = av_strtok(p, " \t", &saveptr1)) {
2349 p = NULL;
2350
2351 if (nb_ccstreams < hls->nb_ccstreams)
2352 ccs = &(hls->cc_streams[nb_ccstreams++]);
2353 else
2354 return AVERROR(EINVAL);
2355
2356 while (keyval = av_strtok(ccstr, ",", &saveptr2)) {
2357 ccstr = NULL;
2358
2359 if (av_strstart(keyval, "ccgroup:", &val)) {
2360 ccs->ccgroup = val;
2361 } else if (av_strstart(keyval, "instreamid:", &val)) {
2362 ccs->instreamid = val;
2363 } else if (av_strstart(keyval, "language:", &val)) {
2364 ccs->language = val;
2365 } else {
2366 av_log(s, AV_LOG_ERROR, "Invalid keyval %s\n", keyval);
2367 return AVERROR(EINVAL);
2368 }
2369 }
2370
2371 if (!ccs->ccgroup || !ccs->instreamid) {
2372 av_log(s, AV_LOG_ERROR, "Insufficient parameters in cc stream map string\n");
2373 return AVERROR(EINVAL);
2374 }
2375
2376 if (av_strstart(ccs->instreamid, "CC", &val)) {
2377 if (atoi(val) < 1 || atoi(val) > 4) {
2378 av_log(s, AV_LOG_ERROR, "Invalid instream ID CC index %d in %s, range 1-4\n",
2379 atoi(val), ccs->instreamid);
2380 return AVERROR(EINVAL);
2381 }
2382 } else if (av_strstart(ccs->instreamid, "SERVICE", &val)) {
2383 if (atoi(val) < 1 || atoi(val) > 63) {
2384 av_log(s, AV_LOG_ERROR, "Invalid instream ID SERVICE index %d in %s, range 1-63 \n",
2385 atoi(val), ccs->instreamid);
2386 return AVERROR(EINVAL);
2387 }
2388 } else {
2389 av_log(s, AV_LOG_ERROR, "Invalid instream ID %s, supported are CCn or SERVICEn\n",
2390 ccs->instreamid);
2391 return AVERROR(EINVAL);
2392 }
2393 }
2394
2395 return 0;
2396}
2397
2399{
2400 HLSContext *hls = s->priv_data;
2401 unsigned int i;
2402 int ret = 0;
2403
2404 if (hls->cc_stream_map) {
2406 if (ret < 0)
2407 return ret;
2408 }
2409
2410 if (hls->var_stream_map) {
2412 } else {
2413 //By default, a single variant stream with all the codec streams is created
2414 hls->var_streams = av_mallocz(sizeof(*hls->var_streams));
2415 if (!hls->var_streams)
2416 return AVERROR(ENOMEM);
2417 hls->nb_varstreams = 1;
2418
2419 hls->var_streams[0].var_stream_idx = 0;
2420 hls->var_streams[0].nb_streams = s->nb_streams;
2421 hls->var_streams[0].streams = av_mallocz(sizeof(AVStream *) *
2422 hls->var_streams[0].nb_streams);
2423 if (!hls->var_streams[0].streams)
2424 return AVERROR(ENOMEM);
2425
2426 //by default, the first available ccgroup is mapped to the variant stream
2427 if (hls->nb_ccstreams)
2428 hls->var_streams[0].ccgroup = hls->cc_streams[0].ccgroup;
2429
2430 for (i = 0; i < s->nb_streams; i++)
2431 hls->var_streams[0].streams[i] = s->streams[i];
2432 }
2433 return 0;
2434}
2435
2437{
2438 HLSContext *hls = s->priv_data;
2439 const char *dir;
2440 char *fn1= NULL, *fn2 = NULL;
2441 int ret = 0;
2442
2443 fn1 = av_strdup(s->url);
2444 if (!fn1)
2445 return AVERROR(ENOMEM);
2446 dir = av_dirname(fn1);
2447
2448 /**
2449 * if output file's directory has %v, variants are created in sub-directories
2450 * then master is created at the sub-directories level
2451 */
2452 if (dir && av_stristr(av_basename(dir), "%v")) {
2453 fn2 = av_strdup(dir);
2454 if (!fn2) {
2455 ret = AVERROR(ENOMEM);
2456 goto fail;
2457 }
2458 dir = av_dirname(fn2);
2459 }
2460
2461 if (dir && strcmp(dir, "."))
2463 else
2465
2466 if (!hls->master_m3u8_url) {
2467 ret = AVERROR(ENOMEM);
2468 goto fail;
2469 }
2470
2471fail:
2472 av_freep(&fn1);
2473 av_freep(&fn2);
2474
2475 return ret;
2476}
2477
2479{
2480 HLSContext *hls = s->priv_data;
2481 int ret, i, j;
2482 VariantStream *vs = NULL;
2483
2484 for (i = 0; i < hls->nb_varstreams; i++) {
2485 int subtitle_streams = 0;
2486 vs = &hls->var_streams[i];
2487
2489 if (ret < 0)
2490 return ret;
2491 //av_assert0(s->nb_streams == hls->avf->nb_streams);
2492 for (j = 0; j < vs->nb_streams; j++) {
2493 AVStream *inner_st;
2494 AVStream *outer_st = vs->streams[j];
2495
2496 if (hls->max_seg_size > 0) {
2497 if ((outer_st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) &&
2498 (outer_st->codecpar->bit_rate > hls->max_seg_size)) {
2499 av_log(s, AV_LOG_WARNING, "Your video bitrate is bigger than hls_segment_size, "
2500 "(%"PRId64 " > %"PRId64 "), the result maybe not be what you want.",
2501 outer_st->codecpar->bit_rate, hls->max_seg_size);
2502 }
2503 }
2504
2505 if (outer_st->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE)
2506 inner_st = vs->avf->streams[j - subtitle_streams];
2507 else if (vs->vtt_avf) {
2508 inner_st = vs->vtt_avf->streams[0];
2509 subtitle_streams++;
2510 } else {
2511 /* We have a subtitle stream, when the user does not want one */
2512 inner_st = NULL;
2513 continue;
2514 }
2515 avpriv_set_pts_info(outer_st, inner_st->pts_wrap_bits, inner_st->time_base.num, inner_st->time_base.den);
2516 if (outer_st->codecpar->codec_id == AV_CODEC_ID_HEVC &&
2517 outer_st->codecpar->codec_tag != MKTAG('h','v','c','1') &&
2518 outer_st->codecpar->codec_tag != MKTAG('h','e','v','1')) {
2519 av_log(s, AV_LOG_WARNING, "Stream HEVC is not hvc1 or hev1, you should use tag:v hvc1 to set it.\n");
2520 }
2521 write_codec_attr(outer_st, vs);
2522
2523 }
2524 /* Update the Codec Attr string for the mapped audio groups */
2525 if (vs->has_video && vs->agroup) {
2526 for (j = 0; j < hls->nb_varstreams; j++) {
2527 VariantStream *vs_agroup = &(hls->var_streams[j]);
2528 if (!vs_agroup->has_video && !vs_agroup->has_subtitle &&
2529 vs_agroup->agroup &&
2530 !av_strcasecmp(vs_agroup->agroup, vs->agroup)) {
2531 write_codec_attr(vs_agroup->streams[0], vs);
2532 }
2533 }
2534 }
2535 }
2536
2537 return 0;
2538}
2539
2541{
2542 HLSContext *hls = s->priv_data;
2544 int ret = 0;
2545
2546 set_http_options(s, &options, hls);
2549 if (ret < 0)
2550 return ret;
2553
2554 return ret;
2555}
2556
2558{
2559 int64_t ret = 0;
2560 int64_t read_byte = 0;
2561 int64_t total_size = 0;
2562 char *filename = NULL;
2563 char buf[BUFSIZE];
2564 AVFormatContext *oc = vs->avf;
2565
2566 hlsenc_io_close(s, &vs->out, vs->basename_tmp);
2567 filename = av_asprintf("%s.tmp", oc->url);
2568 ret = s->io_open(s, &vs->out, filename, AVIO_FLAG_READ, NULL);
2569 if (ret < 0) {
2570 av_free(filename);
2571 return ret;
2572 }
2573
2574 do {
2575 read_byte = avio_read(vs->out, buf, BUFSIZE);
2576 if (read_byte > 0) {
2577 avio_write(vs->out_single_file, buf, read_byte);
2578 total_size += read_byte;
2579 ret = total_size;
2580 }
2581 } while (read_byte > 0);
2582
2583 hlsenc_io_close(s, &vs->out, filename);
2584 av_free(filename);
2585
2586 return ret;
2587}
2589{
2590 HLSContext *hls = s->priv_data;
2591 AVFormatContext *oc = NULL;
2592 AVStream *st = s->streams[pkt->stream_index];
2593 int64_t end_pts = 0;
2594 int is_ref_pkt = 1;
2595 int ret = 0, can_split = 1, i, j;
2596 int stream_index = 0;
2597 int range_length = 0;
2598 const char *proto = NULL;
2599 int use_temp_file = 0;
2600 VariantStream *vs = NULL;
2601 char *old_filename = NULL;
2602
2603 for (i = 0; i < hls->nb_varstreams; i++) {
2604 int subtitle_streams = 0;
2605 vs = &hls->var_streams[i];
2606 for (j = 0; j < vs->nb_streams; j++) {
2608 subtitle_streams++;
2609 }
2610 if (vs->streams[j] == st) {
2612 oc = vs->vtt_avf;
2613 stream_index = 0;
2614 } else {
2615 oc = vs->avf;
2616 stream_index = j - subtitle_streams;
2617 }
2618 break;
2619 }
2620 }
2621
2622 if (oc)
2623 break;
2624 }
2625
2626 if (!oc) {
2627 av_log(s, AV_LOG_ERROR, "Unable to find mapping variant stream\n");
2628 return AVERROR(ENOMEM);
2629 }
2630
2631 end_pts = hls->recording_time * vs->number;
2632
2633 if (vs->sequence - vs->nb_entries > hls->start_sequence && hls->init_time > 0) {
2634 /* reset end_pts, hls->recording_time at end of the init hls list */
2635 int64_t init_list_dur = hls->init_time * vs->nb_entries;
2636 int64_t after_init_list_dur = (vs->sequence - hls->start_sequence - vs->nb_entries) * hls->time;
2637 hls->recording_time = hls->time;
2638 end_pts = init_list_dur + after_init_list_dur ;
2639 }
2640
2641 if (vs->start_pts == AV_NOPTS_VALUE) {
2644 vs->start_pts_from_audio = 1;
2645 }
2647 int64_t video_start = av_rescale_q(pkt->pts, st->time_base, AV_TIME_BASE_Q);
2648 if (vs->start_pts > video_start) {
2649 vs->start_pts = video_start;
2650 vs->start_pts_from_audio = 0;
2651 }
2652 }
2653
2654 if (vs->has_video) {
2656 ((pkt->flags & AV_PKT_FLAG_KEY) || (hls->flags & HLS_SPLIT_BY_TIME));
2657 is_ref_pkt = (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) && (pkt->stream_index == vs->reference_stream_index);
2658 }
2660 is_ref_pkt = can_split = 0;
2661 if (pkt->pts == AV_NOPTS_VALUE)
2662 is_ref_pkt = can_split = 0;
2663
2664 if (is_ref_pkt) {
2665 if (vs->end_pts == AV_NOPTS_VALUE)
2666 vs->end_pts = pkt->pts;
2667 if (vs->new_start) {
2668 vs->new_start = 0;
2669 vs->duration = (double)(pkt->pts - vs->end_pts)
2670 * st->time_base.num / st->time_base.den;
2671 vs->dpp = (double)(pkt->duration) * st->time_base.num / st->time_base.den;
2672 } else {
2673 if (pkt->duration) {
2674 vs->duration += (double)(pkt->duration) * st->time_base.num / st->time_base.den;
2675 } else {
2676 av_log(s, AV_LOG_WARNING, "Stream %d packet with pts %" PRId64 " has duration 0. The segment duration may not be precise.\n",
2677 pkt->stream_index, pkt->pts);
2678 vs->duration = (double)(pkt->pts - vs->end_pts) * st->time_base.num / st->time_base.den;
2679 }
2680 }
2681 }
2682
2683 can_split = can_split && (pkt->pts - vs->end_pts > 0);
2685 >= end_pts)) {
2686 int64_t new_start_pos;
2687 int byterange_mode = (hls->flags & HLS_SINGLE_FILE) || (hls->max_seg_size > 0);
2688 double cur_duration;
2689
2690#if CONFIG_MP4_MUXER
2691 if (hls->segment_type == SEGMENT_TYPE_FMP4 && is_ref_pkt &&
2692 pkt->dts != AV_NOPTS_VALUE)
2693 ff_mov_set_fragment_end_hint(oc, stream_index, pkt, st->time_base);
2694#endif
2695 av_write_frame(oc, NULL); /* Flush any buffered data */
2696 new_start_pos = avio_tell(oc->pb);
2697 vs->size = new_start_pos - vs->start_pos;
2698 avio_flush(oc->pb);
2699 if (hls->segment_type == SEGMENT_TYPE_FMP4 && !vs->init_range_length) {
2700 ret = hls_write_init_file(s, vs);
2701 if (ret < 0)
2702 return ret;
2703 if (!byterange_mode)
2705 }
2706 if (!byterange_mode) {
2707 if (vs->vtt_avf) {
2708 hlsenc_io_close(s, &vs->vtt_avf->pb, vs->vtt_avf->url);
2709 }
2710 }
2711
2712 if (hls->flags & HLS_SINGLE_FILE) {
2713 ret = flush_dynbuf(vs, &range_length);
2714 av_freep(&vs->temp_buffer);
2715 if (ret < 0) {
2716 return ret;
2717 }
2718 vs->size = range_length;
2719 if (hls->key_info_file || hls->encrypt)
2720 vs->size = append_single_file(s, vs);
2721 } else {
2722 if (oc->url[0]) {
2723 proto = avio_find_protocol_name(oc->url);
2724 use_temp_file = proto && !strcmp(proto, "file")
2725 && (hls->flags & HLS_TEMP_FILE);
2726 }
2727
2728 if ((hls->max_seg_size > 0 && (vs->size + vs->start_pos >= hls->max_seg_size)) || !byterange_mode) {
2730 char *filename = NULL;
2731 if (hls->key_info_file || hls->encrypt) {
2732 av_dict_set(&options, "encryption_key", vs->key_string, 0);
2733 av_dict_set(&options, "encryption_iv", vs->iv_string, 0);
2734 filename = av_asprintf("crypto:%s", oc->url);
2735 } else {
2736 filename = av_asprintf("%s", oc->url);
2737 }
2738 if (!filename) {
2740 return AVERROR(ENOMEM);
2741 }
2742
2743 // look to rename the asset name
2744 if (use_temp_file)
2745 av_dict_set(&options, "mpegts_flags", "resend_headers", 0);
2746
2747 set_http_options(s, &options, hls);
2748
2749 ret = hlsenc_io_open(s, &vs->out, filename, &options);
2750 if (ret < 0) {
2752 "Failed to open file '%s'\n", filename);
2753 av_freep(&filename);
2755 return hls->ignore_io_errors ? 0 : ret;
2756 }
2757 if (hls->segment_type == SEGMENT_TYPE_FMP4) {
2758 write_styp(vs->out);
2759 }
2760 ret = flush_dynbuf(vs, &range_length);
2761 if (ret < 0) {
2762 av_freep(&filename);
2764 return ret;
2765 }
2766 vs->size = range_length;
2767 ret = hlsenc_io_close(s, &vs->out, filename);
2768 if (ret < 0) {
2769 av_log(s, AV_LOG_WARNING, "upload segment failed,"
2770 " will retry with a new http session.\n");
2771 ff_format_io_close(s, &vs->out);
2772 ret = hlsenc_io_open(s, &vs->out, filename, &options);
2773 if (ret >= 0) {
2774 reflush_dynbuf(vs, &range_length);
2775 ret = hlsenc_io_close(s, &vs->out, filename);
2776 }
2777 }
2779 av_freep(&vs->temp_buffer);
2780 av_freep(&filename);
2781 }
2782
2783 if (use_temp_file)
2785 }
2786
2787 if (ret < 0)
2788 return ret;
2789
2790 old_filename = av_strdup(oc->url);
2791 if (!old_filename) {
2792 return AVERROR(ENOMEM);
2793 }
2794
2795 cur_duration = (double)(pkt->pts - vs->end_pts) * st->time_base.num / st->time_base.den;
2796 ret = hls_append_segment(s, hls, vs, cur_duration, vs->start_pos, vs->size);
2797 vs->end_pts = pkt->pts;
2798 vs->duration = 0;
2799 if (ret < 0) {
2800 av_freep(&old_filename);
2801 return ret;
2802 }
2803
2804 // if we're building a VOD playlist, skip writing the manifest multiple times, and just wait until the end
2805 if (hls->pl_type != PLAYLIST_TYPE_VOD) {
2806 if ((ret = hls_window(s, 0, vs)) < 0) {
2807 av_log(s, AV_LOG_WARNING, "upload playlist failed, will retry with a new http session.\n");
2808 ff_format_io_close(s, &vs->out);
2809 if ((ret = hls_window(s, 0, vs)) < 0) {
2810 av_freep(&old_filename);
2811 return ret;
2812 }
2813 }
2814 }
2815
2816 if (hls->resend_init_file && hls->segment_type == SEGMENT_TYPE_FMP4) {
2817 ret = hls_init_file_resend(s, vs);
2818 if (ret < 0) {
2819 av_freep(&old_filename);
2820 return ret;
2821 }
2822 }
2823
2824 if (hls->flags & HLS_SINGLE_FILE) {
2825 vs->start_pos += vs->size;
2826 if (hls->key_info_file || hls->encrypt)
2827 ret = hls_start(s, vs);
2828 if (hls->segment_type == SEGMENT_TYPE_MPEGTS && oc->oformat->priv_class && oc->priv_data) {
2829 av_opt_set(oc->priv_data, "mpegts_flags", "resend_headers", 0);
2830 }
2831 } else if (hls->max_seg_size > 0) {
2832 if (vs->size + vs->start_pos >= hls->max_seg_size) {
2833 vs->sequence++;
2834 sls_flag_file_rename(hls, vs, old_filename);
2835 ret = hls_start(s, vs);
2836 vs->start_pos = 0;
2837 /* When split segment by byte, the duration is short than hls_time,
2838 * so it is not enough one segment duration as hls_time, */
2839 } else {
2840 vs->start_pos = new_start_pos;
2841 }
2842 } else {
2843 vs->start_pos = 0;
2844 sls_flag_file_rename(hls, vs, old_filename);
2845 ret = hls_start(s, vs);
2846 }
2847 vs->number++;
2848 av_freep(&old_filename);
2849
2850 if (ret < 0) {
2851 return ret;
2852 }
2853 }
2854
2855 vs->packets_written++;
2856 if (oc->pb) {
2857 ret = ff_write_chained(oc, stream_index, pkt, s, 0);
2858 if (hls->ignore_io_errors)
2859 ret = 0;
2860 }
2861
2862 return ret;
2863}
2864
2866{
2867 HLSContext *hls = s->priv_data;
2868 int i = 0;
2869 VariantStream *vs = NULL;
2870
2871 for (i = 0; i < hls->nb_varstreams; i++) {
2872 vs = &hls->var_streams[i];
2873
2874 av_freep(&vs->basename);
2877 av_freep(&vs->vtt_basename);
2878 av_freep(&vs->vtt_m3u8_name);
2879
2881 if (vs->avf)
2882 ffio_free_dyn_buf(&vs->avf->pb);
2884 if (hls->resend_init_file)
2885 av_freep(&vs->init_buffer);
2888 av_freep(&vs->m3u8_name);
2889 av_freep(&vs->streams);
2890 }
2891
2895 av_freep(&hls->key_basename);
2896 av_freep(&hls->var_streams);
2897 av_freep(&hls->cc_streams);
2899}
2900
2902{
2903 HLSContext *hls = s->priv_data;
2904 AVFormatContext *oc = NULL;
2905 AVFormatContext *vtt_oc = NULL;
2906 char *old_filename = NULL;
2907 const char *proto = NULL;
2908 int use_temp_file = 0;
2909 int i;
2910 int ret = 0;
2911 VariantStream *vs = NULL;
2913 int range_length, byterange_mode;
2914
2915 for (i = 0; i < hls->nb_varstreams; i++) {
2916 char *filename = NULL;
2917 vs = &hls->var_streams[i];
2918 oc = vs->avf;
2919 vtt_oc = vs->vtt_avf;
2920 if (!oc->pb)
2921 continue;
2922 old_filename = av_strdup(oc->url);
2923 use_temp_file = 0;
2924
2925 if (!old_filename) {
2926 return AVERROR(ENOMEM);
2927 }
2928 if (hls->key_info_file || hls->encrypt) {
2929 av_dict_set(&options, "encryption_key", vs->key_string, 0);
2930 av_dict_set(&options, "encryption_iv", vs->iv_string, 0);
2931 filename = av_asprintf("crypto:%s", oc->url);
2932 } else {
2933 filename = av_asprintf("%s", oc->url);
2934 }
2935 if (!filename) {
2937 av_freep(&old_filename);
2938 return AVERROR(ENOMEM);
2939 }
2940
2941 if (hls->segment_type == SEGMENT_TYPE_FMP4 && !vs->init_range_length) {
2942 av_write_frame(oc, NULL); /* Flush any buffered data */
2943
2944 ret = hls_write_init_file(s, vs);
2945 if (ret < 0)
2946 goto failed;
2947 byterange_mode = (hls->flags & HLS_SINGLE_FILE) || (hls->max_seg_size > 0);
2948 if (!byterange_mode) {
2949 ff_format_io_close(s, &vs->out);
2951 }
2952 }
2953 if (!(hls->flags & HLS_SINGLE_FILE)) {
2954 set_http_options(s, &options, hls);
2955 ret = hlsenc_io_open(s, &vs->out, filename, &options);
2956 if (ret < 0) {
2957 av_log(s, AV_LOG_ERROR, "Failed to open file '%s'\n", oc->url);
2958 goto failed;
2959 }
2960 if (hls->segment_type == SEGMENT_TYPE_FMP4)
2961 write_styp(vs->out);
2962 }
2963 ret = flush_dynbuf(vs, &range_length);
2964 if (ret < 0)
2965 goto failed;
2966
2967 vs->size = range_length;
2968 ret = hlsenc_io_close(s, &vs->out, filename);
2969 if (ret < 0) {
2970 av_log(s, AV_LOG_WARNING, "upload segment failed, will retry with a new http session.\n");
2971 ff_format_io_close(s, &vs->out);
2972 ret = hlsenc_io_open(s, &vs->out, filename, &options);
2973 if (ret < 0) {
2974 av_log(s, AV_LOG_ERROR, "Failed to open file '%s'\n", oc->url);
2975 goto failed;
2976 }
2977 reflush_dynbuf(vs, &range_length);
2978 ret = hlsenc_io_close(s, &vs->out, filename);
2979 if (ret < 0)
2980 av_log(s, AV_LOG_WARNING, "Failed to upload file '%s' at the end.\n", oc->url);
2981 }
2982 if (hls->flags & HLS_SINGLE_FILE) {
2983 if (hls->key_info_file || hls->encrypt) {
2984 vs->size = append_single_file(s, vs);
2985 }
2987 }
2988failed:
2989 av_freep(&vs->temp_buffer);
2991 av_freep(&filename);
2992 av_write_trailer(oc);
2993 if (oc->url[0]) {
2994 proto = avio_find_protocol_name(oc->url);
2995 use_temp_file = proto && !strcmp(proto, "file") && (hls->flags & HLS_TEMP_FILE);
2996 }
2997
2998 // rename that segment from .tmp to the real one
2999 if (use_temp_file && !(hls->flags & HLS_SINGLE_FILE)) {
3001 av_freep(&old_filename);
3002 old_filename = av_strdup(oc->url);
3003
3004 if (!old_filename) {
3005 return AVERROR(ENOMEM);
3006 }
3007 }
3008
3009 /* after av_write_trailer, then duration + 1 duration per packet */
3010 hls_append_segment(s, hls, vs, vs->duration + vs->dpp, vs->start_pos, vs->size);
3011
3012 sls_flag_file_rename(hls, vs, old_filename);
3013
3014 if (vtt_oc) {
3015 if (vtt_oc->pb)
3016 av_write_trailer(vtt_oc);
3017 vs->size = avio_tell(vs->vtt_avf->pb) - vs->start_pos;
3018 ff_format_io_close(s, &vtt_oc->pb);
3019 }
3020 ret = hls_window(s, 1, vs);
3021 if (ret < 0) {
3022 av_log(s, AV_LOG_WARNING, "upload playlist failed, will retry with a new http session.\n");
3023 ff_format_io_close(s, &vs->out);
3024 hls_window(s, 1, vs);
3025 }
3026 ffio_free_dyn_buf(&oc->pb);
3027
3028 av_free(old_filename);
3029 }
3030
3031 return 0;
3032}
3033
3034
3036{
3037 int ret = 0;
3038 int i = 0;
3039 int j = 0;
3040 HLSContext *hls = s->priv_data;
3041 const char *pattern;
3042 VariantStream *vs = NULL;
3043 const char *vtt_pattern = hls->flags & HLS_SINGLE_FILE ? ".vtt" : "%d.vtt";
3044 int http_base_proto = ff_is_http_proto(s->url);
3045 int fmp4_init_filename_len = strlen(hls->fmp4_init_filename) + 1;
3046 double initial_program_date_time = av_gettime() / 1000000.0;
3047
3048 if (hls->use_localtime) {
3050 } else {
3051 pattern = hls->segment_type == SEGMENT_TYPE_FMP4 ? "%d.m4s" : "%d.ts";
3052 if (hls->flags & HLS_SINGLE_FILE)
3053 pattern += 2;
3054 }
3055
3056 hls->has_default_key = 0;
3057 hls->has_video_m3u8 = 0;
3059 if (ret < 0) {
3060 av_log(s, AV_LOG_ERROR, "Variant stream info update failed with status %x\n",
3061 ret);
3062 return ret;
3063 }
3064
3065 if (!hls->method && http_base_proto) {
3066 av_log(hls, AV_LOG_WARNING, "No HTTP method set, hls muxer defaulting to method PUT.\n");
3067 }
3068
3069 ret = validate_name(hls->nb_varstreams, s->url);
3070 if (ret < 0)
3071 return ret;
3072
3073 if (hls->segment_filename) {
3075 if (ret < 0)
3076 return ret;
3077 }
3078
3079 if (av_strcasecmp(hls->fmp4_init_filename, "init.mp4")) {
3081 if (ret < 0)
3082 return ret;
3083 }
3084
3085 if (hls->subtitle_filename) {
3087 if (ret < 0)
3088 return ret;
3089 }
3090
3091 if (hls->master_pl_name) {
3093 if (ret < 0) {
3094 av_log(s, AV_LOG_ERROR, "Master stream info update failed with status %x\n",
3095 ret);
3096 return ret;
3097 }
3098 }
3099
3103 time_t t = time(NULL);
3105 hls->start_sequence = av_gettime();
3107 hls->start_sequence = (int64_t)t;
3109 char b[15];
3110 struct tm *p, tmbuf;
3111 if (!(p = localtime_r(&t, &tmbuf)))
3112 return AVERROR(errno);
3113 if (!strftime(b, sizeof(b), "%Y%m%d%H%M%S", p))
3114 return AVERROR(ENOMEM);
3115 hls->start_sequence = strtoll(b, NULL, 10);
3116 }
3117 av_log(hls, AV_LOG_DEBUG, "start_number evaluated to %"PRId64"\n", hls->start_sequence);
3118 }
3119
3120 hls->recording_time = hls->init_time && hls->max_nb_segments > 0 ? hls->init_time : hls->time;
3121
3123 // Independent segments cannot be guaranteed when splitting by time
3126 "'split_by_time' and 'independent_segments' cannot be "
3127 "enabled together. Disabling 'independent_segments' flag\n");
3128 }
3129
3130 for (i = 0; i < hls->nb_varstreams; i++) {
3131 vs = &hls->var_streams[i];
3132
3133 ret = format_name(s->url, &vs->m3u8_name, i, vs->varname);
3134 if (ret < 0)
3135 return ret;
3136
3137 vs->sequence = hls->start_sequence;
3139 vs->end_pts = AV_NOPTS_VALUE;
3141 vs->initial_prog_date_time = initial_program_date_time;
3142
3143 for (j = 0; j < vs->nb_streams; j++) {
3145 /* Get one video stream to reference for split segments
3146 * so use the first video stream index. */
3147 if ((vs->has_video == 1) && (vs->streams[j]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)) {
3148 vs->reference_stream_index = vs->streams[j]->index;
3149 }
3151 }
3152
3153 if (vs->has_video > 1)
3154 av_log(s, AV_LOG_WARNING, "More than a single video stream present, expect issues decoding it.\n");
3155 if (hls->segment_type == SEGMENT_TYPE_FMP4) {
3156#if CONFIG_MP4_MUXER
3158 vs->oformat = &ff_mp4_muxer.p;
3159#else
3161#endif
3162 } else {
3164 vs->oformat = &ff_mpegts_muxer.p;
3165 }
3166
3167 if (hls->segment_filename) {
3168 ret = format_name(hls->segment_filename, &vs->basename, i, vs->varname);
3169 if (ret < 0)
3170 return ret;
3171 } else {
3172 ret = hls_append_segment_pattern(vs->m3u8_name, pattern, &vs->basename);
3173 if (ret < 0)
3174 return ret;
3175 }
3176
3177 if (hls->segment_type == SEGMENT_TYPE_FMP4) {
3178 if (hls->nb_varstreams > 1)
3179 fmp4_init_filename_len += strlen(POSTFIX_PATTERN);
3180 if (hls->flags & HLS_SINGLE_FILE) {
3182 if (!vs->fmp4_init_filename)
3183 return AVERROR(ENOMEM);
3184 } else {
3185 vs->fmp4_init_filename = av_malloc(fmp4_init_filename_len);
3186 if (!vs->fmp4_init_filename)
3187 return AVERROR(ENOMEM);
3189 fmp4_init_filename_len);
3190 if (hls->nb_varstreams > 1) {
3191 if (av_stristr(vs->fmp4_init_filename, "%v")) {
3194 &vs->fmp4_init_filename, i, vs->varname);
3195 } else {
3196 ret = append_postfix(vs->fmp4_init_filename, fmp4_init_filename_len, i);
3197 }
3198 if (ret < 0)
3199 return ret;
3200 }
3201
3202 if (hls->use_localtime) {
3203 int r;
3204 char *expanded = NULL;
3205
3206 r = strftime_expand(vs->fmp4_init_filename, &expanded);
3207 if (r < 0) {
3208 av_log(s, AV_LOG_ERROR, "Could not get segment filename with strftime\n");
3209 return r;
3210 }
3212 vs->fmp4_init_filename = expanded;
3213 }
3214
3215 char *p = strrchr(vs->m3u8_name, '/');
3216 if (p) {
3217 char tmp = *(++p);
3218 *p = '\0';
3219 vs->base_output_dirname = av_asprintf("%s%s", vs->m3u8_name,
3220 vs->fmp4_init_filename);
3221 *p = tmp;
3222 } else {
3224 }
3225 if (!vs->base_output_dirname)
3226 return AVERROR(ENOMEM);
3227 }
3228 }
3229
3231 if (ret < 0)
3232 return ret;
3233
3234 if (vs->has_subtitle) {
3237
3238 ret = hls_append_segment_pattern(vs->m3u8_name, vtt_pattern,
3239 &vs->vtt_basename);
3240 if (ret < 0)
3241 return ret;
3242
3243 if (hls->subtitle_filename) {
3245 if (ret < 0)
3246 return ret;
3247 } else {
3248 ret = hls_append_segment_pattern(vs->m3u8_name, "_vtt.m3u8",
3249 &vs->vtt_m3u8_name);
3250 if (ret < 0)
3251 return ret;
3252 }
3253 }
3254
3255 if ((ret = hls_mux_init(s, vs)) < 0)
3256 return ret;
3257
3258 if (hls->flags & HLS_APPEND_LIST) {
3259 parse_playlist(s, vs->m3u8_name, vs);
3260 vs->discontinuity = 1;
3261 if (hls->init_time > 0) {
3262 av_log(s, AV_LOG_WARNING, "append_list mode does not support hls_init_time,"
3263 " hls_init_time value will have no effect\n");
3264 hls->init_time = 0;
3265 hls->recording_time = hls->time;
3266 }
3267 }
3268
3269 if ((ret = hls_start(s, vs)) < 0)
3270 return ret;
3271 vs->number++;
3272 }
3273
3274 return ret;
3275}
3276
3277#define OFFSET(x) offsetof(HLSContext, x)
3278#define E AV_OPT_FLAG_ENCODING_PARAM
3279static const AVOption options[] = {
3280 {"start_number", "set first number in the sequence", OFFSET(start_sequence),AV_OPT_TYPE_INT64, {.i64 = 0}, 0, INT64_MAX, E},
3281 {"hls_time", "set segment length", OFFSET(time), AV_OPT_TYPE_DURATION, {.i64 = 2000000}, 0, INT64_MAX, E},
3282 {"hls_init_time", "set segment length at init list", OFFSET(init_time), AV_OPT_TYPE_DURATION, {.i64 = 0}, 0, INT64_MAX, E},
3283 {"hls_list_size", "set maximum number of playlist entries", OFFSET(max_nb_segments), AV_OPT_TYPE_INT, {.i64 = 5}, 0, INT_MAX, E},
3284 {"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},
3285 {"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},
3286 {"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},
3287 {"hls_base_url", "url to prepend to each playlist entry", OFFSET(baseurl), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
3288 {"hls_segment_filename", "filename template for segment files", OFFSET(segment_filename), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
3289 {"hls_segment_options","set segments files format options of hls", OFFSET(format_options), AV_OPT_TYPE_DICT, {.str = NULL}, 0, 0, E},
3290 {"hls_segment_size", "maximum size per segment file, (in bytes)", OFFSET(max_seg_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E},
3291 {"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},
3292 {"hls_enc", "enable AES128 encryption support", OFFSET(encrypt), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, E},
3293 {"hls_enc_key", "hex-coded 16 byte key to encrypt the segments", OFFSET(key), AV_OPT_TYPE_STRING, .flags = E},
3294 {"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},
3295 {"hls_enc_iv", "hex-coded 16 byte initialization vector", OFFSET(iv), AV_OPT_TYPE_STRING, .flags = E},
3296 {"hls_subtitle_path", "set path of hls subtitles", OFFSET(subtitle_filename), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
3297 {"hls_segment_type", "set hls segment files type", OFFSET(segment_type), AV_OPT_TYPE_INT, {.i64 = SEGMENT_TYPE_MPEGTS }, 0, SEGMENT_TYPE_FMP4, E, .unit = "segment_type"},
3298 {"mpegts", "make segment file to mpegts files in m3u8", 0, AV_OPT_TYPE_CONST, {.i64 = SEGMENT_TYPE_MPEGTS }, 0, UINT_MAX, E, .unit = "segment_type"},
3299 {"fmp4", "make segment file to fragment mp4 files in m3u8", 0, AV_OPT_TYPE_CONST, {.i64 = SEGMENT_TYPE_FMP4 }, 0, UINT_MAX, E, .unit = "segment_type"},
3300 {"hls_fmp4_init_filename", "set fragment mp4 file init filename", OFFSET(fmp4_init_filename), AV_OPT_TYPE_STRING, {.str = "init.mp4"}, 0, 0, E},
3301 {"hls_fmp4_init_resend", "resend fragment mp4 init file after refresh m3u8 every time", OFFSET(resend_init_file), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, E },
3302 {"hls_flags", "set flags affecting HLS playlist and media file generation", OFFSET(flags), AV_OPT_TYPE_FLAGS, {.i64 = 0 }, 0, UINT_MAX, E, .unit = "flags"},
3303 {"single_file", "generate a single media file indexed with byte ranges", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_SINGLE_FILE }, 0, UINT_MAX, E, .unit = "flags"},
3304 {"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, .unit = "flags"},
3305 {"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, .unit = "flags"},
3306 {"round_durations", "round durations in m3u8 to whole numbers", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_ROUND_DURATIONS }, 0, UINT_MAX, E, .unit = "flags"},
3307 {"discont_start", "start the playlist with a discontinuity tag", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_DISCONT_START }, 0, UINT_MAX, E, .unit = "flags"},
3308 {"omit_endlist", "Do not append an endlist when ending stream", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_OMIT_ENDLIST }, 0, UINT_MAX, E, .unit = "flags"},
3309 {"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, .unit = "flags"},
3310 {"append_list", "append the new segments into old hls segment list", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_APPEND_LIST }, 0, UINT_MAX, E, .unit = "flags"},
3311 {"program_date_time", "add EXT-X-PROGRAM-DATE-TIME", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_PROGRAM_DATE_TIME }, 0, UINT_MAX, E, .unit = "flags"},
3312 {"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, .unit = "flags"},
3313 {"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, .unit = "flags"},
3314 {"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, .unit = "flags"},
3315 {"periodic_rekey", "reload keyinfo file periodically for re-keying", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_PERIODIC_REKEY }, 0, UINT_MAX, E, .unit = "flags"},
3316 {"independent_segments", "add EXT-X-INDEPENDENT-SEGMENTS, whenever applicable", 0, AV_OPT_TYPE_CONST, { .i64 = HLS_INDEPENDENT_SEGMENTS }, 0, UINT_MAX, E, .unit = "flags"},
3317 {"iframes_only", "add EXT-X-I-FRAMES-ONLY, whenever applicable", 0, AV_OPT_TYPE_CONST, { .i64 = HLS_I_FRAMES_ONLY }, 0, UINT_MAX, E, .unit = "flags"},
3318 {"strftime", "set filename expansion with strftime at segment creation", OFFSET(use_localtime), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, E },
3319 {"strftime_mkdir", "create last directory component in strftime-generated filename", OFFSET(use_localtime_mkdir), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, E },
3320 {"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, .unit = "pl_type" },
3321 {"event", "EVENT playlist", 0, AV_OPT_TYPE_CONST, {.i64 = PLAYLIST_TYPE_EVENT }, INT_MIN, INT_MAX, E, .unit = "pl_type" },
3322 {"vod", "VOD playlist", 0, AV_OPT_TYPE_CONST, {.i64 = PLAYLIST_TYPE_VOD }, INT_MIN, INT_MAX, E, .unit = "pl_type" },
3323 {"method", "set the HTTP method(default: PUT)", OFFSET(method), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
3324 {"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_LAST-1, E, .unit = "start_sequence_source_type" },
3325 {"generic", "start_number value (default)", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_START_SEQUENCE_AS_START_NUMBER }, INT_MIN, INT_MAX, E, .unit = "start_sequence_source_type" },
3326 {"epoch", "seconds since epoch", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_START_SEQUENCE_AS_SECONDS_SINCE_EPOCH }, INT_MIN, INT_MAX, E, .unit = "start_sequence_source_type" },
3327 {"epoch_us", "microseconds since epoch", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_START_SEQUENCE_AS_MICROSECONDS_SINCE_EPOCH }, INT_MIN, INT_MAX, E, .unit = "start_sequence_source_type" },
3328 {"datetime", "current datetime as YYYYMMDDhhmmss", 0, AV_OPT_TYPE_CONST, {.i64 = HLS_START_SEQUENCE_AS_FORMATTED_DATETIME }, INT_MIN, INT_MAX, E, .unit = "start_sequence_source_type" },
3329 {"http_user_agent", "override User-Agent field in HTTP header", OFFSET(user_agent), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
3330 {"var_stream_map", "Variant stream map string", OFFSET(var_stream_map), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
3331 {"cc_stream_map", "Closed captions stream map string", OFFSET(cc_stream_map), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
3332 {"master_pl_name", "Create HLS master playlist with this name", OFFSET(master_pl_name), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E},
3333 {"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},
3334 {"http_persistent", "Use persistent HTTP connections", OFFSET(http_persistent), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, E },
3335 {"timeout", "set timeout for socket I/O operations", OFFSET(timeout), AV_OPT_TYPE_DURATION, { .i64 = -1 }, -1, INT_MAX, .flags = E },
3336 {"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 },
3337 {"headers", "set custom HTTP headers, can override built in default headers", OFFSET(headers), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, E },
3338 { NULL },
3339};
3340
3341static const AVClass hls_class = {
3342 .class_name = "hls muxer",
3343 .item_name = av_default_item_name,
3344 .option = options,
3345 .version = LIBAVUTIL_VERSION_INT,
3346};
3347
3348
3350 .p.name = "hls",
3351 .p.long_name = NULL_IF_CONFIG_SMALL("Apple HTTP Live Streaming"),
3352 .p.extensions = "m3u8",
3353 .p.audio_codec = AV_CODEC_ID_AAC,
3354 .p.video_codec = AV_CODEC_ID_H264,
3355 .p.subtitle_codec = AV_CODEC_ID_WEBVTT,
3357 .p.priv_class = &hls_class,
3358 .flags_internal = FF_OFMT_FLAG_ALLOW_FLUSH,
3359 .priv_data_size = sizeof(HLSContext),
3360 .init = hls_init,
3364 .deinit = hls_deinit,
3365};
#define fn(a)
#define fn2(a, b)
static double val(void *priv, double ch)
Definition aeval.c:77
const FFOutputFormat ff_mpegts_muxer
Definition mpegtsenc.c:2550
const FFOutputFormat ff_webvtt_muxer
Definition webvttenc.c:100
const FFOutputFormat ff_mp4_muxer
const FFOutputFormat ff_hls_muxer
Definition hlsenc.c:3349
static AVFormatContext * ctx
static const uint8_t sequence[]
#define EXTERN
simple assert() macros that are a bit more flexible than ISO C assert().
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Definition avassert.h:42
#define E
Definition avdct.c:34
int ff_format_io_close(AVFormatContext *s, AVIOContext **pb)
Definition avformat.c:992
void avpriv_set_pts_info(AVStream *st, int pts_wrap_bits, unsigned int pts_num, unsigned int pts_den)
Set the time base and wrapping info for a given stream.
Definition avformat.c:865
void ff_format_set_url(AVFormatContext *s, char *url)
Set AVFormatContext url field to the provided pointer.
Definition avformat.c:954
Main libavformat public API header.
#define AVFMT_NODIMENSIONS
Format does not need width/height.
Definition avformat.h:504
#define AVFMT_NOFILE
Demuxer will use avio_open, no opened file should be provided by the caller.
Definition avformat.h:490
#define AVFMT_GLOBALHEADER
Format wants global header.
Definition avformat.h:499
int avformat_alloc_output_context2(AVFormatContext **ctx, const AVOutputFormat *oformat, const char *format_name, const char *filename)
Allocate an AVFormatContext for an output format.
Definition mux.c:95
int ffurl_shutdown(URLContext *h, int flags)
Signal the URLContext that we are done reading or writing the stream.
Definition avio.c:928
URLContext * ffio_geturlcontext(AVIOContext *s)
Return the URLContext associated with the AVIOContext.
Definition avio.c:113
const char * avio_find_protocol_name(const char *url)
Return the name of the protocol that will handle the passed URL.
Definition avio.c:733
int ff_rename(const char *url_src, const char *url_dst, void *logctx)
Wrap ffurl_move() and log if error happens.
Definition avio.c:942
int64_t avio_seek(AVIOContext *s, int64_t offset, int whence)
fseek() equivalent for AVIOContext.
Definition aviobuf.c:236
void avio_wb32(AVIOContext *s, unsigned int val)
Definition aviobuf.c:368
#define AVIO_FLAG_READ
read-only
Definition avio.h:630
int avio_feof(AVIOContext *s)
Similar to feof() but also returns nonzero on read errors.
Definition aviobuf.c:349
#define AVIO_FLAG_WRITE
write-only
Definition avio.h:631
static av_always_inline int64_t avio_tell(AVIOContext *s)
ftell() equivalent for AVIOContext.
Definition avio.h:507
int avio_printf(AVIOContext *s, const char *fmt,...) av_printf_format(2
Writes a formatted string to the context.
int avio_close_dyn_buf(AVIOContext *s, uint8_t **pbuffer)
Return the written size and a pointer to the buffer.
Definition aviobuf.c:1378
int avio_read(AVIOContext *s, unsigned char *buf, int size)
Read size bytes from AVIOContext into buf.
Definition aviobuf.c:620
void avio_write(AVIOContext *s, const unsigned char *buf, int size)
Definition aviobuf.c:206
void avio_flush(AVIOContext *s)
Force flushing of buffered data.
Definition aviobuf.c:228
int avio_open_dyn_buf(AVIOContext **s)
Open a write only memory stream.
Definition aviobuf.c:1333
int avio_get_dyn_buf(AVIOContext *s, uint8_t **pbuffer)
Return the written size and a pointer to the buffer.
Definition aviobuf.c:1345
void ffio_free_dyn_buf(AVIOContext **s)
Free a dynamic buffer.
Definition aviobuf.c:1406
static av_always_inline void ffio_wfourcc(AVIOContext *pb, const uint8_t *s)
int ff_get_chomp_line(AVIOContext *s, char *buf, int maxlen)
Same as ff_get_line but strip the white-space characters in the text tail.
Definition aviobuf.c:765
int ff_get_line(AVIOContext *s, char *buf, int maxlen)
Read a whole line of text from AVIOContext.
Definition aviobuf.c:748
char * av_asprintf(const char *fmt,...)
Definition avstring.c:115
#define fn1(name, depth)
Definition blend_modes.c:90
void av_bprintf(AVBPrint *buf, const char *fmt,...)
Definition bprint.c:121
void av_bprint_init(AVBPrint *buf, unsigned size_init, unsigned size_max)
Definition bprint.c:68
AVBPrint public header.
#define AV_BPRINT_SIZE_UNLIMITED
#define flags(name, subs,...)
Definition cbs_h264.c:74
#define i(width, name, range_min, range_max)
Definition cbs_h264.c:63
#define s(width, name)
Definition cbs_vp9.c:198
static void deinit(AVFormatContext *s)
Definition chromaprint.c:53
int avcodec_parameters_copy(AVCodecParameters *dst, const AVCodecParameters *src)
Definition codec_par.c:107
int ff_make_codec_str(void *logctx, const AVCodecParameters *par, const AVRational *frame_rate, struct AVBPrint *out)
Make a RFC 4281/6381 like string describing a codec.
#define NULL
Definition coverity.c:32
long long int64_t
Definition coverity.c:34
static void can_split(const VVCLocalContext *lc, int x0, int y0, int cb_width, int cb_height, int mtt_depth, int depth_offset, int part_idx, VVCSplitMode last_split_mode, VVCTreeType tree_type, VVCModeType mode_type, VVCAllowedSplit *split)
Definition ctu.c:526
Misc types and constants that do not belong anywhere else.
static AVPacket * pkt
int(* init)(AVBSFContext *ctx)
Definition dts2pts.c:613
double value
Definition eval.c:102
static int write_packet(Muxer *mux, OutputStream *ost, AVPacket *pkt)
Definition ffmpeg_mux.c:203
const char * key
static int64_t duration
Definition ffplay.c:359
char * path
Definition ffplay.c:385
int ret
Definition ffplay.c:391
static unsigned int nb_streams
Definition ffprobe.c:390
static void write_header(FFV1Context *f)
Definition ffv1enc.c:397
#define fail
Definition test.h:479
@ AV_OPT_TYPE_CONST
Special option type for declaring named constants.
Definition opt.h:298
@ AV_OPT_TYPE_DURATION
Underlying C type is int64_t.
Definition opt.h:318
@ AV_OPT_TYPE_FLAGS
Underlying C type is unsigned int.
Definition opt.h:254
@ AV_OPT_TYPE_INT64
Underlying C type is int64_t.
Definition opt.h:262
@ AV_OPT_TYPE_INT
Underlying C type is int.
Definition opt.h:258
@ AV_OPT_TYPE_DICT
Underlying C type is AVDictionary*.
Definition opt.h:289
@ AV_OPT_TYPE_BOOL
Underlying C type is int.
Definition opt.h:326
@ AV_OPT_TYPE_STRING
Underlying C type is a uint8_t* that is either NULL or points to a C string allocated with the av_mal...
Definition opt.h:275
@ AV_CODEC_ID_H264
Definition codec_id.h:77
@ AV_CODEC_ID_WEBVTT
Definition codec_id.h:590
@ AV_CODEC_ID_HEVC
Definition codec_id.h:223
@ AV_CODEC_ID_AAC
Definition codec_id.h:461
const AVPacketSideData * av_packet_side_data_get(const AVPacketSideData *sd, int nb_sd, enum AVPacketSideDataType type)
Get side information from a side data array.
Definition packet.c:571
@ AV_PKT_DATA_CPB_PROPERTIES
This side data corresponds to the AVCPBProperties struct.
Definition packet.h:142
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition packet.h:657
AVStream * avformat_new_stream(AVFormatContext *s, const struct AVCodec *c)
Add a new stream to a media file.
int av_program_copy(AVFormatContext *dst, const AVFormatContext *src, int progid, int flags)
Copy an AVProgram from one AVFormatContext to another.
Definition avformat.c:373
void avformat_free_context(AVFormatContext *s)
Free an AVFormatContext and all its streams.
Definition avformat.c:165
av_warn_unused_result int avformat_init_output(AVFormatContext *s, AVDictionary **options)
Allocate the stream private data and initialize the codec, but do not write the header.
Definition mux.c:491
av_warn_unused_result int avformat_write_header(AVFormatContext *s, AVDictionary **options)
Allocate the stream private data and write the stream header to an output media file.
Definition mux.c:512
int av_write_trailer(AVFormatContext *s)
Write the stream trailer to an output media file and free the file private data.
Definition mux.c:1283
int av_write_frame(AVFormatContext *s, AVPacket *pkt)
Write a packet to an output media file.
Definition mux.c:1221
unsigned int av_codec_get_tag(const struct AVCodecTag *const *tags, enum AVCodecID id)
Get the codec tag for the given codec id id.
enum AVCodecID av_codec_get_id(const struct AVCodecTag *const *tags, unsigned int tag)
Get the AVCodecID for the given codec tag tag.
static int av_bprint_is_complete(const AVBPrint *buf)
Test if the print buffer is complete (not truncated).
Definition bprint.h:218
int av_bprint_finalize(AVBPrint *buf, char **ret_str)
Finalize a print buffer.
Definition bprint.c:234
void av_bprint_append_data(AVBPrint *buf, const char *data, unsigned size)
Append data to a print buffer.
Definition bprint.c:147
void av_bprint_chars(AVBPrint *buf, char c, unsigned n)
Append char c n times to a print buffer.
Definition bprint.c:129
void av_bprint_clear(AVBPrint *buf)
Reset the string to "" but keep internal allocated data.
Definition bprint.c:226
void av_bprint_init_for_buffer(AVBPrint *buf, char *buffer, unsigned size)
Init a print buffer using a pre-existing buffer.
Definition bprint.c:84
int av_random_bytes(uint8_t *buf, size_t len)
Generate cryptographically secure random data, i.e.
void av_dict_free(AVDictionary **pm)
Free all the memory allocated for an AVDictionary struct and all keys and values.
Definition dict.c:236
int av_dict_copy(AVDictionary **dst, const AVDictionary *src, int flags)
Copy entries from one AVDictionary struct into another.
Definition dict.c:250
#define AV_DICT_APPEND
If the entry already exists, append to it.
Definition dict.h:82
int av_dict_set(AVDictionary **pm, const char *key, const char *value, int flags)
Set the given entry in *pm, overwriting an existing entry.
Definition dict.c:87
#define AV_DICT_DONT_OVERWRITE
Don't overwrite existing entries.
Definition dict.h:81
int av_dict_count(const AVDictionary *m)
Get number of entries in dictionary.
Definition dict.c:38
int av_dict_set_int(AVDictionary **pm, const char *key, int64_t value, int flags)
Convenience wrapper for av_dict_set() that converts the value to a string and stores it.
Definition dict.c:180
#define AVERROR_PATCHWELCOME
Not yet implemented in FFmpeg, patches welcome.
Definition error.h:64
#define AVERROR_MUXER_NOT_FOUND
Muxer not found.
Definition error.h:62
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition error.h:61
#define AVERROR_EOF
End of file.
Definition error.h:57
#define AVERROR(e)
Definition error.h:45
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition log.h:231
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition log.h:216
#define AV_LOG_VERBOSE
Detailed information.
Definition log.h:226
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition log.h:210
const char * av_default_item_name(void *ptr)
Return the context name.
Definition log.c:247
int64_t av_rescale_q(int64_t a, AVRational bq, AVRational cq)
Rescale a 64-bit integer by 2 rational numbers.
void * av_memdup(const void *p, size_t size)
Duplicate a buffer with av_malloc().
Definition mem.c:408
AVMediaType
Definition avutil.h:198
@ AVMEDIA_TYPE_AUDIO
Definition avutil.h:201
@ AVMEDIA_TYPE_SUBTITLE
Definition avutil.h:203
@ AVMEDIA_TYPE_VIDEO
Definition avutil.h:200
size_t av_strlcat(char *dst, const char *src, size_t size)
Append the string src to the string dst, but to a total length of no more than size - 1 bytes,...
Definition avstring.c:95
char * av_stristr(const char *s1, const char *s2)
Locate the first case-independent occurrence in the string haystack of the string needle.
Definition avstring.c:58
char * av_strtok(char *s, const char *delim, char **saveptr)
Split the string into several tokens which can be accessed by successive calls to av_strtok().
Definition avstring.c:179
int av_strcasecmp(const char *a, const char *b)
Locale-independent case-insensitive compare.
Definition avstring.c:208
static av_const int av_isdigit(int c)
Locale-independent conversion of ASCII isdigit.
Definition avstring.h:202
int av_strstart(const char *str, const char *pfx, const char **ptr)
Return non-zero if pfx is a prefix of str.
Definition avstring.c:36
size_t av_strlcpy(char *dst, const char *src, size_t size)
Copy the string src to dst, but no more than size - 1 bytes, and null-terminate dst.
Definition avstring.c:85
const char * av_dirname(char *path)
Thread safe dirname.
Definition avstring.c:274
const char * av_basename(const char *path)
Thread safe basename.
Definition avstring.c:256
int av_stristart(const char *str, const char *pfx, const char **ptr)
Return non-zero if pfx is a prefix of str independent of case.
Definition avstring.c:47
char * av_append_path_component(const char *path, const char *component)
Append path component to the existing path.
Definition avstring.c:295
int av_strncasecmp(const char *a, const char *b, size_t n)
Locale-independent case-insensitive compare.
Definition avstring.c:218
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition avutil.h:247
#define AV_TIME_BASE_Q
Internal time base represented as fractional value.
Definition avutil.h:263
#define LIBAVUTIL_VERSION_INT
Definition version.h:85
int av_opt_set(void *obj, const char *name, const char *val, int search_flags)
Definition opt.c:904
int index
Definition gxfenc.c:90
static const AVClass hls_class
Definition hls.c:3578
static int sls_flag_check_duration_size_index(HLSContext *hls)
Definition hlsenc.c:1006
static int update_variant_stream_info(AVFormatContext *s)
Definition hlsenc.c:2398
static int64_t get_stream_bit_rate(AVStream *stream)
Definition hlsenc.c:1437
static HLSSegment * find_segment_by_filename(HLSSegment *segment, const char *filename)
Definition hlsenc.c:956
static void set_http_options(AVFormatContext *s, AVDictionary **options, HLSContext *c)
Definition hlsenc.c:335
static int create_master_playlist(AVFormatContext *s, VariantStream *const input_vs, int final)
Definition hlsenc.c:1454
static int hls_init(AVFormatContext *s)
Definition hlsenc.c:3035
static int hls_window(AVFormatContext *s, int last, VariantStream *vs)
Definition hlsenc.c:1634
@ SEGMENT_TYPE_FMP4
Definition hlsenc.c:118
@ SEGMENT_TYPE_MPEGTS
Definition hlsenc.c:117
static int hls_append_segment_pattern(const char *url, const char *pattern, char **filename)
Definition hlsenc.c:2103
static int validate_name(int nb_vs, const char *fn)
Definition hlsenc.c:2023
#define KEYSIZE
Definition hlsenc.c:73
static const char * get_relative_url(const char *master_url, const char *media_url)
Definition hlsenc.c:1417
static int get_nth_codec_stream_index(AVFormatContext *s, enum AVMediaType codec_type, int64_t stream_id)
Definition hlsenc.c:2157
static int hls_rename_temp_file(AVFormatContext *s, AVFormatContext *oc)
Definition hlsenc.c:1402
static int parse_variant_stream_mapstring(AVFormatContext *s)
Definition hlsenc.c:2175
static int extract_segment_number(const char *filename)
Definition hlsenc.c:1221
#define NEXT(s)
static int append_postfix(char *name, int name_buf_len, int i)
Definition hlsenc.c:2004
static void hls_free_segments(HLSSegment *p)
Definition hlsenc.c:1391
static int hls_write_header(AVFormatContext *s)
Definition hlsenc.c:2478
static int hls_append_segment(struct AVFormatContext *s, HLSContext *hls, VariantStream *vs, double duration, int64_t pos, int64_t size)
Definition hlsenc.c:1118
static int format_name(const char *buf, char **s, int index, const char *varname)
Definition hlsenc.c:2057
static int replace_int_data_in_filename(char **s, const char *filename, char placeholder, int64_t number)
Definition hlsenc.c:425
static int replace_str_data_in_filename(char **s, const char *filename, char placeholder, const char *datastring)
Definition hlsenc.c:385
static void reflush_dynbuf(VariantStream *vs, int *range_length)
Definition hlsenc.c:504
static int do_encrypt(AVFormatContext *s, VariantStream *vs)
Definition hlsenc.c:691
static int sls_flag_use_localtime_filename(AVFormatContext *oc, HLSContext *c, VariantStream *vs)
Definition hlsenc.c:1056
static int hlsenc_io_close(AVFormatContext *s, AVIOContext **pb, char *filename)
Definition hlsenc.c:315
static int hls_init_file_resend(AVFormatContext *s, VariantStream *vs)
Definition hlsenc.c:2540
static int64_t append_single_file(AVFormatContext *s, VariantStream *vs)
Definition hlsenc.c:2557
static void sls_flag_file_rename(HLSContext *hls, VariantStream *vs, char *old_filename)
Definition hlsenc.c:1049
static int strftime_expand(const char *fmt, char **dest)
Definition hlsenc.c:271
static int hls_write_trailer(struct AVFormatContext *s)
Definition hlsenc.c:2901
static void hls_deinit(AVFormatContext *s)
Definition hlsenc.c:2865
StartSequenceSourceType
Definition hlsenc.c:60
@ HLS_START_SEQUENCE_AS_MICROSECONDS_SINCE_EPOCH
Definition hlsenc.c:64
@ HLS_START_SEQUENCE_AS_FORMATTED_DATETIME
Definition hlsenc.c:63
@ HLS_START_SEQUENCE_AS_SECONDS_SINCE_EPOCH
Definition hlsenc.c:62
@ HLS_START_SEQUENCE_LAST
Definition hlsenc.c:65
@ HLS_START_SEQUENCE_AS_START_NUMBER
Definition hlsenc.c:61
static int flush_dynbuf(VariantStream *vs, int *range_length)
Definition hlsenc.c:483
static int hlsenc_io_open(AVFormatContext *s, AVIOContext **pb, const char *filename, AVDictionary **options)
Definition hlsenc.c:294
static int parse_playlist(AVFormatContext *s, const char *url, VariantStream *vs)
Definition hlsenc.c:1248
#define HLS_MICROSECOND_UNIT
Definition hlsenc.c:75
#define POSTFIX_PATTERN
Definition hlsenc.c:77
static void hls_update_discontinuity_sequence(VariantStream *vs, const HLSSegment *segment)
Definition hlsenc.c:1105
static int hls_start(AVFormatContext *s, VariantStream *vs)
Definition hlsenc.c:1798
static void write_styp(AVIOContext *pb)
Definition hlsenc.c:473
static const char * get_default_pattern_localtime_fmt(AVFormatContext *s)
Definition hlsenc.c:1983
static int hls_encryption_start(AVFormatContext *s, VariantStream *vs)
Definition hlsenc.c:770
static int hls_write_packet(AVFormatContext *s, AVPacket *pkt)
Definition hlsenc.c:2588
static int hls_mux_init(AVFormatContext *s, VariantStream *vs)
Definition hlsenc.c:829
static int parse_cc_stream_mapstring(AVFormatContext *s)
Definition hlsenc.c:2321
static void hls_increment_discontinuity_sequence(VariantStream *vs)
Definition hlsenc.c:1099
#define OFFSET(x)
Definition hlsenc.c:3277
HLSFlags
Definition hlsenc.c:97
@ HLS_OMIT_ENDLIST
Definition hlsenc.c:103
@ HLS_PERIODIC_REKEY
Definition hlsenc.c:111
@ HLS_SINGLE_FILE
Definition hlsenc.c:99
@ HLS_DELETE_SEGMENTS
Definition hlsenc.c:100
@ HLS_APPEND_LIST
Definition hlsenc.c:105
@ HLS_TEMP_FILE
Definition hlsenc.c:110
@ HLS_SECOND_LEVEL_SEGMENT_INDEX
Definition hlsenc.c:107
@ HLS_PROGRAM_DATE_TIME
Definition hlsenc.c:106
@ HLS_ROUND_DURATIONS
Definition hlsenc.c:101
@ HLS_SPLIT_BY_TIME
Definition hlsenc.c:104
@ HLS_DISCONT_START
Definition hlsenc.c:102
@ HLS_INDEPENDENT_SEGMENTS
Definition hlsenc.c:112
@ HLS_SECOND_LEVEL_SEGMENT_DURATION
Definition hlsenc.c:108
@ HLS_SECOND_LEVEL_SEGMENT_SIZE
Definition hlsenc.c:109
@ HLS_I_FRAMES_ONLY
Definition hlsenc.c:113
CodecAttributeStatus
Definition hlsenc.c:68
@ CODEC_ATTRIBUTE_WILL_NOT_BE_WRITTEN
Definition hlsenc.c:70
@ CODEC_ATTRIBUTE_WRITTEN
Definition hlsenc.c:69
static int hls_write_init_file(AVFormatContext *s, VariantStream *vs)
Definition hlsenc.c:510
#define BUFSIZE
Definition hlsenc.c:76
static int hls_delete_old_segments(AVFormatContext *s, HLSContext *hls, VariantStream *vs)
Definition hlsenc.c:581
static int hls_delete_file(HLSContext *hls, AVFormatContext *avf, char *path, const char *proto)
Definition hlsenc.c:557
static int sls_flags_filename_process(struct AVFormatContext *s, HLSContext *hls, VariantStream *vs, double duration, int64_t pos, int64_t size)
Definition hlsenc.c:966
static int sls_flag_check_duration_size(HLSContext *hls, VariantStream *vs)
Definition hlsenc.c:1029
static int update_master_pl_info(AVFormatContext *s)
Definition hlsenc.c:2436
#define LINE_BUFFER_SIZE
Definition hlsenc.c:74
static void write_codec_attr(AVStream *st, VariantStream *vs)
Definition hlsenc.c:354
void ff_hls_write_playlist_version(AVIOContext *out, int version)
Definition hlsplaylist.c:32
void ff_hls_write_playlist_header(AVIOContext *out, int version, int allowcache, int target_duration, int64_t sequence, uint32_t playlist_type, int iframe_mode)
void ff_hls_write_audio_rendition(AVIOContext *out, const char *agroup, const char *filename, const char *language, int name_id, int is_default, int nb_channels)
Definition hlsplaylist.c:40
void ff_hls_write_init_file(AVIOContext *out, const char *filename, int byterange_mode, int64_t size, int64_t pos)
void ff_hls_write_discontinuity_sequence(AVIOContext *out, int64_t discontinuity_sequence)
void ff_hls_write_subtitle_rendition(AVIOContext *out, const char *sgroup, const char *filename, const char *language, const char *sname, int name_id, int is_default)
Definition hlsplaylist.c:58
void ff_hls_write_end_list(AVIOContext *out)
int ff_hls_write_file_entry(AVIOContext *out, int insert_discont, int byterange_mode, double duration, int round_duration, int64_t size, int64_t pos, const char *baseurl, const char *filename, double *prog_date_time, int iframe_mode)
void ff_hls_write_stream_info(AVStream *st, AVIOContext *out, int bandwidth, int avg_bandwidth, const char *filename, const char *agroup, const char *codecs, const char *ccgroup, const char *sgroup)
Definition hlsplaylist.c:78
@ PLAYLIST_TYPE_VOD
Definition hlsplaylist.h:34
@ PLAYLIST_TYPE_NB
Definition hlsplaylist.h:35
@ PLAYLIST_TYPE_NONE
Definition hlsplaylist.h:32
@ PLAYLIST_TYPE_EVENT
Definition hlsplaylist.h:33
int ff_http_do_new_request(URLContext *h, const char *uri)
Send a new HTTP request, reusing the old connection.
Definition http.c:589
#define r
Definition input.c:42
#define b
Definition input.c:43
#define AV_WB64(p, v)
int ff_mkdir_p(const char *path)
Automatically create sub-directories.
Definition utils.c:424
int ff_is_http_proto(const char *filename)
Utility function to check if the file uses http or https protocol.
Definition utils.c:598
char * ff_data_to_hex(char *buf, const uint8_t *src, int size, int lowercase)
Write hexadecimal string corresponding to given binary data.
Definition utils.c:473
void * ff_bprint_finalize_as_fam(struct AVBPrint *bp, const void *struct_ptr, size_t fam_offset)
Allocate copy of a structure and copy contents of an AVBPrint buffer to the flexible array member of ...
Definition utils.c:705
#define MAX_URL_SIZE
Definition internal.h:30
int ff_write_chained(AVFormatContext *dst, int dst_stream, AVPacket *pkt, AVFormatContext *src, int interleave)
Write a packet to another muxer than the one the user originally intended.
Definition mux.c:1382
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification.
Definition internal.h:97
#define init_buffer(a0, a1, type, width)
Definition llviddsp.c:40
Utility Preprocessor macros.
#define FFMIN(a, b)
Definition macros.h:49
#define MKTAG(a, b, c, d)
Definition macros.h:55
#define FFMAX(a, b)
Definition macros.h:47
Memory handling functions.
int ff_mov_set_fragment_end_hint(AVFormatContext *s, int stream_index, const AVPacket *pkt, AVRational src_time_base)
Definition movenc.c:7316
#define FF_OFMT_FLAG_ALLOW_FLUSH
This flag indicates that the muxer stores data internally and supports flushing it.
Definition mux.h:38
#define av_strdup(s)
Definition ops_static.c:55
#define av_malloc(s)
Definition ops_static.c:52
AVOptions.
miscellaneous OS support macros and functions.
static int is_dos_path(const char *path)
Definition os_support.h:107
char * av_small_strptime(const char *p, const char *fmt, struct tm *dt)
Simplified version of strptime.
Definition parseutils.c:494
misc parsing utilities
SegmentType
Definition pgssubdec.c:42
const char * name
Definition qsvenc.c:142
enum AVMediaType codec_type
Definition rtp.c:37
static const uint8_t start_sequence[]
Definition rtpdec_h264.c:66
unsigned int pos
Definition spdifenc.c:431
This structure describes the bitrate properties of an encoded bitstream.
Definition defs.h:298
int64_t max_bitrate
Maximum bitrate of the stream, in bits per second.
Definition defs.h:303
int nb_channels
Number of channels in this layout.
Describe the class of an AVClass context structure.
Definition log.h:76
int nb_coded_side_data
Amount of entries in coded_side_data.
Definition codec_par.h:88
AVChannelLayout ch_layout
The channel layout and number of channels.
Definition codec_par.h:207
int64_t bit_rate
The average bitrate of the encoded data (in bits per second).
Definition codec_par.h:99
enum AVMediaType codec_type
General type of the encoded data.
Definition codec_par.h:53
uint32_t codec_tag
Additional information about the codec (corresponds to the AVI FOURCC).
Definition codec_par.h:61
enum AVCodecID codec_id
Specific type of the encoded data (the codec used).
Definition codec_par.h:57
AVPacketSideData * coded_side_data
Additional data associated with the entire stream.
Definition codec_par.h:83
Format I/O context.
Definition avformat.h:1401
int(* io_close2)(struct AVFormatContext *s, AVIOContext *pb)
A callback for closing the streams opened with AVFormatContext.io_open().
Definition avformat.h:2037
AVIOContext * pb
I/O context.
Definition avformat.h:1443
AVDictionary * metadata
Metadata that applies to the whole file.
Definition avformat.h:1649
int flags
Flags modifying the (de)muxer behaviour.
Definition avformat.h:1553
const struct AVOutputFormat * oformat
The output container format.
Definition avformat.h:1420
int strict_std_compliance
Allow non-standard and experimental extension.
Definition avformat.h:1776
AVIOInterruptCB interrupt_callback
Custom interrupt callbacks for the I/O layer.
Definition avformat.h:1687
char * url
input or output URL.
Definition avformat.h:1518
void * opaque
User data.
Definition avformat.h:1986
void * priv_data
Format private data.
Definition avformat.h:1429
AVStream ** streams
A list of all streams in the file.
Definition avformat.h:1469
int(* io_open)(struct AVFormatContext *s, AVIOContext **pb, const char *url, int flags, AVDictionary **options)
A callback for opening new IO streams.
Definition avformat.h:2027
Bytestream IO Context.
Definition avio.h:160
int error
contains the error code or 0 if no error happened
Definition avio.h:239
AVOption.
Definition opt.h:428
const struct AVCodecTag *const * codec_tag
List of supported codec_id-codec_tag pairs, ordered by "betterchoice first".
Definition avformat.h:554
const AVClass * priv_class
AVClass for the private context.
Definition avformat.h:557
This structure stores auxiliary information for decoding, presenting, or otherwise processing the cod...
Definition packet.h:431
uint8_t * data
Definition packet.h:432
This structure stores compressed data.
Definition packet.h:587
int num
Numerator.
Definition rational.h:59
int den
Denominator.
Definition rational.h:60
Stream structure.
Definition avformat.h:768
AVCodecParameters * codecpar
Codec parameters associated with this stream.
Definition avformat.h:791
AVRational sample_aspect_ratio
sample aspect ratio (0 if unknown)
Definition avformat.h:846
AVDictionary * metadata
Definition avformat.h:848
int id
Format-specific stream ID.
Definition avformat.h:780
int index
stream index in AVFormatContext
Definition avformat.h:774
int pts_wrap_bits
Number of bits in timestamps.
Definition avformat.h:911
AVRational avg_frame_rate
Average framerate.
Definition avformat.h:857
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented.
Definition avformat.h:807
const char * instreamid
Definition hlsenc.c:200
const char * language
Definition hlsenc.c:201
const char * ccgroup
Definition hlsenc.c:199
char * master_pl_name
Definition hlsenc.c:258
unsigned int nb_ccstreams
Definition hlsenc.c:251
char * cc_stream_map
Definition hlsenc.c:257
uint32_t pl_type
Definition hlsenc.c:214
char * method
Definition hlsenc.c:245
char * segment_filename
Definition hlsenc.c:215
int has_video_m3u8
Definition hlsenc.c:268
ClosedCaptionsStream * cc_streams
Definition hlsenc.c:250
int hls_delete_threshold
Definition hlsenc.c:212
AVDictionary * format_options
Definition hlsenc.c:229
int ignore_io_errors
Definition hlsenc.c:265
char * subtitle_filename
Definition hlsenc.c:228
int encrypt_started
Definition hlsenc.c:236
unsigned int master_publish_rate
Definition hlsenc.c:259
char * iv
Definition hlsenc.c:234
char * master_m3u8_url
Definition hlsenc.c:254
char * key_info_file
Definition hlsenc.c:238
char * user_agent
Definition hlsenc.c:246
uint32_t flags
Definition hlsenc.c:213
char * key_basename
Definition hlsenc.c:235
int has_default_key
Definition hlsenc.c:267
char * headers
Definition hlsenc.c:266
int http_persistent
Definition hls.c:289
VariantStream * var_streams
Definition hlsenc.c:248
uint32_t start_sequence_source_type
Definition hlsenc.c:207
AVIOContext * sub_m3u8_out
Definition hlsenc.c:262
char key_string[KEYSIZE *2+1]
Definition hlsenc.c:241
int version
Definition hlsenc.c:255
char * fmp4_init_filename
Definition hlsenc.c:216
int max_nb_segments
Definition hlsenc.c:211
char * var_stream_map
Definition hlsenc.c:256
int segment_type
Definition hlsenc.c:217
char key_uri[LINE_BUFFER_SIZE+1]
Definition hlsenc.c:240
int use_localtime_mkdir
flag to mkdir dirname in timebased filename
Definition hlsenc.c:221
AVIOContext * m3u8_out
Definition hlsenc.c:261
char * vtt_format_options_str
Definition hlsenc.c:227
int64_t timeout
Definition hlsenc.c:264
int use_localtime
flag to expand filename with localtime
Definition hlsenc.c:220
int64_t init_time
Definition hlsenc.c:210
AVIOContext * http_delete
Definition hlsenc.c:263
int64_t time
Definition hlsenc.c:209
char * key_url
Definition hlsenc.c:233
int64_t max_seg_size
Definition hlsenc.c:224
int64_t start_sequence
Definition hlsenc.c:206
unsigned int nb_varstreams
Definition hlsenc.c:249
int resend_init_file
resend init file into disk after refresh m3u8
Definition hlsenc.c:218
int allowcache
Definition hlsenc.c:222
char * baseurl
Definition hlsenc.c:226
char * key
Definition hlsenc.c:232
int64_t recording_time
Definition hlsenc.c:223
char iv_string[KEYSIZE *2+1]
Definition hlsenc.c:242
AVDictionary * vtt_format_options
Definition hlsenc.c:243
char key_file[LINE_BUFFER_SIZE+1]
Definition hlsenc.c:239
int encrypt
Definition hlsenc.c:231
int master_m3u8_created
Definition hlsenc.c:253
int discont
Definition hlsenc.c:83
double discont_program_date_time
Definition hlsenc.c:92
double duration
Definition hlsenc.c:82
struct HLSSegment * next
Definition hlsenc.c:91
const char * sub_filename
Definition hlsenc.c:81
const char * filename
Definition hlsenc.c:80
char buf[]
Definition hlsenc.c:94
char iv_string[KEYSIZE *2+1]
Definition hlsenc.c:89
int64_t pos
Definition hlsenc.c:84
unsigned var_stream_idx
Definition hlsenc.c:86
const char * key_uri
Definition hlsenc.c:88
int64_t size
Definition hlsenc.c:85
int64_t moov_end
End of the initial moov atom.
Definition movenc.h:233
const char * path
Definition url.h:369
int discontinuity_set
Definition hlsenc.c:149
int discontinuity
Definition hlsenc.c:150
char * basename
Definition hlsenc.c:166
int is_default
Definition hlsenc.c:189
char key_file[LINE_BUFFER_SIZE+1]
Definition hlsenc.c:179
double initial_prog_date_time
Definition hlsenc.c:171
const char * language
Definition hlsenc.c:190
char * vtt_m3u8_name
Definition hlsenc.c:168
int start_pts_from_audio
Definition hlsenc.c:140
int64_t size
Definition hlsenc.c:147
int m3u8_created
Definition hlsenc.c:188
HLSSegment * old_segments
Definition hlsenc.c:163
char codec_attr[128]
Definition hlsenc.c:185
char * vtt_basename
Definition hlsenc.c:167
int discont_start_in_playlist
Definition hlsenc.c:153
int init_range_length
Definition hlsenc.c:130
AVIOContext * out_single_file
Definition hlsenc.c:128
unsigned int nb_streams
Definition hlsenc.c:187
int64_t sequence
Definition hlsenc.c:124
int encrypt_started
Definition hlsenc.c:177
uint8_t * init_buffer
Definition hlsenc.c:132
const char * subtitle_varname
Definition hlsenc.c:195
int has_subtitle
Definition hlsenc.c:138
int nb_entries
Definition hlsenc.c:148
const AVOutputFormat * vtt_oformat
Definition hlsenc.c:126
AVStream ** streams
Definition hlsenc.c:184
int64_t end_pts
Definition hlsenc.c:143
int reference_stream_index
Definition hlsenc.c:154
const AVOutputFormat * oformat
Definition hlsenc.c:125
char * fmp4_init_filename
Definition hlsenc.c:174
int64_t start_pos
Definition hlsenc.c:146
AVIOContext * out
Definition hlsenc.c:127
const char * agroup
Definition hlsenc.c:191
char key_string[KEYSIZE *2+1]
Definition hlsenc.c:181
int64_t start_pts
Definition hlsenc.c:142
unsigned var_stream_idx
Definition hlsenc.c:122
uint8_t * temp_buffer
Definition hlsenc.c:131
int64_t avg_bitrate
Definition hlsenc.c:158
int has_video
Definition hlsenc.c:137
int64_t discontinuity_sequence
Definition hlsenc.c:151
char key_uri[LINE_BUFFER_SIZE+1]
Definition hlsenc.c:180
int64_t total_size
Definition hlsenc.c:156
AVFormatContext * vtt_avf
Definition hlsenc.c:135
unsigned number
Definition hlsenc.c:123
const char * sgroup
Definition hlsenc.c:192
double dpp
Definition hlsenc.c:141
HLSSegment * segments
Definition hlsenc.c:161
int discontinuity_sequence_set
Definition hlsenc.c:152
const char * varname
Definition hlsenc.c:194
int new_start
Definition hlsenc.c:139
AVFormatContext * avf
Definition hlsenc.c:134
const char * ccgroup
Definition hlsenc.c:193
char * m3u8_name
Definition hlsenc.c:169
char * base_output_dirname
Definition hlsenc.c:175
int64_t max_bitrate
Definition hlsenc.c:159
CodecAttributeStatus attr_status
Definition hlsenc.c:186
char current_segment_final_filename_fmt[MAX_URL_SIZE]
Definition hlsenc.c:172
char * basename_tmp
Definition hlsenc.c:165
int packets_written
Definition hlsenc.c:129
double duration
Definition hlsenc.c:145
double total_duration
Definition hlsenc.c:157
char iv_string[KEYSIZE *2+1]
Definition hlsenc.c:182
HLSSegment * last_segment
Definition hlsenc.c:162
int64_t video_lastpos
Definition hlsenc.c:144
Definition hls.c:80
int64_t duration
Definition hls.c:81
#define lrint
Definition tablegen.h:53
#define av_free(p)
#define av_mallocz(s)
#define av_freep(p)
#define av_log(a,...)
static uint8_t tmp[40]
Definition aes_ctr.c:52
int num
Definition error.c:23
static char buffer[20]
Definition seek.c:33
int64_t av_gettime(void)
Get the current time in microseconds.
Definition time.c:40
#define localtime_r
int size
int ff_url_decompose(URLComponents *uc, const char *url, const char *end)
Parse an URL to find the components.
Definition url.c:91
unbuffered private I/O API
#define URL_COMPONENT_HAVE(uc, component)
Definition url.h:385
static int write_trailer(AVFormatContext *s1)
Definition v4l2enc.c:101
int len
static double c[64]