FFmpeg
Loading...
Searching...
No Matches
hls.c
Go to the documentation of this file.
1/*
2 * Apple HTTP Live Streaming demuxer
3 * Copyright (c) 2010 Martin Storsjo
4 * Copyright (c) 2013 Anssi Hannula
5 * Copyright (c) 2021 Nachiket Tarate
6 *
7 * This file is part of FFmpeg.
8 *
9 * FFmpeg is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
13 *
14 * FFmpeg is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
18 *
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with FFmpeg; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22 */
23
24/**
25 * @file
26 * Apple HTTP Live Streaming demuxer
27 * https://www.rfc-editor.org/rfc/rfc8216.txt
28 */
29
30#include "config_components.h"
31
32#include "libavformat/http.h"
33#include "libavutil/aes.h"
34#include "libavutil/avstring.h"
35#include "libavutil/avassert.h"
38#include "libavutil/mem.h"
39#include "libavutil/opt.h"
40#include "libavutil/dict.h"
41#include "libavutil/time.h"
42#include "avformat.h"
43#include "demux.h"
44#include "internal.h"
45#include "avio_internal.h"
46#include "id3v2.h"
47#include "url.h"
48
50
51#define INITIAL_BUFFER_SIZE 32768
52
53#define MAX_FIELD_LEN 64
54#define MAX_CHARACTERISTICS_LEN 512
55
56#define MPEG_TIME_BASE 90000
57#define MPEG_TIME_BASE_Q (AVRational){1, MPEG_TIME_BASE}
58
59#define PACKED_AUDIO_FORMATS "aac,ac3,eac3,mp3"
60
61/*
62 * An apple http stream consists of a playlist with media segment files,
63 * played sequentially. There may be several playlists with the same
64 * video content, in different bandwidth variants, that are played in
65 * parallel (preferably only one bandwidth variant at a time). In this case,
66 * the user supplied the url to a main playlist that only lists the variant
67 * playlists.
68 *
69 * If the main playlist doesn't point at any variants, we still create
70 * one anonymous toplevel variant for this, to maintain the structure.
71 */
72
78
79struct segment {
83 char *url;
84 char *key;
86 uint8_t iv[16];
87 /* associated Media Initialization Section, treated as a segment */
89};
90
91struct rendition;
92
98
99/*
100 * Each playlist has its own demuxer. If it currently is active,
101 * it has an open AVIOContext too, and potentially an AVPacket
102 * containing the next packet from this stream.
103 */
104struct playlist {
113 int index;
117
118 /* main demuxer streams associated with this playlist
119 * indexed by the subdemuxer stream indexes */
122
139
140 /* Currently active Media Initialization Section */
142 uint8_t *init_sec_buf;
143 unsigned int init_sec_buf_size;
144 unsigned int init_sec_data_len;
146
148 uint8_t key[16];
149
150 /* ID3 timestamp handling (elementary audio streams have ID3 timestamps
151 * (and possibly other ID3 tags) in the beginning of each segment) */
152 int is_id3_timestamped; /* -1: not yet known */
153 int64_t id3_mpegts_timestamp; /* in mpegts tb */
154 int64_t id3_offset; /* in stream original tb */
155 uint8_t* id3_buf; /* temp buffer for id3 parsing */
156 unsigned int id3_buf_size;
157 AVDictionary *id3_initial; /* data from first id3 tag */
158 int id3_found; /* ID3 tag found at some point */
159 int id3_changed; /* ID3 tag data has changed at some point */
160 ID3v2ExtraMeta *id3_deferred_extra; /* stored here until subdemuxer is opened */
161
163
164 /* Constant offset of this playlist's DTS baseline relative to
165 * c->first_timestamp. */
169 int seek_stream_index; /* into subdemuxer stream array */
170
171 /* Renditions associated with this playlist, if any.
172 * Alternative rendition playlists have a single rendition associated
173 * with them, and variant main Media Playlists may have
174 * multiple (playlist-less) renditions associated with them. */
177
178 /* Media Initialization Sections (EXT-X-MAP) associated with this
179 * playlist, if any. */
182 int is_subtitle; /* Indicates if it's a subtitle playlist */
183
184 /* Some HLS streams repeat the current timed-ID3 metadata at every segment
185 * boundary so late-joining clients get a fresh copy. Track the last seen
186 * value to avoid raising AVSTREAM_EVENT_FLAG_METADATA_UPDATED spuriously
187 * on those duplicates. timed_id3_stream_index is the subdemuxer stream
188 * index of the first timed-ID3 stream seen; -1 if none. */
191};
192
193/*
194 * Renditions are e.g. alternative subtitle or audio streams.
195 * The rendition may either be an external playlist or it may be
196 * contained in the main Media Playlist of the variant (in which case
197 * playlist is NULL).
198 */
207
208struct variant {
210
211 /* every variant contains at least the main Media Playlist in index 0 */
214
218};
219
253
255{
256 int i;
257 for (i = 0; i < n_segments; i++) {
261 }
262}
263
264static void free_segment_list(struct playlist *pls)
265{
267 av_freep(&pls->segments);
268 pls->n_segments = 0;
269}
270
271static void free_init_section_list(struct playlist *pls)
272{
273 int i;
274 for (i = 0; i < pls->n_init_sections; i++) {
275 av_freep(&pls->init_sections[i]->key);
276 av_freep(&pls->init_sections[i]->url);
277 av_freep(&pls->init_sections[i]);
278 }
279 av_freep(&pls->init_sections);
280 pls->n_init_sections = 0;
281}
282
284{
285 int i;
286 for (i = 0; i < c->n_playlists; i++) {
287 struct playlist *pls = c->playlists[i];
290 av_freep(&pls->main_streams);
291 av_freep(&pls->renditions);
292 av_freep(&pls->id3_buf);
296 av_freep(&pls->init_sec_buf);
297 av_packet_free(&pls->pkt);
298 av_freep(&pls->pb.pub.buffer);
299 ff_format_io_close(c->ctx, &pls->input);
300 pls->input_read_done = 0;
301 pls->input_reuse = 0;
302 ff_format_io_close(c->ctx, &pls->input_next);
303 pls->input_next_requested = 0;
304 if (pls->ctx) {
305 pls->ctx->pb = NULL;
307 }
308 av_free(pls);
309 }
310 av_freep(&c->playlists);
311 c->n_playlists = 0;
312}
313
315{
316 int i;
317 for (i = 0; i < c->n_variants; i++) {
318 struct variant *var = c->variants[i];
319 av_freep(&var->playlists);
320 av_free(var);
321 }
322 av_freep(&c->variants);
323 c->n_variants = 0;
324}
325
327{
328 int i;
329 for (i = 0; i < c->n_renditions; i++)
330 av_freep(&c->renditions[i]);
331 av_freep(&c->renditions);
332 c->n_renditions = 0;
333}
334
335static struct playlist *new_playlist(HLSContext *c, const char *url,
336 const char *base)
337{
338 struct playlist *pls;
339 char abs_url[MAX_URL_SIZE];
340
341 ff_make_absolute_url(abs_url, sizeof(abs_url), base, url);
342 if (!abs_url[0])
343 return NULL;
344
345 for (int i = 0; i < c->n_playlists; i++) {
346 if (!strcmp(c->playlists[i]->url, abs_url))
347 return c->playlists[i];
348 }
349
350 pls = av_mallocz(sizeof(struct playlist));
351 if (!pls)
352 return NULL;
353 pls->pkt = av_packet_alloc();
354 if (!pls->pkt) {
355 av_free(pls);
356 return NULL;
357 }
358 av_strlcpy(pls->url, abs_url, sizeof(pls->url));
361 pls->first_read_seq_no = -1;
362
363 pls->is_id3_timestamped = -1;
365 pls->timed_id3_stream_index = -1;
366
367 dynarray_add(&c->playlists, &c->n_playlists, pls);
368 return pls;
369}
370
372 char bandwidth[20];
373 /* variant group ids: */
377};
378
379static struct variant *new_variant(HLSContext *c, struct variant_info *info,
380 const char *url, const char *base)
381{
382 struct variant *var;
383 struct playlist *pls;
384
385 pls = new_playlist(c, url, base);
386 if (!pls)
387 return NULL;
388
389 var = av_mallocz(sizeof(struct variant));
390 if (!var)
391 return NULL;
392
393 if (info) {
394 var->bandwidth = atoi(info->bandwidth);
395 strcpy(var->audio_group, info->audio);
396 strcpy(var->video_group, info->video);
397 strcpy(var->subtitles_group, info->subtitles);
398 }
399
400 dynarray_add(&c->variants, &c->n_variants, var);
401 dynarray_add(&var->playlists, &var->n_playlists, pls);
402 return var;
403}
404
405static void handle_variant_args(void *context, const char *key,
406 int key_len, char **dest, int *dest_len)
407{
408 struct variant_info *info = context;
409 if (!strncmp(key, "BANDWIDTH=", key_len)) {
410 *dest = info->bandwidth;
411 *dest_len = sizeof(info->bandwidth);
412 } else if (!strncmp(key, "AUDIO=", key_len)) {
413 *dest = info->audio;
414 *dest_len = sizeof(info->audio);
415 } else if (!strncmp(key, "VIDEO=", key_len)) {
416 *dest = info->video;
417 *dest_len = sizeof(info->video);
418 } else if (!strncmp(key, "SUBTITLES=", key_len)) {
419 *dest = info->subtitles;
420 *dest_len = sizeof(info->subtitles);
421 }
422}
423
424struct key_info {
426 char method[11];
427 char iv[35];
428};
429
430static void handle_key_args(void *context, const char *key,
431 int key_len, char **dest, int *dest_len)
432{
433 struct key_info *info = context;
434 if (!strncmp(key, "METHOD=", key_len)) {
435 *dest = info->method;
436 *dest_len = sizeof(info->method);
437 } else if (!strncmp(key, "URI=", key_len)) {
438 *dest = info->uri;
439 *dest_len = sizeof(info->uri);
440 } else if (!strncmp(key, "IV=", key_len)) {
441 *dest = info->iv;
442 *dest_len = sizeof(info->iv);
443 }
444}
445
448 char byterange[32];
449};
450
451static struct segment *new_init_section(struct playlist *pls,
452 struct init_section_info *info,
453 const char *url_base)
454{
455 struct segment *sec;
456 char tmp_str[MAX_URL_SIZE], *ptr = tmp_str;
457
458 if (!info->uri[0])
459 return NULL;
460
461 sec = av_mallocz(sizeof(*sec));
462 if (!sec)
463 return NULL;
464
465 if (!av_strncasecmp(info->uri, "data:", 5)) {
466 ptr = info->uri;
467 } else {
468 ff_make_absolute_url(tmp_str, sizeof(tmp_str), url_base, info->uri);
469 if (!tmp_str[0]) {
470 av_free(sec);
471 return NULL;
472 }
473 }
474 sec->url = av_strdup(ptr);
475 if (!sec->url) {
476 av_free(sec);
477 return NULL;
478 }
479
480 if (info->byterange[0]) {
481 sec->size = strtoll(info->byterange, NULL, 10);
482 ptr = strchr(info->byterange, '@');
483 if (ptr)
484 sec->url_offset = strtoll(ptr+1, NULL, 10);
485 if (sec->size < 0 || sec->url_offset < 0 || sec->size > INT64_MAX - sec->url_offset) {
486 av_freep(&sec->url);
487 av_free(sec);
488 return NULL;
489 }
490 } else {
491 /* the entire file is the init section */
492 sec->size = -1;
493 }
494
495 dynarray_add(&pls->init_sections, &pls->n_init_sections, sec);
496
497 return sec;
498}
499
500static void handle_init_section_args(void *context, const char *key,
501 int key_len, char **dest, int *dest_len)
502{
503 struct init_section_info *info = context;
504 if (!strncmp(key, "URI=", key_len)) {
505 *dest = info->uri;
506 *dest_len = sizeof(info->uri);
507 } else if (!strncmp(key, "BYTERANGE=", key_len)) {
508 *dest = info->byterange;
509 *dest_len = sizeof(info->byterange);
510 }
511}
512
524
525static struct rendition *new_rendition(HLSContext *c, struct rendition_info *info,
526 const char *url_base)
527{
528 struct rendition *rend;
530 char *characteristic;
531 char *chr_ptr;
532 char *saveptr;
533
534 if (!strcmp(info->type, "AUDIO"))
536 else if (!strcmp(info->type, "VIDEO"))
538 else if (!strcmp(info->type, "SUBTITLES"))
540 else if (!strcmp(info->type, "CLOSED-CAPTIONS"))
541 /* CLOSED-CAPTIONS is ignored since we do not support CEA-608 CC in
542 * AVC SEI RBSP anyway */
543 return NULL;
544
545 if (type == AVMEDIA_TYPE_UNKNOWN) {
546 av_log(c->ctx, AV_LOG_WARNING, "Can't support the type: %s\n", info->type);
547 return NULL;
548 }
549
550 /* URI is mandatory for subtitles as per spec */
551 if (type == AVMEDIA_TYPE_SUBTITLE && !info->uri[0]) {
552 av_log(c->ctx, AV_LOG_ERROR, "The URI tag is REQUIRED for subtitle.\n");
553 return NULL;
554 }
555
556 rend = av_mallocz(sizeof(struct rendition));
557 if (!rend)
558 return NULL;
559
560 dynarray_add(&c->renditions, &c->n_renditions, rend);
561
562 rend->type = type;
563 strcpy(rend->group_id, info->group_id);
564 strcpy(rend->language, info->language);
565 strcpy(rend->name, info->name);
566
567 /* add the playlist if this is an external rendition */
568 if (info->uri[0]) {
569 rend->playlist = new_playlist(c, info->uri, url_base);
570 if (rend->playlist) {
572 rend->playlist->is_subtitle = 1;
573 rend->playlist->is_id3_timestamped = 0;
574 }
576 &rend->playlist->n_renditions, rend);
577 }
578 }
579
580 if (info->assoc_language[0]) {
581 size_t langlen = strlen(rend->language);
582 if (langlen < sizeof(rend->language) - 3) {
583 size_t assoc_len;
584 rend->language[langlen] = ',';
585 assoc_len = av_strlcpy(rend->language + langlen + 1,
586 info->assoc_language,
587 sizeof(rend->language) - langlen - 1);
588 if (langlen + assoc_len + 2 > sizeof(rend->language)) // truncation occurred
589 av_log(c->ctx, AV_LOG_WARNING, "Truncated rendition language: %s\n",
590 info->assoc_language);
591 }
592 }
593
594 if (!strcmp(info->defaultr, "YES"))
596 if (!strcmp(info->forced, "YES"))
598
599 chr_ptr = info->characteristics;
600 while ((characteristic = av_strtok(chr_ptr, ",", &saveptr))) {
601 if (!strcmp(characteristic, "public.accessibility.describes-music-and-sound"))
603 else if (!strcmp(characteristic, "public.accessibility.describes-video"))
605
606 chr_ptr = NULL;
607 }
608
609 return rend;
610}
611
612static void handle_rendition_args(void *vinfo, const char *key,
613 int key_len, char **dest, int *dest_len)
614{
615 struct rendition_info *info = vinfo;
616
617 if (!strncmp(key, "TYPE=", key_len)) {
618 *dest = info->type;
619 *dest_len = sizeof(info->type);
620 } else if (!strncmp(key, "URI=", key_len)) {
621 *dest = info->uri;
622 *dest_len = sizeof(info->uri);
623 } else if (!strncmp(key, "GROUP-ID=", key_len)) {
624 *dest = info->group_id;
625 *dest_len = sizeof(info->group_id);
626 } else if (!strncmp(key, "LANGUAGE=", key_len)) {
627 *dest = info->language;
628 *dest_len = sizeof(info->language);
629 } else if (!strncmp(key, "ASSOC-LANGUAGE=", key_len)) {
630 *dest = info->assoc_language;
631 *dest_len = sizeof(info->assoc_language);
632 } else if (!strncmp(key, "NAME=", key_len)) {
633 *dest = info->name;
634 *dest_len = sizeof(info->name);
635 } else if (!strncmp(key, "DEFAULT=", key_len)) {
636 *dest = info->defaultr;
637 *dest_len = sizeof(info->defaultr);
638 } else if (!strncmp(key, "FORCED=", key_len)) {
639 *dest = info->forced;
640 *dest_len = sizeof(info->forced);
641 } else if (!strncmp(key, "CHARACTERISTICS=", key_len)) {
642 *dest = info->characteristics;
643 *dest_len = sizeof(info->characteristics);
644 }
645 /*
646 * ignored:
647 * - AUTOSELECT: client may autoselect based on e.g. system language
648 * - INSTREAM-ID: EIA-608 closed caption number ("CC1".."CC4")
649 */
650}
651
652/* used by parse_playlist to allocate a new variant+playlist when the
653 * playlist is detected to be a Media Playlist (not Master Playlist)
654 * and we have no parent Master Playlist (parsing of which would have
655 * allocated the variant and playlist already)
656 * *pls == NULL => Master Playlist or parentless Media Playlist
657 * *pls != NULL => parented Media Playlist, playlist+variant allocated */
658static int ensure_playlist(HLSContext *c, struct playlist **pls, const char *url)
659{
660 if (*pls)
661 return 0;
662 struct variant *var = new_variant(c, NULL, url, NULL);
663 if (!var)
664 return AVERROR(ENOMEM);
665 *pls = var->playlists[0];
666 return 0;
667}
668
670{
671#if !CONFIG_HTTP_PROTOCOL
672 return 0;
673#else
675 return uc && !strncmp(uc->prot->name, "http", 4);
676#endif
677}
678
680 const char *url, AVDictionary **options)
681{
682#if !CONFIG_HTTP_PROTOCOL
684#else
685 int ret;
687 av_assert0(uc);
688 (*pb)->eof_reached = 0;
689 ret = ff_http_do_new_request2(uc, url, options);
690 if (ret < 0) {
692 }
693 return ret;
694#endif
695}
696
697static int open_url(AVFormatContext *s, AVIOContext **pb, const char *url,
698 AVDictionary **opts, AVDictionary *opts2, int *is_http_out)
699{
700 HLSContext *c = s->priv_data;
702 const char *proto_name = NULL;
703 int ret;
704 int is_http = 0;
705
706 if (av_strstart(url, "crypto", NULL)) {
707 if (url[6] == '+' || url[6] == ':')
708 proto_name = avio_find_protocol_name(url + 7);
709 } else if (av_strstart(url, "data", NULL)) {
710 if (url[4] == '+' || url[4] == ':')
711 proto_name = avio_find_protocol_name(url + 5);
712 }
713
714 if (!proto_name)
715 proto_name = avio_find_protocol_name(url);
716
717 if (!proto_name)
718 return AVERROR_INVALIDDATA;
719
720 // only http(s) & file are allowed
721 if (av_strstart(proto_name, "file", NULL)) {
722 if (strcmp(c->allowed_extensions, "ALL") && !av_match_ext(url, c->allowed_extensions)) {
724 "Filename extension of \'%s\' is not a common multimedia extension, blocked for security reasons.\n"
725 "If you wish to override this adjust allowed_extensions, you can set it to \'ALL\' to allow all\n",
726 url);
727 return AVERROR_INVALIDDATA;
728 }
729 } else if (av_strstart(proto_name, "http", NULL)) {
730 is_http = 1;
731 } else if (av_strstart(proto_name, "data", NULL)) {
732 ;
733 } else
734 return AVERROR_INVALIDDATA;
735
736 if (!strncmp(proto_name, url, strlen(proto_name)) && url[strlen(proto_name)] == ':')
737 ;
738 else if (av_strstart(url, "crypto", NULL) && !strncmp(proto_name, url + 7, strlen(proto_name)) && url[7 + strlen(proto_name)] == ':')
739 ;
740 else if (av_strstart(url, "data", NULL) && !strncmp(proto_name, url + 5, strlen(proto_name)) && url[5 + strlen(proto_name)] == ':')
741 ;
742 else if (strcmp(proto_name, "file") || !strncmp(url, "file,", 5))
743 return AVERROR_INVALIDDATA;
744
745 av_dict_copy(&tmp, *opts, 0);
746 av_dict_copy(&tmp, opts2, 0);
747
748 if (is_http && c->http_persistent && is_native_http(*pb)) {
749 ret = open_url_keepalive(c->ctx, pb, url, &tmp);
750 if (ret == AVERROR_EXIT) {
752 return ret;
753 } else if (ret < 0) {
754 if (ret != AVERROR_EOF)
756 "keepalive request failed for '%s' with error: '%s' when opening url, retrying with new connection\n",
757 url, av_err2str(ret));
758 av_dict_copy(&tmp, *opts, 0);
759 av_dict_copy(&tmp, opts2, 0);
760 ret = s->io_open(s, pb, url, AVIO_FLAG_READ, &tmp);
761 }
762 } else {
763 av_assert0(!*pb);
764 ret = s->io_open(s, pb, url, AVIO_FLAG_READ, &tmp);
765 }
766 if (ret >= 0) {
767 // update cookies on http response with setcookies.
768 char *new_cookies = NULL;
769
770 if (!(s->flags & AVFMT_FLAG_CUSTOM_IO))
771 av_opt_get(*pb, "cookies", AV_OPT_SEARCH_CHILDREN, (uint8_t**)&new_cookies);
772
773 if (new_cookies)
774 av_dict_set(opts, "cookies", new_cookies, AV_DICT_DONT_STRDUP_VAL);
775 }
776
778
779 if (is_http_out)
780 *is_http_out = is_http;
781
782 return ret;
783}
784
785static int test_segment(AVFormatContext *s, const AVInputFormat *in_fmt, struct playlist *pls, struct segment *seg)
786{
787 HLSContext *c = s->priv_data;
788 int matchA = 3;
789 int matchF = 0;
790
791 if (!c->extension_picky)
792 return 0;
793
794 if (strcmp(c->allowed_segment_extensions, "ALL"))
795 matchA = av_match_ext (seg->url, c->allowed_segment_extensions)
796 + 2*(ff_match_url_ext(seg->url, c->allowed_segment_extensions) > 0);
797
798 if (!matchA) {
799 av_log(s, AV_LOG_ERROR, "URL %s is not in allowed_segment_extensions, consider updating hls.c and submitting a patch to ffmpeg-devel, if this should be added\n", seg->url);
800 return AVERROR_INVALIDDATA;
801 }
802
803 if (in_fmt) {
804 if (in_fmt->extensions) {
805 matchF = av_match_ext( seg->url, in_fmt->extensions)
806 + 2*(ff_match_url_ext(seg->url, in_fmt->extensions) > 0);
807 // Youtube uses aac files with .ts extension
808 if(av_match_name("mp4", in_fmt->name) || av_match_name("aac", in_fmt->name)) {
809 matchF |= av_match_ext( seg->url, "ts,m2t,m2ts,mts,mpg,m4s,mpeg,mpegts,cmfv,cmfa")
810 + 2*(ff_match_url_ext(seg->url, "ts,m2t,m2ts,mts,mpg,m4s,mpeg,mpegts,cmfv,cmfa") > 0);
811 }
812 } else if (!strcmp(in_fmt->name, "mpegts")) {
813 const char *str = "ts,m2t,m2ts,mts,mpg,m4s,mpeg,mpegts"
814 ",html" // https://flash1.bogulus.cfd/
815 ;
816 matchF = av_match_ext( seg->url, str)
817 + 2*(ff_match_url_ext(seg->url, str) > 0);
818 } else if (!strcmp(in_fmt->name, "webvtt")) {
819 matchF = av_match_ext( seg->url, "vtt,webvtt")
820 + 2*(ff_match_url_ext(seg->url, "vtt,webvtt") > 0);
821 }
822
823 if (!(matchA & matchF)) {
824 av_log(s, AV_LOG_ERROR, "detected format %s extension %s mismatches allowed extensions in url %s\n", in_fmt->name, in_fmt->extensions ? in_fmt->extensions : "none", seg->url);
825 return AVERROR_INVALIDDATA;
826 }
827 }
828
829 return 0;
830}
831
832static int parse_playlist(HLSContext *c, const char *url,
833 struct playlist *pls, AVIOContext *in)
834{
835 int ret = 0, is_segment = 0, is_variant = 0;
836 int64_t duration = 0;
837 enum KeyType key_type = KEY_NONE;
838 uint8_t iv[16] = "";
839 int has_iv = 0;
840 char key[MAX_URL_SIZE] = "";
841 char line[MAX_URL_SIZE];
842 const char *ptr;
843 int close_in = 0;
844 int64_t seg_offset = 0;
845 int64_t seg_size = -1;
846 uint8_t *new_url = NULL;
848 char tmp_str[MAX_URL_SIZE];
849 struct segment *cur_init_section = NULL;
850 int is_http = av_strstart(url, "http", NULL);
851 struct segment **prev_segments = NULL;
852 int prev_n_segments = 0;
853 int64_t prev_start_seq_no = -1;
854 int64_t load_start = av_gettime_relative();
855
856 if (is_http && !in && c->http_persistent && c->playlist_pb) {
857 in = c->playlist_pb;
858 ret = open_url_keepalive(c->ctx, &c->playlist_pb, url, NULL);
859 if (ret == AVERROR_EXIT) {
860 return ret;
861 } else if (ret < 0) {
862 if (ret != AVERROR_EOF)
863 av_log(c->ctx, AV_LOG_WARNING,
864 "keepalive request failed for '%s' with error: '%s' when parsing playlist\n",
865 url, av_err2str(ret));
866 in = NULL;
867 }
868 }
869
870 if (!in) {
872 av_dict_copy(&opts, c->avio_opts, 0);
873
874 if (c->http_persistent)
875 av_dict_set(&opts, "multiple_requests", "1", 0);
876
877 ret = open_url(c->ctx, &in, url, &opts, NULL, NULL);
879 if (ret < 0)
880 return ret;
881
882 if (is_http && c->http_persistent && is_native_http(in))
883 c->playlist_pb = in;
884 else
885 close_in = 1;
886 }
887
888 if (av_opt_get(in, "location", AV_OPT_SEARCH_CHILDREN, &new_url) >= 0)
889 url = new_url;
890
891 ff_get_chomp_line(in, line, sizeof(line));
892 if (strcmp(line, "#EXTM3U")) {
894 goto fail;
895 }
896
897 if (pls) {
898 prev_start_seq_no = pls->start_seq_no;
899 prev_segments = pls->segments;
900 prev_n_segments = pls->n_segments;
901 pls->segments = NULL;
902 pls->n_segments = 0;
903
904 pls->finished = 0;
906 }
907 while (!avio_feof(in)) {
908 ff_get_chomp_line(in, line, sizeof(line));
909 if (av_strstart(line, "#EXT-X-STREAM-INF:", &ptr)) {
910 if (pls) {
911 av_log(c->ctx, AV_LOG_ERROR,
912 "Master Playlist tag found in a Media Playlist\n");
914 goto fail;
915 }
916 is_variant = 1;
917 memset(&variant_info, 0, sizeof(variant_info));
919 } else if (av_strstart(line, "#EXT-X-KEY:", &ptr)) {
920 struct key_info info = {{0}};
922 key_type = KEY_NONE;
923 has_iv = 0;
924 if (!strcmp(info.method, "AES-128"))
925 key_type = KEY_AES_128;
926 if (!strcmp(info.method, "SAMPLE-AES"))
927 key_type = KEY_SAMPLE_AES;
928 if (!av_strncasecmp(info.iv, "0x", 2)) {
929 ff_hex_to_data(iv, info.iv + 2);
930 has_iv = 1;
931 }
932 av_strlcpy(key, info.uri, sizeof(key));
933 } else if (av_strstart(line, "#EXT-X-MEDIA:", &ptr)) {
934 struct rendition_info info = {{0}};
935 if (pls) {
936 av_log(c->ctx, AV_LOG_ERROR,
937 "Master Playlist tag found in a Media Playlist\n");
939 goto fail;
940 }
942 new_rendition(c, &info, url);
943 } else if (av_strstart(line, "#EXT-X-TARGETDURATION:", &ptr)) {
944 int64_t t;
945 ret = ensure_playlist(c, &pls, url);
946 if (ret < 0)
947 goto fail;
948 t = strtoll(ptr, NULL, 10);
949 if (t < 0 || t >= INT64_MAX / AV_TIME_BASE) {
951 goto fail;
952 }
953 pls->target_duration = t * AV_TIME_BASE;
954 } else if (av_strstart(line, "#EXT-X-MEDIA-SEQUENCE:", &ptr)) {
955 uint64_t seq_no;
956 ret = ensure_playlist(c, &pls, url);
957 if (ret < 0)
958 goto fail;
959 seq_no = strtoull(ptr, NULL, 10);
960 if (seq_no > INT64_MAX/2) {
961 av_log(c->ctx, AV_LOG_DEBUG, "MEDIA-SEQUENCE higher than "
962 "INT64_MAX/2, mask out the highest bit\n");
963 seq_no &= INT64_MAX/2;
964 }
965 pls->start_seq_no = seq_no;
966 } else if (av_strstart(line, "#EXT-X-PLAYLIST-TYPE:", &ptr)) {
967 ret = ensure_playlist(c, &pls, url);
968 if (ret < 0)
969 goto fail;
970 if (!strcmp(ptr, "EVENT"))
971 pls->type = PLS_TYPE_EVENT;
972 else if (!strcmp(ptr, "VOD"))
973 pls->type = PLS_TYPE_VOD;
974 } else if (av_strstart(line, "#EXT-X-MAP:", &ptr)) {
975 struct init_section_info info = {{0}};
976 ret = ensure_playlist(c, &pls, url);
977 if (ret < 0)
978 goto fail;
980 cur_init_section = new_init_section(pls, &info, url);
981 if (!cur_init_section) {
982 ret = AVERROR(ENOMEM);
983 goto fail;
984 }
985 cur_init_section->key_type = key_type;
986 if (has_iv) {
987 memcpy(cur_init_section->iv, iv, sizeof(iv));
988 } else {
989 int64_t seq = pls->start_seq_no + pls->n_segments;
990 memset(cur_init_section->iv, 0, sizeof(cur_init_section->iv));
991 AV_WB64(cur_init_section->iv + 8, seq);
992 }
993
994 if (key_type != KEY_NONE) {
995 ff_make_absolute_url(tmp_str, sizeof(tmp_str), url, key);
996 if (!tmp_str[0]) {
997 av_free(cur_init_section);
999 goto fail;
1000 }
1001 cur_init_section->key = av_strdup(tmp_str);
1002 if (!cur_init_section->key) {
1003 av_free(cur_init_section);
1004 ret = AVERROR(ENOMEM);
1005 goto fail;
1006 }
1007 } else {
1008 cur_init_section->key = NULL;
1009 }
1010
1011 } else if (av_strstart(line, "#EXT-X-START:", &ptr)) {
1012 const char *time_offset_value = NULL;
1013 ret = ensure_playlist(c, &pls, url);
1014 if (ret < 0) {
1015 goto fail;
1016 }
1017 if (av_strstart(ptr, "TIME-OFFSET=", &time_offset_value)) {
1018 double offset = strtod(time_offset_value, NULL) * AV_TIME_BASE;
1019 if (offset >= -0x1p63 && offset < 0x1p63) {
1021 pls->time_offset_flag = 1;
1022 } else {
1023 av_log(c->ctx, AV_LOG_WARNING, "TIME-OFFSET value is"
1024 "invalid, it will be ignored");
1025 }
1026 } else {
1027 av_log(c->ctx, AV_LOG_WARNING, "#EXT-X-START value is"
1028 "invalid, it will be ignored");
1029 continue;
1030 }
1031 } else if (av_strstart(line, "#EXT-X-ENDLIST", &ptr)) {
1032 if (pls)
1033 pls->finished = 1;
1034 } else if (av_strstart(line, "#EXTINF:", &ptr)) {
1035 double d = atof(ptr) * AV_TIME_BASE;
1036 if (d < 0 || d > INT64_MAX || isnan(d)) {
1037 av_log(c->ctx, AV_LOG_WARNING, "EXTINF %f unsupported\n", d / AV_TIME_BASE);
1038 d = 0;
1039 }
1040 duration = d;
1041 is_segment = 1;
1042 } else if (av_strstart(line, "#EXT-X-BYTERANGE:", &ptr)) {
1043 seg_size = strtoll(ptr, NULL, 10);
1044 ptr = strchr(ptr, '@');
1045 if (ptr)
1046 seg_offset = strtoll(ptr+1, NULL, 10);
1047 if (seg_size < 0 || seg_offset > INT64_MAX - seg_size) {
1048 ret = AVERROR_INVALIDDATA;
1049 goto fail;
1050 }
1051 } else if (av_strstart(line, "#", NULL)) {
1052 av_log(c->ctx, AV_LOG_VERBOSE, "Skip ('%s')\n", line);
1053 continue;
1054 } else if (line[0]) {
1055 if (is_variant) {
1056 if (!new_variant(c, &variant_info, line, url)) {
1057 ret = AVERROR(ENOMEM);
1058 goto fail;
1059 }
1060 is_variant = 0;
1061 }
1062 if (is_segment) {
1063 struct segment *seg;
1064 ret = ensure_playlist(c, &pls, url);
1065 if (ret < 0)
1066 goto fail;
1067 seg = av_malloc(sizeof(struct segment));
1068 if (!seg) {
1069 ret = AVERROR(ENOMEM);
1070 goto fail;
1071 }
1072 if (has_iv) {
1073 memcpy(seg->iv, iv, sizeof(iv));
1074 } else {
1075 uint64_t seq = pls->start_seq_no + (uint64_t)pls->n_segments;
1076 memset(seg->iv, 0, sizeof(seg->iv));
1077 AV_WB64(seg->iv + 8, seq);
1078 }
1079
1080 if (key_type != KEY_NONE) {
1081 ff_make_absolute_url(tmp_str, sizeof(tmp_str), url, key);
1082 if (!tmp_str[0]) {
1083 ret = AVERROR_INVALIDDATA;
1084 av_free(seg);
1085 goto fail;
1086 }
1087 seg->key = av_strdup(tmp_str);
1088 if (!seg->key) {
1089 av_free(seg);
1090 ret = AVERROR(ENOMEM);
1091 goto fail;
1092 }
1093 } else {
1094 seg->key = NULL;
1095 }
1096
1097 ff_make_absolute_url(tmp_str, sizeof(tmp_str), url, line);
1098 if (!tmp_str[0]) {
1099 ret = AVERROR_INVALIDDATA;
1100 if (seg->key)
1101 av_free(seg->key);
1102 av_free(seg);
1103 goto fail;
1104 }
1105 seg->url = av_strdup(tmp_str);
1106 if (!seg->url) {
1107 av_free(seg->key);
1108 av_free(seg);
1109 ret = AVERROR(ENOMEM);
1110 goto fail;
1111 }
1112
1113 ret = test_segment(c->ctx, pls->ctx ? pls->ctx->iformat : NULL, pls, seg);
1114 if (ret < 0) {
1115 av_free(seg->url);
1116 av_free(seg->key);
1117 av_free(seg);
1118 goto fail;
1119 }
1120
1121 if (duration < 0.001 * AV_TIME_BASE) {
1122 av_log(c->ctx, AV_LOG_WARNING, "Cannot get correct #EXTINF value of segment %s,"
1123 " set to default value to 1ms.\n", seg->url);
1124 duration = 0.001 * AV_TIME_BASE;
1125 }
1126 seg->duration = duration;
1127 seg->key_type = key_type;
1128 dynarray_add(&pls->segments, &pls->n_segments, seg);
1129 is_segment = 0;
1130
1131 seg->size = seg_size;
1132 if (seg_size >= 0) {
1133 seg->url_offset = seg_offset;
1134 seg_offset += seg_size;
1135 seg_size = -1;
1136 } else {
1137 seg->url_offset = 0;
1138 seg_offset = 0;
1139 }
1140
1141 seg->init_section = cur_init_section;
1142 }
1143 }
1144 }
1145 if (prev_segments) {
1146 if (pls->start_seq_no > prev_start_seq_no && c->first_timestamp != AV_NOPTS_VALUE &&
1147 c->first_timestamp_pls == pls) {
1148 int64_t prev_timestamp = c->first_timestamp;
1149 int i;
1150 int64_t diff = pls->start_seq_no - prev_start_seq_no;
1151 for (i = 0; i < prev_n_segments && i < diff; i++) {
1152 c->first_timestamp += prev_segments[i]->duration;
1153 }
1154 av_log(c->ctx, AV_LOG_DEBUG, "Media sequence change (%"PRId64" -> %"PRId64")"
1155 " reflected in first_timestamp: %"PRId64" -> %"PRId64"\n",
1156 prev_start_seq_no, pls->start_seq_no,
1157 prev_timestamp, c->first_timestamp);
1158 } else if (pls->start_seq_no < prev_start_seq_no) {
1159 av_log(c->ctx, AV_LOG_WARNING, "Media sequence changed unexpectedly: %"PRId64" -> %"PRId64"\n",
1160 prev_start_seq_no, pls->start_seq_no);
1161 }
1162 }
1163
1164fail:
1165 free_segment_dynarray(prev_segments, prev_n_segments);
1166 av_freep(&prev_segments);
1167 if (pls)
1168 pls->last_load_time = load_start;
1169 av_free(new_url);
1170 if (close_in)
1171 ff_format_io_close(c->ctx, &in);
1172 c->ctx->ctx_flags = c->ctx->ctx_flags & ~(unsigned)AVFMTCTX_UNSEEKABLE;
1173 if (!c->n_variants || !c->variants[0]->n_playlists ||
1174 !c->variants[0]->playlists[0]->n_segments)
1175 c->ctx->ctx_flags |= AVFMTCTX_UNSEEKABLE;
1176
1177 if (c->n_variants && c->variants[0]->n_playlists &&
1178 c->variants[0]->playlists[0]->type == PLS_TYPE_EVENT &&
1179 !c->variants[0]->playlists[0]->finished) {
1180 struct playlist *p = c->variants[0]->playlists[0];
1181 int64_t duration = 0;
1182 for (int i = 0; i < p->n_segments; i++)
1183 duration += p->segments[i]->duration;
1184 c->ctx->duration = duration;
1185 }
1186
1187 return ret;
1188}
1189
1190static struct segment *current_segment(struct playlist *pls)
1191{
1192 int64_t n = pls->cur_seq_no - pls->start_seq_no;
1193 if (n >= pls->n_segments)
1194 return NULL;
1195 return pls->segments[n];
1196}
1197
1198static struct segment *next_segment(struct playlist *pls)
1199{
1200 int64_t n = pls->cur_seq_no - pls->start_seq_no + 1;
1201 if (n >= pls->n_segments)
1202 return NULL;
1203 return pls->segments[n];
1204}
1205
1206/* True if 'next' can be reached by seeking the open 'in' instead of reopening.
1207 * An unencrypted, contiguous byte range directly following 'cur' in the same
1208 * seekable resource (i.e. consecutive EXT-X-BYTERANGE segments). */
1209static int segment_reusable(AVIOContext *in, const struct segment *cur,
1210 const struct segment *next)
1211{
1212 return in && cur && next &&
1214 cur->size >= 0 && next->size >= 0 &&
1215 next->url_offset == cur->url_offset + cur->size &&
1216 cur->key_type == KEY_NONE && next->key_type == KEY_NONE &&
1217 next->init_section == cur->init_section &&
1218 !strcmp(next->url, cur->url);
1219}
1220
1221static int read_from_url(struct playlist *pls, struct segment *seg,
1222 uint8_t *buf, int buf_size)
1223{
1224 int ret;
1225
1226 /* limit read if the segment was only a part of a file */
1227 if (seg->size >= 0)
1228 buf_size = FFMIN(buf_size, seg->size - pls->cur_seg_offset);
1229
1230 ret = avio_read(pls->input, buf, buf_size);
1231 if (ret > 0)
1232 pls->cur_seg_offset += ret;
1233
1234 return ret;
1235}
1236
1237/* Parse the raw ID3 data and pass contents to caller */
1239 AVDictionary **metadata, int64_t *dts, HLSAudioSetupInfo *audio_setup_info,
1240 ID3v2ExtraMetaAPIC **apic, ID3v2ExtraMeta **extra_meta)
1241{
1242 static const char id3_priv_owner_ts[] = "com.apple.streaming.transportStreamTimestamp";
1243 static const char id3_priv_owner_audio_setup[] = "com.apple.streaming.audioDescription";
1244 ID3v2ExtraMeta *meta;
1245
1247 for (meta = *extra_meta; meta; meta = meta->next) {
1248 if (!strcmp(meta->tag, "PRIV")) {
1249 ID3v2ExtraMetaPRIV *priv = &meta->data.priv;
1250 if (priv->datasize == 8 && !av_strncasecmp(priv->owner, id3_priv_owner_ts, 44)) {
1251 /* 33-bit MPEG timestamp */
1252 int64_t ts = AV_RB64(priv->data);
1253 av_log(s, AV_LOG_DEBUG, "HLS ID3 audio timestamp %"PRId64"\n", ts);
1254 if ((ts & ~((1ULL << 33) - 1)) == 0)
1255 *dts = ts;
1256 else
1257 av_log(s, AV_LOG_ERROR, "Invalid HLS ID3 audio timestamp %"PRId64"\n", ts);
1258 } else if (priv->datasize >= 8 && !av_strncasecmp(priv->owner, id3_priv_owner_audio_setup, 36)) {
1259 ff_hls_senc_read_audio_setup_info(audio_setup_info, priv->data, priv->datasize);
1260 }
1261 } else if (!strcmp(meta->tag, "APIC") && apic)
1262 *apic = &meta->data.apic;
1263 }
1264}
1265
1266/* Check if the ID3 metadata contents have changed */
1268 ID3v2ExtraMetaAPIC *apic)
1269{
1270 const AVDictionaryEntry *entry = NULL;
1271 const AVDictionaryEntry *oldentry;
1272 /* check that no keys have changed values */
1273 while ((entry = av_dict_iterate(metadata, entry))) {
1274 oldentry = av_dict_get(pls->id3_initial, entry->key, NULL, AV_DICT_MATCH_CASE);
1275 if (!oldentry || strcmp(oldentry->value, entry->value) != 0)
1276 return 1;
1277 }
1278
1279 /* check if apic appeared */
1280 if (apic && (pls->ctx->nb_streams != 2 || !pls->ctx->streams[1]->attached_pic.data))
1281 return 1;
1282
1283 if (apic) {
1284 int size = pls->ctx->streams[1]->attached_pic.size;
1285 if (size != apic->buf->size - AV_INPUT_BUFFER_PADDING_SIZE)
1286 return 1;
1287
1288 if (memcmp(apic->buf->data, pls->ctx->streams[1]->attached_pic.data, size) != 0)
1289 return 1;
1290 }
1291
1292 return 0;
1293}
1294
1295/* Parse ID3 data and handle the found data */
1296static void handle_id3(AVIOContext *pb, struct playlist *pls)
1297{
1299 ID3v2ExtraMetaAPIC *apic = NULL;
1300 ID3v2ExtraMeta *extra_meta = NULL;
1301 int64_t timestamp = AV_NOPTS_VALUE;
1302
1303 parse_id3(pls->ctx, pb, &metadata, &timestamp, &pls->audio_setup_info, &apic, &extra_meta);
1304
1305 if (timestamp != AV_NOPTS_VALUE) {
1306 pls->id3_mpegts_timestamp = timestamp;
1307 pls->id3_offset = 0;
1308 }
1309
1310 if (!pls->id3_found) {
1311 /* initial ID3 tags */
1313 pls->id3_found = 1;
1314
1315 /* get picture attachment and set text metadata */
1316 if (pls->ctx->nb_streams) {
1318 ff_id3v2_parse_apic(pls->ctx, extra_meta);
1319 } else
1320 /* demuxer not yet opened, defer picture attachment */
1321 pls->id3_deferred_extra = extra_meta;
1322
1323 ff_id3v2_parse_priv_dict(&metadata, extra_meta);
1324 av_dict_copy(&pls->ctx->metadata, metadata, 0);
1325 pls->id3_initial = metadata;
1326
1327 } else {
1328 if (!pls->id3_changed && id3_has_changed_values(pls, metadata, apic)) {
1329 avpriv_report_missing_feature(pls->parent, "Changing ID3 metadata in HLS audio elementary stream");
1330 pls->id3_changed = 1;
1331 }
1333 }
1334
1335 if (pls->id3_deferred_extra != extra_meta)
1336 ff_id3v2_free_extra_meta(&extra_meta);
1337}
1338
1339static void intercept_id3(struct playlist *pls, uint8_t *buf,
1340 int buf_size, int *len)
1341{
1342 /* intercept id3 tags, we do not want to pass them to the raw
1343 * demuxer on all segment switches */
1344 int bytes;
1345 int id3_buf_pos = 0;
1346 int fill_buf = 0;
1347 struct segment *seg = current_segment(pls);
1348
1349 /* gather all the id3 tags */
1350 while (1) {
1351 /* see if we can retrieve enough data for ID3 header */
1353 bytes = read_from_url(pls, seg, buf + *len, ID3v2_HEADER_SIZE - *len);
1354 if (bytes > 0) {
1355
1356 if (bytes == ID3v2_HEADER_SIZE - *len)
1357 /* no EOF yet, so fill the caller buffer again after
1358 * we have stripped the ID3 tags */
1359 fill_buf = 1;
1360
1361 *len += bytes;
1362
1363 } else if (*len <= 0) {
1364 /* error/EOF */
1365 *len = bytes;
1366 fill_buf = 0;
1367 }
1368 }
1369
1370 if (*len < ID3v2_HEADER_SIZE)
1371 break;
1372
1374 int64_t maxsize = seg->size >= 0 ? seg->size : 1024*1024;
1375 int taglen = ff_id3v2_tag_len(buf);
1376 int tag_got_bytes = FFMIN(taglen, *len);
1377 int remaining = taglen - tag_got_bytes;
1378
1379 if (taglen > maxsize) {
1380 av_log(pls->parent, AV_LOG_ERROR, "Too large HLS ID3 tag (%d > %"PRId64" bytes)\n",
1381 taglen, maxsize);
1382 break;
1383 }
1384
1385 /*
1386 * Copy the id3 tag to our temporary id3 buffer.
1387 * We could read a small id3 tag directly without memcpy, but
1388 * we would still need to copy the large tags, and handling
1389 * both of those cases together with the possibility for multiple
1390 * tags would make the handling a bit complex.
1391 */
1392 pls->id3_buf = av_fast_realloc(pls->id3_buf, &pls->id3_buf_size, id3_buf_pos + taglen);
1393 if (!pls->id3_buf)
1394 break;
1395 memcpy(pls->id3_buf + id3_buf_pos, buf, tag_got_bytes);
1396 id3_buf_pos += tag_got_bytes;
1397
1398 /* strip the intercepted bytes */
1399 *len -= tag_got_bytes;
1400 memmove(buf, buf + tag_got_bytes, *len);
1401 av_log(pls->parent, AV_LOG_DEBUG, "Stripped %d HLS ID3 bytes\n", tag_got_bytes);
1402
1403 if (remaining > 0) {
1404 /* read the rest of the tag in */
1405 if (read_from_url(pls, seg, pls->id3_buf + id3_buf_pos, remaining) != remaining)
1406 break;
1407 id3_buf_pos += remaining;
1408 av_log(pls->parent, AV_LOG_DEBUG, "Stripped additional %d HLS ID3 bytes\n", remaining);
1409 }
1410
1411 } else {
1412 /* no more ID3 tags */
1413 break;
1414 }
1415 }
1416
1417 /* re-fill buffer for the caller unless EOF */
1418 if (*len >= 0 && (fill_buf || *len == 0)) {
1419 bytes = read_from_url(pls, seg, buf + *len, buf_size - *len);
1420
1421 /* ignore error if we already had some data */
1422 if (bytes >= 0)
1423 *len += bytes;
1424 else if (*len == 0)
1425 *len = bytes;
1426 }
1427
1428 if (pls->id3_buf) {
1429 /* Now parse all the ID3 tags */
1430 FFIOContext id3ioctx;
1431 ffio_init_read_context(&id3ioctx, pls->id3_buf, id3_buf_pos);
1432 handle_id3(&id3ioctx.pub, pls);
1433 }
1434
1435 if (pls->is_id3_timestamped == -1)
1437}
1438
1439static int read_key(HLSContext *c, struct playlist *pls, struct segment *seg)
1440{
1441 AVIOContext *pb = NULL;
1442
1443 int ret = open_url(pls->parent, &pb, seg->key, &c->avio_opts, NULL, NULL);
1444 if (ret < 0) {
1445 av_log(pls->parent, AV_LOG_ERROR, "Unable to open key file %s, %s\n",
1446 seg->key, av_err2str(ret));
1447 return ret;
1448 }
1449
1450 ret = avio_read(pb, pls->key, sizeof(pls->key));
1451 ff_format_io_close(pls->parent, &pb);
1452 if (ret != sizeof(pls->key)) {
1453 if (ret < 0) {
1454 av_log(pls->parent, AV_LOG_ERROR, "Unable to read key file %s, %s\n",
1455 seg->key, av_err2str(ret));
1456 } else {
1457 av_log(pls->parent, AV_LOG_ERROR, "Unable to read key file %s, read bytes %d != %zu\n",
1458 seg->key, ret, sizeof(pls->key));
1459 ret = AVERROR_INVALIDDATA;
1460 }
1461
1462 return ret;
1463 }
1464
1465 av_strlcpy(pls->key_url, seg->key, sizeof(pls->key_url));
1466
1467 return 0;
1468}
1469
1470static int open_input(HLSContext *c, struct playlist *pls, struct segment *seg, AVIOContext **in)
1471{
1473 int ret;
1474 int is_http = 0;
1475
1476 /* Reuse a kept-open connection to the same resource by seeking instead of
1477 * reopening. For contiguous ranges the seek is a no-op and issues no request. */
1478 if (*in && pls->input_reuse && seg->key_type == KEY_NONE &&
1479 ((*in)->seekable & AVIO_SEEKABLE_NORMAL)) {
1480 int64_t seek_ret = avio_seek(*in, seg->url_offset, SEEK_SET);
1481 pls->input_reuse = 0;
1482 if (seek_ret >= 0) {
1484 "HLS reusing connection for url '%s', offset %"PRId64", playlist %d\n",
1485 seg->url, seg->url_offset, pls->index);
1486 pls->input_read_done = 0;
1487 pls->cur_seg_offset = 0;
1488 return 0;
1489 }
1490 /* Seek failed: drop the connection and reopen. */
1491 ff_format_io_close(pls->parent, in);
1492 }
1493 pls->input_reuse = 0;
1494
1495 if (c->http_persistent)
1496 av_dict_set(&opts, "multiple_requests", "1", 0);
1497
1498 if (seg->size >= 0) {
1499 /* Restrict the request to the wanted byte range. The end is extended
1500 * across following contiguous segments of the same resource so one
1501 * connection serves the whole run. */
1502 int64_t end_offset = seg->url_offset + seg->size;
1503 if (seg == current_segment(pls)) {
1504 int64_t n = pls->cur_seq_no - pls->start_seq_no + 1;
1505 while (n < pls->n_segments) {
1506 struct segment *ns = pls->segments[n];
1507 if (ns->size < 0 || ns->url_offset != end_offset ||
1508 ns->key_type != KEY_NONE ||
1509 ns->init_section != seg->init_section ||
1510 strcmp(ns->url, seg->url))
1511 break;
1512 end_offset = ns->url_offset + ns->size;
1513 n++;
1514 }
1515 }
1516 av_dict_set_int(&opts, "offset", seg->url_offset, 0);
1517 av_dict_set_int(&opts, "end_offset", end_offset, 0);
1518 }
1519
1520 av_log(pls->parent, AV_LOG_VERBOSE, "HLS request for url '%s', offset %"PRId64", playlist %d\n",
1521 seg->url, seg->url_offset, pls->index);
1522
1523 if (seg->key_type == KEY_AES_128 || seg->key_type == KEY_SAMPLE_AES) {
1524 if (strcmp(seg->key, pls->key_url)) {
1525 ret = read_key(c, pls, seg);
1526 if (ret < 0)
1527 goto cleanup;
1528 }
1529 }
1530
1531 if (seg->key_type == KEY_AES_128) {
1532 char iv[33], key[33], url[MAX_URL_SIZE];
1533 ff_data_to_hex(iv, seg->iv, sizeof(seg->iv), 0);
1534 ff_data_to_hex(key, pls->key, sizeof(pls->key), 0);
1535 if (strstr(seg->url, "://"))
1536 snprintf(url, sizeof(url), "crypto+%s", seg->url);
1537 else
1538 snprintf(url, sizeof(url), "crypto:%s", seg->url);
1539
1540 av_dict_set(&opts, "key", key, 0);
1541 av_dict_set(&opts, "iv", iv, 0);
1542
1543 ret = open_url(pls->parent, in, url, &c->avio_opts, opts, &is_http);
1544 if (ret < 0) {
1545 goto cleanup;
1546 }
1547 ret = 0;
1548 } else {
1549 ret = open_url(pls->parent, in, seg->url, &c->avio_opts, opts, &is_http);
1550 }
1551
1552 /* Seek to the requested position. If this was a HTTP request, the offset
1553 * should already be where want it to, but this allows e.g. local testing
1554 * without a HTTP server.
1555 *
1556 * This is not done for HTTP at all as avio_seek() does internal bookkeeping
1557 * of file offset which is out-of-sync with the actual offset when "offset"
1558 * AVOption is used with http protocol, causing the seek to not be a no-op
1559 * as would be expected. Wrong offset received from the server will not be
1560 * noticed without the call, though.
1561 */
1562 if (ret == 0 && !is_http && seg->url_offset) {
1563 int64_t seekret = avio_seek(*in, seg->url_offset, SEEK_SET);
1564 if (seekret < 0) {
1565 av_log(pls->parent, AV_LOG_ERROR, "Unable to seek to offset %"PRId64" of HLS segment '%s'\n", seg->url_offset, seg->url);
1566 ret = seekret;
1567 ff_format_io_close(pls->parent, in);
1568 }
1569 }
1570
1571cleanup:
1573 pls->cur_seg_offset = 0;
1574 return ret;
1575}
1576
1577static int update_init_section(struct playlist *pls, struct segment *seg)
1578{
1579 static const int max_init_section_size = 1024*1024;
1580 HLSContext *c = pls->parent->priv_data;
1581 int64_t sec_size;
1582 int64_t urlsize;
1583 int ret;
1584
1585 if (seg->init_section == pls->cur_init_section)
1586 return 0;
1587
1588 pls->cur_init_section = NULL;
1589
1590 if (!seg->init_section)
1591 return 0;
1592
1593 ret = open_input(c, pls, seg->init_section, &pls->input);
1594 if (ret < 0) {
1596 "Failed to open an initialization section in playlist %d\n",
1597 pls->index);
1598 return ret;
1599 }
1600
1601 if (seg->init_section->size >= 0)
1602 sec_size = seg->init_section->size;
1603 else if ((urlsize = avio_size(pls->input)) >= 0)
1604 sec_size = urlsize;
1605 else
1606 sec_size = max_init_section_size;
1607
1609 "Downloading an initialization section of size %"PRId64"\n",
1610 sec_size);
1611
1612 sec_size = FFMIN(sec_size, max_init_section_size);
1613
1614 av_fast_malloc(&pls->init_sec_buf, &pls->init_sec_buf_size, sec_size);
1615
1616 ret = read_from_url(pls, seg->init_section, pls->init_sec_buf,
1617 pls->init_sec_buf_size);
1618 ff_format_io_close(pls->parent, &pls->input);
1619
1620 if (ret < 0)
1621 return ret;
1622
1623 pls->cur_init_section = seg->init_section;
1624 pls->init_sec_data_len = ret;
1625 pls->init_sec_buf_read_offset = 0;
1626
1627 /* spec says audio elementary streams do not have media initialization
1628 * sections, so there should be no ID3 timestamps */
1629 pls->is_id3_timestamped = 0;
1630
1631 return 0;
1632}
1633
1635{
1636 return pls->n_segments > 0 ?
1637 pls->segments[pls->n_segments - 1]->duration :
1638 pls->target_duration;
1639}
1640
1641static int playlist_needed(struct playlist *pls)
1642{
1643 AVFormatContext *s = pls->parent;
1644 int i, j;
1645 int stream_needed = 0;
1646 int first_st;
1647
1648 /* If there is no context or streams yet, the playlist is needed */
1649 if ((!pls->ctx || !pls->n_main_streams) && !pls->is_subtitle)
1650 return 1;
1651
1652 /* check if any of the streams in the playlist are needed */
1653 for (i = 0; i < pls->n_main_streams; i++) {
1654 if (pls->main_streams[i]->discard < AVDISCARD_ALL) {
1655 stream_needed = 1;
1656 break;
1657 }
1658 }
1659
1660 /* If all streams in the playlist were discarded, the playlist is not
1661 * needed (regardless of whether whole programs are discarded or not). */
1662 if (!stream_needed)
1663 return 0;
1664
1665 /* Otherwise, check if all the programs (variants) this playlist is in are
1666 * discarded. Since all streams in the playlist are part of the same programs
1667 * we can just check the programs of the first stream. */
1668
1669 first_st = pls->main_streams[0]->index;
1670
1671 for (i = 0; i < s->nb_programs; i++) {
1672 AVProgram *program = s->programs[i];
1673 if (program->discard < AVDISCARD_ALL) {
1674 for (j = 0; j < program->nb_stream_indexes; j++) {
1675 if (program->stream_index[j] == first_st) {
1676 /* playlist is in an undiscarded program */
1677 return 1;
1678 }
1679 }
1680 }
1681 }
1682
1683 /* some streams were not discarded but all the programs were */
1684 return 0;
1685}
1686
1687static int reload_playlist(struct playlist *v, HLSContext *c)
1688{
1689 int ret = 0;
1690 int reload_count = 0;
1691
1692 v->needed = playlist_needed(v);
1693
1694 if (!v->needed)
1695 return AVERROR_EOF;
1696
1697 if (!v->input || (c->http_persistent && v->input_read_done)) {
1698 int64_t reload_interval;
1699
1700 /* Check that the playlist is still needed before opening a new
1701 * segment. */
1702 v->needed = playlist_needed(v);
1703
1704 if (!v->needed) {
1705 av_log(v->parent, AV_LOG_INFO, "No longer receiving playlist %d ('%s')\n",
1706 v->index, v->url);
1707 return AVERROR_EOF;
1708 }
1709
1710 /* If this is a live stream and the reload interval has elapsed since
1711 * the last playlist reload, reload the playlists now. */
1712 reload_interval = default_reload_interval(v);
1713
1714reload:
1715 reload_count++;
1716 if (reload_count > c->max_reload)
1717 return AVERROR_EOF;
1718 if (!v->finished &&
1719 av_gettime_relative() - v->last_load_time >= reload_interval) {
1720 if ((ret = parse_playlist(c, v->url, v, NULL)) < 0) {
1721 if (ret != AVERROR_EXIT)
1722 av_log(v->parent, AV_LOG_WARNING, "Failed to reload playlist %d\n",
1723 v->index);
1724 return ret;
1725 }
1726 /* If we need to reload the playlist again below (if
1727 * there's still no more segments), switch to a reload
1728 * interval of half the target duration. */
1729 reload_interval = v->target_duration / 2;
1730 }
1731 if (v->cur_seq_no < v->start_seq_no) {
1733 "skipping %"PRId64" segments ahead, expired from playlists\n",
1734 v->start_seq_no - v->cur_seq_no);
1735 v->cur_seq_no = v->start_seq_no;
1736 }
1737 if (v->cur_seq_no > v->last_seq_no) {
1738 v->last_seq_no = v->cur_seq_no;
1739 v->m3u8_hold_counters = 0;
1740 } else if (v->last_seq_no == v->cur_seq_no) {
1741 v->m3u8_hold_counters++;
1742 if (v->m3u8_hold_counters >= c->m3u8_hold_counters) {
1743 return AVERROR_EOF;
1744 }
1745 } else {
1746 av_log(v->parent, AV_LOG_WARNING, "The m3u8 list sequence may have been wrapped.\n");
1747 }
1748 if (v->cur_seq_no >= v->start_seq_no + v->n_segments) {
1749 if (v->finished || v->is_subtitle)
1750 return AVERROR_EOF;
1751 while (av_gettime_relative() - v->last_load_time < reload_interval) {
1752 if (ff_check_interrupt(c->interrupt_callback))
1753 return AVERROR_EXIT;
1754 av_usleep(100*1000);
1755 }
1756 /* Enough time has elapsed since the last reload */
1757 goto reload;
1758 }
1759
1760 }
1761 return ret;
1762}
1763
1764static int read_data_continuous(void *opaque, uint8_t *buf, int buf_size)
1765{
1766 struct playlist *v = opaque;
1768 int ret;
1769 int just_opened = 0;
1770 int segment_retries = 0;
1771 struct segment *seg;
1772
1773 if (c->http_persistent && v->input_read_done) {
1774 av_assert0(v->input);
1775 ret = reload_playlist(v, c);
1776 if (ret < 0)
1777 return ret;
1778 }
1779
1780 v->input_read_done = 0;
1781
1782restart:
1783 ret = reload_playlist(v, c);
1784 if (ret < 0)
1785 return ret;
1786
1787 seg = current_segment(v);
1788
1789 if (!v->input || v->input_read_done) {
1790 /* load/update Media Initialization Section, if any */
1791 ret = update_init_section(v, seg);
1792 if (ret)
1793 return ret;
1794
1795 if (c->http_multiple == 1 && v->input_next_requested) {
1797 v->cur_seg_offset = 0;
1798 v->input_next_requested = 0;
1799 ret = 0;
1800 } else {
1801 ret = open_input(c, v, seg, &v->input);
1802 }
1803 if (ret < 0) {
1804 if (ff_check_interrupt(c->interrupt_callback))
1805 return AVERROR_EXIT;
1806 av_log(v->parent, AV_LOG_WARNING, "Failed to open segment %"PRId64" of playlist %d\n",
1807 v->cur_seq_no,
1808 v->index);
1809 if (segment_retries >= c->seg_max_retry) {
1810 av_log(v->parent, AV_LOG_WARNING, "Segment %"PRId64" of playlist %d failed too many times, skipping\n",
1811 v->cur_seq_no,
1812 v->index);
1813 v->cur_seq_no++;
1814 segment_retries = 0;
1815 } else {
1816 segment_retries++;
1817 }
1818 goto restart;
1819 }
1820 segment_retries = 0;
1821 just_opened = 1;
1822 if (v->first_read_seq_no < 0)
1824 }
1825
1826 if (c->http_multiple == -1) {
1827 uint8_t *http_version_opt = NULL;
1828 int r = av_opt_get(v->input, "http_version", AV_OPT_SEARCH_CHILDREN, &http_version_opt);
1829 if (r >= 0) {
1830 c->http_multiple = (!strncmp((const char *)http_version_opt, "1.1", 3) || !strncmp((const char *)http_version_opt, "2.0", 3));
1831 av_freep(&http_version_opt);
1832 }
1833 }
1834
1835 seg = next_segment(v);
1836 if (c->http_multiple == 1 && !v->input_next_requested &&
1837 seg && seg->key_type == KEY_NONE && av_strstart(seg->url, "http", NULL) &&
1838 !segment_reusable(v->input, current_segment(v), seg)) {
1839 ret = open_input(c, v, seg, &v->input_next);
1840 if (ret < 0) {
1841 if (ff_check_interrupt(c->interrupt_callback))
1842 return AVERROR_EXIT;
1843 av_log(v->parent, AV_LOG_WARNING, "Failed to open segment %"PRId64" of playlist %d\n",
1844 v->cur_seq_no + 1,
1845 v->index);
1846 } else {
1847 v->input_next_requested = 1;
1848 }
1849 }
1850
1852 /* Push init section out first before first actual segment */
1853 int copy_size = FFMIN(v->init_sec_data_len - v->init_sec_buf_read_offset, buf_size);
1854 memcpy(buf, v->init_sec_buf + v->init_sec_buf_read_offset, copy_size);
1855 v->init_sec_buf_read_offset += copy_size;
1856 return copy_size;
1857 }
1858
1859 seg = current_segment(v);
1860 ret = read_from_url(v, seg, buf, buf_size);
1861 if (ret > 0) {
1862 if (just_opened && v->is_id3_timestamped != 0) {
1863 /* Intercept ID3 tags here, elementary audio streams are required
1864 * to convey timestamps using them in the beginning of each segment. */
1865 intercept_id3(v, buf, buf_size, &ret);
1866 }
1867
1868 return ret;
1869 }
1870 if (ret == 0 && segment_reusable(v->input, seg, next_segment(v))) {
1871 /* Clean boundary, and the next segment continues this resource. Keep
1872 * the connection open and read it as a whole. Note that splitting
1873 * segments in these cases is useful for dynamic variant/quality
1874 * switching, but this is not supported by our HLS demuxer, so we
1875 * join the ranges. */
1876 v->input_reuse = 1;
1877 v->input_read_done = 1;
1878 } else if (c->http_persistent && is_native_http(v->input) &&
1879 seg->key_type == KEY_NONE && av_strstart(seg->url, "http", NULL)) {
1880 v->input_read_done = 1;
1881 } else {
1883 }
1884 v->cur_seq_no++;
1885
1886 c->cur_seq_no = v->cur_seq_no;
1887
1888 goto restart;
1889}
1890
1891static int read_data_subtitle_segment(void *opaque, uint8_t *buf, int buf_size)
1892{
1893 struct playlist *v = opaque;
1895 int ret;
1896 struct segment *seg;
1897
1898 if (!v->needed || v->cur_seq_no - v->start_seq_no >= v->n_segments) {
1899 return AVERROR_EOF;
1900 } else {
1901 seg = current_segment(v);
1902 }
1903
1904 if (!v->input) {
1905 ret = open_input(c, v, seg, &v->input);
1906 if (ret < 0) {
1907 if (ff_check_interrupt(c->interrupt_callback))
1908 return AVERROR_EXIT;
1909 av_log(v->parent, AV_LOG_WARNING, "Failed to open segment of playlist %d\n",
1910 v->index);
1911 return ret;
1912 }
1913 if (v->first_read_seq_no < 0)
1915 }
1916
1917 return read_from_url(v, seg, buf, buf_size);
1918}
1919
1920static int nested_io_open(AVFormatContext *s, AVIOContext **pb, const char *url,
1921 int flags, AVDictionary **opts)
1922{
1924 "A HLS playlist item '%s' referred to an external file '%s'. "
1925 "Opening this file was forbidden for security reasons\n",
1926 s->url, url);
1927 return AVERROR(EPERM);
1928}
1929
1930static int init_subtitle_context(struct playlist *pls)
1931{
1932 HLSContext *c = pls->parent->priv_data;
1933 const AVInputFormat *in_fmt;
1935 uint8_t *buf;
1936 int ret;
1937
1938 if (!(pls->ctx = avformat_alloc_context()))
1939 return AVERROR(ENOMEM);
1940
1942 if (!buf) {
1944 pls->ctx = NULL;
1945 return AVERROR(ENOMEM);
1946 }
1947
1948 av_freep(&pls->pb.pub.buffer);
1949 ffio_init_context(&pls->pb, buf, INITIAL_BUFFER_SIZE, 0, pls,
1951 pls->pb.pub.seekable = 0;
1952 pls->ctx->pb = &pls->pb.pub;
1953 pls->ctx->io_open = nested_io_open;
1954
1955 ret = ff_copy_whiteblacklists(pls->ctx, pls->parent);
1956 if (ret < 0) {
1958 pls->ctx = NULL;
1959 return ret;
1960 }
1961
1962 in_fmt = av_find_input_format("webvtt");
1963 av_dict_copy(&opts, c->seg_format_opts, 0);
1964 ret = avformat_open_input(&pls->ctx, current_segment(pls)->url, in_fmt, &opts);
1966
1967 return ret;
1968}
1969
1971{
1973 int ret;
1974
1975restart:
1976 ret = reload_playlist(v, c);
1977 if (ret < 0)
1978 return ret;
1979
1980 if (v->input && !v->ctx)
1982
1983 if (!v->input && !v->ctx) {
1984 ret = init_subtitle_context(v);
1985 if (ret < 0)
1986 return ret;
1987 }
1988
1989 ret = av_read_frame(v->ctx, v->pkt);
1990 if (!ret) {
1991 return ret;
1992 }
1994 v->cur_seq_no++;
1995 c->cur_seq_no = v->cur_seq_no;
1996
1998
1999 goto restart;
2000}
2001
2003 enum AVMediaType type, const char *group_id)
2004{
2005 int i;
2006
2007 for (i = 0; i < c->n_renditions; i++) {
2008 struct rendition *rend = c->renditions[i];
2009
2010 if (rend->type == type && !strcmp(rend->group_id, group_id)) {
2011
2012 if (rend->playlist)
2013 /* rendition is an external playlist
2014 * => add the playlist to the variant */
2015 dynarray_add(&var->playlists, &var->n_playlists, rend->playlist);
2016 else
2017 /* rendition is part of the variant main Media Playlist
2018 * => add the rendition to the main Media Playlist */
2020 &var->playlists[0]->n_renditions,
2021 rend);
2022 }
2023 }
2024}
2025
2027 enum AVMediaType type)
2028{
2029 int rend_idx = 0;
2030 int i;
2031
2032 for (i = 0; i < pls->n_main_streams; i++) {
2033 AVStream *st = pls->main_streams[i];
2034
2035 if (st->codecpar->codec_type != type)
2036 continue;
2037
2038 for (; rend_idx < pls->n_renditions; rend_idx++) {
2039 struct rendition *rend = pls->renditions[rend_idx];
2040
2041 if (rend->type != type)
2042 continue;
2043
2044 if (rend->language[0])
2045 av_dict_set(&st->metadata, "language", rend->language, 0);
2046 if (rend->name[0])
2047 av_dict_set(&st->metadata, "comment", rend->name, 0);
2048
2049 st->disposition |= rend->disposition;
2050 }
2051 if (rend_idx >=pls->n_renditions)
2052 break;
2053 }
2054}
2055
2056/* if timestamp was in valid range: returns 1 and sets seq_no
2057 * if not: returns 0 and sets seq_no to closest segment */
2059 int64_t timestamp, int64_t *seq_no,
2060 int64_t *seg_start_ts)
2061{
2062 int i;
2063 int64_t pos = c->first_timestamp == AV_NOPTS_VALUE ?
2064 0 : c->first_timestamp;
2065
2066 if (timestamp < pos) {
2067 /* Seeking before the start of the playlist, clamp to the first segment. */
2068 *seq_no = pls->start_seq_no;
2069 if (seg_start_ts)
2070 *seg_start_ts = pos;
2071 return 1;
2072 }
2073
2074 for (i = 0; i < pls->n_segments; i++) {
2075 int64_t diff = pos + pls->segments[i]->duration - timestamp;
2076 if (diff > 0) {
2077 *seq_no = pls->start_seq_no + i;
2078 if (seg_start_ts) {
2079 *seg_start_ts = pos;
2080 }
2081 return 1;
2082 }
2083 pos += pls->segments[i]->duration;
2084 }
2085
2086 *seq_no = pls->start_seq_no + pls->n_segments - 1;
2087
2088 if (!pls->finished && pls->n_segments > 0) {
2089 if (seg_start_ts)
2090 *seg_start_ts = pos - pls->segments[pls->n_segments - 1]->duration;
2091 return 1;
2092 }
2093
2094 return 0;
2095}
2096
2098{
2099 int64_t seq_no;
2100
2101 if (!pls->finished && !c->first_packet &&
2103 /* reload the playlist since it was suspended */
2104 parse_playlist(c, pls->url, pls, NULL);
2105
2106 /* If playback is already in progress (we are just selecting a new
2107 * playlist) and this is a complete file, find the matching segment
2108 * by counting durations. */
2109 if (pls->finished && c->cur_timestamp != AV_NOPTS_VALUE) {
2110 find_timestamp_in_playlist(c, pls, c->cur_timestamp, &seq_no, NULL);
2111 return seq_no;
2112 }
2113
2114 if (!pls->finished) {
2115 if (!c->first_packet && /* we are doing a segment selection during playback */
2116 c->cur_seq_no >= pls->start_seq_no &&
2117 c->cur_seq_no < pls->start_seq_no + pls->n_segments)
2118 /* While spec 3.4.3 says that we cannot assume anything about the
2119 * content at the same sequence number on different playlists,
2120 * in practice this seems to work and doing it otherwise would
2121 * require us to download a segment to inspect its timestamps. */
2122 return c->cur_seq_no;
2123
2124 /* If this is a live stream, start live_start_index segments from the
2125 * start or end */
2126 if (c->live_start_index < 0)
2127 seq_no = pls->start_seq_no + FFMAX(pls->n_segments +
2128 c->live_start_index, 0);
2129 else
2130 seq_no = pls->start_seq_no + FFMIN(c->live_start_index,
2131 pls->n_segments - 1);
2132
2133 /* If #EXT-X-START in playlist, need to recalculate */
2134 if (pls->time_offset_flag && c->prefer_x_start) {
2135 int64_t start_timestamp;
2136 int64_t playlist_duration = 0;
2137 int64_t cur_timestamp = c->cur_timestamp == AV_NOPTS_VALUE ? 0 :
2138 c->cur_timestamp;
2139
2140 for (int i = 0; i < pls->n_segments; i++)
2141 playlist_duration += pls->segments[i]->duration;
2142
2143 /* If the absolute value of TIME-OFFSET exceeds
2144 * the duration of the playlist, it indicates either the end of the
2145 * playlist (if positive) or the beginning of the playlist (if
2146 * negative). */
2147 if (pls->start_time_offset >=0 &&
2148 pls->start_time_offset > playlist_duration)
2149 start_timestamp = cur_timestamp + playlist_duration;
2150 else if (pls->start_time_offset >= 0 &&
2151 pls->start_time_offset <= playlist_duration)
2152 start_timestamp = cur_timestamp + pls->start_time_offset;
2153 else if (pls->start_time_offset < 0 &&
2154 pls->start_time_offset < -playlist_duration)
2155 start_timestamp = cur_timestamp;
2156 else if (pls->start_time_offset < 0 &&
2157 pls->start_time_offset > -playlist_duration)
2158 start_timestamp = cur_timestamp + playlist_duration +
2159 pls->start_time_offset;
2160 else
2161 start_timestamp = cur_timestamp;
2162
2163 find_timestamp_in_playlist(c, pls, start_timestamp, &seq_no, NULL);
2164 }
2165 return seq_no;
2166 }
2167
2168 /* Otherwise just start on the first segment. */
2169 return pls->start_seq_no;
2170}
2171
2172static void add_stream_to_programs(AVFormatContext *s, struct playlist *pls, AVStream *stream)
2173{
2174 HLSContext *c = s->priv_data;
2175 int i, j;
2176 int bandwidth = -1;
2177
2178 for (i = 0; i < c->n_variants; i++) {
2179 struct variant *v = c->variants[i];
2180
2181 for (j = 0; j < v->n_playlists; j++) {
2182 if (v->playlists[j] != pls)
2183 continue;
2184
2186
2187 if (bandwidth == -1)
2188 bandwidth = v->bandwidth;
2189 else if (bandwidth != v->bandwidth)
2190 bandwidth = -2; /* stream in multiple variants with different bandwidths */
2191 }
2192 }
2193
2194 if (bandwidth >= 0)
2195 av_dict_set_int(&stream->metadata, "variant_bitrate", bandwidth, 0);
2196}
2197
2199{
2200 int err;
2201
2202 err = avcodec_parameters_copy(st->codecpar, ist->codecpar);
2203 if (err < 0)
2204 return err;
2205
2206 if (pls->is_id3_timestamped) /* custom timestamps via id3 */
2208 else
2210
2211 // copy disposition
2212 st->disposition = ist->disposition;
2213
2214 av_dict_copy(&st->metadata, ist->metadata, 0);
2215
2217
2218 return 0;
2219}
2220
2221/* add new subdemuxer streams to our context, if any */
2223{
2224 HLSContext *c = s->priv_data;
2225 int err;
2226
2227 while (pls->n_main_streams < pls->ctx->nb_streams) {
2228 int ist_idx = pls->n_main_streams;
2230 AVStream *ist = pls->ctx->streams[ist_idx];
2231
2232 if (!st)
2233 return AVERROR(ENOMEM);
2234
2235 st->id = pls->index;
2236 dynarray_add(&pls->main_streams, &pls->n_main_streams, st);
2237
2238 add_stream_to_programs(s, pls, st);
2239
2240 err = set_stream_info_from_input_stream(st, pls, ist);
2241 if (err < 0)
2242 return err;
2243
2244 /* Match the start_time of streams created before playback began. */
2245 if (c->first_timestamp != AV_NOPTS_VALUE)
2246 st->start_time = av_rescale_q(c->first_timestamp,
2248
2250 if (pls->timed_id3_stream_index < 0)
2251 pls->timed_id3_stream_index = ist_idx;
2252 else
2254 "Playlist has multiple timed ID3 streams; "
2255 "only stream %d will be used for metadata propagation\n",
2257 }
2258 }
2259
2260 return 0;
2261}
2262
2264{
2265 HLSContext *c = s->priv_data;
2266 int flag_needed = 0;
2267 int i;
2268
2269 for (i = 0; i < c->n_playlists; i++) {
2270 struct playlist *pls = c->playlists[i];
2271
2272 if (pls->has_noheader_flag) {
2273 flag_needed = 1;
2274 break;
2275 }
2276 }
2277
2278 if (flag_needed)
2279 s->ctx_flags |= AVFMTCTX_NOHEADER;
2280 else
2281 s->ctx_flags &= ~AVFMTCTX_NOHEADER;
2282}
2283
2285{
2286 HLSContext *c = s->priv_data;
2287
2291
2292 if (c->crypto_ctx.aes_ctx)
2293 av_free(c->crypto_ctx.aes_ctx);
2294
2295 av_dict_free(&c->avio_opts);
2296 ff_format_io_close(c->ctx, &c->playlist_pb);
2297
2298 return 0;
2299}
2300
2302{
2303 HLSContext *c = s->priv_data;
2304 int ret = 0, i;
2305 int64_t highest_cur_seq_no = 0;
2306
2307 c->ctx = s;
2308 c->interrupt_callback = &s->interrupt_callback;
2309
2310 c->first_packet = 1;
2311 c->first_timestamp = AV_NOPTS_VALUE;
2312 c->first_timestamp_pls = NULL;
2313 c->first_timestamp_locked = 0;
2314 c->cur_timestamp = AV_NOPTS_VALUE;
2315
2316 if ((ret = ffio_copy_url_options(s->pb, &c->avio_opts)) < 0)
2317 return ret;
2318
2319 /* http_persistent and http_multiple auto-detection both rely on the
2320 * AVIOContext being backed by the builtin URLContext. Neither works
2321 * when io_open is overridden with a custom callback. */
2322 if (!ffio_geturlcontext(s->pb)) {
2323 if (c->http_persistent) {
2324 av_log(s, AV_LOG_WARNING, "Disabling http_persistent due to custom io_open.\n");
2325 c->http_persistent = 0;
2326 }
2327 /* Only auto-detection is disabled, enabling http_multiple can still work
2328 * with custom io_open. */
2329 if (c->http_multiple == -1) {
2330 av_log(s, AV_LOG_WARNING, "Disabling http_multiple due to custom io_open.\n");
2331 c->http_multiple = 0;
2332 }
2333 }
2334
2335 /* XXX: Some HLS servers don't like being sent the range header,
2336 in this case, we need to set http_seekable = 0 to disable
2337 the range header */
2338 av_dict_set_int(&c->avio_opts, "seekable", c->http_seekable, 0);
2339
2340 if ((ret = parse_playlist(c, s->url, NULL, s->pb)) < 0)
2341 return ret;
2342
2343 if (c->n_variants == 0) {
2344 av_log(s, AV_LOG_WARNING, "Empty playlist\n");
2345 return AVERROR_EOF;
2346 }
2347 /* If the playlist only contained playlists (Master Playlist),
2348 * parse each individual playlist. */
2349 if (c->n_playlists > 1 || c->playlists[0]->n_segments == 0) {
2350 for (i = 0; i < c->n_playlists; i++) {
2351 struct playlist *pls = c->playlists[i];
2352 pls->m3u8_hold_counters = 0;
2353 if ((ret = parse_playlist(c, pls->url, pls, NULL)) < 0) {
2354 av_log(s, AV_LOG_WARNING, "parse_playlist error %s [%s]\n", av_err2str(ret), pls->url);
2355 pls->broken = 1;
2356 if (c->n_playlists > 1)
2357 continue;
2358 return ret;
2359 }
2360 }
2361 }
2362
2363 for (i = 0; i < c->n_variants; i++) {
2364 if (c->variants[i]->playlists[0]->n_segments == 0) {
2365 av_log(s, AV_LOG_WARNING, "Empty segment [%s]\n", c->variants[i]->playlists[0]->url);
2366 c->variants[i]->playlists[0]->broken = 1;
2367 }
2368 }
2369
2370 /* Calculate the total duration of the stream if all segments are
2371 * available (finished or EVENT playlists). */
2372 if (c->variants[0]->playlists[0]->finished ||
2373 c->variants[0]->playlists[0]->type == PLS_TYPE_EVENT) {
2374 int64_t duration = 0;
2375 for (i = 0; i < c->variants[0]->playlists[0]->n_segments; i++)
2376 duration += c->variants[0]->playlists[0]->segments[i]->duration;
2377 s->duration = duration;
2378 }
2379
2380 /* Associate renditions with variants */
2381 for (i = 0; i < c->n_variants; i++) {
2382 struct variant *var = c->variants[i];
2383
2384 if (var->audio_group[0])
2386 if (var->video_group[0])
2388 if (var->subtitles_group[0])
2390 }
2391
2392 /* Create a program for each variant */
2393 for (i = 0; i < c->n_variants; i++) {
2394 struct variant *v = c->variants[i];
2395 AVProgram *program;
2396
2397 program = av_new_program(s, i);
2398 if (!program)
2399 return AVERROR(ENOMEM);
2400 av_dict_set_int(&program->metadata, "variant_bitrate", v->bandwidth, 0);
2401 }
2402
2403 /* Select the starting segments */
2404 for (i = 0; i < c->n_playlists; i++) {
2405 struct playlist *pls = c->playlists[i];
2406
2407 if (pls->n_segments == 0)
2408 continue;
2409
2410 pls->cur_seq_no = select_cur_seq_no(c, pls);
2411 highest_cur_seq_no = FFMAX(highest_cur_seq_no, pls->cur_seq_no);
2412 }
2413
2414 av_dict_set(&c->seg_format_opts, "prefer_hls_mpegts_pts", "1", 0);
2415
2416 /* Open the demuxer for each playlist */
2417 for (i = 0; i < c->n_playlists; i++) {
2418 struct playlist *pls = c->playlists[i];
2419 const AVInputFormat *in_fmt = NULL;
2420 char *url;
2422 struct segment *seg = NULL;
2423 uint8_t *buf;
2424 int buf_size;
2425
2426 if (!(pls->ctx = avformat_alloc_context()))
2427 return AVERROR(ENOMEM);
2428
2429 if (pls->n_segments == 0)
2430 continue;
2431
2432 pls->index = i;
2433 pls->needed = 1;
2434 pls->parent = s;
2435
2436 /*
2437 * If this is a live stream and this playlist looks like it is one segment
2438 * behind, try to sync it up so that every substream starts at the same
2439 * time position (so e.g. avformat_find_stream_info() will see packets from
2440 * all active streams within the first few seconds). This is not very generic,
2441 * though, as the sequence numbers are technically independent.
2442 */
2443 if (!pls->finished && pls->cur_seq_no == highest_cur_seq_no - 1 &&
2444 highest_cur_seq_no < pls->start_seq_no + pls->n_segments) {
2445 pls->cur_seq_no = highest_cur_seq_no;
2446 }
2447
2448 if (pls->is_subtitle) {
2449 buf_size = strlen("WEBVTT\n");
2450 buf = av_memdup("WEBVTT\n", buf_size);
2451 } else {
2452 buf_size = INITIAL_BUFFER_SIZE;
2453 buf = av_malloc(buf_size);
2454 }
2455 if (!buf) {
2457 pls->ctx = NULL;
2458 return AVERROR(ENOMEM);
2459 }
2460
2461 ffio_init_context(&pls->pb, buf, buf_size, 0, pls,
2463
2464 /*
2465 * If encryption scheme is SAMPLE-AES, try to read ID3 tags of
2466 * external audio track that contains audio setup information
2467 */
2468 seg = current_segment(pls);
2469 if (seg && seg->key_type == KEY_SAMPLE_AES && pls->n_renditions > 0 &&
2470 pls->renditions[0]->type == AVMEDIA_TYPE_AUDIO) {
2471 uint8_t buf[HLS_MAX_ID3_TAGS_DATA_LEN];
2472 if ((ret = avio_read(&pls->pb.pub, buf, HLS_MAX_ID3_TAGS_DATA_LEN)) < 0) {
2473 /* Fail if error was not end of file */
2474 if (ret != AVERROR_EOF) {
2476 pls->ctx = NULL;
2477 return ret;
2478 }
2479 }
2480 ret = 0;
2481 /* Reset reading */
2482 ff_format_io_close(pls->parent, &pls->input);
2483 pls->input = NULL;
2484 pls->input_read_done = 0;
2485 pls->input_reuse = 0;
2487 pls->input_next = NULL;
2488 pls->input_next_requested = 0;
2489 pls->cur_seg_offset = 0;
2490 pls->cur_init_section = NULL;
2491 /* Reset EOF flag */
2492 pls->pb.pub.eof_reached = 0;
2493 /* Clear any buffered data */
2494 pls->pb.pub.buf_end = pls->pb.pub.buf_ptr = pls->pb.pub.buffer;
2495 /* Reset the position */
2496 pls->pb.pub.pos = 0;
2497 }
2498
2499 /*
2500 * If encryption scheme is SAMPLE-AES and audio setup information is present in external audio track,
2501 * use that information to find the media format, otherwise probe input data
2502 */
2503 seg = current_segment(pls);
2504 if (seg && seg->key_type == KEY_SAMPLE_AES && pls->is_id3_timestamped &&
2509 // Keep this list in sync with ff_hls_senc_read_audio_setup_info()
2511 pls->audio_setup_info.codec_id == AV_CODEC_ID_AC3 ? "ac3" : "eac3");
2512 } else {
2513 pls->ctx->probesize = s->probesize > 0 ? s->probesize : 1024 * 4;
2514 pls->ctx->max_analyze_duration = s->max_analyze_duration > 0 ? s->max_analyze_duration : 4 * AV_TIME_BASE;
2515 pls->ctx->interrupt_callback = s->interrupt_callback;
2516 url = av_strdup(pls->segments[0]->url);
2517 ret = av_probe_input_buffer(&pls->pb.pub, &in_fmt, url, NULL, 0, 0);
2518
2519 for (int n = 0; n < pls->n_segments; n++)
2520 if (ret >= 0)
2521 ret = test_segment(s, in_fmt, pls, pls->segments[n]);
2522
2523 if (ret < 0) {
2524 /* Free the ctx - it isn't initialized properly at this point,
2525 * so avformat_close_input shouldn't be called. If
2526 * avformat_open_input fails below, it frees and zeros the
2527 * context, so it doesn't need any special treatment like this. */
2528 av_log(s, AV_LOG_ERROR, "Error when loading first segment '%s'\n", url);
2530 pls->ctx = NULL;
2531 av_free(url);
2532 return ret;
2533 }
2534 av_free(url);
2535 }
2536
2537 seg = current_segment(pls);
2538 if (seg && seg->key_type == KEY_SAMPLE_AES) {
2539 if (strstr(in_fmt->name, "mov")) {
2540 char key[33];
2541 ff_data_to_hex(key, pls->key, sizeof(pls->key), 0);
2542 av_dict_set(&options, "decryption_key", key, 0);
2543 } else if (!c->crypto_ctx.aes_ctx) {
2544 c->crypto_ctx.aes_ctx = av_aes_alloc();
2545 if (!c->crypto_ctx.aes_ctx) {
2547 pls->ctx = NULL;
2548 return AVERROR(ENOMEM);
2549 }
2550 }
2551 }
2552
2553 pls->ctx->pb = &pls->pb.pub;
2554 pls->ctx->io_open = nested_io_open;
2555 pls->ctx->flags |= s->flags & ~AVFMT_FLAG_CUSTOM_IO;
2556
2557 if ((ret = ff_copy_whiteblacklists(pls->ctx, s)) < 0)
2558 return ret;
2559
2560 av_dict_copy(&options, c->seg_format_opts, 0);
2561
2562 ret = avformat_open_input(&pls->ctx, pls->segments[0]->url, in_fmt, &options);
2564 if (ret < 0)
2565 return ret;
2566
2567 if (pls->id3_deferred_extra && pls->ctx->nb_streams == 1) {
2573 }
2574
2575 if (pls->is_id3_timestamped == -1)
2576 av_log(s, AV_LOG_WARNING, "No expected HTTP requests have been made\n");
2577
2578 /*
2579 * For ID3 timestamped raw audio streams we need to detect the packet
2580 * durations to calculate timestamps in fill_timing_for_id3_timestamped_stream(),
2581 * but for other streams we can rely on our user calling avformat_find_stream_info()
2582 * on us if they want to.
2583 */
2584 if (pls->is_id3_timestamped || (pls->n_renditions > 0 && pls->renditions[0]->type == AVMEDIA_TYPE_AUDIO)) {
2585 seg = current_segment(pls);
2586 if (seg && seg->key_type == KEY_SAMPLE_AES && pls->audio_setup_info.setup_data_length > 0 &&
2587 pls->ctx->nb_streams == 1)
2589 else
2590 ret = avformat_find_stream_info(pls->ctx, NULL);
2591
2592 if (ret < 0)
2593 return ret;
2594 }
2595
2597
2598 /* Create new AVStreams for each stream in this playlist */
2600 if (ret < 0)
2601 return ret;
2602
2603 /*
2604 * Copy any metadata from playlist to main streams, but do not set
2605 * event flags.
2606 */
2607 if (pls->n_main_streams)
2608 av_dict_copy(&pls->main_streams[0]->metadata, pls->ctx->metadata, 0);
2609
2610 if (pls->is_subtitle) {
2612 pls->ctx = NULL;
2613 pls->needed = 0;
2615 }
2616
2620 }
2621
2623
2624 return 0;
2625}
2626
2628{
2629 HLSContext *c = s->priv_data;
2630 int i, changed = 0;
2631 int cur_needed;
2632
2633 /* Check if any new streams are needed */
2634 for (i = 0; i < c->n_playlists; i++) {
2635 struct playlist *pls = c->playlists[i];
2636
2637 cur_needed = playlist_needed(c->playlists[i]);
2638
2639 if (pls->broken) {
2640 continue;
2641 }
2642 if (cur_needed && !pls->needed) {
2643 pls->needed = 1;
2644 changed = 1;
2645 pls->cur_seq_no = select_cur_seq_no(c, pls);
2646 pls->first_read_seq_no = -1;
2647 pls->pb.pub.eof_reached = 0;
2648 if (c->cur_timestamp != AV_NOPTS_VALUE) {
2649 /* catch up */
2650 pls->seek_timestamp = c->cur_timestamp +
2651 (pls->ts_offset != AV_NOPTS_VALUE ? pls->ts_offset : 0);
2653 pls->seek_stream_index = -1;
2654 }
2655 av_log(s, AV_LOG_INFO, "Now receiving playlist %d, segment %"PRId64"\n", i, pls->cur_seq_no);
2656 } else if (first && !cur_needed && pls->needed) {
2657 ff_format_io_close(pls->parent, &pls->input);
2658 pls->input_read_done = 0;
2659 pls->input_reuse = 0;
2661 pls->input_next_requested = 0;
2662 if (pls->is_subtitle)
2664 pls->needed = 0;
2665 changed = 1;
2666 av_log(s, AV_LOG_INFO, "No longer receiving playlist %d\n", i);
2667 }
2668 }
2669 return changed;
2670}
2671
2673{
2674 if (pls->id3_offset >= 0) {
2675 pls->pkt->dts = pls->id3_mpegts_timestamp +
2677 pls->ctx->streams[pls->pkt->stream_index]->time_base,
2679 if (pls->pkt->duration)
2680 pls->id3_offset += pls->pkt->duration;
2681 else
2682 pls->id3_offset = -1;
2683 } else {
2684 /* there have been packets with unknown duration
2685 * since the last id3 tag, should not normally happen */
2686 pls->pkt->dts = AV_NOPTS_VALUE;
2687 }
2688
2689 if (pls->pkt->duration)
2690 pls->pkt->duration = av_rescale_q(pls->pkt->duration,
2691 pls->ctx->streams[pls->pkt->stream_index]->time_base,
2693
2694 pls->pkt->pts = AV_NOPTS_VALUE;
2695}
2696
2698{
2699 if (pls->is_id3_timestamped)
2700 return MPEG_TIME_BASE_Q;
2701
2702 return pls->ctx->streams[pls->pkt->stream_index]->time_base;
2703}
2704
2705static int compare_ts_with_wrapdetect(int64_t ts_a, struct playlist *pls_a,
2706 int64_t ts_b, struct playlist *pls_b)
2707{
2708 int64_t scaled_ts_a = av_rescale_q(ts_a, get_timebase(pls_a), MPEG_TIME_BASE_Q);
2709 int64_t scaled_ts_b = av_rescale_q(ts_b, get_timebase(pls_b), MPEG_TIME_BASE_Q);
2710
2711 return av_compare_mod(scaled_ts_a, scaled_ts_b, 1LL << 33);
2712}
2713
2714/**
2715 * Check whether any entry in @p update differs from the corresponding entry
2716 * in @p current.
2717 *
2718 * HLS segments can repeat timed ID3 metadata in every segment so that
2719 * listeners joining mid-stream immediately receive the current track
2720 * information. Only signal a metadata change when values actually differ
2721 * to avoid spurious updates on every segment boundary.
2722 */
2724 const AVDictionary *update)
2725{
2727 return 1;
2728 const AVDictionaryEntry *e = NULL;
2729 while ((e = av_dict_iterate(update, e))) {
2730 const AVDictionaryEntry *cur = av_dict_get(current, e->key, NULL, 0);
2731 if (!cur || strcmp(cur->value, e->value))
2732 return 1;
2733 }
2734 return 0;
2735}
2736
2738{
2739 HLSContext *c = s->priv_data;
2740 int ret, i, minplaylist = -1;
2741
2742 recheck_discard_flags(s, c->first_packet);
2743 c->first_packet = 0;
2744
2745 for (i = 0; i < c->n_playlists; i++) {
2746 struct playlist *pls = c->playlists[i];
2747 /* Make sure we've got one buffered packet from each open playlist
2748 * stream */
2749 if (pls->needed && !pls->pkt->data) {
2750 while (1) {
2751 int64_t ts_diff;
2752 AVRational tb;
2753 struct segment *seg = NULL;
2754 if (pls->is_subtitle)
2755 ret = read_subtitle_packet(pls, pls->pkt);
2756 else
2757 ret = av_read_frame(pls->ctx, pls->pkt);
2758 if (ret < 0) {
2759 if (!avio_feof(&pls->pb.pub) && ret != AVERROR_EOF)
2760 return ret;
2761 break;
2762 }
2763
2764 /* stream_index check prevents matching picture attachments etc. */
2765 if (pls->is_id3_timestamped && pls->pkt->stream_index == 0) {
2766 /* audio elementary streams are id3 timestamped */
2768 }
2769
2770 if (pls->pkt->dts != AV_NOPTS_VALUE &&
2771 (pls->ts_offset == AV_NOPTS_VALUE ||
2772 (!c->first_timestamp_locked &&
2773 c->first_timestamp_pls == pls &&
2774 pls->cur_seq_no <= pls->first_read_seq_no + 1))) {
2775 int adjusted = 0;
2776 /* Packet timestamp rebased onto the start of the segment list. */
2777 int64_t seg_idx = pls->first_read_seq_no - pls->start_seq_no;
2778 int64_t ts = av_rescale_q(pls->pkt->pts != AV_NOPTS_VALUE ?
2779 pls->pkt->pts : pls->pkt->dts,
2781
2782 for (int64_t k = 0; k < seg_idx && k < pls->n_segments; k++)
2783 ts -= pls->segments[k]->duration;
2784
2785 if (c->first_timestamp == AV_NOPTS_VALUE) {
2786 c->first_timestamp = ts;
2787 c->first_timestamp_pls = pls;
2788 adjusted = 1;
2789 } else if (c->first_timestamp_pls == pls) {
2790 /* first_timestamp came from the first packet in mux
2791 * order, but another stream in the same segment may
2792 * start earlier. Lower the estimate while packets of
2793 * that segment are still arriving. */
2794 int64_t delta = c->first_timestamp - ts;
2795
2796 if (delta > 0 && delta <= pls->target_duration) {
2797 c->first_timestamp = ts;
2798 for (int k = 0; k < c->n_playlists; k++)
2799 if (c->playlists[k]->ts_offset != AV_NOPTS_VALUE)
2800 c->playlists[k]->ts_offset += delta;
2801 adjusted = 1;
2802 }
2803 }
2804
2805 if (pls->ts_offset == AV_NOPTS_VALUE)
2806 pls->ts_offset = ts - c->first_timestamp;
2807
2808 if (adjusted) {
2809 for (unsigned k = 0; k < s->nb_streams; k++)
2810 s->streams[k]->start_time =
2811 av_rescale_q(c->first_timestamp, AV_TIME_BASE_Q,
2812 s->streams[k]->time_base);
2814 "First timestamp %"PRId64" from playlist %d\n",
2815 c->first_timestamp, pls->index);
2816 }
2817 }
2818
2819 seg = current_segment(pls);
2820 if (seg && seg->key_type == KEY_SAMPLE_AES && !strstr(pls->ctx->iformat->name, "mov")) {
2822 memcpy(c->crypto_ctx.iv, seg->iv, sizeof(seg->iv));
2823 memcpy(c->crypto_ctx.key, pls->key, sizeof(pls->key));
2824 ff_hls_senc_decrypt_frame(codec_id, &c->crypto_ctx, pls->pkt);
2825 }
2826
2827 if (pls->seek_timestamp == AV_NOPTS_VALUE)
2828 break;
2829
2830 if (pls->seek_stream_index < 0 ||
2831 pls->seek_stream_index == pls->pkt->stream_index) {
2832
2833 if (pls->pkt->dts == AV_NOPTS_VALUE) {
2835 break;
2836 }
2837
2838 tb = get_timebase(pls);
2839 ts_diff = av_rescale_q_rnd(pls->pkt->dts, tb,
2841 pls->seek_timestamp;
2842 if (ts_diff >= 0 && (pls->seek_flags & AVSEEK_FLAG_ANY ||
2843 pls->pkt->flags & AV_PKT_FLAG_KEY)) {
2845 break;
2846 }
2847 }
2848 av_packet_unref(pls->pkt);
2849 }
2850 }
2851 /* Check if this stream has the packet with the lowest dts */
2852 if (pls->pkt->data) {
2853 struct playlist *minpls = minplaylist < 0 ?
2854 NULL : c->playlists[minplaylist];
2855 if (minplaylist < 0) {
2856 minplaylist = i;
2857 } else {
2858 int64_t dts = pls->pkt->dts;
2859 int64_t mindts = minpls->pkt->dts;
2860
2861 if (dts == AV_NOPTS_VALUE ||
2862 (mindts != AV_NOPTS_VALUE && compare_ts_with_wrapdetect(dts, pls, mindts, minpls) < 0))
2863 minplaylist = i;
2864 }
2865 }
2866 }
2867
2868 /* If we got a packet, return it */
2869 if (minplaylist >= 0) {
2870 struct playlist *pls = c->playlists[minplaylist];
2871 AVStream *ist;
2872 AVStream *st;
2873
2875 if (ret < 0) {
2876 av_packet_unref(pls->pkt);
2877 return ret;
2878 }
2879
2880 // If sub-demuxer reports updated metadata, copy it to the first stream
2881 // and set its AVSTREAM_EVENT_FLAG_METADATA_UPDATED flag.
2883 if (pls->n_main_streams) {
2884 st = pls->main_streams[0];
2885 av_dict_copy(&st->metadata, pls->ctx->metadata, 0);
2887 }
2889 }
2890
2891 /* check if noheader flag has been cleared by the subdemuxer */
2892 if (pls->has_noheader_flag && !(pls->ctx->ctx_flags & AVFMTCTX_NOHEADER)) {
2893 pls->has_noheader_flag = 0;
2895 }
2896
2897 if (pls->pkt->stream_index >= pls->n_main_streams) {
2898 av_log(s, AV_LOG_ERROR, "stream index inconsistency: index %d, %d main streams, %d subdemuxer streams\n",
2899 pls->pkt->stream_index, pls->n_main_streams, pls->ctx->nb_streams);
2900 av_packet_unref(pls->pkt);
2901 return AVERROR_BUG;
2902 }
2903
2904 ist = pls->ctx->streams[pls->pkt->stream_index];
2905 st = pls->main_streams[pls->pkt->stream_index];
2906
2907 // Propagate timed-ID3 metadata changes to the main stream, suppressing
2908 // duplicate packets that repeat unchanged metadata at segment boundaries.
2910 pls->pkt->stream_index == pls->timed_id3_stream_index &&
2914 int ret = av_dict_copy(&st->metadata, ist->metadata, 0);
2915 if (ret < 0)
2916 return ret;
2918 ret = av_dict_copy(&pls->timed_id3_metadata, ist->metadata, 0);
2919 if (ret < 0)
2920 return ret;
2922 }
2923 }
2924
2925 av_packet_move_ref(pkt, pls->pkt);
2926 pkt->stream_index = st->index;
2927
2928 if (pkt->dts != AV_NOPTS_VALUE)
2929 c->cur_timestamp = av_rescale_q(pkt->dts,
2930 ist->time_base,
2932
2933 /* There may be more situations where this would be useful, but this at least
2934 * handles newly probed codecs properly (i.e. request_probe by mpegts). */
2935 if (ist->codecpar->codec_id != st->codecpar->codec_id) {
2936 ret = set_stream_info_from_input_stream(st, pls, ist);
2937 if (ret < 0) {
2938 return ret;
2939 }
2940 }
2941
2942 return 0;
2943 }
2944 return AVERROR_EOF;
2945}
2946
2947static int hls_read_seek(AVFormatContext *s, int stream_index,
2948 int64_t timestamp, int flags)
2949{
2950 HLSContext *c = s->priv_data;
2951 struct playlist *seek_pls = NULL;
2952 int i, j;
2953 int stream_subdemuxer_index;
2954 int64_t first_timestamp, seek_timestamp, duration;
2955 int64_t seq_no, seg_start_ts;
2956 int snapped_to_segment = 0;
2957
2958 if ((flags & AVSEEK_FLAG_BYTE) || (c->ctx->ctx_flags & AVFMTCTX_UNSEEKABLE))
2959 return AVERROR(ENOSYS);
2960
2961 seek_timestamp = av_rescale_q_rnd(timestamp,
2962 s->streams[stream_index]->time_base,
2964
2965 /* find the playlist with the specified stream */
2966 for (i = 0; i < c->n_playlists; i++) {
2967 struct playlist *pls = c->playlists[i];
2968 for (j = 0; j < pls->n_main_streams; j++) {
2969 if (pls->main_streams[j] == s->streams[stream_index]) {
2970 seek_pls = pls;
2971 stream_subdemuxer_index = j;
2972 break;
2973 }
2974 }
2975 }
2976 if (!seek_pls)
2977 return AVERROR(EIO);
2978
2979 /* Live and EVENT playlists may have gained segments since the last load,
2980 * and sliding-window playlists may also have expired some. Refresh before
2981 * resolving a seek that may fall outside the loaded window, rate limited
2982 * to the minimum reload interval (RFC 8216 6.3.4). */
2983 if (!seek_pls->finished) {
2984 int64_t elapsed = av_gettime_relative() - seek_pls->last_load_time;
2985 int64_t start = c->first_timestamp == AV_NOPTS_VALUE ?
2986 0 : c->first_timestamp;
2987 int64_t end = start;
2988 int need_refresh;
2989 for (i = 0; i < seek_pls->n_segments; i++)
2990 end += seek_pls->segments[i]->duration;
2991 need_refresh = seek_timestamp >= end;
2992 if (seek_pls->type == PLS_TYPE_UNSPECIFIED)
2993 need_refresh |= seek_timestamp < start + elapsed +
2994 seek_pls->target_duration;
2995 if (need_refresh && elapsed >= default_reload_interval(seek_pls))
2996 parse_playlist(c, seek_pls->url, seek_pls, NULL);
2997 }
2998
2999 first_timestamp = c->first_timestamp == AV_NOPTS_VALUE ?
3000 0 : c->first_timestamp;
3001
3002 duration = s->duration == AV_NOPTS_VALUE ?
3003 0 : s->duration;
3004
3005 /* Only finished playlists cannot grow past the known duration. */
3006 if (seek_pls->finished &&
3007 0 < duration && duration < seek_timestamp - first_timestamp)
3008 return AVERROR(EIO);
3009
3010 /* check if the timestamp is valid for the playlist with the
3011 * specified stream index */
3012 if (!find_timestamp_in_playlist(c, seek_pls, seek_timestamp, &seq_no, &seg_start_ts))
3013 return AVERROR(EIO);
3014
3015 if (s->streams[stream_index]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
3017 /* Seeking to start of segment ensures we seek to a keyframe located
3018 * before the given timestamp. */
3019 seek_timestamp = seg_start_ts;
3020 snapped_to_segment = 1;
3021 }
3022
3023 av_log(s, AV_LOG_DEBUG, "Seek to %"PRId64" mapped to segment %"PRId64
3024 " of playlist %d (start %"PRId64")\n",
3025 seek_timestamp, seq_no, seek_pls->index, seg_start_ts);
3026
3027 /* Keep timeline start fixed from now on. */
3028 c->first_timestamp_locked = 1;
3029
3030 /* set segment now so we do not need to search again below */
3031 seek_pls->cur_seq_no = seq_no;
3032 seek_pls->seek_stream_index = stream_subdemuxer_index;
3033
3034 /* Reset PTS wrap detection so backward seeks don't get misinterpreted
3035 * as a forward PTS wrap. */
3036 for (i = 0; i < (int)s->nb_streams; i++)
3038
3039 for (i = 0; i < c->n_playlists; i++) {
3040 /* Reset reading */
3041 struct playlist *pls = c->playlists[i];
3042 AVIOContext *const pb = &pls->pb.pub;
3043 ff_format_io_close(pls->parent, &pls->input);
3044 pls->input_read_done = 0;
3045 pls->first_read_seq_no = -1;
3046 pls->input_reuse = 0;
3048 pls->input_next_requested = 0;
3049 av_packet_unref(pls->pkt);
3050 pb->eof_reached = 0;
3051 /* Clear any buffered data */
3052 pb->buf_end = pb->buf_ptr = pb->buffer;
3053 /* Reset the pos, to let the mpegts/mov demuxer know we've seeked. */
3054 pb->pos = 0;
3055 /* Flush the packet queue of the subdemuxer. */
3056 if (pls->ctx) {
3058 for (j = 0; j < (int)pls->ctx->nb_streams; j++)
3060 }
3061 if (pls->is_subtitle)
3063
3064 /* Reset the init segment so it's re-fetched and served appropriately */
3065 pls->cur_init_section = NULL;
3066
3067 /* The discard in hls_read_packet compares this playlist's packet DTS
3068 * against seek_timestamp, but seek_timestamp is on c->first_timestamp's
3069 * baseline (whichever stream produced the first packet). Streams can
3070 * have different DTS baselines, so translate the threshold onto this
3071 * playlist's own baseline using its captured offset. */
3072 if (pls->ts_offset != AV_NOPTS_VALUE)
3074 else
3076 pls->seek_flags = flags;
3077
3078 if (pls == seek_pls && snapped_to_segment) {
3079 /* The first keyframe of the target segment may have a slightly
3080 * lower DTS than the EXTINF-derived seg_start_ts. Relax the cutoff
3081 * to not discard the keyframe and land one segment late. */
3082 int64_t idx = seq_no - pls->start_seq_no;
3083 if (idx >= 0 && idx < pls->n_segments)
3084 pls->seek_timestamp -= pls->segments[idx]->duration;
3085 }
3086
3087 if (pls != seek_pls) {
3088 /* set closest segment seq_no for playlists not handled above */
3090 /* seek the playlist to the given position without taking
3091 * keyframes into account since this playlist does not have the
3092 * specified stream where we should look for the keyframes */
3093 pls->seek_stream_index = -1;
3095 }
3096
3097 pls->last_seq_no = pls->cur_seq_no;
3098 }
3099
3100 c->cur_timestamp = seek_timestamp;
3101
3102 return 0;
3103}
3104
3105static int hls_probe(const AVProbeData *p)
3106{
3107 /* Require #EXTM3U at the start, and either one of the ones below
3108 * somewhere for a proper match. */
3109 if (strncmp(p->buf, "#EXTM3U", 7))
3110 return 0;
3111
3112 if (strstr(p->buf, "#EXT-X-STREAM-INF:") ||
3113 strstr(p->buf, "#EXT-X-TARGETDURATION:") ||
3114 strstr(p->buf, "#EXT-X-MEDIA-SEQUENCE:")) {
3115
3116 int mime_ok = p->mime_type && !(
3117 av_strcasecmp(p->mime_type, "application/vnd.apple.mpegurl") &&
3118 av_strcasecmp(p->mime_type, "audio/mpegurl")
3119 );
3120
3121 int mime_x = p->mime_type && !(
3122 av_strcasecmp(p->mime_type, "audio/x-mpegurl") &&
3123 av_strcasecmp(p->mime_type, "application/x-mpegurl")
3124 );
3125
3126 if (!mime_ok &&
3127 !mime_x &&
3128 !av_match_ext (p->filename, "m3u8,m3u") &&
3129 ff_match_url_ext(p->filename, "m3u8,m3u") <= 0) {
3130 av_log(NULL, AV_LOG_ERROR, "Not detecting m3u8/hls with non standard extension and non standard mime type\n");
3131 return 0;
3132 }
3133 if (mime_x)
3134 av_log(NULL, AV_LOG_WARNING, "mime type is not rfc8216 compliant\n");
3135
3136 return AVPROBE_SCORE_MAX;
3137 }
3138 return 0;
3139}
3140
3141#define OFFSET(x) offsetof(HLSContext, x)
3142#define FLAGS AV_OPT_FLAG_DECODING_PARAM
3143static const AVOption hls_options[] = {
3144 {"live_start_index", "segment index to start live streams at (negative values are from the end)",
3145 OFFSET(live_start_index), AV_OPT_TYPE_INT, {.i64 = -3}, INT_MIN, INT_MAX, FLAGS},
3146 {"prefer_x_start", "prefer to use #EXT-X-START if it's in playlist instead of live_start_index",
3147 OFFSET(prefer_x_start), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, FLAGS},
3148 {"allowed_extensions", "List of file extensions that hls is allowed to access",
3149 OFFSET(allowed_extensions), AV_OPT_TYPE_STRING,
3150 {.str = "3gp,aac,avi,ac3,eac3,flac,mkv,m3u8,m4a,m4s,m4v,mpg,mov,mp2,mp3,mp4,mpeg,mpegts,ogg,ogv,oga,ts,vob,vtt,wav,webvtt"
3151 ",cmfv,cmfa" // Ticket11526 www.nicovideo.jp
3152 ",ec3" // part of Ticket11435 (Elisa Viihde (Finnish online recording service))
3153 ",fmp4" // https://github.com/yt-dlp/yt-dlp/issues/12700
3154 },
3155 INT_MIN, INT_MAX, FLAGS},
3156 {"allowed_segment_extensions", "List of file extensions that hls is allowed to access",
3157 OFFSET(allowed_segment_extensions), AV_OPT_TYPE_STRING,
3158 {.str = "3gp,aac,avi,ac3,eac3,flac,mkv,m3u8,m4a,m4s,m4v,mpg,mov,mp2,mp3,mp4,mpeg,mpegts,ogg,ogv,oga,ts,vob,vtt,wav,webvtt"
3159 ",cmfv,cmfa" // Ticket11526 www.nicovideo.jp
3160 ",ec3" // part of Ticket11435 (Elisa Viihde (Finnish online recording service))
3161 ",fmp4" // https://github.com/yt-dlp/yt-dlp/issues/12700
3162 ",html" // https://flash1.bogulus.cfd/
3163 },
3164 INT_MIN, INT_MAX, FLAGS},
3165 {"extension_picky", "Be picky with all extensions matching",
3166 OFFSET(extension_picky), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, FLAGS},
3167 {"max_reload", "Maximum number of times a insufficient list is attempted to be reloaded",
3168 OFFSET(max_reload), AV_OPT_TYPE_INT, {.i64 = 100}, 0, INT_MAX, FLAGS},
3169 {"m3u8_hold_counters", "The maximum number of times to load m3u8 when it refreshes without new segments",
3170 OFFSET(m3u8_hold_counters), AV_OPT_TYPE_INT, {.i64 = 1000}, 0, INT_MAX, FLAGS},
3171 {"http_persistent", "Use persistent HTTP connections",
3172 OFFSET(http_persistent), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, FLAGS },
3173 {"http_multiple", "Use multiple HTTP connections for fetching segments",
3174 OFFSET(http_multiple), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, FLAGS},
3175 {"http_seekable", "Use HTTP partial requests, 0 = disable, 1 = enable, -1 = auto",
3176 OFFSET(http_seekable), AV_OPT_TYPE_BOOL, { .i64 = -1}, -1, 1, FLAGS},
3177 {"seg_format_options", "Set options for segment demuxer",
3178 OFFSET(seg_format_opts), AV_OPT_TYPE_DICT, {.str = NULL}, 0, 0, FLAGS},
3179 {"seg_max_retry", "Maximum number of times to reload a segment on error.",
3180 OFFSET(seg_max_retry), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, FLAGS},
3181 {NULL}
3182};
3183
3184static const AVClass hls_class = {
3185 .class_name = "hls demuxer",
3186 .item_name = av_default_item_name,
3187 .option = hls_options,
3188 .version = LIBAVUTIL_VERSION_INT,
3189};
3190
3192 .p.name = "hls",
3193 .p.long_name = NULL_IF_CONFIG_SMALL("Apple HTTP Live Streaming"),
3194 .p.priv_class = &hls_class,
3196 .priv_data_size = sizeof(HLSContext),
3197 .flags_internal = FF_INFMT_FLAG_INIT_CLEANUP,
3203};
static av_always_inline void update(AVFilterContext *ctx, AVFrame *insamples, int is_silence, int current_sample, int64_t nb_samples_notify, AVRational time_base)
const FFInputFormat ff_hls_demuxer
Definition hls.c:3191
#define entry
static AVDictionary * opts
simple assert() macros that are a bit more flexible than ISO C assert().
#define av_assert1(cond)
assert() equivalent, that does not lie in speed critical code.
Definition avassert.h:58
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Definition avassert.h:42
int ff_format_io_close(AVFormatContext *s, AVIOContext **pb)
Definition avformat.c:966
int ff_copy_whiteblacklists(AVFormatContext *dst, const AVFormatContext *src)
Copies the whilelists from one context to the other.
Definition avformat.c:884
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:839
void av_program_add_stream_index(AVFormatContext *ac, int progid, unsigned idx)
Definition avformat.c:345
Main libavformat public API header.
#define AVFMT_EVENT_FLAG_METADATA_UPDATED
Definition avformat.h:1731
#define AVPROBE_SCORE_MAX
maximum score
Definition avformat.h:485
#define AV_DISPOSITION_HEARING_IMPAIRED
The stream is intended for hearing impaired audiences.
Definition avformat.h:678
#define AVFMTCTX_NOHEADER
signal that no header is present (streams are added dynamically)
Definition avformat.h:1288
#define AVFMT_TS_DISCONT
Format allows timestamp discontinuities.
Definition avformat.h:502
#define AVFMT_NO_BYTE_SEEK
Format does not allow seeking by bytes.
Definition avformat.h:508
#define AVSEEK_FLAG_BYTE
seeking based on position in bytes
Definition avformat.h:2621
#define AVFMT_NOGENSEARCH
Format does not allow to fall back on generic search.
Definition avformat.h:507
#define AVFMT_SHOW_IDS
Show format stream IDs numbers.
Definition avformat.h:498
#define AVSEEK_FLAG_ANY
seek to any frame, even non-keyframes
Definition avformat.h:2622
#define AVFMTCTX_UNSEEKABLE
signal that the stream is definitely not seekable, and attempts to call the seek function will fail.
Definition avformat.h:1290
#define AV_DISPOSITION_FORCED
Track should be used during playback by default.
Definition avformat.h:674
#define AV_DISPOSITION_VISUAL_IMPAIRED
The stream is intended for visually impaired audiences.
Definition avformat.h:682
#define AVSTREAM_EVENT_FLAG_METADATA_UPDATED
Definition avformat.h:886
#define AVFMT_FLAG_CUSTOM_IO
The caller has supplied a custom AVIOContext, don't avio_close() it.
Definition avformat.h:1496
#define AVSEEK_FLAG_BACKWARD
seek backward
Definition avformat.h:2620
#define AV_DISPOSITION_DEFAULT
The stream should be chosen by default among other streams of the same type, unless the user has expl...
Definition avformat.h:641
URLContext * ffio_geturlcontext(AVIOContext *s)
Return the URLContext associated with the AVIOContext.
Definition avio.c:113
int ff_check_interrupt(AVIOInterruptCB *cb)
Check if the user has requested to interrupt a blocking function associated with cb.
Definition avio.c:929
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
int64_t avio_seek(AVIOContext *s, int64_t offset, int whence)
fseek() equivalent for AVIOContext.
Definition aviobuf.c:236
#define AVIO_SEEKABLE_NORMAL
Seeking works like for a local file.
Definition avio.h:41
#define AVIO_FLAG_READ
read-only
Definition avio.h:617
int64_t avio_size(AVIOContext *s)
Get the filesize.
Definition aviobuf.c:326
int avio_feof(AVIOContext *s)
Similar to feof() but also returns nonzero on read errors.
Definition aviobuf.c:349
int avio_read(AVIOContext *s, unsigned char *buf, int size)
Read size bytes from AVIOContext into buf.
Definition aviobuf.c:615
void ffio_init_context(FFIOContext *s, unsigned char *buffer, int buffer_size, int write_flag, void *opaque, int(*read_packet)(void *opaque, uint8_t *buf, int buf_size), int(*write_packet)(void *opaque, const uint8_t *buf, int buf_size), int64_t(*seek)(void *opaque, int64_t offset, int whence))
Definition aviobuf.c:50
void ffio_init_read_context(FFIOContext *s, const uint8_t *buffer, int buffer_size)
Wrap a buffer in an AVIOContext for reading.
Definition aviobuf.c:99
int ffio_copy_url_options(AVIOContext *pb, AVDictionary **avio_opts)
Read url related dictionary options from the AVIOContext and write to the given dictionary.
Definition aviobuf.c:953
static int read_packet(void *opaque, uint8_t *buf, int buf_size)
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
static int FUNC metadata(CodedBitstreamContext *ctx, RWContext *rw, APVRawMetadata *current)
#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 int read_probe(const AVProbeData *p)
Definition cdg.c:30
#define FLAGS
Definition cmdutils.c:596
int avcodec_parameters_copy(AVCodecParameters *dst, const AVCodecParameters *src)
Definition codec_par.c:107
#define NULL
Definition coverity.c:32
long long int64_t
Definition coverity.c:34
#define INITIAL_BUFFER_SIZE
Definition dashdec.c:36
static int nested_io_open(AVFormatContext *s, AVIOContext **pb, const char *url, int flags, AVDictionary **opts)
Definition dashdec.c:1922
#define FF_INFMT_FLAG_INIT_CLEANUP
For an FFInputFormat with this flag set read_close() needs to be called by the caller upon read_heade...
Definition demux.h:35
void ff_read_frame_flush(AVFormatContext *s)
Flush the frame reader.
Definition seek.c:719
static AVPacket * pkt
Public dictionary API.
static struct @111144215057303131116103221376075045141373005341 current
static int read_key(void)
Definition ffmpeg.c:264
const char * key
static int64_t duration
Definition ffplay.c:399
static int read_header(FFV1Context *f, RangeCoder *c)
Definition ffv1dec.c:578
static av_cold void cleanup(FlashSV2Context *s)
#define fail
Definition test.h:479
@ 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
AVCodecID
Identify the syntax and semantics of the bitstream.
Definition codec_id.h:47
@ AV_CODEC_ID_TIMED_ID3
Definition codec_id.h:610
@ AV_CODEC_ID_EAC3
Definition codec_id.h:497
@ AV_CODEC_ID_NONE
Definition codec_id.h:48
@ AV_CODEC_ID_AAC
Definition codec_id.h:459
@ AV_CODEC_ID_AC3
Definition codec_id.h:460
#define AV_INPUT_BUFFER_PADDING_SIZE
Required number of additionally allocated bytes at the end of the input bitstream for decoding.
Definition defs.h:40
@ AVDISCARD_ALL
discard all
Definition defs.h:246
void av_packet_free(AVPacket **pkt)
Free the packet, if the packet is reference counted, it will be unreferenced first.
Definition packet.c:74
void av_packet_unref(AVPacket *pkt)
Wipe the packet.
Definition packet.c:434
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition packet.h:650
void av_packet_move_ref(AVPacket *dst, AVPacket *src)
Move every field in src to dst and reset src.
Definition packet.c:491
AVPacket * av_packet_alloc(void)
Allocate an AVPacket and set its fields to default values.
Definition packet.c:63
AVProgram * av_new_program(AVFormatContext *ac, int id)
Definition avformat.c:284
AVStream * avformat_new_stream(AVFormatContext *s, const struct AVCodec *c)
Add a new stream to a media file.
AVFormatContext * avformat_alloc_context(void)
Allocate an AVFormatContext.
Definition options.c:165
void avformat_free_context(AVFormatContext *s)
Free an AVFormatContext and all its streams.
Definition avformat.c:151
const AVInputFormat * av_find_input_format(const char *short_name)
Find AVInputFormat based on the short name of the input format.
Definition format.c:146
int av_read_frame(AVFormatContext *s, AVPacket *pkt)
Return the next frame of a stream.
Definition demux.c:1588
int av_probe_input_buffer(AVIOContext *pb, const AVInputFormat **fmt, const char *url, void *logctx, unsigned int offset, unsigned int max_probe_size)
Like av_probe_input_buffer2() but returns 0 on success.
Definition format.c:348
int avformat_open_input(AVFormatContext **ps, const char *url, const AVInputFormat *fmt, AVDictionary **options)
Open an input stream and read the header.
Definition demux.c:231
int avformat_find_stream_info(AVFormatContext *ic, AVDictionary **options)
Read packets of a media file to get stream information.
Definition demux.c:2616
void avformat_close_input(AVFormatContext **s)
Close an opened input AVFormatContext.
Definition demux.c:377
int avformat_queue_attached_pictures(AVFormatContext *s)
Definition demux_utils.c:87
int av_match_ext(const char *filename, const char *extensions)
Return a positive value if the given filename has one of the given extensions, 0 otherwise.
Definition format.c:41
struct AVAES * av_aes_alloc(void)
Allocate an AVAES context.
Definition aes.c:37
void av_dict_free(AVDictionary **pm)
Free all the memory allocated for an AVDictionary struct and all keys and values.
Definition dict.c:233
AVDictionaryEntry * av_dict_get(const AVDictionary *m, const char *key, const AVDictionaryEntry *prev, int flags)
Get a dictionary entry with matching key.
Definition dict.c:60
const AVDictionaryEntry * av_dict_iterate(const AVDictionary *m, const AVDictionaryEntry *prev)
Iterate over a dictionary.
Definition dict.c:42
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_DONT_STRDUP_VAL
Take ownership of a value that's been allocated with av_malloc() or another memory allocation functio...
Definition dict.h:79
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
int av_dict_count(const AVDictionary *m)
Get number of entries in dictionary.
Definition dict.c:37
#define AV_DICT_MATCH_CASE
Only get an entry with exact-case key match.
Definition dict.h:74
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_EXIT
Immediate exit was requested; the called function should not be restarted.
Definition error.h:58
#define AVERROR_PROTOCOL_NOT_FOUND
Protocol not found.
Definition error.h:65
#define AVERROR_BUG
Internal bug, also see AVERROR_BUG2.
Definition error.h:52
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition error.h:61
#define AVERROR_EOF
End of file.
Definition error.h:57
#define av_err2str(errnum)
Convenience macro, the return value should be used only directly in function arguments but never stan...
Definition error.h:122
#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_INFO
Standard information.
Definition log.h:221
#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_rnd(int64_t a, AVRational bq, AVRational cq, enum AVRounding rnd)
Rescale a 64-bit integer by 2 rational numbers with specified rounding.
int64_t av_rescale_q(int64_t a, AVRational bq, AVRational cq)
Rescale a 64-bit integer by 2 rational numbers.
int64_t av_compare_mod(uint64_t a, uint64_t b, uint64_t mod)
Compare the remainders of two integer operands divided by a common divisor.
@ AV_ROUND_DOWN
Round toward -infinity.
void * av_fast_realloc(void *ptr, unsigned int *size, size_t min_size)
Reallocate the given buffer if it is not large enough, otherwise do nothing.
Definition mem.c:601
void av_fast_malloc(void *ptr, unsigned int *size, size_t min_size)
Allocate a buffer, reusing the given one if large enough.
Definition mem.c:661
void * av_memdup(const void *p, size_t size)
Duplicate a buffer with av_malloc().
Definition mem.c:408
AVMediaType
Definition avutil.h:198
@ AVMEDIA_TYPE_AUDIO
Definition avutil.h:201
@ AVMEDIA_TYPE_SUBTITLE
Definition avutil.h:203
@ AVMEDIA_TYPE_VIDEO
Definition avutil.h:200
@ AVMEDIA_TYPE_UNKNOWN
Usually treated as AVMEDIA_TYPE_DATA.
Definition avutil.h:199
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
int av_match_name(const char *name, const char *names)
Match instances of a name in a comma-separated list of names.
Definition avstring.c:344
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
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
Internal time base represented as integer.
Definition avutil.h:253
#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_get(void *obj, const char *name, int search_flags, uint8_t **out_val)
Definition opt.c:1291
#define AV_OPT_SEARCH_CHILDREN
Search in possible children of the given object first.
Definition opt.h:604
static void update_noheader_flag(AVFormatContext *s)
Definition hls.c:2263
#define MAX_CHARACTERISTICS_LEN
Definition hls.c:54
#define MAX_FIELD_LEN
Definition hls.c:53
static int open_input(HLSContext *c, struct playlist *pls, struct segment *seg, AVIOContext **in)
Definition hls.c:1470
static int is_native_http(AVIOContext *pb)
Definition hls.c:669
static int update_init_section(struct playlist *pls, struct segment *seg)
Definition hls.c:1577
static struct rendition * new_rendition(HLSContext *c, struct rendition_info *info, const char *url_base)
Definition hls.c:525
static int read_from_url(struct playlist *pls, struct segment *seg, uint8_t *buf, int buf_size)
Definition hls.c:1221
static struct segment * new_init_section(struct playlist *pls, struct init_section_info *info, const char *url_base)
Definition hls.c:451
static int find_timestamp_in_playlist(HLSContext *c, struct playlist *pls, int64_t timestamp, int64_t *seq_no, int64_t *seg_start_ts)
Definition hls.c:2058
static int read_data_continuous(void *opaque, uint8_t *buf, int buf_size)
Definition hls.c:1764
static int hls_read_header(AVFormatContext *s)
Definition hls.c:2301
static struct playlist * new_playlist(HLSContext *c, const char *url, const char *base)
Definition hls.c:335
static int read_subtitle_packet(struct playlist *v, AVPacket *pkt)
Definition hls.c:1970
static int set_stream_info_from_input_stream(AVStream *st, struct playlist *pls, AVStream *ist)
Definition hls.c:2198
static int test_segment(AVFormatContext *s, const AVInputFormat *in_fmt, struct playlist *pls, struct segment *seg)
Definition hls.c:785
static void free_segment_list(struct playlist *pls)
Definition hls.c:264
static void handle_key_args(void *context, const char *key, int key_len, char **dest, int *dest_len)
Definition hls.c:430
#define MPEG_TIME_BASE
Definition hls.c:56
static void free_init_section_list(struct playlist *pls)
Definition hls.c:271
static void add_renditions_to_variant(HLSContext *c, struct variant *var, enum AVMediaType type, const char *group_id)
Definition hls.c:2002
static int hls_probe(const AVProbeData *p)
Definition hls.c:3105
static int ensure_playlist(HLSContext *c, struct playlist **pls, const char *url)
Definition hls.c:658
PlaylistType
Definition hls.c:93
@ PLS_TYPE_UNSPECIFIED
Definition hls.c:94
@ PLS_TYPE_VOD
Definition hls.c:96
@ PLS_TYPE_EVENT
Definition hls.c:95
static int recheck_discard_flags(AVFormatContext *s, int first)
Definition hls.c:2627
static AVRational get_timebase(struct playlist *pls)
Definition hls.c:2697
static void fill_timing_for_id3_timestamped_stream(struct playlist *pls)
Definition hls.c:2672
static int64_t default_reload_interval(struct playlist *pls)
Definition hls.c:1634
static int open_url_keepalive(AVFormatContext *s, AVIOContext **pb, const char *url, AVDictionary **options)
Definition hls.c:679
static void add_metadata_from_renditions(AVFormatContext *s, struct playlist *pls, enum AVMediaType type)
Definition hls.c:2026
static int update_streams_from_subdemuxer(AVFormatContext *s, struct playlist *pls)
Definition hls.c:2222
static void add_stream_to_programs(AVFormatContext *s, struct playlist *pls, AVStream *stream)
Definition hls.c:2172
static int hls_close(AVFormatContext *s)
Definition hls.c:2284
static int metadata_has_changed(const AVDictionary *current, const AVDictionary *update)
Check whether any entry in update differs from the corresponding entry in current.
Definition hls.c:2723
static struct segment * next_segment(struct playlist *pls)
Definition hls.c:1198
static int nested_io_open(AVFormatContext *s, AVIOContext **pb, const char *url, int flags, AVDictionary **opts)
Definition hls.c:1920
static int reload_playlist(struct playlist *v, HLSContext *c)
Definition hls.c:1687
static void handle_id3(AVIOContext *pb, struct playlist *pls)
Definition hls.c:1296
#define PACKED_AUDIO_FORMATS
Definition hls.c:59
static void handle_rendition_args(void *vinfo, const char *key, int key_len, char **dest, int *dest_len)
Definition hls.c:612
static void free_segment_dynarray(struct segment **segments, int n_segments)
Definition hls.c:254
static int read_data_subtitle_segment(void *opaque, uint8_t *buf, int buf_size)
Definition hls.c:1891
static int init_subtitle_context(struct playlist *pls)
Definition hls.c:1930
static int compare_ts_with_wrapdetect(int64_t ts_a, struct playlist *pls_a, int64_t ts_b, struct playlist *pls_b)
Definition hls.c:2705
static int parse_playlist(HLSContext *c, const char *url, struct playlist *pls, AVIOContext *in)
Definition hls.c:832
#define MPEG_TIME_BASE_Q
Definition hls.c:57
static int segment_reusable(AVIOContext *in, const struct segment *cur, const struct segment *next)
Definition hls.c:1209
KeyType
Definition hls.c:73
@ KEY_SAMPLE_AES
Definition hls.c:76
@ KEY_NONE
Definition hls.c:74
@ KEY_AES_128
Definition hls.c:75
static void handle_variant_args(void *context, const char *key, int key_len, char **dest, int *dest_len)
Definition hls.c:405
static struct segment * current_segment(struct playlist *pls)
Definition hls.c:1190
static int hls_read_packet(AVFormatContext *s, AVPacket *pkt)
Definition hls.c:2737
static const AVOption hls_options[]
Definition hls.c:3143
static void free_rendition_list(HLSContext *c)
Definition hls.c:326
static int open_url(AVFormatContext *s, AVIOContext **pb, const char *url, AVDictionary **opts, AVDictionary *opts2, int *is_http_out)
Definition hls.c:697
#define OFFSET(x)
Definition hls.c:3141
static int id3_has_changed_values(struct playlist *pls, AVDictionary *metadata, ID3v2ExtraMetaAPIC *apic)
Definition hls.c:1267
static void free_playlist_list(HLSContext *c)
Definition hls.c:283
static const AVClass hls_class
Definition hls.c:3184
static int64_t select_cur_seq_no(HLSContext *c, struct playlist *pls)
Definition hls.c:2097
static struct variant * new_variant(HLSContext *c, struct variant_info *info, const char *url, const char *base)
Definition hls.c:379
static void intercept_id3(struct playlist *pls, uint8_t *buf, int buf_size, int *len)
Definition hls.c:1339
static int playlist_needed(struct playlist *pls)
Definition hls.c:1641
static void free_variant_list(HLSContext *c)
Definition hls.c:314
static void parse_id3(AVFormatContext *s, AVIOContext *pb, AVDictionary **metadata, int64_t *dts, HLSAudioSetupInfo *audio_setup_info, ID3v2ExtraMetaAPIC **apic, ID3v2ExtraMeta **extra_meta)
Definition hls.c:1238
static void handle_init_section_args(void *context, const char *key, int key_len, char **dest, int *dest_len)
Definition hls.c:500
static int hls_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
Definition hls.c:2947
int ff_hls_senc_decrypt_frame(enum AVCodecID codec_id, HLSCryptoContext *crypto_ctx, AVPacket *pkt)
int ff_hls_senc_parse_audio_setup_info(AVStream *st, HLSAudioSetupInfo *info)
void ff_hls_senc_read_audio_setup_info(HLSAudioSetupInfo *info, const uint8_t *buf, size_t size)
Apple HTTP Live Streaming Sample Encryption https://developer.apple.com/library/ios/documentation/Aud...
#define HLS_MAX_ID3_TAGS_DATA_LEN
int ff_http_do_new_request2(URLContext *h, const char *uri, AVDictionary **opts)
Send a new HTTP request, reusing the old connection.
Definition http.c:555
int ff_id3v2_tag_len(const uint8_t *buf)
Get the length of an ID3v2 tag.
Definition id3v2.c:165
int ff_id3v2_match(const uint8_t *buf, const char *magic)
Detect ID3v2 Header.
Definition id3v2.c:152
void ff_id3v2_free_extra_meta(ID3v2ExtraMeta **extra_meta)
Free memory allocated parsing special (non-text) metadata.
Definition id3v2.c:1186
int ff_id3v2_parse_priv_dict(AVDictionary **metadata, ID3v2ExtraMeta *extra_meta)
Parse PRIV tags into a dictionary.
Definition id3v2.c:1258
int ff_id3v2_parse_apic(AVFormatContext *s, ID3v2ExtraMeta *extra_meta)
Create a stream for each APIC (attached picture) extracted from the ID3v2 header.
Definition id3v2.c:1202
int ff_id3v2_parse_priv(AVFormatContext *s, ID3v2ExtraMeta *extra_meta)
Add metadata for all PRIV tags in the ID3v2 header.
Definition id3v2.c:1298
void ff_id3v2_read_dict(AVFormatContext *s, AVIOContext *pb, AVDictionary **metadata, const char *magic, ID3v2ExtraMeta **extra_meta)
Read an ID3v2 tag into specified dictionary and retrieve supported extra metadata.
Definition id3v2.c:1174
#define ID3v2_DEFAULT_MAGIC
Default magic bytes for ID3v2 header: "ID3".
Definition id3v2.h:35
#define ID3v2_HEADER_SIZE
Definition id3v2.h:30
#define r
Definition input.c:42
#define AV_WB64(p, v)
#define AV_RB64(p)
uint32_t type
Definition jpegmpfenc.c:80
unsigned offset
Definition libaomenc.c:763
int ff_match_url_ext(const char *url, const char *extensions)
Return a positive value if the given url has one of the given extensions, negative AVERROR on error,...
Definition format.c:54
int ff_hex_to_data(uint8_t *data, const char *p)
Parse a string of hexadecimal strings.
Definition utils.c:495
static av_always_inline FFStream * ffstream(AVStream *st)
Definition internal.h:365
#define dynarray_add(tab, nb_ptr, elem)
Definition internal.h:376
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
#define MAX_URL_SIZE
Definition internal.h:30
void ff_parse_key_value(const char *str, ff_parse_key_val_cb callback_get_buf, void *context)
Parse a string with comma-separated key=value pairs.
Definition utils.c:523
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification.
Definition internal.h:97
void avpriv_report_missing_feature(void *avc, const char *msg,...) av_printf_format(2
Log a generic warning message about a missing feature.
static av_cold int read_close(AVFormatContext *ctx)
Definition libcdio.c:143
static int read_seek(AVFormatContext *ctx, int stream_index, int64_t timestamp, int flags)
Definition libcdio.c:151
#define FFSWAP(type, a, b)
Definition macros.h:52
#define FFMIN(a, b)
Definition macros.h:49
#define FFMAX(a, b)
Definition macros.h:47
Memory handling functions.
#define av_strdup(s)
Definition ops_static.c:55
#define av_malloc(s)
Definition ops_static.c:52
AVOptions.
unsigned int pos
Definition spdifenc.c:431
double strtod(const char *, char **)
uint8_t * data
The data buffer.
Definition buffer.h:90
size_t size
Size of data in bytes.
Definition buffer.h:94
Describe the class of an AVClass context structure.
Definition log.h:76
enum AVMediaType codec_type
General type of the encoded data.
Definition codec_par.h:53
enum AVCodecID codec_id
Specific type of the encoded data (the codec used).
Definition codec_par.h:57
char * key
Definition dict.h:91
char * value
Definition dict.h:92
Format I/O context.
Definition avformat.h:1337
int event_flags
Flags indicating events happening on the file, a combination of AVFMT_EVENT_FLAG_*.
Definition avformat.h:1724
unsigned int nb_streams
Number of elements in AVFormatContext.streams.
Definition avformat.h:1393
AVIOContext * pb
I/O context.
Definition avformat.h:1379
AVDictionary * metadata
Metadata that applies to the whole file.
Definition avformat.h:1584
int flags
Flags modifying the (de)muxer behaviour.
Definition avformat.h:1488
int64_t max_analyze_duration
Maximum duration (in AV_TIME_BASE units) of the data read from input in avformat_find_stream_info().
Definition avformat.h:1544
int ctx_flags
Flags signalling stream properties.
Definition avformat.h:1386
AVIOInterruptCB interrupt_callback
Custom interrupt callbacks for the I/O layer.
Definition avformat.h:1622
const struct AVInputFormat * iformat
The input container format.
Definition avformat.h:1349
void * priv_data
Format private data.
Definition avformat.h:1365
int64_t probesize
Maximum number of bytes read from input in order to determine stream properties.
Definition avformat.h:1536
AVStream ** streams
A list of all streams in the file.
Definition avformat.h:1405
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:1957
Bytestream IO Context.
Definition avio.h:160
unsigned char * buf_end
End of the data, may be less than buffer+buffer_size if the read function returned less data than req...
Definition avio.h:228
int seekable
A combination of AVIO_SEEKABLE_ flags or 0 when the stream is not seekable.
Definition avio.h:261
unsigned char * buf_ptr
Current position in the buffer.
Definition avio.h:227
int64_t pos
position in the file of the current buffer
Definition avio.h:237
unsigned char * buffer
Start of the buffer.
Definition avio.h:225
int eof_reached
true if was unable to read due to error or eof
Definition avio.h:238
Callback for checking whether to abort blocking functions.
Definition avio.h:59
const char * name
A comma separated list of short names for the format.
Definition avformat.h:572
const char * extensions
If extensions are defined, then no probe is done.
Definition avformat.h:594
AVOption.
Definition opt.h:428
This structure stores compressed data.
Definition packet.h:580
int stream_index
Definition packet.h:605
int flags
A combination of AV_PKT_FLAG values.
Definition packet.h:609
int size
Definition packet.h:604
int64_t duration
Duration of this packet in AVStream->time_base units, 0 if unknown.
Definition packet.h:621
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
Definition packet.h:596
int64_t dts
Decompression timestamp in AVStream->time_base units; the time at which the packet is decompressed.
Definition packet.h:602
uint8_t * data
Definition packet.h:603
This structure contains the data a format has to probe a file.
Definition avformat.h:473
New fields can be added to the end with minor version bumps.
Definition avformat.h:1261
unsigned int nb_stream_indexes
Definition avformat.h:1266
unsigned int * stream_index
Definition avformat.h:1265
enum AVDiscard discard
selects which program to discard and which to feed to the caller
Definition avformat.h:1264
AVDictionary * metadata
Definition avformat.h:1267
Rational number (pair of numerator and denominator).
Definition rational.h:58
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
enum AVDiscard discard
Selects which packets can be discarded at will and do not need to be demuxed.
Definition avformat.h:839
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
int64_t start_time
Decoding: pts of the first frame of the stream in presentation order, in stream time base.
Definition avformat.h:817
AVPacket attached_pic
For streams with AV_DISPOSITION_ATTACHED_PIC disposition, this packet will contain the attached pictu...
Definition avformat.h:866
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented.
Definition avformat.h:807
int event_flags
Flags indicating events happening on the stream, a combination of AVSTREAM_EVENT_FLAG_*.
Definition avformat.h:879
int disposition
Stream disposition - a combination of AV_DISPOSITION_* flags.
Definition avformat.h:837
AVIOContext pub
int64_t pts_wrap_reference
Internal data to check for wrapping of the time stamp.
Definition internal.h:262
int need_context_update
Whether the internal avctx needs to be updated from codecpar (after a late change to codecpar)
Definition internal.h:180
int prefer_x_start
Definition hls.c:233
int first_timestamp_locked
Definition hls.c:237
int n_renditions
Definition hls.c:227
int http_multiple
Definition hls.c:247
AVDictionary * seg_format_opts
Definition hls.c:241
struct rendition ** renditions
Definition hls.c:228
int m3u8_hold_counters
Definition hls.c:231
AVIOInterruptCB * interrupt_callback
Definition hls.c:239
int seg_max_retry
Definition hls.c:249
AVDictionary * avio_opts
Definition hls.c:240
char * allowed_segment_extensions
Definition hls.c:243
int n_variants
Definition hls.c:223
int http_persistent
Definition hls.c:246
struct variant ** variants
Definition hls.c:224
int extension_picky
Definition hls.c:244
AVFormatContext * ctx
Definition hls.c:222
int64_t cur_seq_no
Definition hls.c:230
int live_start_index
Definition hls.c:232
AVIOContext * playlist_pb
Definition hls.c:250
int first_packet
Definition hls.c:234
int max_reload
Definition hls.c:245
int n_playlists
Definition hls.c:225
struct playlist * first_timestamp_pls
Definition hls.c:236
int64_t cur_timestamp
Definition hls.c:238
HLSCryptoContext crypto_ctx
Definition hls.c:251
int64_t first_timestamp
Definition hls.c:235
struct playlist ** playlists
Definition hls.c:226
char * allowed_extensions
Definition hls.c:242
int http_seekable
Definition hls.c:248
AVBufferRef * buf
Definition id3v2.h:66
uint8_t * data
Definition id3v2.h:74
uint32_t datasize
Definition id3v2.h:75
uint8_t * owner
Definition id3v2.h:73
ID3v2ExtraMetaPRIV priv
Definition id3v2.h:91
ID3v2ExtraMetaAPIC apic
Definition id3v2.h:88
union ID3v2ExtraMeta::@257041253361347165140143067330023232307201221326 data
const char * tag
Definition id3v2.h:85
struct ID3v2ExtraMeta * next
Definition id3v2.h:86
const struct URLProtocol * prot
Definition url.h:37
const char * name
Definition url.h:55
char uri[MAX_URL_SIZE]
Definition hls.c:447
char byterange[32]
Definition hls.c:448
char iv[35]
Definition hls.c:427
char uri[MAX_URL_SIZE]
Definition hls.c:425
char method[11]
Definition hls.c:426
int finished
Definition hls.c:123
int id3_changed
Definition hls.c:159
int broken
Definition hls.c:132
int64_t cur_seg_offset
Definition hls.c:137
int input_reuse
Definition hls.c:109
AVIOContext * input
Definition hls.c:107
int64_t cur_seq_no
Definition hls.c:133
int n_renditions
Definition hls.c:175
int64_t first_read_seq_no
Definition hls.c:135
int64_t id3_mpegts_timestamp
Definition hls.c:153
FFIOContext pb
Definition hls.c:106
struct rendition ** renditions
Definition hls.c:176
unsigned int init_sec_data_len
Definition hls.c:144
int64_t id3_offset
Definition hls.c:154
int64_t target_duration
Definition hls.c:125
int64_t last_load_time
Definition hls.c:138
int64_t last_seq_no
Definition hls.c:134
int seek_stream_index
Definition hls.c:169
HLSAudioSetupInfo audio_setup_info
Definition hls.c:162
int64_t start_seq_no
Definition hls.c:126
int is_subtitle
Definition hls.c:182
unsigned int id3_buf_size
Definition hls.c:156
AVStream ** main_streams
Definition hls.c:120
AVIOContext * input_next
Definition hls.c:110
unsigned int init_sec_buf_read_offset
Definition hls.c:145
int64_t ts_offset
Definition hls.c:166
int64_t seek_timestamp
Definition hls.c:167
AVPacket * pkt
Definition hls.c:115
int input_read_done
Definition hls.c:108
AVFormatContext * ctx
Definition hls.c:114
uint8_t * init_sec_buf
Definition hls.c:142
struct segment * cur_init_section
Definition hls.c:141
uint8_t * id3_buf
Definition hls.c:155
uint8_t key[16]
Definition hls.c:148
int id3_found
Definition hls.c:158
int index
Definition hls.c:113
int m3u8_hold_counters
Definition hls.c:136
int needed
Definition hls.c:131
int has_noheader_flag
Definition hls.c:116
char key_url[MAX_URL_SIZE]
Definition hls.c:147
int timed_id3_stream_index
Definition hls.c:190
int n_init_sections
Definition hls.c:180
int64_t start_time_offset
Definition hls.c:128
AVDictionary * timed_id3_metadata
Definition hls.c:189
struct segment ** segments
Definition hls.c:130
int n_segments
Definition hls.c:129
struct segment ** init_sections
Definition hls.c:181
char url[MAX_URL_SIZE]
Definition hls.c:105
AVFormatContext * parent
Definition hls.c:112
int time_offset_flag
Definition hls.c:127
int seek_flags
Definition hls.c:168
int is_id3_timestamped
Definition hls.c:152
unsigned int init_sec_buf_size
Definition hls.c:143
int n_main_streams
Definition hls.c:121
int input_next_requested
Definition hls.c:111
ID3v2ExtraMeta * id3_deferred_extra
Definition hls.c:160
AVDictionary * id3_initial
Definition hls.c:157
enum PlaylistType type
Definition hls.c:124
char type[16]
Definition hls.c:514
char defaultr[4]
Definition hls.c:520
char name[MAX_FIELD_LEN]
Definition hls.c:519
char language[MAX_FIELD_LEN]
Definition hls.c:517
char forced[4]
Definition hls.c:521
char uri[MAX_URL_SIZE]
Definition hls.c:515
char group_id[MAX_FIELD_LEN]
Definition hls.c:516
char characteristics[MAX_CHARACTERISTICS_LEN]
Definition hls.c:522
char assoc_language[MAX_FIELD_LEN]
Definition hls.c:518
char name[MAX_FIELD_LEN]
Definition hls.c:204
enum AVMediaType type
Definition hls.c:200
char group_id[MAX_FIELD_LEN]
Definition hls.c:202
char language[MAX_FIELD_LEN]
Definition hls.c:203
int disposition
Definition hls.c:205
struct playlist * playlist
Definition hls.c:201
Definition hls.c:79
struct segment * init_section
Definition hls.c:88
int64_t size
Definition hls.c:82
uint8_t iv[16]
Definition hls.c:86
char * url
Definition hls.c:83
int64_t duration
Definition hls.c:80
int64_t url_offset
Definition hls.c:81
char * key
Definition hls.c:84
enum KeyType key_type
Definition hls.c:85
char bandwidth[20]
Definition hls.c:372
char video[MAX_FIELD_LEN]
Definition hls.c:375
char subtitles[MAX_FIELD_LEN]
Definition hls.c:376
char audio[MAX_FIELD_LEN]
Definition hls.c:374
Definition hls.c:208
int bandwidth
Definition hls.c:209
char audio_group[MAX_FIELD_LEN]
Definition hls.c:215
int n_playlists
Definition hls.c:212
struct playlist ** playlists
Definition hls.c:213
char video_group[MAX_FIELD_LEN]
Definition hls.c:216
char subtitles_group[MAX_FIELD_LEN]
Definition hls.c:217
#define av_free(p)
#define av_mallocz(s)
#define av_freep(p)
#define av_log(a,...)
static uint8_t tmp[40]
Definition aes_ctr.c:52
int av_usleep(unsigned usec)
Sleep for a period of time.
Definition time.c:93
int64_t av_gettime_relative(void)
Get the current time in microseconds since some unspecified starting point.
Definition time.c:57
int size
int ff_make_absolute_url(char *buf, int size, const char *base, const char *rel)
Convert a relative url into an absolute url, given a base url.
Definition url.c:321
unbuffered private I/O API
enum AVCodecID codec_id
static void fill_buf(uint8_t *data, int w, int h, int linesize, uint8_t v)
static av_always_inline int diff(const struct color_info *a, const struct color_info *b, const int trans_thresh)
float delta
int len
uint8_t base
Definition vp3data.h:128
static double c[64]