FFmpeg  4.4.9
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  *
6  * This file is part of FFmpeg.
7  *
8  * FFmpeg is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * FFmpeg is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with FFmpeg; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22 
23 /**
24  * @file
25  * Apple HTTP Live Streaming demuxer
26  * https://www.rfc-editor.org/rfc/rfc8216.txt
27  */
28 
29 #include "libavformat/http.h"
30 #include "libavutil/avstring.h"
31 #include "libavutil/avassert.h"
32 #include "libavutil/intreadwrite.h"
33 #include "libavutil/mathematics.h"
34 #include "libavutil/opt.h"
35 #include "libavutil/dict.h"
36 #include "libavutil/time.h"
37 #include "avformat.h"
38 #include "internal.h"
39 #include "avio_internal.h"
40 #include "id3v2.h"
41 
42 #define INITIAL_BUFFER_SIZE 32768
43 
44 #define MAX_FIELD_LEN 64
45 #define MAX_CHARACTERISTICS_LEN 512
46 
47 #define MPEG_TIME_BASE 90000
48 #define MPEG_TIME_BASE_Q (AVRational){1, MPEG_TIME_BASE}
49 
50 #define PACKED_AUDIO_FORMATS "aac,ac3,eac3,mp3"
51 
52 /*
53  * An apple http stream consists of a playlist with media segment files,
54  * played sequentially. There may be several playlists with the same
55  * video content, in different bandwidth variants, that are played in
56  * parallel (preferably only one bandwidth variant at a time). In this case,
57  * the user supplied the url to a main playlist that only lists the variant
58  * playlists.
59  *
60  * If the main playlist doesn't point at any variants, we still create
61  * one anonymous toplevel variant for this, to maintain the structure.
62  */
63 
64 enum KeyType {
68 };
69 
70 struct segment {
74  char *url;
75  char *key;
76  enum KeyType key_type;
77  uint8_t iv[16];
78  /* associated Media Initialization Section, treated as a segment */
80 };
81 
82 struct rendition;
83 
88 };
89 
90 /*
91  * Each playlist has its own demuxer. If it currently is active,
92  * it has an open AVIOContext too, and potentially an AVPacket
93  * containing the next packet from this stream.
94  */
95 struct playlist {
104  int index;
108 
109  /* main demuxer streams associated with this playlist
110  * indexed by the subdemuxer stream indexes */
113 
114  int finished;
115  enum PlaylistType type;
119  struct segment **segments;
120  int needed;
121  int broken;
127 
128  /* Currently active Media Initialization Section */
131  unsigned int init_sec_buf_size;
132  unsigned int init_sec_data_len;
134 
137 
138  /* ID3 timestamp handling (elementary audio streams have ID3 timestamps
139  * (and possibly other ID3 tags) in the beginning of each segment) */
140  int is_id3_timestamped; /* -1: not yet known */
141  int64_t id3_mpegts_timestamp; /* in mpegts tb */
142  int64_t id3_offset; /* in stream original tb */
143  uint8_t* id3_buf; /* temp buffer for id3 parsing */
144  unsigned int id3_buf_size;
145  AVDictionary *id3_initial; /* data from first id3 tag */
146  int id3_found; /* ID3 tag found at some point */
147  int id3_changed; /* ID3 tag data has changed at some point */
148  ID3v2ExtraMeta *id3_deferred_extra; /* stored here until subdemuxer is opened */
149 
152  int seek_stream_index; /* into subdemuxer stream array */
153 
154  /* Renditions associated with this playlist, if any.
155  * Alternative rendition playlists have a single rendition associated
156  * with them, and variant main Media Playlists may have
157  * multiple (playlist-less) renditions associated with them. */
160 
161  /* Media Initialization Sections (EXT-X-MAP) associated with this
162  * playlist, if any. */
165 };
166 
167 /*
168  * Renditions are e.g. alternative subtitle or audio streams.
169  * The rendition may either be an external playlist or it may be
170  * contained in the main Media Playlist of the variant (in which case
171  * playlist is NULL).
172  */
173 struct rendition {
174  enum AVMediaType type;
180 };
181 
182 struct variant {
184 
185  /* every variant contains at least the main Media Playlist in index 0 */
187  struct playlist **playlists;
188 
192 };
193 
194 typedef struct HLSContext {
195  AVClass *class;
198  struct variant **variants;
200  struct playlist **playlists;
203 
220 } HLSContext;
221 
222 static void free_segment_dynarray(struct segment **segments, int n_segments)
223 {
224  int i;
225  for (i = 0; i < n_segments; i++) {
226  av_freep(&segments[i]->key);
227  av_freep(&segments[i]->url);
228  av_freep(&segments[i]);
229  }
230 }
231 
232 static void free_segment_list(struct playlist *pls)
233 {
235  av_freep(&pls->segments);
236  pls->n_segments = 0;
237 }
238 
239 static void free_init_section_list(struct playlist *pls)
240 {
241  int i;
242  for (i = 0; i < pls->n_init_sections; i++) {
243  av_freep(&pls->init_sections[i]->key);
244  av_freep(&pls->init_sections[i]->url);
245  av_freep(&pls->init_sections[i]);
246  }
247  av_freep(&pls->init_sections);
248  pls->n_init_sections = 0;
249 }
250 
252 {
253  int i;
254  for (i = 0; i < c->n_playlists; i++) {
255  struct playlist *pls = c->playlists[i];
256  free_segment_list(pls);
258  av_freep(&pls->main_streams);
259  av_freep(&pls->renditions);
260  av_freep(&pls->id3_buf);
261  av_dict_free(&pls->id3_initial);
263  av_freep(&pls->init_sec_buf);
264  av_packet_free(&pls->pkt);
265  av_freep(&pls->pb.buffer);
266  ff_format_io_close(c->ctx, &pls->input);
267  pls->input_read_done = 0;
268  ff_format_io_close(c->ctx, &pls->input_next);
269  pls->input_next_requested = 0;
270  if (pls->ctx) {
271  pls->ctx->pb = NULL;
272  avformat_close_input(&pls->ctx);
273  }
274  av_free(pls);
275  }
276  av_freep(&c->playlists);
277  c->n_playlists = 0;
278 }
279 
281 {
282  int i;
283  for (i = 0; i < c->n_variants; i++) {
284  struct variant *var = c->variants[i];
285  av_freep(&var->playlists);
286  av_free(var);
287  }
288  av_freep(&c->variants);
289  c->n_variants = 0;
290 }
291 
293 {
294  int i;
295  for (i = 0; i < c->n_renditions; i++)
296  av_freep(&c->renditions[i]);
297  av_freep(&c->renditions);
298  c->n_renditions = 0;
299 }
300 
301 static struct playlist *new_playlist(HLSContext *c, const char *url,
302  const char *base)
303 {
304  struct playlist *pls = av_mallocz(sizeof(struct playlist));
305  if (!pls)
306  return NULL;
307  pls->pkt = av_packet_alloc();
308  if (!pls->pkt) {
309  av_free(pls);
310  return NULL;
311  }
312  ff_make_absolute_url(pls->url, sizeof(pls->url), base, url);
313  if (!pls->url[0]) {
314  av_packet_free(&pls->pkt);
315  av_free(pls);
316  return NULL;
317  }
319 
320  pls->is_id3_timestamped = -1;
322 
323  dynarray_add(&c->playlists, &c->n_playlists, pls);
324  return pls;
325 }
326 
327 struct variant_info {
328  char bandwidth[20];
329  /* variant group ids: */
333 };
334 
335 static struct variant *new_variant(HLSContext *c, struct variant_info *info,
336  const char *url, const char *base)
337 {
338  struct variant *var;
339  struct playlist *pls;
340 
341  pls = new_playlist(c, url, base);
342  if (!pls)
343  return NULL;
344 
345  var = av_mallocz(sizeof(struct variant));
346  if (!var)
347  return NULL;
348 
349  if (info) {
350  var->bandwidth = atoi(info->bandwidth);
351  strcpy(var->audio_group, info->audio);
352  strcpy(var->video_group, info->video);
353  strcpy(var->subtitles_group, info->subtitles);
354  }
355 
356  dynarray_add(&c->variants, &c->n_variants, var);
357  dynarray_add(&var->playlists, &var->n_playlists, pls);
358  return var;
359 }
360 
361 static void handle_variant_args(struct variant_info *info, const char *key,
362  int key_len, char **dest, int *dest_len)
363 {
364  if (!strncmp(key, "BANDWIDTH=", key_len)) {
365  *dest = info->bandwidth;
366  *dest_len = sizeof(info->bandwidth);
367  } else if (!strncmp(key, "AUDIO=", key_len)) {
368  *dest = info->audio;
369  *dest_len = sizeof(info->audio);
370  } else if (!strncmp(key, "VIDEO=", key_len)) {
371  *dest = info->video;
372  *dest_len = sizeof(info->video);
373  } else if (!strncmp(key, "SUBTITLES=", key_len)) {
374  *dest = info->subtitles;
375  *dest_len = sizeof(info->subtitles);
376  }
377 }
378 
379 struct key_info {
381  char method[11];
382  char iv[35];
383 };
384 
385 static void handle_key_args(struct key_info *info, const char *key,
386  int key_len, char **dest, int *dest_len)
387 {
388  if (!strncmp(key, "METHOD=", key_len)) {
389  *dest = info->method;
390  *dest_len = sizeof(info->method);
391  } else if (!strncmp(key, "URI=", key_len)) {
392  *dest = info->uri;
393  *dest_len = sizeof(info->uri);
394  } else if (!strncmp(key, "IV=", key_len)) {
395  *dest = info->iv;
396  *dest_len = sizeof(info->iv);
397  }
398 }
399 
402  char byterange[32];
403 };
404 
405 static struct segment *new_init_section(struct playlist *pls,
406  struct init_section_info *info,
407  const char *url_base)
408 {
409  struct segment *sec;
410  char tmp_str[MAX_URL_SIZE], *ptr = tmp_str;
411 
412  if (!info->uri[0])
413  return NULL;
414 
415  sec = av_mallocz(sizeof(*sec));
416  if (!sec)
417  return NULL;
418 
419  if (!av_strncasecmp(info->uri, "data:", 5)) {
420  ptr = info->uri;
421  } else {
422  ff_make_absolute_url(tmp_str, sizeof(tmp_str), url_base, info->uri);
423  if (!tmp_str[0]) {
424  av_free(sec);
425  return NULL;
426  }
427  }
428  sec->url = av_strdup(ptr);
429  if (!sec->url) {
430  av_free(sec);
431  return NULL;
432  }
433 
434  if (info->byterange[0]) {
435  sec->size = strtoll(info->byterange, NULL, 10);
436  ptr = strchr(info->byterange, '@');
437  if (ptr)
438  sec->url_offset = strtoll(ptr+1, NULL, 10);
439  if (sec->size < 0 || sec->url_offset < 0 || sec->size > INT64_MAX - sec->url_offset) {
440  av_freep(&sec->url);
441  av_free(sec);
442  return NULL;
443  }
444  } else {
445  /* the entire file is the init section */
446  sec->size = -1;
447  }
448 
449  dynarray_add(&pls->init_sections, &pls->n_init_sections, sec);
450 
451  return sec;
452 }
453 
454 static void handle_init_section_args(void *context, const char *key,
455  int key_len, char **dest, int *dest_len)
456 {
457  struct init_section_info *info = context;
458  if (!strncmp(key, "URI=", key_len)) {
459  *dest = info->uri;
460  *dest_len = sizeof(info->uri);
461  } else if (!strncmp(key, "BYTERANGE=", key_len)) {
462  *dest = info->byterange;
463  *dest_len = sizeof(info->byterange);
464  }
465 }
466 
468  char type[16];
474  char defaultr[4];
475  char forced[4];
477 };
478 
479 static struct rendition *new_rendition(HLSContext *c, struct rendition_info *info,
480  const char *url_base)
481 {
482  struct rendition *rend;
484  char *characteristic;
485  char *chr_ptr;
486  char *saveptr;
487 
488  if (!strcmp(info->type, "AUDIO"))
490  else if (!strcmp(info->type, "VIDEO"))
492  else if (!strcmp(info->type, "SUBTITLES"))
494  else if (!strcmp(info->type, "CLOSED-CAPTIONS"))
495  /* CLOSED-CAPTIONS is ignored since we do not support CEA-608 CC in
496  * AVC SEI RBSP anyway */
497  return NULL;
498 
499  if (type == AVMEDIA_TYPE_UNKNOWN) {
500  av_log(c->ctx, AV_LOG_WARNING, "Can't support the type: %s\n", info->type);
501  return NULL;
502  }
503 
504  /* URI is mandatory for subtitles as per spec */
505  if (type == AVMEDIA_TYPE_SUBTITLE && !info->uri[0]) {
506  av_log(c->ctx, AV_LOG_ERROR, "The URI tag is REQUIRED for subtitle.\n");
507  return NULL;
508  }
509 
510  /* TODO: handle subtitles (each segment has to parsed separately) */
511  if (c->ctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL)
512  if (type == AVMEDIA_TYPE_SUBTITLE) {
513  av_log(c->ctx, AV_LOG_WARNING, "Can't support the subtitle(uri: %s)\n", info->uri);
514  return NULL;
515  }
516 
517  rend = av_mallocz(sizeof(struct rendition));
518  if (!rend)
519  return NULL;
520 
521  dynarray_add(&c->renditions, &c->n_renditions, rend);
522 
523  rend->type = type;
524  strcpy(rend->group_id, info->group_id);
525  strcpy(rend->language, info->language);
526  strcpy(rend->name, info->name);
527 
528  /* add the playlist if this is an external rendition */
529  if (info->uri[0]) {
530  rend->playlist = new_playlist(c, info->uri, url_base);
531  if (rend->playlist)
533  &rend->playlist->n_renditions, rend);
534  }
535 
536  if (info->assoc_language[0]) {
537  int langlen = strlen(rend->language);
538  if (langlen < sizeof(rend->language) - 3) {
539  rend->language[langlen] = ',';
540  strncpy(rend->language + langlen + 1, info->assoc_language,
541  sizeof(rend->language) - langlen - 2);
542  }
543  }
544 
545  if (!strcmp(info->defaultr, "YES"))
547  if (!strcmp(info->forced, "YES"))
549 
550  chr_ptr = info->characteristics;
551  while ((characteristic = av_strtok(chr_ptr, ",", &saveptr))) {
552  if (!strcmp(characteristic, "public.accessibility.describes-music-and-sound"))
554  else if (!strcmp(characteristic, "public.accessibility.describes-video"))
556 
557  chr_ptr = NULL;
558  }
559 
560  return rend;
561 }
562 
563 static void handle_rendition_args(void *vinfo, const char *key,
564  int key_len, char **dest, int *dest_len)
565 {
566  struct rendition_info *info = vinfo;
567 
568  if (!strncmp(key, "TYPE=", key_len)) {
569  *dest = info->type;
570  *dest_len = sizeof(info->type);
571  } else if (!strncmp(key, "URI=", key_len)) {
572  *dest = info->uri;
573  *dest_len = sizeof(info->uri);
574  } else if (!strncmp(key, "GROUP-ID=", key_len)) {
575  *dest = info->group_id;
576  *dest_len = sizeof(info->group_id);
577  } else if (!strncmp(key, "LANGUAGE=", key_len)) {
578  *dest = info->language;
579  *dest_len = sizeof(info->language);
580  } else if (!strncmp(key, "ASSOC-LANGUAGE=", key_len)) {
581  *dest = info->assoc_language;
582  *dest_len = sizeof(info->assoc_language);
583  } else if (!strncmp(key, "NAME=", key_len)) {
584  *dest = info->name;
585  *dest_len = sizeof(info->name);
586  } else if (!strncmp(key, "DEFAULT=", key_len)) {
587  *dest = info->defaultr;
588  *dest_len = sizeof(info->defaultr);
589  } else if (!strncmp(key, "FORCED=", key_len)) {
590  *dest = info->forced;
591  *dest_len = sizeof(info->forced);
592  } else if (!strncmp(key, "CHARACTERISTICS=", key_len)) {
593  *dest = info->characteristics;
594  *dest_len = sizeof(info->characteristics);
595  }
596  /*
597  * ignored:
598  * - AUTOSELECT: client may autoselect based on e.g. system language
599  * - INSTREAM-ID: EIA-608 closed caption number ("CC1".."CC4")
600  */
601 }
602 
603 /* used by parse_playlist to allocate a new variant+playlist when the
604  * playlist is detected to be a Media Playlist (not Master Playlist)
605  * and we have no parent Master Playlist (parsing of which would have
606  * allocated the variant and playlist already)
607  * *pls == NULL => Master Playlist or parentless Media Playlist
608  * *pls != NULL => parented Media Playlist, playlist+variant allocated */
609 static int ensure_playlist(HLSContext *c, struct playlist **pls, const char *url)
610 {
611  if (*pls)
612  return 0;
613  struct variant *var = new_variant(c, NULL, url, NULL);
614  if (!var)
615  return AVERROR(ENOMEM);
616  *pls = var->playlists[0];
617  return 0;
618 }
619 
621  const char *url, AVDictionary **options)
622 {
623 #if !CONFIG_HTTP_PROTOCOL
625 #else
626  int ret;
627  URLContext *uc = ffio_geturlcontext(*pb);
628  av_assert0(uc);
629  (*pb)->eof_reached = 0;
630  ret = ff_http_do_new_request2(uc, url, options);
631  if (ret < 0) {
632  ff_format_io_close(s, pb);
633  }
634  return ret;
635 #endif
636 }
637 
638 static int open_url(AVFormatContext *s, AVIOContext **pb, const char *url,
639  AVDictionary **opts, AVDictionary *opts2, int *is_http_out)
640 {
641  HLSContext *c = s->priv_data;
642  AVDictionary *tmp = NULL;
643  const char *proto_name = NULL;
644  int ret;
645  int is_http = 0;
646 
647  if (av_strstart(url, "crypto", NULL)) {
648  if (url[6] == '+' || url[6] == ':')
649  proto_name = avio_find_protocol_name(url + 7);
650  } else if (av_strstart(url, "data", NULL)) {
651  if (url[4] == '+' || url[4] == ':')
652  proto_name = avio_find_protocol_name(url + 5);
653  }
654 
655  if (!proto_name)
656  proto_name = avio_find_protocol_name(url);
657 
658  if (!proto_name)
659  return AVERROR_INVALIDDATA;
660 
661  // only http(s) & file are allowed
662  if (av_strstart(proto_name, "file", NULL)) {
663  if (strcmp(c->allowed_extensions, "ALL") && !av_match_ext(url, c->allowed_extensions)) {
665  "Filename extension of \'%s\' is not a common multimedia extension, blocked for security reasons.\n"
666  "If you wish to override this adjust allowed_extensions, you can set it to \'ALL\' to allow all\n",
667  url);
668  return AVERROR_INVALIDDATA;
669  }
670  } else if (av_strstart(proto_name, "http", NULL)) {
671  is_http = 1;
672  } else if (av_strstart(proto_name, "data", NULL)) {
673  ;
674  } else
675  return AVERROR_INVALIDDATA;
676 
677  if (!strncmp(proto_name, url, strlen(proto_name)) && url[strlen(proto_name)] == ':')
678  ;
679  else if (av_strstart(url, "crypto", NULL) && !strncmp(proto_name, url + 7, strlen(proto_name)) && url[7 + strlen(proto_name)] == ':')
680  ;
681  else if (av_strstart(url, "data", NULL) && !strncmp(proto_name, url + 5, strlen(proto_name)) && url[5 + strlen(proto_name)] == ':')
682  ;
683  else if (strcmp(proto_name, "file") || !strncmp(url, "file,", 5))
684  return AVERROR_INVALIDDATA;
685 
686  av_dict_copy(&tmp, *opts, 0);
687  av_dict_copy(&tmp, opts2, 0);
688 
689  if (is_http && c->http_persistent && *pb) {
690  ret = open_url_keepalive(c->ctx, pb, url, &tmp);
691  if (ret == AVERROR_EXIT) {
692  av_dict_free(&tmp);
693  return ret;
694  } else if (ret < 0) {
695  if (ret != AVERROR_EOF)
697  "keepalive request failed for '%s' with error: '%s' when opening url, retrying with new connection\n",
698  url, av_err2str(ret));
699  av_dict_copy(&tmp, *opts, 0);
700  av_dict_copy(&tmp, opts2, 0);
701  ret = s->io_open(s, pb, url, AVIO_FLAG_READ, &tmp);
702  }
703  } else {
704  ret = s->io_open(s, pb, url, AVIO_FLAG_READ, &tmp);
705  }
706  if (ret >= 0) {
707  // update cookies on http response with setcookies.
708  char *new_cookies = NULL;
709 
710  if (!(s->flags & AVFMT_FLAG_CUSTOM_IO))
711  av_opt_get(*pb, "cookies", AV_OPT_SEARCH_CHILDREN, (uint8_t**)&new_cookies);
712 
713  if (new_cookies)
714  av_dict_set(opts, "cookies", new_cookies, AV_DICT_DONT_STRDUP_VAL);
715  }
716 
717  av_dict_free(&tmp);
718 
719  if (is_http_out)
720  *is_http_out = is_http;
721 
722  return ret;
723 }
724 
725 static int test_segment(AVFormatContext *s, const AVInputFormat *in_fmt, struct playlist *pls, struct segment *seg)
726 {
727  HLSContext *c = s->priv_data;
728  int matchA = 3;
729  int matchF = 0;
730 
731  if (!c->extension_picky)
732  return 0;
733 
734  if (strcmp(c->allowed_segment_extensions, "ALL"))
735  matchA = av_match_ext (seg->url, c->allowed_segment_extensions)
736  + 2*(ff_match_url_ext(seg->url, c->allowed_segment_extensions) > 0);
737 
738  if (!matchA) {
739  av_log(s, AV_LOG_ERROR, "URL %s is not in allowed_segment_extensions\n", seg->url);
740  return AVERROR_INVALIDDATA;
741  }
742 
743  if (in_fmt) {
744  if (in_fmt->extensions) {
745  matchF = av_match_ext( seg->url, in_fmt->extensions)
746  + 2*(ff_match_url_ext(seg->url, in_fmt->extensions) > 0);
747  // Youtube uses aac files with .ts extension
748  if(av_match_name("mp4", in_fmt->name) || av_match_name("aac", in_fmt->name)) {
749  matchF |= av_match_ext( seg->url, "ts,m2t,m2ts,mts,mpg,m4s,mpeg,mpegts,cmfv,cmfa")
750  + 2*(ff_match_url_ext(seg->url, "ts,m2t,m2ts,mts,mpg,m4s,mpeg,mpegts,cmfv,cmfa") > 0);
751  }
752  } else if (!strcmp(in_fmt->name, "mpegts")) {
753  const char *str = "ts,m2t,m2ts,mts,mpg,m4s,mpeg,mpegts"
754  ",html" // https://flash1.bogulus.cfd/
755  ;
756  matchF = av_match_ext( seg->url, str)
757  + 2*(ff_match_url_ext(seg->url, str) > 0);
758  }
759 
760  if (!(matchA & matchF)) {
761  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);
762  return AVERROR_INVALIDDATA;
763  }
764  }
765 
766  return 0;
767 }
768 
769 static int parse_playlist(HLSContext *c, const char *url,
770  struct playlist *pls, AVIOContext *in)
771 {
772  int ret = 0, is_segment = 0, is_variant = 0;
773  int64_t duration = 0;
774  enum KeyType key_type = KEY_NONE;
775  uint8_t iv[16] = "";
776  int has_iv = 0;
777  char key[MAX_URL_SIZE] = "";
778  char line[MAX_URL_SIZE];
779  const char *ptr;
780  int close_in = 0;
781  int64_t seg_offset = 0;
782  int64_t seg_size = -1;
783  uint8_t *new_url = NULL;
784  struct variant_info variant_info;
785  char tmp_str[MAX_URL_SIZE];
786  struct segment *cur_init_section = NULL;
787  int is_http = av_strstart(url, "http", NULL);
788  struct segment **prev_segments = NULL;
789  int prev_n_segments = 0;
790  int64_t prev_start_seq_no = -1;
791 
792  if (is_http && !in && c->http_persistent && c->playlist_pb) {
793  in = c->playlist_pb;
794  ret = open_url_keepalive(c->ctx, &c->playlist_pb, url, NULL);
795  if (ret == AVERROR_EXIT) {
796  return ret;
797  } else if (ret < 0) {
798  if (ret != AVERROR_EOF)
799  av_log(c->ctx, AV_LOG_WARNING,
800  "keepalive request failed for '%s' with error: '%s' when parsing playlist\n",
801  url, av_err2str(ret));
802  in = NULL;
803  }
804  }
805 
806  if (!in) {
808  av_dict_copy(&opts, c->avio_opts, 0);
809 
810  if (c->http_persistent)
811  av_dict_set(&opts, "multiple_requests", "1", 0);
812 
813  ret = open_url(c->ctx, &in, url, &opts, NULL, NULL);
814  av_dict_free(&opts);
815  if (ret < 0)
816  return ret;
817 
818  if (is_http && c->http_persistent)
819  c->playlist_pb = in;
820  else
821  close_in = 1;
822  }
823 
824  if (av_opt_get(in, "location", AV_OPT_SEARCH_CHILDREN, &new_url) >= 0)
825  url = new_url;
826 
827  ff_get_chomp_line(in, line, sizeof(line));
828  if (strcmp(line, "#EXTM3U")) {
829  ret = AVERROR_INVALIDDATA;
830  goto fail;
831  }
832 
833  if (pls) {
834  prev_start_seq_no = pls->start_seq_no;
835  prev_segments = pls->segments;
836  prev_n_segments = pls->n_segments;
837  pls->segments = NULL;
838  pls->n_segments = 0;
839 
840  pls->finished = 0;
841  pls->type = PLS_TYPE_UNSPECIFIED;
842  }
843  while (!avio_feof(in)) {
844  ff_get_chomp_line(in, line, sizeof(line));
845  if (av_strstart(line, "#EXT-X-STREAM-INF:", &ptr)) {
846  if (pls) {
847  av_log(c->ctx, AV_LOG_ERROR,
848  "Master Playlist tag found in a Media Playlist\n");
849  ret = AVERROR_INVALIDDATA;
850  goto fail;
851  }
852  is_variant = 1;
853  memset(&variant_info, 0, sizeof(variant_info));
855  &variant_info);
856  } else if (av_strstart(line, "#EXT-X-KEY:", &ptr)) {
857  struct key_info info = {{0}};
859  &info);
860  key_type = KEY_NONE;
861  has_iv = 0;
862  if (!strcmp(info.method, "AES-128"))
863  key_type = KEY_AES_128;
864  if (!strcmp(info.method, "SAMPLE-AES"))
865  key_type = KEY_SAMPLE_AES;
866  if (!strncmp(info.iv, "0x", 2) || !strncmp(info.iv, "0X", 2)) {
867  ff_hex_to_data(iv, info.iv + 2);
868  has_iv = 1;
869  }
870  av_strlcpy(key, info.uri, sizeof(key));
871  } else if (av_strstart(line, "#EXT-X-MEDIA:", &ptr)) {
872  struct rendition_info info = {{0}};
873  if (pls) {
874  av_log(c->ctx, AV_LOG_ERROR,
875  "Master Playlist tag found in a Media Playlist\n");
876  ret = AVERROR_INVALIDDATA;
877  goto fail;
878  }
880  &info);
881  new_rendition(c, &info, url);
882  } else if (av_strstart(line, "#EXT-X-TARGETDURATION:", &ptr)) {
883  int64_t t;
884  ret = ensure_playlist(c, &pls, url);
885  if (ret < 0)
886  goto fail;
887  t = strtoll(ptr, NULL, 10);
888  if (t < 0 || t >= INT64_MAX / AV_TIME_BASE) {
889  ret = AVERROR_INVALIDDATA;
890  goto fail;
891  }
892  pls->target_duration = t * AV_TIME_BASE;
893  } else if (av_strstart(line, "#EXT-X-MEDIA-SEQUENCE:", &ptr)) {
894  uint64_t seq_no;
895  ret = ensure_playlist(c, &pls, url);
896  if (ret < 0)
897  goto fail;
898  seq_no = strtoull(ptr, NULL, 10);
899  if (seq_no > INT64_MAX/2) {
900  av_log(c->ctx, AV_LOG_DEBUG, "MEDIA-SEQUENCE higher than "
901  "INT64_MAX/2, mask out the highest bit\n");
902  seq_no &= INT64_MAX/2;
903  }
904  pls->start_seq_no = seq_no;
905  } else if (av_strstart(line, "#EXT-X-PLAYLIST-TYPE:", &ptr)) {
906  ret = ensure_playlist(c, &pls, url);
907  if (ret < 0)
908  goto fail;
909  if (!strcmp(ptr, "EVENT"))
910  pls->type = PLS_TYPE_EVENT;
911  else if (!strcmp(ptr, "VOD"))
912  pls->type = PLS_TYPE_VOD;
913  } else if (av_strstart(line, "#EXT-X-MAP:", &ptr)) {
914  struct init_section_info info = {{0}};
915  ret = ensure_playlist(c, &pls, url);
916  if (ret < 0)
917  goto fail;
919  cur_init_section = new_init_section(pls, &info, url);
920  if (!cur_init_section) {
921  ret = AVERROR(ENOMEM);
922  goto fail;
923  }
924  cur_init_section->key_type = key_type;
925  if (has_iv) {
926  memcpy(cur_init_section->iv, iv, sizeof(iv));
927  } else {
928  int64_t seq = pls->start_seq_no + pls->n_segments;
929  memset(cur_init_section->iv, 0, sizeof(cur_init_section->iv));
930  AV_WB64(cur_init_section->iv + 8, seq);
931  }
932 
933  if (key_type != KEY_NONE) {
934  ff_make_absolute_url(tmp_str, sizeof(tmp_str), url, key);
935  if (!tmp_str[0]) {
936  av_free(cur_init_section);
937  ret = AVERROR_INVALIDDATA;
938  goto fail;
939  }
940  cur_init_section->key = av_strdup(tmp_str);
941  if (!cur_init_section->key) {
942  av_free(cur_init_section);
943  ret = AVERROR(ENOMEM);
944  goto fail;
945  }
946  } else {
947  cur_init_section->key = NULL;
948  }
949 
950  } else if (av_strstart(line, "#EXT-X-ENDLIST", &ptr)) {
951  if (pls)
952  pls->finished = 1;
953  } else if (av_strstart(line, "#EXTINF:", &ptr)) {
954  double d = atof(ptr) * AV_TIME_BASE;
955  if (d < 0 || d > INT64_MAX || isnan(d)) {
956  av_log(c->ctx, AV_LOG_WARNING, "EXTINF %f unsupported\n", d / AV_TIME_BASE);
957  d = 0;
958  }
959  duration = d;
960  is_segment = 1;
961  } else if (av_strstart(line, "#EXT-X-BYTERANGE:", &ptr)) {
962  seg_size = strtoll(ptr, NULL, 10);
963  ptr = strchr(ptr, '@');
964  if (ptr)
965  seg_offset = strtoll(ptr+1, NULL, 10);
966  if (seg_size < 0 || seg_offset > INT64_MAX - seg_size) {
967  ret = AVERROR_INVALIDDATA;
968  goto fail;
969  }
970  } else if (av_strstart(line, "#", NULL)) {
971  av_log(c->ctx, AV_LOG_INFO, "Skip ('%s')\n", line);
972  continue;
973  } else if (line[0]) {
974  if (is_variant) {
975  if (!new_variant(c, &variant_info, line, url)) {
976  ret = AVERROR(ENOMEM);
977  goto fail;
978  }
979  is_variant = 0;
980  }
981  if (is_segment) {
982  struct segment *seg;
983  ret = ensure_playlist(c, &pls, url);
984  if (ret < 0)
985  goto fail;
986  seg = av_malloc(sizeof(struct segment));
987  if (!seg) {
988  ret = AVERROR(ENOMEM);
989  goto fail;
990  }
991  if (has_iv) {
992  memcpy(seg->iv, iv, sizeof(iv));
993  } else {
994  uint64_t seq = pls->start_seq_no + (uint64_t)pls->n_segments;
995  memset(seg->iv, 0, sizeof(seg->iv));
996  AV_WB64(seg->iv + 8, seq);
997  }
998 
999  if (key_type != KEY_NONE) {
1000  ff_make_absolute_url(tmp_str, sizeof(tmp_str), url, key);
1001  if (!tmp_str[0]) {
1002  ret = AVERROR_INVALIDDATA;
1003  av_free(seg);
1004  goto fail;
1005  }
1006  seg->key = av_strdup(tmp_str);
1007  if (!seg->key) {
1008  av_free(seg);
1009  ret = AVERROR(ENOMEM);
1010  goto fail;
1011  }
1012  } else {
1013  seg->key = NULL;
1014  }
1015 
1016  ff_make_absolute_url(tmp_str, sizeof(tmp_str), url, line);
1017  if (!tmp_str[0]) {
1018  ret = AVERROR_INVALIDDATA;
1019  if (seg->key)
1020  av_free(seg->key);
1021  av_free(seg);
1022  goto fail;
1023  }
1024  seg->url = av_strdup(tmp_str);
1025  if (!seg->url) {
1026  av_free(seg->key);
1027  av_free(seg);
1028  ret = AVERROR(ENOMEM);
1029  goto fail;
1030  }
1031 
1032  ret = test_segment(c->ctx, pls->ctx ? pls->ctx->iformat : NULL, pls, seg);
1033  if (ret < 0) {
1034  av_free(seg->url);
1035  av_free(seg->key);
1036  av_free(seg);
1037  goto fail;
1038  }
1039 
1040  if (duration < 0.001 * AV_TIME_BASE) {
1041  av_log(c->ctx, AV_LOG_WARNING, "Cannot get correct #EXTINF value of segment %s,"
1042  " set to default value to 1ms.\n", seg->url);
1043  duration = 0.001 * AV_TIME_BASE;
1044  }
1045  seg->duration = duration;
1046  seg->key_type = key_type;
1047  dynarray_add(&pls->segments, &pls->n_segments, seg);
1048  is_segment = 0;
1049 
1050  seg->size = seg_size;
1051  if (seg_size >= 0) {
1052  seg->url_offset = seg_offset;
1053  seg_offset += seg_size;
1054  seg_size = -1;
1055  } else {
1056  seg->url_offset = 0;
1057  seg_offset = 0;
1058  }
1059 
1060  seg->init_section = cur_init_section;
1061  }
1062  }
1063  }
1064  if (prev_segments) {
1065  if (pls->start_seq_no > prev_start_seq_no && c->first_timestamp != AV_NOPTS_VALUE) {
1066  int64_t prev_timestamp = c->first_timestamp;
1067  int i;
1068  int64_t diff = pls->start_seq_no - prev_start_seq_no;
1069  for (i = 0; i < prev_n_segments && i < diff; i++) {
1070  c->first_timestamp += prev_segments[i]->duration;
1071  }
1072  av_log(c->ctx, AV_LOG_DEBUG, "Media sequence change (%"PRId64" -> %"PRId64")"
1073  " reflected in first_timestamp: %"PRId64" -> %"PRId64"\n",
1074  prev_start_seq_no, pls->start_seq_no,
1075  prev_timestamp, c->first_timestamp);
1076  } else if (pls->start_seq_no < prev_start_seq_no) {
1077  av_log(c->ctx, AV_LOG_WARNING, "Media sequence changed unexpectedly: %"PRId64" -> %"PRId64"\n",
1078  prev_start_seq_no, pls->start_seq_no);
1079  }
1080  free_segment_dynarray(prev_segments, prev_n_segments);
1081  av_freep(&prev_segments);
1082  }
1083  if (pls)
1085 
1086 fail:
1087  av_free(new_url);
1088  if (close_in)
1089  ff_format_io_close(c->ctx, &in);
1090  c->ctx->ctx_flags = c->ctx->ctx_flags & ~(unsigned)AVFMTCTX_UNSEEKABLE;
1091  if (!c->n_variants || !c->variants[0]->n_playlists ||
1092  !(c->variants[0]->playlists[0]->finished ||
1093  c->variants[0]->playlists[0]->type == PLS_TYPE_EVENT))
1094  c->ctx->ctx_flags |= AVFMTCTX_UNSEEKABLE;
1095  return ret;
1096 }
1097 
1098 static struct segment *current_segment(struct playlist *pls)
1099 {
1100  return pls->segments[pls->cur_seq_no - pls->start_seq_no];
1101 }
1102 
1103 static struct segment *next_segment(struct playlist *pls)
1104 {
1105  int64_t n = pls->cur_seq_no - pls->start_seq_no + 1;
1106  if (n >= pls->n_segments)
1107  return NULL;
1108  return pls->segments[n];
1109 }
1110 
1111 static int read_from_url(struct playlist *pls, struct segment *seg,
1112  uint8_t *buf, int buf_size)
1113 {
1114  int ret;
1115 
1116  /* limit read if the segment was only a part of a file */
1117  if (seg->size >= 0)
1118  buf_size = FFMIN(buf_size, seg->size - pls->cur_seg_offset);
1119 
1120  ret = avio_read(pls->input, buf, buf_size);
1121  if (ret > 0)
1122  pls->cur_seg_offset += ret;
1123 
1124  return ret;
1125 }
1126 
1127 /* Parse the raw ID3 data and pass contents to caller */
1129  AVDictionary **metadata, int64_t *dts,
1130  ID3v2ExtraMetaAPIC **apic, ID3v2ExtraMeta **extra_meta)
1131 {
1132  static const char id3_priv_owner_ts[] = "com.apple.streaming.transportStreamTimestamp";
1133  ID3v2ExtraMeta *meta;
1134 
1135  ff_id3v2_read_dict(pb, metadata, ID3v2_DEFAULT_MAGIC, extra_meta);
1136  for (meta = *extra_meta; meta; meta = meta->next) {
1137  if (!strcmp(meta->tag, "PRIV")) {
1138  ID3v2ExtraMetaPRIV *priv = &meta->data.priv;
1139  if (priv->datasize == 8 && !strcmp(priv->owner, id3_priv_owner_ts)) {
1140  /* 33-bit MPEG timestamp */
1141  int64_t ts = AV_RB64(priv->data);
1142  av_log(s, AV_LOG_DEBUG, "HLS ID3 audio timestamp %"PRId64"\n", ts);
1143  if ((ts & ~((1ULL << 33) - 1)) == 0)
1144  *dts = ts;
1145  else
1146  av_log(s, AV_LOG_ERROR, "Invalid HLS ID3 audio timestamp %"PRId64"\n", ts);
1147  }
1148  } else if (!strcmp(meta->tag, "APIC") && apic)
1149  *apic = &meta->data.apic;
1150  }
1151 }
1152 
1153 /* Check if the ID3 metadata contents have changed */
1154 static int id3_has_changed_values(struct playlist *pls, AVDictionary *metadata,
1155  ID3v2ExtraMetaAPIC *apic)
1156 {
1157  AVDictionaryEntry *entry = NULL;
1158  AVDictionaryEntry *oldentry;
1159  /* check that no keys have changed values */
1160  while ((entry = av_dict_get(metadata, "", entry, AV_DICT_IGNORE_SUFFIX))) {
1161  oldentry = av_dict_get(pls->id3_initial, entry->key, NULL, AV_DICT_MATCH_CASE);
1162  if (!oldentry || strcmp(oldentry->value, entry->value) != 0)
1163  return 1;
1164  }
1165 
1166  /* check if apic appeared */
1167  if (apic && (pls->ctx->nb_streams != 2 || !pls->ctx->streams[1]->attached_pic.data))
1168  return 1;
1169 
1170  if (apic) {
1171  int size = pls->ctx->streams[1]->attached_pic.size;
1172  if (size != apic->buf->size - AV_INPUT_BUFFER_PADDING_SIZE)
1173  return 1;
1174 
1175  if (memcmp(apic->buf->data, pls->ctx->streams[1]->attached_pic.data, size) != 0)
1176  return 1;
1177  }
1178 
1179  return 0;
1180 }
1181 
1182 /* Parse ID3 data and handle the found data */
1183 static void handle_id3(AVIOContext *pb, struct playlist *pls)
1184 {
1185  AVDictionary *metadata = NULL;
1186  ID3v2ExtraMetaAPIC *apic = NULL;
1187  ID3v2ExtraMeta *extra_meta = NULL;
1188  int64_t timestamp = AV_NOPTS_VALUE;
1189 
1190  parse_id3(pls->ctx, pb, &metadata, &timestamp, &apic, &extra_meta);
1191 
1192  if (timestamp != AV_NOPTS_VALUE) {
1193  pls->id3_mpegts_timestamp = timestamp;
1194  pls->id3_offset = 0;
1195  }
1196 
1197  if (!pls->id3_found) {
1198  /* initial ID3 tags */
1200  pls->id3_found = 1;
1201 
1202  /* get picture attachment and set text metadata */
1203  if (pls->ctx->nb_streams) {
1205  ff_id3v2_parse_apic(pls->ctx, extra_meta);
1206  } else
1207  /* demuxer not yet opened, defer picture attachment */
1208  pls->id3_deferred_extra = extra_meta;
1209 
1210  ff_id3v2_parse_priv_dict(&metadata, extra_meta);
1211  av_dict_copy(&pls->ctx->metadata, metadata, 0);
1212  pls->id3_initial = metadata;
1213 
1214  } else {
1215  if (!pls->id3_changed && id3_has_changed_values(pls, metadata, apic)) {
1216  avpriv_report_missing_feature(pls->parent, "Changing ID3 metadata in HLS audio elementary stream");
1217  pls->id3_changed = 1;
1218  }
1219  av_dict_free(&metadata);
1220  }
1221 
1222  if (pls->id3_deferred_extra != extra_meta)
1223  ff_id3v2_free_extra_meta(&extra_meta);
1224 }
1225 
1226 static void intercept_id3(struct playlist *pls, uint8_t *buf,
1227  int buf_size, int *len)
1228 {
1229  /* intercept id3 tags, we do not want to pass them to the raw
1230  * demuxer on all segment switches */
1231  int bytes;
1232  int id3_buf_pos = 0;
1233  int fill_buf = 0;
1234  struct segment *seg = current_segment(pls);
1235 
1236  /* gather all the id3 tags */
1237  while (1) {
1238  /* see if we can retrieve enough data for ID3 header */
1239  if (*len < ID3v2_HEADER_SIZE && buf_size >= ID3v2_HEADER_SIZE) {
1240  bytes = read_from_url(pls, seg, buf + *len, ID3v2_HEADER_SIZE - *len);
1241  if (bytes > 0) {
1242 
1243  if (bytes == ID3v2_HEADER_SIZE - *len)
1244  /* no EOF yet, so fill the caller buffer again after
1245  * we have stripped the ID3 tags */
1246  fill_buf = 1;
1247 
1248  *len += bytes;
1249 
1250  } else if (*len <= 0) {
1251  /* error/EOF */
1252  *len = bytes;
1253  fill_buf = 0;
1254  }
1255  }
1256 
1257  if (*len < ID3v2_HEADER_SIZE)
1258  break;
1259 
1260  if (ff_id3v2_match(buf, ID3v2_DEFAULT_MAGIC)) {
1261  int64_t maxsize = seg->size >= 0 ? seg->size : 1024*1024;
1262  int taglen = ff_id3v2_tag_len(buf);
1263  int tag_got_bytes = FFMIN(taglen, *len);
1264  int remaining = taglen - tag_got_bytes;
1265 
1266  if (taglen > maxsize) {
1267  av_log(pls->parent, AV_LOG_ERROR, "Too large HLS ID3 tag (%d > %"PRId64" bytes)\n",
1268  taglen, maxsize);
1269  break;
1270  }
1271 
1272  /*
1273  * Copy the id3 tag to our temporary id3 buffer.
1274  * We could read a small id3 tag directly without memcpy, but
1275  * we would still need to copy the large tags, and handling
1276  * both of those cases together with the possibility for multiple
1277  * tags would make the handling a bit complex.
1278  */
1279  pls->id3_buf = av_fast_realloc(pls->id3_buf, &pls->id3_buf_size, id3_buf_pos + taglen);
1280  if (!pls->id3_buf)
1281  break;
1282  memcpy(pls->id3_buf + id3_buf_pos, buf, tag_got_bytes);
1283  id3_buf_pos += tag_got_bytes;
1284 
1285  /* strip the intercepted bytes */
1286  *len -= tag_got_bytes;
1287  memmove(buf, buf + tag_got_bytes, *len);
1288  av_log(pls->parent, AV_LOG_DEBUG, "Stripped %d HLS ID3 bytes\n", tag_got_bytes);
1289 
1290  if (remaining > 0) {
1291  /* read the rest of the tag in */
1292  if (read_from_url(pls, seg, pls->id3_buf + id3_buf_pos, remaining) != remaining)
1293  break;
1294  id3_buf_pos += remaining;
1295  av_log(pls->parent, AV_LOG_DEBUG, "Stripped additional %d HLS ID3 bytes\n", remaining);
1296  }
1297 
1298  } else {
1299  /* no more ID3 tags */
1300  break;
1301  }
1302  }
1303 
1304  /* re-fill buffer for the caller unless EOF */
1305  if (*len >= 0 && (fill_buf || *len == 0)) {
1306  bytes = read_from_url(pls, seg, buf + *len, buf_size - *len);
1307 
1308  /* ignore error if we already had some data */
1309  if (bytes >= 0)
1310  *len += bytes;
1311  else if (*len == 0)
1312  *len = bytes;
1313  }
1314 
1315  if (pls->id3_buf) {
1316  /* Now parse all the ID3 tags */
1317  AVIOContext id3ioctx;
1318  ffio_init_context(&id3ioctx, pls->id3_buf, id3_buf_pos, 0, NULL, NULL, NULL, NULL);
1319  handle_id3(&id3ioctx, pls);
1320  }
1321 
1322  if (pls->is_id3_timestamped == -1)
1324 }
1325 
1326 static int open_input(HLSContext *c, struct playlist *pls, struct segment *seg, AVIOContext **in)
1327 {
1328  AVDictionary *opts = NULL;
1329  int ret;
1330  int is_http = 0;
1331 
1332  if (c->http_persistent)
1333  av_dict_set(&opts, "multiple_requests", "1", 0);
1334 
1335  if (seg->size >= 0) {
1336  /* try to restrict the HTTP request to the part we want
1337  * (if this is in fact a HTTP request) */
1338  av_dict_set_int(&opts, "offset", seg->url_offset, 0);
1339  av_dict_set_int(&opts, "end_offset", seg->url_offset + seg->size, 0);
1340  }
1341 
1342  av_log(pls->parent, AV_LOG_VERBOSE, "HLS request for url '%s', offset %"PRId64", playlist %d\n",
1343  seg->url, seg->url_offset, pls->index);
1344 
1345  if (seg->key_type == KEY_NONE) {
1346  ret = open_url(pls->parent, in, seg->url, &c->avio_opts, opts, &is_http);
1347  } else if (seg->key_type == KEY_AES_128) {
1348  char iv[33], key[33], url[MAX_URL_SIZE];
1349  if (strcmp(seg->key, pls->key_url)) {
1350  AVIOContext *pb = NULL;
1351  if (open_url(pls->parent, &pb, seg->key, &c->avio_opts, NULL, NULL) == 0) {
1352  ret = avio_read(pb, pls->key, sizeof(pls->key));
1353  if (ret != sizeof(pls->key)) {
1354  av_log(pls->parent, AV_LOG_ERROR, "Unable to read key file %s\n",
1355  seg->key);
1356  }
1357  ff_format_io_close(pls->parent, &pb);
1358  } else {
1359  av_log(pls->parent, AV_LOG_ERROR, "Unable to open key file %s\n",
1360  seg->key);
1361  }
1362  av_strlcpy(pls->key_url, seg->key, sizeof(pls->key_url));
1363  }
1364  ff_data_to_hex(iv, seg->iv, sizeof(seg->iv), 0);
1365  ff_data_to_hex(key, pls->key, sizeof(pls->key), 0);
1366  iv[32] = key[32] = '\0';
1367  if (strstr(seg->url, "://"))
1368  snprintf(url, sizeof(url), "crypto+%s", seg->url);
1369  else
1370  snprintf(url, sizeof(url), "crypto:%s", seg->url);
1371 
1372  av_dict_set(&opts, "key", key, 0);
1373  av_dict_set(&opts, "iv", iv, 0);
1374 
1375  ret = open_url(pls->parent, in, url, &c->avio_opts, opts, &is_http);
1376  if (ret < 0) {
1377  goto cleanup;
1378  }
1379  ret = 0;
1380  } else if (seg->key_type == KEY_SAMPLE_AES) {
1381  av_log(pls->parent, AV_LOG_ERROR,
1382  "SAMPLE-AES encryption is not supported yet\n");
1383  ret = AVERROR_PATCHWELCOME;
1384  }
1385  else
1386  ret = AVERROR(ENOSYS);
1387 
1388  /* Seek to the requested position. If this was a HTTP request, the offset
1389  * should already be where want it to, but this allows e.g. local testing
1390  * without a HTTP server.
1391  *
1392  * This is not done for HTTP at all as avio_seek() does internal bookkeeping
1393  * of file offset which is out-of-sync with the actual offset when "offset"
1394  * AVOption is used with http protocol, causing the seek to not be a no-op
1395  * as would be expected. Wrong offset received from the server will not be
1396  * noticed without the call, though.
1397  */
1398  if (ret == 0 && !is_http && seg->url_offset) {
1399  int64_t seekret = avio_seek(*in, seg->url_offset, SEEK_SET);
1400  if (seekret < 0) {
1401  av_log(pls->parent, AV_LOG_ERROR, "Unable to seek to offset %"PRId64" of HLS segment '%s'\n", seg->url_offset, seg->url);
1402  ret = seekret;
1403  ff_format_io_close(pls->parent, in);
1404  }
1405  }
1406 
1407 cleanup:
1408  av_dict_free(&opts);
1409  pls->cur_seg_offset = 0;
1410  return ret;
1411 }
1412 
1413 static int update_init_section(struct playlist *pls, struct segment *seg)
1414 {
1415  static const int max_init_section_size = 1024*1024;
1416  HLSContext *c = pls->parent->priv_data;
1417  int64_t sec_size;
1418  int64_t urlsize;
1419  int ret;
1420 
1421  if (seg->init_section == pls->cur_init_section)
1422  return 0;
1423 
1424  pls->cur_init_section = NULL;
1425 
1426  if (!seg->init_section)
1427  return 0;
1428 
1429  ret = open_input(c, pls, seg->init_section, &pls->input);
1430  if (ret < 0) {
1432  "Failed to open an initialization section in playlist %d\n",
1433  pls->index);
1434  return ret;
1435  }
1436 
1437  if (seg->init_section->size >= 0)
1438  sec_size = seg->init_section->size;
1439  else if ((urlsize = avio_size(pls->input)) >= 0)
1440  sec_size = urlsize;
1441  else
1442  sec_size = max_init_section_size;
1443 
1444  av_log(pls->parent, AV_LOG_DEBUG,
1445  "Downloading an initialization section of size %"PRId64"\n",
1446  sec_size);
1447 
1448  sec_size = FFMIN(sec_size, max_init_section_size);
1449 
1450  av_fast_malloc(&pls->init_sec_buf, &pls->init_sec_buf_size, sec_size);
1451 
1452  ret = read_from_url(pls, seg->init_section, pls->init_sec_buf,
1453  pls->init_sec_buf_size);
1454  ff_format_io_close(pls->parent, &pls->input);
1455 
1456  if (ret < 0)
1457  return ret;
1458 
1459  pls->cur_init_section = seg->init_section;
1460  pls->init_sec_data_len = ret;
1461  pls->init_sec_buf_read_offset = 0;
1462 
1463  /* spec says audio elementary streams do not have media initialization
1464  * sections, so there should be no ID3 timestamps */
1465  pls->is_id3_timestamped = 0;
1466 
1467  return 0;
1468 }
1469 
1471 {
1472  return pls->n_segments > 0 ?
1473  pls->segments[pls->n_segments - 1]->duration :
1474  pls->target_duration;
1475 }
1476 
1477 static int playlist_needed(struct playlist *pls)
1478 {
1479  AVFormatContext *s = pls->parent;
1480  int i, j;
1481  int stream_needed = 0;
1482  int first_st;
1483 
1484  /* If there is no context or streams yet, the playlist is needed */
1485  if (!pls->ctx || !pls->n_main_streams)
1486  return 1;
1487 
1488  /* check if any of the streams in the playlist are needed */
1489  for (i = 0; i < pls->n_main_streams; i++) {
1490  if (pls->main_streams[i]->discard < AVDISCARD_ALL) {
1491  stream_needed = 1;
1492  break;
1493  }
1494  }
1495 
1496  /* If all streams in the playlist were discarded, the playlist is not
1497  * needed (regardless of whether whole programs are discarded or not). */
1498  if (!stream_needed)
1499  return 0;
1500 
1501  /* Otherwise, check if all the programs (variants) this playlist is in are
1502  * discarded. Since all streams in the playlist are part of the same programs
1503  * we can just check the programs of the first stream. */
1504 
1505  first_st = pls->main_streams[0]->index;
1506 
1507  for (i = 0; i < s->nb_programs; i++) {
1508  AVProgram *program = s->programs[i];
1509  if (program->discard < AVDISCARD_ALL) {
1510  for (j = 0; j < program->nb_stream_indexes; j++) {
1511  if (program->stream_index[j] == first_st) {
1512  /* playlist is in an undiscarded program */
1513  return 1;
1514  }
1515  }
1516  }
1517  }
1518 
1519  /* some streams were not discarded but all the programs were */
1520  return 0;
1521 }
1522 
1523 static int read_data(void *opaque, uint8_t *buf, int buf_size)
1524 {
1525  struct playlist *v = opaque;
1526  HLSContext *c = v->parent->priv_data;
1527  int ret;
1528  int just_opened = 0;
1529  int reload_count = 0;
1530  struct segment *seg;
1531 
1532 restart:
1533  if (!v->needed)
1534  return AVERROR_EOF;
1535 
1536  if (!v->input || (c->http_persistent && v->input_read_done)) {
1537  int64_t reload_interval;
1538 
1539  /* Check that the playlist is still needed before opening a new
1540  * segment. */
1541  v->needed = playlist_needed(v);
1542 
1543  if (!v->needed) {
1544  av_log(v->parent, AV_LOG_INFO, "No longer receiving playlist %d ('%s')\n",
1545  v->index, v->url);
1546  return AVERROR_EOF;
1547  }
1548 
1549  /* If this is a live stream and the reload interval has elapsed since
1550  * the last playlist reload, reload the playlists now. */
1551  reload_interval = default_reload_interval(v);
1552 
1553 reload:
1554  reload_count++;
1555  if (reload_count > c->max_reload)
1556  return AVERROR_EOF;
1557  if (!v->finished &&
1558  av_gettime_relative() - v->last_load_time >= reload_interval) {
1559  if ((ret = parse_playlist(c, v->url, v, NULL)) < 0) {
1560  if (ret != AVERROR_EXIT)
1561  av_log(v->parent, AV_LOG_WARNING, "Failed to reload playlist %d\n",
1562  v->index);
1563  return ret;
1564  }
1565  /* If we need to reload the playlist again below (if
1566  * there's still no more segments), switch to a reload
1567  * interval of half the target duration. */
1568  reload_interval = v->target_duration / 2;
1569  }
1570  if (v->cur_seq_no < v->start_seq_no) {
1572  "skipping %"PRId64" segments ahead, expired from playlists\n",
1573  v->start_seq_no - v->cur_seq_no);
1574  v->cur_seq_no = v->start_seq_no;
1575  }
1576  if (v->cur_seq_no > v->last_seq_no) {
1577  v->last_seq_no = v->cur_seq_no;
1578  v->m3u8_hold_counters = 0;
1579  } else if (v->last_seq_no == v->cur_seq_no) {
1580  v->m3u8_hold_counters++;
1581  if (v->m3u8_hold_counters >= c->m3u8_hold_counters) {
1582  return AVERROR_EOF;
1583  }
1584  } else {
1585  av_log(v->parent, AV_LOG_WARNING, "maybe the m3u8 list sequence have been wraped.\n");
1586  }
1587  if (v->cur_seq_no >= v->start_seq_no + v->n_segments) {
1588  if (v->finished)
1589  return AVERROR_EOF;
1590  while (av_gettime_relative() - v->last_load_time < reload_interval) {
1591  if (ff_check_interrupt(c->interrupt_callback))
1592  return AVERROR_EXIT;
1593  av_usleep(100*1000);
1594  }
1595  /* Enough time has elapsed since the last reload */
1596  goto reload;
1597  }
1598 
1599  v->input_read_done = 0;
1600  seg = current_segment(v);
1601 
1602  /* load/update Media Initialization Section, if any */
1603  ret = update_init_section(v, seg);
1604  if (ret)
1605  return ret;
1606 
1607  if (c->http_multiple == 1 && v->input_next_requested) {
1608  FFSWAP(AVIOContext *, v->input, v->input_next);
1609  v->cur_seg_offset = 0;
1610  v->input_next_requested = 0;
1611  ret = 0;
1612  } else {
1613  ret = open_input(c, v, seg, &v->input);
1614  }
1615  if (ret < 0) {
1616  if (ff_check_interrupt(c->interrupt_callback))
1617  return AVERROR_EXIT;
1618  av_log(v->parent, AV_LOG_WARNING, "Failed to open segment %"PRId64" of playlist %d\n",
1619  v->cur_seq_no,
1620  v->index);
1621  v->cur_seq_no += 1;
1622  goto reload;
1623  }
1624  just_opened = 1;
1625  }
1626 
1627  if (c->http_multiple == -1) {
1628  uint8_t *http_version_opt = NULL;
1629  int r = av_opt_get(v->input, "http_version", AV_OPT_SEARCH_CHILDREN, &http_version_opt);
1630  if (r >= 0) {
1631  c->http_multiple = (!strncmp((const char *)http_version_opt, "1.1", 3) || !strncmp((const char *)http_version_opt, "2.0", 3));
1632  av_freep(&http_version_opt);
1633  }
1634  }
1635 
1636  seg = next_segment(v);
1637  if (c->http_multiple == 1 && !v->input_next_requested &&
1638  seg && seg->key_type == KEY_NONE && av_strstart(seg->url, "http", NULL)) {
1639  ret = open_input(c, v, seg, &v->input_next);
1640  if (ret < 0) {
1641  if (ff_check_interrupt(c->interrupt_callback))
1642  return AVERROR_EXIT;
1643  av_log(v->parent, AV_LOG_WARNING, "Failed to open segment %"PRId64" of playlist %d\n",
1644  v->cur_seq_no + 1,
1645  v->index);
1646  } else {
1647  v->input_next_requested = 1;
1648  }
1649  }
1650 
1652  /* Push init section out first before first actual segment */
1653  int copy_size = FFMIN(v->init_sec_data_len - v->init_sec_buf_read_offset, buf_size);
1654  memcpy(buf, v->init_sec_buf + v->init_sec_buf_read_offset, copy_size);
1655  v->init_sec_buf_read_offset += copy_size;
1656  return copy_size;
1657  }
1658 
1659  seg = current_segment(v);
1660  ret = read_from_url(v, seg, buf, buf_size);
1661  if (ret > 0) {
1662  if (just_opened && v->is_id3_timestamped != 0) {
1663  /* Intercept ID3 tags here, elementary audio streams are required
1664  * to convey timestamps using them in the beginning of each segment. */
1665  intercept_id3(v, buf, buf_size, &ret);
1666  }
1667 
1668  return ret;
1669  }
1670  if (c->http_persistent &&
1671  seg->key_type == KEY_NONE && av_strstart(seg->url, "http", NULL)) {
1672  v->input_read_done = 1;
1673  } else {
1674  ff_format_io_close(v->parent, &v->input);
1675  }
1676  v->cur_seq_no++;
1677 
1678  c->cur_seq_no = v->cur_seq_no;
1679 
1680  goto restart;
1681 }
1682 
1683 static void add_renditions_to_variant(HLSContext *c, struct variant *var,
1684  enum AVMediaType type, const char *group_id)
1685 {
1686  int i;
1687 
1688  for (i = 0; i < c->n_renditions; i++) {
1689  struct rendition *rend = c->renditions[i];
1690 
1691  if (rend->type == type && !strcmp(rend->group_id, group_id)) {
1692 
1693  if (rend->playlist)
1694  /* rendition is an external playlist
1695  * => add the playlist to the variant */
1696  dynarray_add(&var->playlists, &var->n_playlists, rend->playlist);
1697  else
1698  /* rendition is part of the variant main Media Playlist
1699  * => add the rendition to the main Media Playlist */
1700  dynarray_add(&var->playlists[0]->renditions,
1701  &var->playlists[0]->n_renditions,
1702  rend);
1703  }
1704  }
1705 }
1706 
1708  enum AVMediaType type)
1709 {
1710  int rend_idx = 0;
1711  int i;
1712 
1713  for (i = 0; i < pls->n_main_streams; i++) {
1714  AVStream *st = pls->main_streams[i];
1715 
1716  if (st->codecpar->codec_type != type)
1717  continue;
1718 
1719  for (; rend_idx < pls->n_renditions; rend_idx++) {
1720  struct rendition *rend = pls->renditions[rend_idx];
1721 
1722  if (rend->type != type)
1723  continue;
1724 
1725  if (rend->language[0])
1726  av_dict_set(&st->metadata, "language", rend->language, 0);
1727  if (rend->name[0])
1728  av_dict_set(&st->metadata, "comment", rend->name, 0);
1729 
1730  st->disposition |= rend->disposition;
1731  }
1732  if (rend_idx >=pls->n_renditions)
1733  break;
1734  }
1735 }
1736 
1737 /* if timestamp was in valid range: returns 1 and sets seq_no
1738  * if not: returns 0 and sets seq_no to closest segment */
1740  int64_t timestamp, int64_t *seq_no)
1741 {
1742  int i;
1743  int64_t pos = c->first_timestamp == AV_NOPTS_VALUE ?
1744  0 : c->first_timestamp;
1745 
1746  if (timestamp < pos) {
1747  *seq_no = pls->start_seq_no;
1748  return 0;
1749  }
1750 
1751  for (i = 0; i < pls->n_segments; i++) {
1752  int64_t diff = pos + pls->segments[i]->duration - timestamp;
1753  if (diff > 0) {
1754  *seq_no = pls->start_seq_no + i;
1755  return 1;
1756  }
1757  pos += pls->segments[i]->duration;
1758  }
1759 
1760  *seq_no = pls->start_seq_no + pls->n_segments - 1;
1761 
1762  return 0;
1763 }
1764 
1766 {
1767  int64_t seq_no;
1768 
1769  if (!pls->finished && !c->first_packet &&
1771  /* reload the playlist since it was suspended */
1772  parse_playlist(c, pls->url, pls, NULL);
1773 
1774  /* If playback is already in progress (we are just selecting a new
1775  * playlist) and this is a complete file, find the matching segment
1776  * by counting durations. */
1777  if (pls->finished && c->cur_timestamp != AV_NOPTS_VALUE) {
1778  find_timestamp_in_playlist(c, pls, c->cur_timestamp, &seq_no);
1779  return seq_no;
1780  }
1781 
1782  if (!pls->finished) {
1783  if (!c->first_packet && /* we are doing a segment selection during playback */
1784  c->cur_seq_no >= pls->start_seq_no &&
1785  c->cur_seq_no < pls->start_seq_no + pls->n_segments)
1786  /* While spec 3.4.3 says that we cannot assume anything about the
1787  * content at the same sequence number on different playlists,
1788  * in practice this seems to work and doing it otherwise would
1789  * require us to download a segment to inspect its timestamps. */
1790  return c->cur_seq_no;
1791 
1792  /* If this is a live stream, start live_start_index segments from the
1793  * start or end */
1794  if (c->live_start_index < 0)
1795  return pls->start_seq_no + FFMAX(pls->n_segments + c->live_start_index, 0);
1796  else
1797  return pls->start_seq_no + FFMIN(c->live_start_index, pls->n_segments - 1);
1798  }
1799 
1800  /* Otherwise just start on the first segment. */
1801  return pls->start_seq_no;
1802 }
1803 
1805 {
1806  HLSContext *c = s->priv_data;
1807  static const char * const opts[] = {
1808  "headers", "http_proxy", "user_agent", "cookies", "referer", "rw_timeout", "icy", NULL };
1809  const char * const * opt = opts;
1810  uint8_t *buf;
1811  int ret = 0;
1812 
1813  while (*opt) {
1814  if (av_opt_get(s->pb, *opt, AV_OPT_SEARCH_CHILDREN | AV_OPT_ALLOW_NULL, &buf) >= 0) {
1815  ret = av_dict_set(&c->avio_opts, *opt, buf,
1817  if (ret < 0)
1818  return ret;
1819  }
1820  opt++;
1821  }
1822 
1823  return ret;
1824 }
1825 
1826 static int nested_io_open(AVFormatContext *s, AVIOContext **pb, const char *url,
1827  int flags, AVDictionary **opts)
1828 {
1830  "A HLS playlist item '%s' referred to an external file '%s'. "
1831  "Opening this file was forbidden for security reasons\n",
1832  s->url, url);
1833  return AVERROR(EPERM);
1834 }
1835 
1836 static void add_stream_to_programs(AVFormatContext *s, struct playlist *pls, AVStream *stream)
1837 {
1838  HLSContext *c = s->priv_data;
1839  int i, j;
1840  int bandwidth = -1;
1841 
1842  for (i = 0; i < c->n_variants; i++) {
1843  struct variant *v = c->variants[i];
1844 
1845  for (j = 0; j < v->n_playlists; j++) {
1846  if (v->playlists[j] != pls)
1847  continue;
1848 
1849  av_program_add_stream_index(s, i, stream->index);
1850 
1851  if (bandwidth < 0)
1852  bandwidth = v->bandwidth;
1853  else if (bandwidth != v->bandwidth)
1854  bandwidth = -1; /* stream in multiple variants with different bandwidths */
1855  }
1856  }
1857 
1858  if (bandwidth >= 0)
1859  av_dict_set_int(&stream->metadata, "variant_bitrate", bandwidth, 0);
1860 }
1861 
1863 {
1864  int err;
1865 
1866  err = avcodec_parameters_copy(st->codecpar, ist->codecpar);
1867  if (err < 0)
1868  return err;
1869 
1870  if (pls->is_id3_timestamped) /* custom timestamps via id3 */
1871  avpriv_set_pts_info(st, 33, 1, MPEG_TIME_BASE);
1872  else
1874 
1875  // copy disposition
1876  st->disposition = ist->disposition;
1877 
1878  // copy side data
1879  for (int i = 0; i < ist->nb_side_data; i++) {
1880  const AVPacketSideData *sd_src = &ist->side_data[i];
1881  uint8_t *dst_data;
1882 
1883  dst_data = av_stream_new_side_data(st, sd_src->type, sd_src->size);
1884  if (!dst_data)
1885  return AVERROR(ENOMEM);
1886  memcpy(dst_data, sd_src->data, sd_src->size);
1887  }
1888 
1889  st->internal->need_context_update = 1;
1890 
1891  return 0;
1892 }
1893 
1894 /* add new subdemuxer streams to our context, if any */
1896 {
1897  int err;
1898 
1899  while (pls->n_main_streams < pls->ctx->nb_streams) {
1900  int ist_idx = pls->n_main_streams;
1902  AVStream *ist = pls->ctx->streams[ist_idx];
1903 
1904  if (!st)
1905  return AVERROR(ENOMEM);
1906 
1907  st->id = pls->index;
1908  dynarray_add(&pls->main_streams, &pls->n_main_streams, st);
1909 
1910  add_stream_to_programs(s, pls, st);
1911 
1912  err = set_stream_info_from_input_stream(st, pls, ist);
1913  if (err < 0)
1914  return err;
1915  }
1916 
1917  return 0;
1918 }
1919 
1921 {
1922  HLSContext *c = s->priv_data;
1923  int flag_needed = 0;
1924  int i;
1925 
1926  for (i = 0; i < c->n_playlists; i++) {
1927  struct playlist *pls = c->playlists[i];
1928 
1929  if (pls->has_noheader_flag) {
1930  flag_needed = 1;
1931  break;
1932  }
1933  }
1934 
1935  if (flag_needed)
1936  s->ctx_flags |= AVFMTCTX_NOHEADER;
1937  else
1938  s->ctx_flags &= ~AVFMTCTX_NOHEADER;
1939 }
1940 
1942 {
1943  HLSContext *c = s->priv_data;
1944 
1948 
1949  av_dict_free(&c->avio_opts);
1950  ff_format_io_close(c->ctx, &c->playlist_pb);
1951 
1952  return 0;
1953 }
1954 
1956 {
1957  HLSContext *c = s->priv_data;
1958  int ret = 0, i;
1959  int64_t highest_cur_seq_no = 0;
1960 
1961  c->ctx = s;
1962  c->interrupt_callback = &s->interrupt_callback;
1963 
1964  c->first_packet = 1;
1965  c->first_timestamp = AV_NOPTS_VALUE;
1966  c->cur_timestamp = AV_NOPTS_VALUE;
1967 
1968  if ((ret = save_avio_options(s)) < 0)
1969  goto fail;
1970 
1971  /* http_persistent and http_multiple auto-detection both rely on the
1972  * AVIOContext being backed by the builtin URLContext. Neither works
1973  * when io_open is overridden with a custom callback. */
1974  if (!ffio_geturlcontext(s->pb)) {
1975  if (c->http_persistent) {
1976  av_log(s, AV_LOG_WARNING, "Disabling http_persistent due to custom io_open.\n");
1977  c->http_persistent = 0;
1978  }
1979  /* Only auto-detection is disabled, enabling http_multiple can still work
1980  * with custom io_open. */
1981  if (c->http_multiple == -1) {
1982  av_log(s, AV_LOG_WARNING, "Disabling http_multiple due to custom io_open.\n");
1983  c->http_multiple = 0;
1984  }
1985  }
1986 
1987  /* XXX: Some HLS servers don't like being sent the range header,
1988  in this case, need to setting http_seekable = 0 to disable
1989  the range header */
1990  av_dict_set_int(&c->avio_opts, "seekable", c->http_seekable, 0);
1991 
1992  if ((ret = parse_playlist(c, s->url, NULL, s->pb)) < 0)
1993  goto fail;
1994 
1995  if (c->n_variants == 0) {
1996  av_log(s, AV_LOG_WARNING, "Empty playlist\n");
1997  ret = AVERROR_EOF;
1998  goto fail;
1999  }
2000  /* If the playlist only contained playlists (Master Playlist),
2001  * parse each individual playlist. */
2002  if (c->n_playlists > 1 || c->playlists[0]->n_segments == 0) {
2003  for (i = 0; i < c->n_playlists; i++) {
2004  struct playlist *pls = c->playlists[i];
2005  pls->m3u8_hold_counters = 0;
2006  if ((ret = parse_playlist(c, pls->url, pls, NULL)) < 0) {
2007  av_log(s, AV_LOG_WARNING, "parse_playlist error %s [%s]\n", av_err2str(ret), pls->url);
2008  pls->broken = 1;
2009  if (c->n_playlists > 1)
2010  continue;
2011  goto fail;
2012  }
2013  }
2014  }
2015 
2016  for (i = 0; i < c->n_variants; i++) {
2017  if (c->variants[i]->playlists[0]->n_segments == 0) {
2018  av_log(s, AV_LOG_WARNING, "Empty segment [%s]\n", c->variants[i]->playlists[0]->url);
2019  c->variants[i]->playlists[0]->broken = 1;
2020  }
2021  }
2022 
2023  /* If this isn't a live stream, calculate the total duration of the
2024  * stream. */
2025  if (c->variants[0]->playlists[0]->finished) {
2026  int64_t duration = 0;
2027  for (i = 0; i < c->variants[0]->playlists[0]->n_segments; i++)
2028  duration += c->variants[0]->playlists[0]->segments[i]->duration;
2029  s->duration = duration;
2030  }
2031 
2032  /* Associate renditions with variants */
2033  for (i = 0; i < c->n_variants; i++) {
2034  struct variant *var = c->variants[i];
2035 
2036  if (var->audio_group[0])
2038  if (var->video_group[0])
2040  if (var->subtitles_group[0])
2042  }
2043 
2044  /* Create a program for each variant */
2045  for (i = 0; i < c->n_variants; i++) {
2046  struct variant *v = c->variants[i];
2047  AVProgram *program;
2048 
2049  program = av_new_program(s, i);
2050  if (!program)
2051  goto fail;
2052  av_dict_set_int(&program->metadata, "variant_bitrate", v->bandwidth, 0);
2053  }
2054 
2055  /* Select the starting segments */
2056  for (i = 0; i < c->n_playlists; i++) {
2057  struct playlist *pls = c->playlists[i];
2058 
2059  if (pls->n_segments == 0)
2060  continue;
2061 
2062  pls->cur_seq_no = select_cur_seq_no(c, pls);
2063  highest_cur_seq_no = FFMAX(highest_cur_seq_no, pls->cur_seq_no);
2064  }
2065 
2066  /* Open the demuxer for each playlist */
2067  for (i = 0; i < c->n_playlists; i++) {
2068  struct playlist *pls = c->playlists[i];
2069  char *url;
2070  ff_const59 AVInputFormat *in_fmt = NULL;
2071 
2072  if (!(pls->ctx = avformat_alloc_context())) {
2073  ret = AVERROR(ENOMEM);
2074  goto fail;
2075  }
2076 
2077  if (pls->n_segments == 0)
2078  continue;
2079 
2080  pls->index = i;
2081  pls->needed = 1;
2082  pls->parent = s;
2083 
2084  /*
2085  * If this is a live stream and this playlist looks like it is one segment
2086  * behind, try to sync it up so that every substream starts at the same
2087  * time position (so e.g. avformat_find_stream_info() will see packets from
2088  * all active streams within the first few seconds). This is not very generic,
2089  * though, as the sequence numbers are technically independent.
2090  */
2091  if (!pls->finished && pls->cur_seq_no == highest_cur_seq_no - 1 &&
2092  highest_cur_seq_no < pls->start_seq_no + pls->n_segments) {
2093  pls->cur_seq_no = highest_cur_seq_no;
2094  }
2095 
2097  if (!pls->read_buffer){
2098  ret = AVERROR(ENOMEM);
2099  avformat_free_context(pls->ctx);
2100  pls->ctx = NULL;
2101  goto fail;
2102  }
2103  ffio_init_context(&pls->pb, pls->read_buffer, INITIAL_BUFFER_SIZE, 0, pls,
2104  read_data, NULL, NULL);
2105  pls->ctx->probesize = s->probesize > 0 ? s->probesize : 1024 * 4;
2106  pls->ctx->max_analyze_duration = s->max_analyze_duration > 0 ? s->max_analyze_duration : 4 * AV_TIME_BASE;
2107  pls->ctx->interrupt_callback = s->interrupt_callback;
2108  url = av_strdup(pls->segments[0]->url);
2109  ret = av_probe_input_buffer(&pls->pb, &in_fmt, url, NULL, 0, 0);
2110 
2111  for (int n = 0; n < pls->n_segments; n++)
2112  if (ret >= 0)
2113  ret = test_segment(s, in_fmt, pls, pls->segments[n]);
2114 
2115  if (ret < 0) {
2116  /* Free the ctx - it isn't initialized properly at this point,
2117  * so avformat_close_input shouldn't be called. If
2118  * avformat_open_input fails below, it frees and zeros the
2119  * context, so it doesn't need any special treatment like this. */
2120  av_log(s, AV_LOG_ERROR, "Error when loading first segment '%s'\n", url);
2121  avformat_free_context(pls->ctx);
2122  pls->ctx = NULL;
2123  av_free(url);
2124  goto fail;
2125  }
2126  av_free(url);
2127  pls->ctx->pb = &pls->pb;
2128  pls->ctx->io_open = nested_io_open;
2129  pls->ctx->flags |= s->flags & ~AVFMT_FLAG_CUSTOM_IO;
2130 
2131  if ((ret = ff_copy_whiteblacklists(pls->ctx, s)) < 0)
2132  goto fail;
2133 
2134  ret = avformat_open_input(&pls->ctx, pls->segments[0]->url, in_fmt, NULL);
2135  if (ret < 0)
2136  goto fail;
2137 
2138  if (pls->id3_deferred_extra && pls->ctx->nb_streams == 1) {
2144  }
2145 
2146  if (pls->is_id3_timestamped == -1)
2147  av_log(s, AV_LOG_WARNING, "No expected HTTP requests have been made\n");
2148 
2149  /*
2150  * For ID3 timestamped raw audio streams we need to detect the packet
2151  * durations to calculate timestamps in fill_timing_for_id3_timestamped_stream(),
2152  * but for other streams we can rely on our user calling avformat_find_stream_info()
2153  * on us if they want to.
2154  */
2155  if (pls->is_id3_timestamped || (pls->n_renditions > 0 && pls->renditions[0]->type == AVMEDIA_TYPE_AUDIO)) {
2156  ret = avformat_find_stream_info(pls->ctx, NULL);
2157  if (ret < 0)
2158  goto fail;
2159  }
2160 
2161  pls->has_noheader_flag = !!(pls->ctx->ctx_flags & AVFMTCTX_NOHEADER);
2162 
2163  /* Create new AVStreams for each stream in this playlist */
2164  ret = update_streams_from_subdemuxer(s, pls);
2165  if (ret < 0)
2166  goto fail;
2167 
2168  /*
2169  * Copy any metadata from playlist to main streams, but do not set
2170  * event flags.
2171  */
2172  if (pls->n_main_streams)
2173  av_dict_copy(&pls->main_streams[0]->metadata, pls->ctx->metadata, 0);
2174 
2178  }
2179 
2181 
2182  return 0;
2183 fail:
2184  hls_close(s);
2185  return ret;
2186 }
2187 
2188 static int recheck_discard_flags(AVFormatContext *s, int first)
2189 {
2190  HLSContext *c = s->priv_data;
2191  int i, changed = 0;
2192  int cur_needed;
2193 
2194  /* Check if any new streams are needed */
2195  for (i = 0; i < c->n_playlists; i++) {
2196  struct playlist *pls = c->playlists[i];
2197 
2198  cur_needed = playlist_needed(c->playlists[i]);
2199 
2200  if (pls->broken) {
2201  continue;
2202  }
2203  if (cur_needed && !pls->needed) {
2204  pls->needed = 1;
2205  changed = 1;
2206  pls->cur_seq_no = select_cur_seq_no(c, pls);
2207  pls->pb.eof_reached = 0;
2208  if (c->cur_timestamp != AV_NOPTS_VALUE) {
2209  /* catch up */
2210  pls->seek_timestamp = c->cur_timestamp;
2211  pls->seek_flags = AVSEEK_FLAG_ANY;
2212  pls->seek_stream_index = -1;
2213  }
2214  av_log(s, AV_LOG_INFO, "Now receiving playlist %d, segment %"PRId64"\n", i, pls->cur_seq_no);
2215  } else if (first && !cur_needed && pls->needed) {
2216  ff_format_io_close(pls->parent, &pls->input);
2217  pls->input_read_done = 0;
2218  ff_format_io_close(pls->parent, &pls->input_next);
2219  pls->input_next_requested = 0;
2220  pls->needed = 0;
2221  changed = 1;
2222  av_log(s, AV_LOG_INFO, "No longer receiving playlist %d\n", i);
2223  }
2224  }
2225  return changed;
2226 }
2227 
2229 {
2230  if (pls->id3_offset >= 0) {
2232  av_rescale_q(pls->id3_offset,
2233  pls->ctx->streams[pls->pkt->stream_index]->time_base,
2234  MPEG_TIME_BASE_Q));
2235  if (pls->pkt->duration)
2236  pls->id3_offset = av_sat_add64(pls->id3_offset, pls->pkt->duration);
2237  else
2238  pls->id3_offset = -1;
2239  } else {
2240  /* there have been packets with unknown duration
2241  * since the last id3 tag, should not normally happen */
2242  pls->pkt->dts = AV_NOPTS_VALUE;
2243  }
2244 
2245  if (pls->pkt->duration)
2246  pls->pkt->duration = av_rescale_q(pls->pkt->duration,
2247  pls->ctx->streams[pls->pkt->stream_index]->time_base,
2249 
2250  pls->pkt->pts = AV_NOPTS_VALUE;
2251 }
2252 
2253 static AVRational get_timebase(struct playlist *pls)
2254 {
2255  if (pls->is_id3_timestamped)
2256  return MPEG_TIME_BASE_Q;
2257 
2258  return pls->ctx->streams[pls->pkt->stream_index]->time_base;
2259 }
2260 
2261 static int compare_ts_with_wrapdetect(int64_t ts_a, struct playlist *pls_a,
2262  int64_t ts_b, struct playlist *pls_b)
2263 {
2264  int64_t scaled_ts_a = av_rescale_q(ts_a, get_timebase(pls_a), MPEG_TIME_BASE_Q);
2265  int64_t scaled_ts_b = av_rescale_q(ts_b, get_timebase(pls_b), MPEG_TIME_BASE_Q);
2266 
2267  return av_compare_mod(scaled_ts_a, scaled_ts_b, 1LL << 33);
2268 }
2269 
2271 {
2272  HLSContext *c = s->priv_data;
2273  int ret, i, minplaylist = -1;
2274 
2275  recheck_discard_flags(s, c->first_packet);
2276  c->first_packet = 0;
2277 
2278  for (i = 0; i < c->n_playlists; i++) {
2279  struct playlist *pls = c->playlists[i];
2280  /* Make sure we've got one buffered packet from each open playlist
2281  * stream */
2282  if (pls->needed && !pls->pkt->data) {
2283  while (1) {
2284  int64_t ts_diff;
2285  AVRational tb;
2286  ret = av_read_frame(pls->ctx, pls->pkt);
2287  if (ret < 0) {
2288  if (!avio_feof(&pls->pb) && ret != AVERROR_EOF)
2289  return ret;
2290  break;
2291  } else {
2292  /* stream_index check prevents matching picture attachments etc. */
2293  if (pls->is_id3_timestamped && pls->pkt->stream_index == 0) {
2294  /* audio elementary streams are id3 timestamped */
2296  }
2297 
2298  if (c->first_timestamp == AV_NOPTS_VALUE &&
2299  pls->pkt->dts != AV_NOPTS_VALUE)
2300  c->first_timestamp = av_rescale_q(pls->pkt->dts,
2302  }
2303 
2304  if (pls->seek_timestamp == AV_NOPTS_VALUE)
2305  break;
2306 
2307  if (pls->seek_stream_index < 0 ||
2308  pls->seek_stream_index == pls->pkt->stream_index) {
2309 
2310  if (pls->pkt->dts == AV_NOPTS_VALUE) {
2312  break;
2313  }
2314 
2315  tb = get_timebase(pls);
2316  ts_diff = av_rescale_rnd(pls->pkt->dts, AV_TIME_BASE,
2317  tb.den, AV_ROUND_DOWN) -
2318  pls->seek_timestamp;
2319  if (ts_diff >= 0 && (pls->seek_flags & AVSEEK_FLAG_ANY ||
2320  pls->pkt->flags & AV_PKT_FLAG_KEY)) {
2322  break;
2323  }
2324  }
2325  av_packet_unref(pls->pkt);
2326  }
2327  }
2328  /* Check if this stream has the packet with the lowest dts */
2329  if (pls->pkt->data) {
2330  struct playlist *minpls = minplaylist < 0 ?
2331  NULL : c->playlists[minplaylist];
2332  if (minplaylist < 0) {
2333  minplaylist = i;
2334  } else {
2335  int64_t dts = pls->pkt->dts;
2336  int64_t mindts = minpls->pkt->dts;
2337 
2338  if (dts == AV_NOPTS_VALUE ||
2339  (mindts != AV_NOPTS_VALUE && compare_ts_with_wrapdetect(dts, pls, mindts, minpls) < 0))
2340  minplaylist = i;
2341  }
2342  }
2343  }
2344 
2345  /* If we got a packet, return it */
2346  if (minplaylist >= 0) {
2347  struct playlist *pls = c->playlists[minplaylist];
2348  AVStream *ist;
2349  AVStream *st;
2350 
2351  ret = update_streams_from_subdemuxer(s, pls);
2352  if (ret < 0) {
2353  av_packet_unref(pls->pkt);
2354  return ret;
2355  }
2356 
2357  // If sub-demuxer reports updated metadata, copy it to the first stream
2358  // and set its AVSTREAM_EVENT_FLAG_METADATA_UPDATED flag.
2360  if (pls->n_main_streams) {
2361  st = pls->main_streams[0];
2362  av_dict_copy(&st->metadata, pls->ctx->metadata, 0);
2364  }
2366  }
2367 
2368  /* check if noheader flag has been cleared by the subdemuxer */
2369  if (pls->has_noheader_flag && !(pls->ctx->ctx_flags & AVFMTCTX_NOHEADER)) {
2370  pls->has_noheader_flag = 0;
2372  }
2373 
2374  if (pls->pkt->stream_index >= pls->n_main_streams) {
2375  av_log(s, AV_LOG_ERROR, "stream index inconsistency: index %d, %d main streams, %d subdemuxer streams\n",
2376  pls->pkt->stream_index, pls->n_main_streams, pls->ctx->nb_streams);
2377  av_packet_unref(pls->pkt);
2378  return AVERROR_BUG;
2379  }
2380 
2381  ist = pls->ctx->streams[pls->pkt->stream_index];
2382  st = pls->main_streams[pls->pkt->stream_index];
2383 
2384  av_packet_move_ref(pkt, pls->pkt);
2385  pkt->stream_index = st->index;
2386 
2387  if (pkt->dts != AV_NOPTS_VALUE)
2388  c->cur_timestamp = av_rescale_q(pkt->dts,
2389  ist->time_base,
2390  AV_TIME_BASE_Q);
2391 
2392  /* There may be more situations where this would be useful, but this at least
2393  * handles newly probed codecs properly (i.e. request_probe by mpegts). */
2394  if (ist->codecpar->codec_id != st->codecpar->codec_id) {
2395  ret = set_stream_info_from_input_stream(st, pls, ist);
2396  if (ret < 0) {
2397  return ret;
2398  }
2399  }
2400 
2401  return 0;
2402  }
2403  return AVERROR_EOF;
2404 }
2405 
2406 static int hls_read_seek(AVFormatContext *s, int stream_index,
2407  int64_t timestamp, int flags)
2408 {
2409  HLSContext *c = s->priv_data;
2410  struct playlist *seek_pls = NULL;
2411  int i, j;
2412  int stream_subdemuxer_index;
2413  int64_t first_timestamp, seek_timestamp, duration;
2414  int64_t seq_no;
2415 
2416  if ((flags & AVSEEK_FLAG_BYTE) || (c->ctx->ctx_flags & AVFMTCTX_UNSEEKABLE))
2417  return AVERROR(ENOSYS);
2418 
2419  first_timestamp = c->first_timestamp == AV_NOPTS_VALUE ?
2420  0 : c->first_timestamp;
2421 
2423  s->streams[stream_index]->time_base.den,
2426 
2427  duration = s->duration == AV_NOPTS_VALUE ?
2428  0 : s->duration;
2429 
2430  if (0 < duration && duration < seek_timestamp - first_timestamp)
2431  return AVERROR(EIO);
2432 
2433  /* find the playlist with the specified stream */
2434  for (i = 0; i < c->n_playlists; i++) {
2435  struct playlist *pls = c->playlists[i];
2436  for (j = 0; j < pls->n_main_streams; j++) {
2437  if (pls->main_streams[j] == s->streams[stream_index]) {
2438  seek_pls = pls;
2439  stream_subdemuxer_index = j;
2440  break;
2441  }
2442  }
2443  }
2444  /* check if the timestamp is valid for the playlist with the
2445  * specified stream index */
2446  if (!seek_pls || !find_timestamp_in_playlist(c, seek_pls, seek_timestamp, &seq_no))
2447  return AVERROR(EIO);
2448 
2449  /* set segment now so we do not need to search again below */
2450  seek_pls->cur_seq_no = seq_no;
2451  seek_pls->seek_stream_index = stream_subdemuxer_index;
2452 
2453  for (i = 0; i < c->n_playlists; i++) {
2454  /* Reset reading */
2455  struct playlist *pls = c->playlists[i];
2456  ff_format_io_close(pls->parent, &pls->input);
2457  pls->input_read_done = 0;
2458  ff_format_io_close(pls->parent, &pls->input_next);
2459  pls->input_next_requested = 0;
2460  av_packet_unref(pls->pkt);
2461  pls->pb.eof_reached = 0;
2462  /* Clear any buffered data */
2463  pls->pb.buf_end = pls->pb.buf_ptr = pls->pb.buffer;
2464  /* Reset the pos, to let the mpegts demuxer know we've seeked. */
2465  pls->pb.pos = 0;
2466  /* Flush the packet queue of the subdemuxer. */
2467  ff_read_frame_flush(pls->ctx);
2468 
2469  /* Reset the init segment so it's re-fetched and served appropiately */
2470  pls->cur_init_section = NULL;
2471 
2473  pls->seek_flags = flags;
2474 
2475  if (pls != seek_pls) {
2476  /* set closest segment seq_no for playlists not handled above */
2478  /* seek the playlist to the given position without taking
2479  * keyframes into account since this playlist does not have the
2480  * specified stream where we should look for the keyframes */
2481  pls->seek_stream_index = -1;
2482  pls->seek_flags |= AVSEEK_FLAG_ANY;
2483  }
2484  }
2485 
2486  c->cur_timestamp = seek_timestamp;
2487 
2488  return 0;
2489 }
2490 
2491 static int hls_probe(const AVProbeData *p)
2492 {
2493  /* Require #EXTM3U at the start, and either one of the ones below
2494  * somewhere for a proper match. */
2495  if (strncmp(p->buf, "#EXTM3U", 7))
2496  return 0;
2497 
2498  if (strstr(p->buf, "#EXT-X-STREAM-INF:") ||
2499  strstr(p->buf, "#EXT-X-TARGETDURATION:") ||
2500  strstr(p->buf, "#EXT-X-MEDIA-SEQUENCE:"))
2501  return AVPROBE_SCORE_MAX;
2502  return 0;
2503 }
2504 
2505 #define OFFSET(x) offsetof(HLSContext, x)
2506 #define FLAGS AV_OPT_FLAG_DECODING_PARAM
2507 static const AVOption hls_options[] = {
2508  {"live_start_index", "segment index to start live streams at (negative values are from the end)",
2509  OFFSET(live_start_index), AV_OPT_TYPE_INT, {.i64 = -3}, INT_MIN, INT_MAX, FLAGS},
2510  {"allowed_extensions", "List of file extensions that hls is allowed to access",
2511  OFFSET(allowed_extensions), AV_OPT_TYPE_STRING,
2512  {.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"
2513  ",cmfv,cmfa" // Ticket11526 www.nicovideo.jp
2514  ",ec3" // part of Ticket11435 (Elisa Viihde (Finnish online recording service))
2515  ",fmp4" // https://github.com/yt-dlp/yt-dlp/issues/12700
2516  },
2517  INT_MIN, INT_MAX, FLAGS},
2518  {"allowed_segment_extensions", "List of file extensions that hls is allowed to access",
2519  OFFSET(allowed_segment_extensions), AV_OPT_TYPE_STRING,
2520  {.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"
2521  ",cmfv,cmfa" // Ticket11526 www.nicovideo.jp
2522  ",ec3" // part of Ticket11435 (Elisa Viihde (Finnish online recording service))
2523  ",fmp4" // https://github.com/yt-dlp/yt-dlp/issues/12700
2524  ",html" // https://flash1.bogulus.cfd/
2525  },
2526  INT_MIN, INT_MAX, FLAGS},
2527  {"extension_picky", "Be picky with all extensions matching",
2528  OFFSET(extension_picky), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, FLAGS},
2529  {"max_reload", "Maximum number of times a insufficient list is attempted to be reloaded",
2530  OFFSET(max_reload), AV_OPT_TYPE_INT, {.i64 = 100}, 0, INT_MAX, FLAGS},
2531  {"m3u8_hold_counters", "The maximum number of times to load m3u8 when it refreshes without new segments",
2532  OFFSET(m3u8_hold_counters), AV_OPT_TYPE_INT, {.i64 = 1000}, 0, INT_MAX, FLAGS},
2533  {"http_persistent", "Use persistent HTTP connections",
2534  OFFSET(http_persistent), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, FLAGS },
2535  {"http_multiple", "Use multiple HTTP connections for fetching segments",
2536  OFFSET(http_multiple), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, FLAGS},
2537  {"http_seekable", "Use HTTP partial requests, 0 = disable, 1 = enable, -1 = auto",
2538  OFFSET(http_seekable), AV_OPT_TYPE_BOOL, { .i64 = -1}, -1, 1, FLAGS},
2539  {NULL}
2540 };
2541 
2542 static const AVClass hls_class = {
2543  .class_name = "hls demuxer",
2544  .item_name = av_default_item_name,
2545  .option = hls_options,
2546  .version = LIBAVUTIL_VERSION_INT,
2547 };
2548 
2550  .name = "hls",
2551  .long_name = NULL_IF_CONFIG_SMALL("Apple HTTP Live Streaming"),
2552  .priv_class = &hls_class,
2553  .priv_data_size = sizeof(HLSContext),
2555  .read_probe = hls_probe,
2558  .read_close = hls_close,
2560 };
uint8_t pi<< 24) CONV_FUNC_GROUP(AV_SAMPLE_FMT_FLT, float, AV_SAMPLE_FMT_U8, uint8_t,(*(const uint8_t *) pi - 0x80) *(1.0f/(1<< 7))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_DBL, double, AV_SAMPLE_FMT_U8, uint8_t,(*(const uint8_t *) pi - 0x80) *(1.0/(1<< 7))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_U8, uint8_t, AV_SAMPLE_FMT_S16, int16_t,(*(const int16_t *) pi >> 8)+0x80) CONV_FUNC_GROUP(AV_SAMPLE_FMT_FLT, float, AV_SAMPLE_FMT_S16, int16_t, *(const int16_t *) pi *(1.0f/(1<< 15))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_DBL, double, AV_SAMPLE_FMT_S16, int16_t, *(const int16_t *) pi *(1.0/(1<< 15))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_U8, uint8_t, AV_SAMPLE_FMT_S32, int32_t,(*(const int32_t *) pi >> 24)+0x80) CONV_FUNC_GROUP(AV_SAMPLE_FMT_FLT, float, AV_SAMPLE_FMT_S32, int32_t, *(const int32_t *) pi *(1.0f/(1U<< 31))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_DBL, double, AV_SAMPLE_FMT_S32, int32_t, *(const int32_t *) pi *(1.0/(1U<< 31))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_U8, uint8_t, AV_SAMPLE_FMT_FLT, float, av_clip_uint8(lrintf(*(const float *) pi *(1<< 7))+0x80)) CONV_FUNC_GROUP(AV_SAMPLE_FMT_S16, int16_t, AV_SAMPLE_FMT_FLT, float, av_clip_int16(lrintf(*(const float *) pi *(1<< 15)))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_S32, int32_t, AV_SAMPLE_FMT_FLT, float, av_clipl_int32(llrintf(*(const float *) pi *(1U<< 31)))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_U8, uint8_t, AV_SAMPLE_FMT_DBL, double, av_clip_uint8(lrint(*(const double *) pi *(1<< 7))+0x80)) CONV_FUNC_GROUP(AV_SAMPLE_FMT_S16, int16_t, AV_SAMPLE_FMT_DBL, double, av_clip_int16(lrint(*(const double *) pi *(1<< 15)))) CONV_FUNC_GROUP(AV_SAMPLE_FMT_S32, int32_t, AV_SAMPLE_FMT_DBL, double, av_clipl_int32(llrint(*(const double *) pi *(1U<< 31)))) #define SET_CONV_FUNC_GROUP(ofmt, ifmt) static void set_generic_function(AudioConvert *ac) { } void ff_audio_convert_free(AudioConvert **ac) { if(! *ac) return;ff_dither_free(&(*ac) ->dc);av_freep(ac);} AudioConvert *ff_audio_convert_alloc(AVAudioResampleContext *avr, enum AVSampleFormat out_fmt, enum AVSampleFormat in_fmt, int channels, int sample_rate, int apply_map) { AudioConvert *ac;int in_planar, out_planar;ac=av_mallocz(sizeof(*ac));if(!ac) return NULL;ac->avr=avr;ac->out_fmt=out_fmt;ac->in_fmt=in_fmt;ac->channels=channels;ac->apply_map=apply_map;if(avr->dither_method !=AV_RESAMPLE_DITHER_NONE &&av_get_packed_sample_fmt(out_fmt)==AV_SAMPLE_FMT_S16 &&av_get_bytes_per_sample(in_fmt) > 2) { ac->dc=ff_dither_alloc(avr, out_fmt, in_fmt, channels, sample_rate, apply_map);if(!ac->dc) { av_free(ac);return NULL;} return ac;} in_planar=ff_sample_fmt_is_planar(in_fmt, channels);out_planar=ff_sample_fmt_is_planar(out_fmt, channels);if(in_planar==out_planar) { ac->func_type=CONV_FUNC_TYPE_FLAT;ac->planes=in_planar ? ac->channels :1;} else if(in_planar) ac->func_type=CONV_FUNC_TYPE_INTERLEAVE;else ac->func_type=CONV_FUNC_TYPE_DEINTERLEAVE;set_generic_function(ac);if(ARCH_AARCH64) ff_audio_convert_init_aarch64(ac);if(ARCH_ARM) ff_audio_convert_init_arm(ac);if(ARCH_X86) ff_audio_convert_init_x86(ac);return ac;} int ff_audio_convert(AudioConvert *ac, AudioData *out, AudioData *in) { int use_generic=1;int len=in->nb_samples;int p;if(ac->dc) { av_log(ac->avr, AV_LOG_TRACE, "%d samples - audio_convert: %s to %s (dithered)\n", len, av_get_sample_fmt_name(ac->in_fmt), av_get_sample_fmt_name(ac->out_fmt));return ff_convert_dither(ac-> in
uint8_t
simple assert() macros that are a bit more flexible than ISO C assert().
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Definition: avassert.h:37
#define FF_COMPLIANCE_EXPERIMENTAL
Allow nonstandardized experimental things.
Definition: avcodec.h:1610
Main libavformat public API header.
#define AVFMT_EVENT_FLAG_METADATA_UPDATED
Definition: avformat.h:1562
#define AVPROBE_SCORE_MAX
maximum score
Definition: avformat.h:453
#define AV_DISPOSITION_HEARING_IMPAIRED
stream for hearing impaired audiences
Definition: avformat.h:831
#define AVFMTCTX_NOHEADER
signal that no header is present (streams are added dynamically)
Definition: avformat.h:1177
#define AVFMT_TS_DISCONT
Format allows timestamp discontinuities.
Definition: avformat.h:464
#define AVSEEK_FLAG_BYTE
seeking based on position in bytes
Definition: avformat.h:2416
#define AVFMT_NOGENSEARCH
Format does not allow to fall back on generic search.
Definition: avformat.h:469
#define AVSEEK_FLAG_ANY
seek to any frame, even non-keyframes
Definition: avformat.h:2417
#define ff_const59
The ff_const59 define is not part of the public API and will be removed without further warning.
Definition: avformat.h:533
#define AVFMTCTX_UNSEEKABLE
signal that the stream is definitely not seekable, and attempts to call the seek function will fail.
Definition: avformat.h:1179
#define AV_DISPOSITION_FORCED
Track should be used during playback by default.
Definition: avformat.h:830
#define AV_DISPOSITION_VISUAL_IMPAIRED
stream for visual impaired audiences
Definition: avformat.h:832
#define AVSTREAM_EVENT_FLAG_METADATA_UPDATED
Definition: avformat.h:999
#define AVFMT_FLAG_CUSTOM_IO
The caller has supplied a custom AVIOContext, don't avio_close() it.
Definition: avformat.h:1371
#define AVSEEK_FLAG_BACKWARD
Definition: avformat.h:2415
#define AV_DISPOSITION_DEFAULT
Definition: avformat.h:818
int ff_check_interrupt(AVIOInterruptCB *cb)
Check if the user has requested to interrupt a blocking function associated with cb.
Definition: avio.c:661
const char * avio_find_protocol_name(const char *url)
Return the name of the protocol that will handle the passed URL.
Definition: avio.c:470
int64_t avio_seek(AVIOContext *s, int64_t offset, int whence)
fseek() equivalent for AVIOContext.
Definition: aviobuf.c:260
#define AVIO_FLAG_READ
read-only
Definition: avio.h:674
int64_t avio_size(AVIOContext *s)
Get the filesize.
Definition: aviobuf.c:349
int avio_feof(AVIOContext *s)
Similar to feof() but also returns nonzero on read errors.
Definition: aviobuf.c:371
int avio_read(AVIOContext *s, unsigned char *buf, int size)
Read size bytes from AVIOContext into buf.
Definition: aviobuf.c:645
URLContext * ffio_geturlcontext(AVIOContext *s)
Return the URLContext associated with the AVIOContext.
Definition: aviobuf.c:993
int ffio_init_context(AVIOContext *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, uint8_t *buf, int buf_size), int64_t(*seek)(void *opaque, int64_t offset, int whence))
Definition: aviobuf.c:88
static int read_packet(void *opaque, uint8_t *buf, int buf_size)
Definition: avio_reading.c:42
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:822
#define AV_RB64
Definition: intreadwrite.h:164
#define flags(name, subs,...)
Definition: cbs_av1.c:572
#define s(width, name)
Definition: cbs_vp9.c:257
#define fail()
Definition: checkasm.h:133
int avcodec_parameters_copy(AVCodecParameters *dst, const AVCodecParameters *src)
Copy the contents of src to dst.
Definition: codec_par.c:72
#define FFSWAP(type, a, b)
Definition: common.h:108
#define FFMIN(a, b)
Definition: common.h:105
#define av_sat_add64
Definition: common.h:164
#define FFMAX(a, b)
Definition: common.h:103
#define NULL
Definition: coverity.c:32
long long int64_t
Definition: coverity.c:34
Public dictionary API.
const OptionDef options[]
static int read_header(FFV1Context *f)
Definition: ffv1dec.c:555
static av_cold void cleanup(FlashSV2Context *s)
Definition: flashsv2enc.c:127
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:51
#define AV_OPT_SEARCH_CHILDREN
Search in possible children of the given object first.
Definition: opt.h:560
#define AV_OPT_ALLOW_NULL
In av_opt_get, return NULL if the option has a pointer type and is set to NULL, rather than returning...
Definition: opt.h:574
@ AV_OPT_TYPE_INT
Definition: opt.h:225
@ AV_OPT_TYPE_BOOL
Definition: opt.h:242
@ AV_OPT_TYPE_STRING
Definition: opt.h:229
#define AV_INPUT_BUFFER_PADDING_SIZE
Required number of additionally allocated bytes at the end of the input bitstream for decoding.
Definition: avcodec.h:215
@ AVDISCARD_ALL
discard all
Definition: avcodec.h:236
void av_packet_free(AVPacket **pkt)
Free the packet, if the packet is reference counted, it will be unreferenced first.
Definition: avpacket.c:75
void av_packet_unref(AVPacket *pkt)
Wipe the packet.
Definition: avpacket.c:634
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition: packet.h:410
void av_packet_move_ref(AVPacket *dst, AVPacket *src)
Move every field in src to dst and reset src.
Definition: avpacket.c:690
AVPacket * av_packet_alloc(void)
Allocate an AVPacket and set its fields to default values.
Definition: avpacket.c:64
uint8_t * av_stream_new_side_data(AVStream *stream, enum AVPacketSideDataType type, size_t size)
Allocate new information from stream.
AVProgram * av_new_program(AVFormatContext *s, int id)
Definition: utils.c:4606
void avformat_free_context(AVFormatContext *s)
Free an AVFormatContext and all its streams.
Definition: utils.c:4436
AVFormatContext * avformat_alloc_context(void)
Allocate an AVFormatContext.
Definition: options.c:211
AVStream * avformat_new_stream(AVFormatContext *s, const AVCodec *c)
Add a new stream to a media file.
Definition: utils.c:4508
int av_probe_input_buffer(AVIOContext *pb, ff_const59 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:339
int av_read_frame(AVFormatContext *s, AVPacket *pkt)
Return the next frame of a stream.
Definition: utils.c:1741
void av_program_add_stream_index(AVFormatContext *ac, int progid, unsigned int idx)
int avformat_find_stream_info(AVFormatContext *ic, AVDictionary **options)
Read packets of a media file to get stream information.
Definition: utils.c:3602
void avformat_close_input(AVFormatContext **s)
Close an opened input AVFormatContext.
Definition: utils.c:4481
int avformat_open_input(AVFormatContext **ps, const char *url, ff_const59 AVInputFormat *fmt, AVDictionary **options)
Open an input stream and read the header.
Definition: utils.c:512
int avformat_queue_attached_pictures(AVFormatContext *s)
Definition: utils.c:454
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:38
void av_dict_free(AVDictionary **pm)
Free all the memory allocated for an AVDictionary struct and all keys and values.
Definition: dict.c:199
#define AV_DICT_IGNORE_SUFFIX
Return first entry in a dictionary whose first part corresponds to the search key,...
Definition: dict.h:70
int av_dict_copy(AVDictionary **dst, const AVDictionary *src, int flags)
Copy entries from one AVDictionary struct into another.
Definition: dict.c:213
#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:74
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:70
#define AV_DICT_MATCH_CASE
Only get an entry with exact-case key match.
Definition: dict.h:69
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:40
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:143
#define AVERROR_EXIT
Immediate exit was requested; the called function should not be restarted.
Definition: error.h:56
#define AVERROR_PROTOCOL_NOT_FOUND
Protocol not found.
Definition: error.h:63
#define AVERROR_PATCHWELCOME
Not yet implemented in FFmpeg, patches welcome.
Definition: error.h:62
#define AVERROR_BUG
Internal bug, also see AVERROR_BUG2.
Definition: error.h:50
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition: error.h:59
#define AVERROR_EOF
End of file.
Definition: error.h:55
#define av_err2str(errnum)
Convenience macro, the return value should be used only directly in function arguments but never stan...
Definition: error.h:119
#define AVERROR(e)
Definition: error.h:43
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition: log.h:215
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:200
#define AV_LOG_VERBOSE
Detailed information.
Definition: log.h:210
#define AV_LOG_INFO
Standard information.
Definition: log.h:205
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:194
const char * av_default_item_name(void *ptr)
Return the context name.
Definition: log.c:235
int64_t av_rescale_rnd(int64_t a, int64_t b, int64_t c, enum AVRounding rnd)
Rescale a 64-bit integer with specified rounding.
Definition: mathematics.c:58
@ AV_ROUND_DOWN
Round toward -infinity.
Definition: mathematics.h:82
@ AV_ROUND_UP
Round toward +infinity.
Definition: mathematics.h:83
int64_t av_rescale_q(int64_t a, AVRational bq, AVRational cq)
Rescale a 64-bit integer by 2 rational numbers.
Definition: mathematics.c:142
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.
Definition: mathematics.c:160
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:502
void * av_mallocz(size_t size)
Allocate a memory block with alignment suitable for all memory accesses (including vectors if availab...
Definition: mem.c:237
char * av_strdup(const char *s)
Duplicate a string.
Definition: mem.c:253
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:478
AVMediaType
Definition: avutil.h:199
@ AVMEDIA_TYPE_AUDIO
Definition: avutil.h:202
@ AVMEDIA_TYPE_SUBTITLE
Definition: avutil.h:204
@ AVMEDIA_TYPE_VIDEO
Definition: avutil.h:201
@ AVMEDIA_TYPE_UNKNOWN
Usually treated as AVMEDIA_TYPE_DATA.
Definition: avutil.h:200
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:186
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:356
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:34
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:83
int av_strncasecmp(const char *a, const char *b, size_t n)
Locale-independent case-insensitive compare.
Definition: avstring.c:225
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition: avutil.h:248
#define AV_TIME_BASE
Internal time base represented as integer.
Definition: avutil.h:254
#define AV_TIME_BASE_Q
Internal time base represented as fractional value.
Definition: avutil.h:260
#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:789
static void update_noheader_flag(AVFormatContext *s)
Definition: hls.c:1920
#define MAX_CHARACTERISTICS_LEN
Definition: hls.c:45
static void handle_variant_args(struct variant_info *info, const char *key, int key_len, char **dest, int *dest_len)
Definition: hls.c:361
#define MAX_FIELD_LEN
Definition: hls.c:44
static int open_input(HLSContext *c, struct playlist *pls, struct segment *seg, AVIOContext **in)
Definition: hls.c:1326
static int update_init_section(struct playlist *pls, struct segment *seg)
Definition: hls.c:1413
static struct segment * next_segment(struct playlist *pls)
Definition: hls.c:1103
static struct rendition * new_rendition(HLSContext *c, struct rendition_info *info, const char *url_base)
Definition: hls.c:479
static int read_from_url(struct playlist *pls, struct segment *seg, uint8_t *buf, int buf_size)
Definition: hls.c:1111
#define INITIAL_BUFFER_SIZE
Definition: hls.c:42
static int hls_read_header(AVFormatContext *s)
Definition: hls.c:1955
static struct segment * current_segment(struct playlist *pls)
Definition: hls.c:1098
static int read_data(void *opaque, uint8_t *buf, int buf_size)
Definition: hls.c:1523
static int set_stream_info_from_input_stream(AVStream *st, struct playlist *pls, AVStream *ist)
Definition: hls.c:1862
static int test_segment(AVFormatContext *s, const AVInputFormat *in_fmt, struct playlist *pls, struct segment *seg)
Definition: hls.c:725
static void free_segment_list(struct playlist *pls)
Definition: hls.c:232
#define MPEG_TIME_BASE
Definition: hls.c:47
static void free_init_section_list(struct playlist *pls)
Definition: hls.c:239
static void add_renditions_to_variant(HLSContext *c, struct variant *var, enum AVMediaType type, const char *group_id)
Definition: hls.c:1683
static int hls_probe(const AVProbeData *p)
Definition: hls.c:2491
static int ensure_playlist(HLSContext *c, struct playlist **pls, const char *url)
Definition: hls.c:609
PlaylistType
Definition: hls.c:84
@ PLS_TYPE_UNSPECIFIED
Definition: hls.c:85
@ PLS_TYPE_VOD
Definition: hls.c:87
@ PLS_TYPE_EVENT
Definition: hls.c:86
static int recheck_discard_flags(AVFormatContext *s, int first)
Definition: hls.c:2188
static AVRational get_timebase(struct playlist *pls)
Definition: hls.c:2253
static void fill_timing_for_id3_timestamped_stream(struct playlist *pls)
Definition: hls.c:2228
static void parse_id3(AVFormatContext *s, AVIOContext *pb, AVDictionary **metadata, int64_t *dts, ID3v2ExtraMetaAPIC **apic, ID3v2ExtraMeta **extra_meta)
Definition: hls.c:1128
static void handle_key_args(struct key_info *info, const char *key, int key_len, char **dest, int *dest_len)
Definition: hls.c:385
static int64_t default_reload_interval(struct playlist *pls)
Definition: hls.c:1470
static int find_timestamp_in_playlist(HLSContext *c, struct playlist *pls, int64_t timestamp, int64_t *seq_no)
Definition: hls.c:1739
static int open_url_keepalive(AVFormatContext *s, AVIOContext **pb, const char *url, AVDictionary **options)
Definition: hls.c:620
static void add_metadata_from_renditions(AVFormatContext *s, struct playlist *pls, enum AVMediaType type)
Definition: hls.c:1707
static int update_streams_from_subdemuxer(AVFormatContext *s, struct playlist *pls)
Definition: hls.c:1895
#define FLAGS
Definition: hls.c:2506
static void add_stream_to_programs(AVFormatContext *s, struct playlist *pls, AVStream *stream)
Definition: hls.c:1836
static int hls_close(AVFormatContext *s)
Definition: hls.c:1941
static struct playlist * new_playlist(HLSContext *c, const char *url, const char *base)
Definition: hls.c:301
static int nested_io_open(AVFormatContext *s, AVIOContext **pb, const char *url, int flags, AVDictionary **opts)
Definition: hls.c:1826
static void handle_id3(AVIOContext *pb, struct playlist *pls)
Definition: hls.c:1183
#define PACKED_AUDIO_FORMATS
Definition: hls.c:50
static void handle_rendition_args(void *vinfo, const char *key, int key_len, char **dest, int *dest_len)
Definition: hls.c:563
static void free_segment_dynarray(struct segment **segments, int n_segments)
Definition: hls.c:222
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:2261
static struct segment * new_init_section(struct playlist *pls, struct init_section_info *info, const char *url_base)
Definition: hls.c:405
static int parse_playlist(HLSContext *c, const char *url, struct playlist *pls, AVIOContext *in)
Definition: hls.c:769
#define MPEG_TIME_BASE_Q
Definition: hls.c:48
KeyType
Definition: hls.c:64
@ KEY_SAMPLE_AES
Definition: hls.c:67
@ KEY_NONE
Definition: hls.c:65
@ KEY_AES_128
Definition: hls.c:66
static int hls_read_packet(AVFormatContext *s, AVPacket *pkt)
Definition: hls.c:2270
static int save_avio_options(AVFormatContext *s)
Definition: hls.c:1804
static const AVOption hls_options[]
Definition: hls.c:2507
static void free_rendition_list(HLSContext *c)
Definition: hls.c:292
static int open_url(AVFormatContext *s, AVIOContext **pb, const char *url, AVDictionary **opts, AVDictionary *opts2, int *is_http_out)
Definition: hls.c:638
#define OFFSET(x)
Definition: hls.c:2505
static int id3_has_changed_values(struct playlist *pls, AVDictionary *metadata, ID3v2ExtraMetaAPIC *apic)
Definition: hls.c:1154
static void free_playlist_list(HLSContext *c)
Definition: hls.c:251
static const AVClass hls_class
Definition: hls.c:2542
static int64_t select_cur_seq_no(HLSContext *c, struct playlist *pls)
Definition: hls.c:1765
static struct variant * new_variant(HLSContext *c, struct variant_info *info, const char *url, const char *base)
Definition: hls.c:335
static void intercept_id3(struct playlist *pls, uint8_t *buf, int buf_size, int *len)
Definition: hls.c:1226
static int playlist_needed(struct playlist *pls)
Definition: hls.c:1477
static void free_variant_list(HLSContext *c)
Definition: hls.c:280
AVInputFormat ff_hls_demuxer
Definition: hls.c:2549
static void handle_init_section_args(void *context, const char *key, int key_len, char **dest, int *dest_len)
Definition: hls.c:454
static int hls_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
Definition: hls.c:2406
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:424
cl_device_type type
const char * key
int ff_id3v2_tag_len(const uint8_t *buf)
Get the length of an ID3v2 tag.
Definition: id3v2.c:156
int ff_id3v2_match(const uint8_t *buf, const char *magic)
Detect ID3v2 Header.
Definition: id3v2.c:143
void ff_id3v2_free_extra_meta(ID3v2ExtraMeta **extra_meta)
Free memory allocated parsing special (non-text) metadata.
Definition: id3v2.c:1128
int ff_id3v2_parse_priv_dict(AVDictionary **metadata, ID3v2ExtraMeta *extra_meta)
Parse PRIV tags into a dictionary.
Definition: id3v2.c:1235
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:1144
int ff_id3v2_parse_priv(AVFormatContext *s, ID3v2ExtraMeta *extra_meta)
Add metadata for all PRIV tags in the ID3v2 header.
Definition: id3v2.c:1275
void ff_id3v2_read_dict(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:1116
#define ID3v2_DEFAULT_MAGIC
Default magic bytes for ID3v2 header: "ID3".
Definition: id3v2.h:35
#define ID3v2_HEADER_SIZE
Definition: id3v2.h:30
int i
Definition: input.c:407
#define AV_WB64(p, v)
Definition: intreadwrite.h:433
void(* ff_parse_key_val_cb)(void *context, const char *key, int key_len, char **dest, int *dest_len)
Callback function type for ff_parse_key_value.
Definition: internal.h:511
int ff_copy_whiteblacklists(AVFormatContext *dst, const AVFormatContext *src)
Copies the whilelists from one context to the other.
Definition: utils.c:160
int ff_hex_to_data(uint8_t *data, const char *p)
Parse a string of hexadecimal strings.
Definition: utils.c:4916
#define dynarray_add(tab, nb_ptr, elem)
Definition: internal.h:355
char * ff_data_to_hex(char *buf, const uint8_t *src, int size, int lowercase)
Definition: utils.c:4895
void avpriv_set_pts_info(AVStream *s, int pts_wrap_bits, unsigned int pts_num, unsigned int pts_den)
Set the time base and wrapping info for a given stream.
Definition: utils.c:4944
#define MAX_URL_SIZE
Definition: internal.h:30
void ff_read_frame_flush(AVFormatContext *s)
Flush the frame reader.
Definition: utils.c:1892
void ff_format_io_close(AVFormatContext *s, AVIOContext **pb)
Definition: utils.c:5691
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:4974
static int read_probe(const AVProbeData *pd)
Definition: jvdec.c:55
common internal API header
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification.
Definition: internal.h:117
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:145
static int read_seek(AVFormatContext *ctx, int stream_index, int64_t timestamp, int flags)
Definition: libcdio.c:153
#define isnan(x)
Definition: libm.h:340
AVOptions.
#define tb
Definition: regdef.h:68
#define snprintf
Definition: snprintf.h:34
unsigned int pos
Definition: spdifenc.c:412
int size
Size of data in bytes.
Definition: buffer.h:97
uint8_t * data
The data buffer.
Definition: buffer.h:92
Describe the class of an AVClass context structure.
Definition: log.h:67
const char * class_name
The name of the class; usually it is the same name as the context structure type to which the AVClass...
Definition: log.h:72
enum AVMediaType codec_type
General type of the encoded data.
Definition: codec_par.h:56
enum AVCodecID codec_id
Specific type of the encoded data (the codec used).
Definition: codec_par.h:60
char * key
Definition: dict.h:82
char * value
Definition: dict.h:83
Format I/O context.
Definition: avformat.h:1232
int event_flags
Flags indicating events happening on the file, a combination of AVFMT_EVENT_FLAG_*.
Definition: avformat.h:1555
unsigned int nb_streams
Number of elements in AVFormatContext.streams.
Definition: avformat.h:1288
AVIOContext * pb
I/O context.
Definition: avformat.h:1274
AVDictionary * metadata
Metadata that applies to the whole file.
Definition: avformat.h:1474
int flags
Flags modifying the (de)muxer behaviour.
Definition: avformat.h:1363
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:1408
int ctx_flags
Flags signalling stream properties.
Definition: avformat.h:1281
ff_const59 struct AVInputFormat * iformat
The input container format.
Definition: avformat.h:1244
AVIOInterruptCB interrupt_callback
Custom interrupt callbacks for the I/O layer.
Definition: avformat.h:1512
void * priv_data
Format private data.
Definition: avformat.h:1260
int64_t probesize
Maximum size of the data read from input for determining the input container format.
Definition: avformat.h:1400
AVStream ** streams
A list of all streams in the file.
Definition: avformat.h:1300
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:1828
Bytestream IO Context.
Definition: avio.h:161
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:229
unsigned char * buf_ptr
Current position in the buffer.
Definition: avio.h:228
int64_t pos
position in the file of the current buffer
Definition: avio.h:238
unsigned char * buffer
Start of the buffer.
Definition: avio.h:226
int eof_reached
true if was unable to read due to error or eof
Definition: avio.h:239
Callback for checking whether to abort blocking functions.
Definition: avio.h:58
const char * name
A comma separated list of short names for the format.
Definition: avformat.h:645
const char * extensions
If extensions are defined, then no probe is done.
Definition: avformat.h:666
AVOption.
Definition: opt.h:248
uint8_t * data
Definition: packet.h:307
enum AVPacketSideDataType type
Definition: packet.h:313
size_t size
Definition: packet.h:311
This structure stores compressed data.
Definition: packet.h:346
int stream_index
Definition: packet.h:371
int flags
A combination of AV_PKT_FLAG values.
Definition: packet.h:375
int size
Definition: packet.h:370
int64_t duration
Duration of this packet in AVStream->time_base units, 0 if unknown.
Definition: packet.h:387
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
Definition: packet.h:362
int64_t dts
Decompression timestamp in AVStream->time_base units; the time at which the packet is decompressed.
Definition: packet.h:368
uint8_t * data
Definition: packet.h:369
This structure contains the data a format has to probe a file.
Definition: avformat.h:441
unsigned char * buf
Buffer must have AVPROBE_PADDING_SIZE of extra allocated bytes filled with zero.
Definition: avformat.h:443
New fields can be added to the end with minor version bumps.
Definition: avformat.h:1150
unsigned int nb_stream_indexes
Definition: avformat.h:1155
unsigned int * stream_index
Definition: avformat.h:1154
enum AVDiscard discard
selects which program to discard and which to feed to the caller
Definition: avformat.h:1153
AVDictionary * metadata
Definition: avformat.h:1156
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
int need_context_update
Whether the internal avctx needs to be updated from codecpar (after a late change to codecpar)
Definition: internal.h:200
Stream structure.
Definition: avformat.h:873
AVPacketSideData * side_data
An array of side data that applies to the whole stream (i.e.
Definition: avformat.h:975
AVCodecParameters * codecpar
Codec parameters associated with this stream.
Definition: avformat.h:1038
enum AVDiscard discard
Selects which packets can be discarded at will and do not need to be demuxed.
Definition: avformat.h:928
AVDictionary * metadata
Definition: avformat.h:937
int id
Format-specific stream ID.
Definition: avformat.h:880
int index
stream index in AVFormatContext
Definition: avformat.h:874
int pts_wrap_bits
number of bits in pts (used for wrapping control)
Definition: avformat.h:1055
AVPacket attached_pic
For streams with AV_DISPOSITION_ATTACHED_PIC disposition, this packet will contain the attached pictu...
Definition: avformat.h:955
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented.
Definition: avformat.h:902
int event_flags
Flags indicating events happening on the stream, a combination of AVSTREAM_EVENT_FLAG_*.
Definition: avformat.h:992
int nb_side_data
The number of elements in the AVStream.side_data array.
Definition: avformat.h:979
AVStreamInternal * internal
An opaque field for libavformat internal usage.
Definition: avformat.h:1113
int disposition
AV_DISPOSITION_* bit field.
Definition: avformat.h:926
int n_renditions
Definition: hls.c:201
int http_multiple
Definition: hls.c:217
struct rendition ** renditions
Definition: hls.c:202
int m3u8_hold_counters
Definition: hls.c:205
AVIOInterruptCB * interrupt_callback
Definition: hls.c:210
AVDictionary * avio_opts
Definition: hls.c:211
char * allowed_segment_extensions
Definition: hls.c:213
int n_variants
Definition: hls.c:197
int http_persistent
Definition: hls.c:216
int extension_picky
Definition: hls.c:214
AVFormatContext * ctx
Definition: hls.c:196
int64_t cur_seq_no
Definition: hls.c:204
int live_start_index
Definition: hls.c:206
AVIOContext * playlist_pb
Definition: hls.c:219
int first_packet
Definition: hls.c:207
int max_reload
Definition: hls.c:215
int n_playlists
Definition: hls.c:199
int64_t cur_timestamp
Definition: hls.c:209
struct variant ** variants
Definition: hls.c:198
int64_t first_timestamp
Definition: hls.c:208
struct playlist ** playlists
Definition: hls.c:200
char * allowed_extensions
Definition: hls.c:212
int http_seekable
Definition: hls.c:218
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::@259 data
const char * tag
Definition: id3v2.h:85
struct ID3v2ExtraMeta * next
Definition: id3v2.h:86
Definition: url.h:38
char uri[MAX_URL_SIZE]
Definition: hls.c:401
char byterange[32]
Definition: hls.c:402
Definition: hls.c:379
char iv[35]
Definition: hls.c:382
char uri[MAX_URL_SIZE]
Definition: hls.c:380
char method[11]
Definition: hls.c:381
Definition: graph2dot.c:48
Definition: hls.c:95
int finished
Definition: hls.c:114
int id3_changed
Definition: hls.c:147
int broken
Definition: hls.c:121
int64_t cur_seg_offset
Definition: hls.c:125
AVIOContext * input
Definition: hls.c:99
uint8_t * read_buffer
Definition: hls.c:98
int64_t cur_seq_no
Definition: hls.c:122
int n_renditions
Definition: hls.c:158
int64_t id3_mpegts_timestamp
Definition: hls.c:141
struct rendition ** renditions
Definition: hls.c:159
unsigned int init_sec_data_len
Definition: hls.c:132
int64_t id3_offset
Definition: hls.c:142
int64_t target_duration
Definition: hls.c:116
int64_t last_load_time
Definition: hls.c:126
int64_t last_seq_no
Definition: hls.c:123
int seek_stream_index
Definition: hls.c:152
int64_t start_seq_no
Definition: hls.c:117
unsigned int id3_buf_size
Definition: hls.c:144
AVStream ** main_streams
Definition: hls.c:111
AVIOContext * input_next
Definition: hls.c:101
unsigned int init_sec_buf_read_offset
Definition: hls.c:133
AVIOContext pb
Definition: hls.c:97
int64_t seek_timestamp
Definition: hls.c:150
AVPacket * pkt
Definition: hls.c:106
int input_read_done
Definition: hls.c:100
AVFormatContext * ctx
Definition: hls.c:105
uint8_t * init_sec_buf
Definition: hls.c:130
struct segment * cur_init_section
Definition: hls.c:129
uint8_t * id3_buf
Definition: hls.c:143
uint8_t key[16]
Definition: hls.c:136
int id3_found
Definition: hls.c:146
int index
Definition: hls.c:104
int m3u8_hold_counters
Definition: hls.c:124
int needed
Definition: hls.c:120
int has_noheader_flag
Definition: hls.c:107
char key_url[MAX_URL_SIZE]
Definition: hls.c:135
int n_init_sections
Definition: hls.c:163
struct segment ** segments
Definition: hls.c:119
int n_segments
Definition: hls.c:118
struct segment ** init_sections
Definition: hls.c:164
char url[MAX_URL_SIZE]
Definition: hls.c:96
AVFormatContext * parent
Definition: hls.c:103
int seek_flags
Definition: hls.c:151
int is_id3_timestamped
Definition: hls.c:140
unsigned int init_sec_buf_size
Definition: hls.c:131
int n_main_streams
Definition: hls.c:112
int input_next_requested
Definition: hls.c:102
ID3v2ExtraMeta * id3_deferred_extra
Definition: hls.c:148
AVDictionary * id3_initial
Definition: hls.c:145
enum PlaylistType type
Definition: hls.c:115
char type[16]
Definition: hls.c:468
char defaultr[4]
Definition: hls.c:474
char name[MAX_FIELD_LEN]
Definition: hls.c:473
char language[MAX_FIELD_LEN]
Definition: hls.c:471
char forced[4]
Definition: hls.c:475
char uri[MAX_URL_SIZE]
Definition: hls.c:469
char group_id[MAX_FIELD_LEN]
Definition: hls.c:470
char characteristics[MAX_CHARACTERISTICS_LEN]
Definition: hls.c:476
char assoc_language[MAX_FIELD_LEN]
Definition: hls.c:472
Definition: hls.c:173
char name[MAX_FIELD_LEN]
Definition: hls.c:178
enum AVMediaType type
Definition: hls.c:174
char group_id[MAX_FIELD_LEN]
Definition: hls.c:176
char language[MAX_FIELD_LEN]
Definition: hls.c:177
int disposition
Definition: hls.c:179
struct playlist * playlist
Definition: hls.c:175
Definition: hls.c:70
struct segment * init_section
Definition: hls.c:79
int64_t size
Definition: hls.c:73
uint8_t iv[16]
Definition: hls.c:77
char * url
Definition: hls.c:74
int64_t duration
Definition: hls.c:71
int64_t url_offset
Definition: hls.c:72
char * key
Definition: hls.c:75
enum KeyType key_type
Definition: hls.c:76
char bandwidth[20]
Definition: hls.c:328
char video[MAX_FIELD_LEN]
Definition: hls.c:331
char subtitles[MAX_FIELD_LEN]
Definition: hls.c:332
char audio[MAX_FIELD_LEN]
Definition: hls.c:330
Definition: hls.c:182
int bandwidth
Definition: hls.c:183
char audio_group[MAX_FIELD_LEN]
Definition: hls.c:189
int n_playlists
Definition: hls.c:186
char url[MAX_URL_SIZE]
Definition: hlsproto.c:55
struct playlist ** playlists
Definition: hls.c:187
char video_group[MAX_FIELD_LEN]
Definition: hls.c:190
char subtitles_group[MAX_FIELD_LEN]
Definition: hls.c:191
#define av_free(p)
#define av_freep(p)
#define av_malloc(s)
#define av_log(a,...)
static uint8_t tmp[11]
Definition: aes_ctr.c:27
int64_t duration
Definition: movenc.c:64
AVPacket * pkt
Definition: movenc.c:59
AVDictionary * opts
Definition: movenc.c:50
int av_usleep(unsigned usec)
Sleep for a period of time.
Definition: time.c:84
int64_t av_gettime_relative(void)
Get the current time in microseconds since some unspecified starting point.
Definition: time.c:56
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:319
const char * r
Definition: vf_curves.c:117
static void fill_buf(uint8_t *data, int w, int h, int linesize, uint8_t v)
static av_always_inline int diff(const uint32_t a, const uint32_t b)
int len
uint8_t base
Definition: vp3data.h:141
static double c[64]