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