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