You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2348 lines
78KB

  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. * @file
  24. * Apple HTTP Live Streaming demuxer
  25. * http://tools.ietf.org/html/draft-pantos-http-live-streaming
  26. */
  27. #include "libavformat/http.h"
  28. #include "libavutil/avstring.h"
  29. #include "libavutil/avassert.h"
  30. #include "libavutil/intreadwrite.h"
  31. #include "libavutil/mathematics.h"
  32. #include "libavutil/opt.h"
  33. #include "libavutil/dict.h"
  34. #include "libavutil/time.h"
  35. #include "avformat.h"
  36. #include "internal.h"
  37. #include "avio_internal.h"
  38. #include "id3v2.h"
  39. #define INITIAL_BUFFER_SIZE 32768
  40. #define MAX_FIELD_LEN 64
  41. #define MAX_CHARACTERISTICS_LEN 512
  42. #define MPEG_TIME_BASE 90000
  43. #define MPEG_TIME_BASE_Q (AVRational){1, MPEG_TIME_BASE}
  44. /*
  45. * An apple http stream consists of a playlist with media segment files,
  46. * played sequentially. There may be several playlists with the same
  47. * video content, in different bandwidth variants, that are played in
  48. * parallel (preferably only one bandwidth variant at a time). In this case,
  49. * the user supplied the url to a main playlist that only lists the variant
  50. * playlists.
  51. *
  52. * If the main playlist doesn't point at any variants, we still create
  53. * one anonymous toplevel variant for this, to maintain the structure.
  54. */
  55. enum KeyType {
  56. KEY_NONE,
  57. KEY_AES_128,
  58. KEY_SAMPLE_AES
  59. };
  60. struct segment {
  61. int64_t duration;
  62. int64_t url_offset;
  63. int64_t size;
  64. char *url;
  65. char *key;
  66. enum KeyType key_type;
  67. uint8_t iv[16];
  68. /* associated Media Initialization Section, treated as a segment */
  69. struct segment *init_section;
  70. };
  71. struct rendition;
  72. enum PlaylistType {
  73. PLS_TYPE_UNSPECIFIED,
  74. PLS_TYPE_EVENT,
  75. PLS_TYPE_VOD
  76. };
  77. /*
  78. * Each playlist has its own demuxer. If it currently is active,
  79. * it has an open AVIOContext too, and potentially an AVPacket
  80. * containing the next packet from this stream.
  81. */
  82. struct playlist {
  83. char url[MAX_URL_SIZE];
  84. AVIOContext pb;
  85. uint8_t* read_buffer;
  86. AVIOContext *input;
  87. int input_read_done;
  88. AVIOContext *input_next;
  89. int input_next_requested;
  90. AVFormatContext *parent;
  91. int index;
  92. AVFormatContext *ctx;
  93. AVPacket pkt;
  94. int has_noheader_flag;
  95. /* main demuxer streams associated with this playlist
  96. * indexed by the subdemuxer stream indexes */
  97. AVStream **main_streams;
  98. int n_main_streams;
  99. int finished;
  100. enum PlaylistType type;
  101. int64_t target_duration;
  102. int start_seq_no;
  103. int n_segments;
  104. struct segment **segments;
  105. int needed;
  106. int cur_seq_no;
  107. int64_t cur_seg_offset;
  108. int64_t last_load_time;
  109. /* Currently active Media Initialization Section */
  110. struct segment *cur_init_section;
  111. uint8_t *init_sec_buf;
  112. unsigned int init_sec_buf_size;
  113. unsigned int init_sec_data_len;
  114. unsigned int init_sec_buf_read_offset;
  115. char key_url[MAX_URL_SIZE];
  116. uint8_t key[16];
  117. /* ID3 timestamp handling (elementary audio streams have ID3 timestamps
  118. * (and possibly other ID3 tags) in the beginning of each segment) */
  119. int is_id3_timestamped; /* -1: not yet known */
  120. int64_t id3_mpegts_timestamp; /* in mpegts tb */
  121. int64_t id3_offset; /* in stream original tb */
  122. uint8_t* id3_buf; /* temp buffer for id3 parsing */
  123. unsigned int id3_buf_size;
  124. AVDictionary *id3_initial; /* data from first id3 tag */
  125. int id3_found; /* ID3 tag found at some point */
  126. int id3_changed; /* ID3 tag data has changed at some point */
  127. ID3v2ExtraMeta *id3_deferred_extra; /* stored here until subdemuxer is opened */
  128. int64_t seek_timestamp;
  129. int seek_flags;
  130. int seek_stream_index; /* into subdemuxer stream array */
  131. /* Renditions associated with this playlist, if any.
  132. * Alternative rendition playlists have a single rendition associated
  133. * with them, and variant main Media Playlists may have
  134. * multiple (playlist-less) renditions associated with them. */
  135. int n_renditions;
  136. struct rendition **renditions;
  137. /* Media Initialization Sections (EXT-X-MAP) associated with this
  138. * playlist, if any. */
  139. int n_init_sections;
  140. struct segment **init_sections;
  141. };
  142. /*
  143. * Renditions are e.g. alternative subtitle or audio streams.
  144. * The rendition may either be an external playlist or it may be
  145. * contained in the main Media Playlist of the variant (in which case
  146. * playlist is NULL).
  147. */
  148. struct rendition {
  149. enum AVMediaType type;
  150. struct playlist *playlist;
  151. char group_id[MAX_FIELD_LEN];
  152. char language[MAX_FIELD_LEN];
  153. char name[MAX_FIELD_LEN];
  154. int disposition;
  155. };
  156. struct variant {
  157. int bandwidth;
  158. /* every variant contains at least the main Media Playlist in index 0 */
  159. int n_playlists;
  160. struct playlist **playlists;
  161. char audio_group[MAX_FIELD_LEN];
  162. char video_group[MAX_FIELD_LEN];
  163. char subtitles_group[MAX_FIELD_LEN];
  164. };
  165. typedef struct HLSContext {
  166. AVClass *class;
  167. AVFormatContext *ctx;
  168. int n_variants;
  169. struct variant **variants;
  170. int n_playlists;
  171. struct playlist **playlists;
  172. int n_renditions;
  173. struct rendition **renditions;
  174. int cur_seq_no;
  175. int live_start_index;
  176. int first_packet;
  177. int64_t first_timestamp;
  178. int64_t cur_timestamp;
  179. AVIOInterruptCB *interrupt_callback;
  180. char *user_agent; ///< holds HTTP user agent set as an AVOption to the HTTP protocol context
  181. char *cookies; ///< holds HTTP cookie values set in either the initial response or as an AVOption to the HTTP protocol context
  182. char *headers; ///< holds HTTP headers set as an AVOption to the HTTP protocol context
  183. char *http_proxy; ///< holds the address of the HTTP proxy server
  184. AVDictionary *avio_opts;
  185. int strict_std_compliance;
  186. char *allowed_extensions;
  187. int max_reload;
  188. int http_persistent;
  189. int http_multiple;
  190. AVIOContext *playlist_pb;
  191. } HLSContext;
  192. static int read_chomp_line(AVIOContext *s, char *buf, int maxlen)
  193. {
  194. int len = ff_get_line(s, buf, maxlen);
  195. while (len > 0 && av_isspace(buf[len - 1]))
  196. buf[--len] = '\0';
  197. return len;
  198. }
  199. static void free_segment_list(struct playlist *pls)
  200. {
  201. int i;
  202. for (i = 0; i < pls->n_segments; i++) {
  203. av_freep(&pls->segments[i]->key);
  204. av_freep(&pls->segments[i]->url);
  205. av_freep(&pls->segments[i]);
  206. }
  207. av_freep(&pls->segments);
  208. pls->n_segments = 0;
  209. }
  210. static void free_init_section_list(struct playlist *pls)
  211. {
  212. int i;
  213. for (i = 0; i < pls->n_init_sections; i++) {
  214. av_freep(&pls->init_sections[i]->url);
  215. av_freep(&pls->init_sections[i]);
  216. }
  217. av_freep(&pls->init_sections);
  218. pls->n_init_sections = 0;
  219. }
  220. static void free_playlist_list(HLSContext *c)
  221. {
  222. int i;
  223. for (i = 0; i < c->n_playlists; i++) {
  224. struct playlist *pls = c->playlists[i];
  225. free_segment_list(pls);
  226. free_init_section_list(pls);
  227. av_freep(&pls->main_streams);
  228. av_freep(&pls->renditions);
  229. av_freep(&pls->id3_buf);
  230. av_dict_free(&pls->id3_initial);
  231. ff_id3v2_free_extra_meta(&pls->id3_deferred_extra);
  232. av_freep(&pls->init_sec_buf);
  233. av_packet_unref(&pls->pkt);
  234. av_freep(&pls->pb.buffer);
  235. if (pls->input)
  236. ff_format_io_close(c->ctx, &pls->input);
  237. pls->input_read_done = 0;
  238. if (pls->input_next)
  239. ff_format_io_close(c->ctx, &pls->input_next);
  240. pls->input_next_requested = 0;
  241. if (pls->ctx) {
  242. pls->ctx->pb = NULL;
  243. avformat_close_input(&pls->ctx);
  244. }
  245. av_free(pls);
  246. }
  247. av_freep(&c->playlists);
  248. av_freep(&c->cookies);
  249. av_freep(&c->user_agent);
  250. av_freep(&c->headers);
  251. av_freep(&c->http_proxy);
  252. c->n_playlists = 0;
  253. }
  254. static void free_variant_list(HLSContext *c)
  255. {
  256. int i;
  257. for (i = 0; i < c->n_variants; i++) {
  258. struct variant *var = c->variants[i];
  259. av_freep(&var->playlists);
  260. av_free(var);
  261. }
  262. av_freep(&c->variants);
  263. c->n_variants = 0;
  264. }
  265. static void free_rendition_list(HLSContext *c)
  266. {
  267. int i;
  268. for (i = 0; i < c->n_renditions; i++)
  269. av_freep(&c->renditions[i]);
  270. av_freep(&c->renditions);
  271. c->n_renditions = 0;
  272. }
  273. /*
  274. * Used to reset a statically allocated AVPacket to a clean slate,
  275. * containing no data.
  276. */
  277. static void reset_packet(AVPacket *pkt)
  278. {
  279. av_init_packet(pkt);
  280. pkt->data = NULL;
  281. }
  282. static struct playlist *new_playlist(HLSContext *c, const char *url,
  283. const char *base)
  284. {
  285. struct playlist *pls = av_mallocz(sizeof(struct playlist));
  286. if (!pls)
  287. return NULL;
  288. reset_packet(&pls->pkt);
  289. ff_make_absolute_url(pls->url, sizeof(pls->url), base, url);
  290. pls->seek_timestamp = AV_NOPTS_VALUE;
  291. pls->is_id3_timestamped = -1;
  292. pls->id3_mpegts_timestamp = AV_NOPTS_VALUE;
  293. dynarray_add(&c->playlists, &c->n_playlists, pls);
  294. return pls;
  295. }
  296. struct variant_info {
  297. char bandwidth[20];
  298. /* variant group ids: */
  299. char audio[MAX_FIELD_LEN];
  300. char video[MAX_FIELD_LEN];
  301. char subtitles[MAX_FIELD_LEN];
  302. };
  303. static struct variant *new_variant(HLSContext *c, struct variant_info *info,
  304. const char *url, const char *base)
  305. {
  306. struct variant *var;
  307. struct playlist *pls;
  308. pls = new_playlist(c, url, base);
  309. if (!pls)
  310. return NULL;
  311. var = av_mallocz(sizeof(struct variant));
  312. if (!var)
  313. return NULL;
  314. if (info) {
  315. var->bandwidth = atoi(info->bandwidth);
  316. strcpy(var->audio_group, info->audio);
  317. strcpy(var->video_group, info->video);
  318. strcpy(var->subtitles_group, info->subtitles);
  319. }
  320. dynarray_add(&c->variants, &c->n_variants, var);
  321. dynarray_add(&var->playlists, &var->n_playlists, pls);
  322. return var;
  323. }
  324. static void handle_variant_args(struct variant_info *info, const char *key,
  325. int key_len, char **dest, int *dest_len)
  326. {
  327. if (!strncmp(key, "BANDWIDTH=", key_len)) {
  328. *dest = info->bandwidth;
  329. *dest_len = sizeof(info->bandwidth);
  330. } else if (!strncmp(key, "AUDIO=", key_len)) {
  331. *dest = info->audio;
  332. *dest_len = sizeof(info->audio);
  333. } else if (!strncmp(key, "VIDEO=", key_len)) {
  334. *dest = info->video;
  335. *dest_len = sizeof(info->video);
  336. } else if (!strncmp(key, "SUBTITLES=", key_len)) {
  337. *dest = info->subtitles;
  338. *dest_len = sizeof(info->subtitles);
  339. }
  340. }
  341. struct key_info {
  342. char uri[MAX_URL_SIZE];
  343. char method[11];
  344. char iv[35];
  345. };
  346. static void handle_key_args(struct key_info *info, const char *key,
  347. int key_len, char **dest, int *dest_len)
  348. {
  349. if (!strncmp(key, "METHOD=", key_len)) {
  350. *dest = info->method;
  351. *dest_len = sizeof(info->method);
  352. } else if (!strncmp(key, "URI=", key_len)) {
  353. *dest = info->uri;
  354. *dest_len = sizeof(info->uri);
  355. } else if (!strncmp(key, "IV=", key_len)) {
  356. *dest = info->iv;
  357. *dest_len = sizeof(info->iv);
  358. }
  359. }
  360. struct init_section_info {
  361. char uri[MAX_URL_SIZE];
  362. char byterange[32];
  363. };
  364. static struct segment *new_init_section(struct playlist *pls,
  365. struct init_section_info *info,
  366. const char *url_base)
  367. {
  368. struct segment *sec;
  369. char *ptr;
  370. char tmp_str[MAX_URL_SIZE];
  371. if (!info->uri[0])
  372. return NULL;
  373. sec = av_mallocz(sizeof(*sec));
  374. if (!sec)
  375. return NULL;
  376. ff_make_absolute_url(tmp_str, sizeof(tmp_str), url_base, info->uri);
  377. sec->url = av_strdup(tmp_str);
  378. if (!sec->url) {
  379. av_free(sec);
  380. return NULL;
  381. }
  382. if (info->byterange[0]) {
  383. sec->size = strtoll(info->byterange, NULL, 10);
  384. ptr = strchr(info->byterange, '@');
  385. if (ptr)
  386. sec->url_offset = strtoll(ptr+1, NULL, 10);
  387. } else {
  388. /* the entire file is the init section */
  389. sec->size = -1;
  390. }
  391. dynarray_add(&pls->init_sections, &pls->n_init_sections, sec);
  392. return sec;
  393. }
  394. static void handle_init_section_args(struct init_section_info *info, const char *key,
  395. int key_len, char **dest, int *dest_len)
  396. {
  397. if (!strncmp(key, "URI=", key_len)) {
  398. *dest = info->uri;
  399. *dest_len = sizeof(info->uri);
  400. } else if (!strncmp(key, "BYTERANGE=", key_len)) {
  401. *dest = info->byterange;
  402. *dest_len = sizeof(info->byterange);
  403. }
  404. }
  405. struct rendition_info {
  406. char type[16];
  407. char uri[MAX_URL_SIZE];
  408. char group_id[MAX_FIELD_LEN];
  409. char language[MAX_FIELD_LEN];
  410. char assoc_language[MAX_FIELD_LEN];
  411. char name[MAX_FIELD_LEN];
  412. char defaultr[4];
  413. char forced[4];
  414. char characteristics[MAX_CHARACTERISTICS_LEN];
  415. };
  416. static struct rendition *new_rendition(HLSContext *c, struct rendition_info *info,
  417. const char *url_base)
  418. {
  419. struct rendition *rend;
  420. enum AVMediaType type = AVMEDIA_TYPE_UNKNOWN;
  421. char *characteristic;
  422. char *chr_ptr;
  423. char *saveptr;
  424. if (!strcmp(info->type, "AUDIO"))
  425. type = AVMEDIA_TYPE_AUDIO;
  426. else if (!strcmp(info->type, "VIDEO"))
  427. type = AVMEDIA_TYPE_VIDEO;
  428. else if (!strcmp(info->type, "SUBTITLES"))
  429. type = AVMEDIA_TYPE_SUBTITLE;
  430. else if (!strcmp(info->type, "CLOSED-CAPTIONS"))
  431. /* CLOSED-CAPTIONS is ignored since we do not support CEA-608 CC in
  432. * AVC SEI RBSP anyway */
  433. return NULL;
  434. if (type == AVMEDIA_TYPE_UNKNOWN)
  435. return NULL;
  436. /* URI is mandatory for subtitles as per spec */
  437. if (type == AVMEDIA_TYPE_SUBTITLE && !info->uri[0])
  438. return NULL;
  439. /* TODO: handle subtitles (each segment has to parsed separately) */
  440. if (c->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL)
  441. if (type == AVMEDIA_TYPE_SUBTITLE)
  442. return NULL;
  443. rend = av_mallocz(sizeof(struct rendition));
  444. if (!rend)
  445. return NULL;
  446. dynarray_add(&c->renditions, &c->n_renditions, rend);
  447. rend->type = type;
  448. strcpy(rend->group_id, info->group_id);
  449. strcpy(rend->language, info->language);
  450. strcpy(rend->name, info->name);
  451. /* add the playlist if this is an external rendition */
  452. if (info->uri[0]) {
  453. rend->playlist = new_playlist(c, info->uri, url_base);
  454. if (rend->playlist)
  455. dynarray_add(&rend->playlist->renditions,
  456. &rend->playlist->n_renditions, rend);
  457. }
  458. if (info->assoc_language[0]) {
  459. int langlen = strlen(rend->language);
  460. if (langlen < sizeof(rend->language) - 3) {
  461. rend->language[langlen] = ',';
  462. strncpy(rend->language + langlen + 1, info->assoc_language,
  463. sizeof(rend->language) - langlen - 2);
  464. }
  465. }
  466. if (!strcmp(info->defaultr, "YES"))
  467. rend->disposition |= AV_DISPOSITION_DEFAULT;
  468. if (!strcmp(info->forced, "YES"))
  469. rend->disposition |= AV_DISPOSITION_FORCED;
  470. chr_ptr = info->characteristics;
  471. while ((characteristic = av_strtok(chr_ptr, ",", &saveptr))) {
  472. if (!strcmp(characteristic, "public.accessibility.describes-music-and-sound"))
  473. rend->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
  474. else if (!strcmp(characteristic, "public.accessibility.describes-video"))
  475. rend->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED;
  476. chr_ptr = NULL;
  477. }
  478. return rend;
  479. }
  480. static void handle_rendition_args(struct rendition_info *info, const char *key,
  481. int key_len, char **dest, int *dest_len)
  482. {
  483. if (!strncmp(key, "TYPE=", key_len)) {
  484. *dest = info->type;
  485. *dest_len = sizeof(info->type);
  486. } else if (!strncmp(key, "URI=", key_len)) {
  487. *dest = info->uri;
  488. *dest_len = sizeof(info->uri);
  489. } else if (!strncmp(key, "GROUP-ID=", key_len)) {
  490. *dest = info->group_id;
  491. *dest_len = sizeof(info->group_id);
  492. } else if (!strncmp(key, "LANGUAGE=", key_len)) {
  493. *dest = info->language;
  494. *dest_len = sizeof(info->language);
  495. } else if (!strncmp(key, "ASSOC-LANGUAGE=", key_len)) {
  496. *dest = info->assoc_language;
  497. *dest_len = sizeof(info->assoc_language);
  498. } else if (!strncmp(key, "NAME=", key_len)) {
  499. *dest = info->name;
  500. *dest_len = sizeof(info->name);
  501. } else if (!strncmp(key, "DEFAULT=", key_len)) {
  502. *dest = info->defaultr;
  503. *dest_len = sizeof(info->defaultr);
  504. } else if (!strncmp(key, "FORCED=", key_len)) {
  505. *dest = info->forced;
  506. *dest_len = sizeof(info->forced);
  507. } else if (!strncmp(key, "CHARACTERISTICS=", key_len)) {
  508. *dest = info->characteristics;
  509. *dest_len = sizeof(info->characteristics);
  510. }
  511. /*
  512. * ignored:
  513. * - AUTOSELECT: client may autoselect based on e.g. system language
  514. * - INSTREAM-ID: EIA-608 closed caption number ("CC1".."CC4")
  515. */
  516. }
  517. /* used by parse_playlist to allocate a new variant+playlist when the
  518. * playlist is detected to be a Media Playlist (not Master Playlist)
  519. * and we have no parent Master Playlist (parsing of which would have
  520. * allocated the variant and playlist already)
  521. * *pls == NULL => Master Playlist or parentless Media Playlist
  522. * *pls != NULL => parented Media Playlist, playlist+variant allocated */
  523. static int ensure_playlist(HLSContext *c, struct playlist **pls, const char *url)
  524. {
  525. if (*pls)
  526. return 0;
  527. if (!new_variant(c, NULL, url, NULL))
  528. return AVERROR(ENOMEM);
  529. *pls = c->playlists[c->n_playlists - 1];
  530. return 0;
  531. }
  532. static void update_options(char **dest, const char *name, void *src)
  533. {
  534. av_freep(dest);
  535. av_opt_get(src, name, AV_OPT_SEARCH_CHILDREN, (uint8_t**)dest);
  536. if (*dest && !strlen(*dest))
  537. av_freep(dest);
  538. }
  539. static int open_url_keepalive(AVFormatContext *s, AVIOContext **pb,
  540. const char *url)
  541. {
  542. #if !CONFIG_HTTP_PROTOCOL
  543. return AVERROR_PROTOCOL_NOT_FOUND;
  544. #else
  545. int ret;
  546. URLContext *uc = ffio_geturlcontext(*pb);
  547. av_assert0(uc);
  548. (*pb)->eof_reached = 0;
  549. ret = ff_http_do_new_request(uc, url);
  550. if (ret < 0) {
  551. ff_format_io_close(s, pb);
  552. }
  553. return ret;
  554. #endif
  555. }
  556. static int open_url(AVFormatContext *s, AVIOContext **pb, const char *url,
  557. AVDictionary *opts, AVDictionary *opts2, int *is_http_out)
  558. {
  559. HLSContext *c = s->priv_data;
  560. AVDictionary *tmp = NULL;
  561. const char *proto_name = NULL;
  562. int ret;
  563. int is_http = 0;
  564. av_dict_copy(&tmp, opts, 0);
  565. av_dict_copy(&tmp, opts2, 0);
  566. if (av_strstart(url, "crypto", NULL)) {
  567. if (url[6] == '+' || url[6] == ':')
  568. proto_name = avio_find_protocol_name(url + 7);
  569. }
  570. if (!proto_name)
  571. proto_name = avio_find_protocol_name(url);
  572. if (!proto_name)
  573. return AVERROR_INVALIDDATA;
  574. // only http(s) & file are allowed
  575. if (av_strstart(proto_name, "file", NULL)) {
  576. if (strcmp(c->allowed_extensions, "ALL") && !av_match_ext(url, c->allowed_extensions)) {
  577. av_log(s, AV_LOG_ERROR,
  578. "Filename extension of \'%s\' is not a common multimedia extension, blocked for security reasons.\n"
  579. "If you wish to override this adjust allowed_extensions, you can set it to \'ALL\' to allow all\n",
  580. url);
  581. return AVERROR_INVALIDDATA;
  582. }
  583. } else if (av_strstart(proto_name, "http", NULL)) {
  584. is_http = 1;
  585. } else
  586. return AVERROR_INVALIDDATA;
  587. if (!strncmp(proto_name, url, strlen(proto_name)) && url[strlen(proto_name)] == ':')
  588. ;
  589. else if (av_strstart(url, "crypto", NULL) && !strncmp(proto_name, url + 7, strlen(proto_name)) && url[7 + strlen(proto_name)] == ':')
  590. ;
  591. else if (strcmp(proto_name, "file") || !strncmp(url, "file,", 5))
  592. return AVERROR_INVALIDDATA;
  593. if (is_http && c->http_persistent && *pb) {
  594. ret = open_url_keepalive(c->ctx, pb, url);
  595. if (ret == AVERROR_EXIT) {
  596. return ret;
  597. } else if (ret < 0) {
  598. if (ret != AVERROR_EOF)
  599. av_log(s, AV_LOG_WARNING,
  600. "keepalive request failed for '%s', retrying with new connection: %s\n",
  601. url, av_err2str(ret));
  602. ret = s->io_open(s, pb, url, AVIO_FLAG_READ, &tmp);
  603. }
  604. } else {
  605. ret = s->io_open(s, pb, url, AVIO_FLAG_READ, &tmp);
  606. }
  607. if (ret >= 0) {
  608. // update cookies on http response with setcookies.
  609. char *new_cookies = NULL;
  610. if (!(s->flags & AVFMT_FLAG_CUSTOM_IO))
  611. av_opt_get(*pb, "cookies", AV_OPT_SEARCH_CHILDREN, (uint8_t**)&new_cookies);
  612. if (new_cookies) {
  613. av_free(c->cookies);
  614. c->cookies = new_cookies;
  615. }
  616. av_dict_set(&opts, "cookies", c->cookies, 0);
  617. }
  618. av_dict_free(&tmp);
  619. if (is_http_out)
  620. *is_http_out = is_http;
  621. return ret;
  622. }
  623. static int parse_playlist(HLSContext *c, const char *url,
  624. struct playlist *pls, AVIOContext *in)
  625. {
  626. int ret = 0, is_segment = 0, is_variant = 0;
  627. int64_t duration = 0;
  628. enum KeyType key_type = KEY_NONE;
  629. uint8_t iv[16] = "";
  630. int has_iv = 0;
  631. char key[MAX_URL_SIZE] = "";
  632. char line[MAX_URL_SIZE];
  633. const char *ptr;
  634. int close_in = 0;
  635. int64_t seg_offset = 0;
  636. int64_t seg_size = -1;
  637. uint8_t *new_url = NULL;
  638. struct variant_info variant_info;
  639. char tmp_str[MAX_URL_SIZE];
  640. struct segment *cur_init_section = NULL;
  641. int is_http = av_strstart(url, "http", NULL);
  642. if (is_http && !in && c->http_persistent && c->playlist_pb) {
  643. in = c->playlist_pb;
  644. ret = open_url_keepalive(c->ctx, &c->playlist_pb, url);
  645. if (ret == AVERROR_EXIT) {
  646. return ret;
  647. } else if (ret < 0) {
  648. if (ret != AVERROR_EOF)
  649. av_log(c->ctx, AV_LOG_WARNING,
  650. "keepalive request failed for '%s', retrying with new connection: %s\n",
  651. url, av_err2str(ret));
  652. in = NULL;
  653. }
  654. }
  655. if (!in) {
  656. #if 1
  657. AVDictionary *opts = NULL;
  658. /* Some HLS servers don't like being sent the range header */
  659. av_dict_set(&opts, "seekable", "0", 0);
  660. // broker prior HTTP options that should be consistent across requests
  661. av_dict_set(&opts, "user_agent", c->user_agent, 0);
  662. av_dict_set(&opts, "cookies", c->cookies, 0);
  663. av_dict_set(&opts, "headers", c->headers, 0);
  664. av_dict_set(&opts, "http_proxy", c->http_proxy, 0);
  665. if (c->http_persistent)
  666. av_dict_set(&opts, "multiple_requests", "1", 0);
  667. ret = c->ctx->io_open(c->ctx, &in, url, AVIO_FLAG_READ, &opts);
  668. av_dict_free(&opts);
  669. if (ret < 0)
  670. return ret;
  671. if (is_http && c->http_persistent)
  672. c->playlist_pb = in;
  673. else
  674. close_in = 1;
  675. #else
  676. ret = open_in(c, &in, url);
  677. if (ret < 0)
  678. return ret;
  679. close_in = 1;
  680. #endif
  681. }
  682. if (av_opt_get(in, "location", AV_OPT_SEARCH_CHILDREN, &new_url) >= 0)
  683. url = new_url;
  684. read_chomp_line(in, line, sizeof(line));
  685. if (strcmp(line, "#EXTM3U")) {
  686. ret = AVERROR_INVALIDDATA;
  687. goto fail;
  688. }
  689. if (pls) {
  690. free_segment_list(pls);
  691. pls->finished = 0;
  692. pls->type = PLS_TYPE_UNSPECIFIED;
  693. }
  694. while (!avio_feof(in)) {
  695. read_chomp_line(in, line, sizeof(line));
  696. if (av_strstart(line, "#EXT-X-STREAM-INF:", &ptr)) {
  697. is_variant = 1;
  698. memset(&variant_info, 0, sizeof(variant_info));
  699. ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_variant_args,
  700. &variant_info);
  701. } else if (av_strstart(line, "#EXT-X-KEY:", &ptr)) {
  702. struct key_info info = {{0}};
  703. ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_key_args,
  704. &info);
  705. key_type = KEY_NONE;
  706. has_iv = 0;
  707. if (!strcmp(info.method, "AES-128"))
  708. key_type = KEY_AES_128;
  709. if (!strcmp(info.method, "SAMPLE-AES"))
  710. key_type = KEY_SAMPLE_AES;
  711. if (!strncmp(info.iv, "0x", 2) || !strncmp(info.iv, "0X", 2)) {
  712. ff_hex_to_data(iv, info.iv + 2);
  713. has_iv = 1;
  714. }
  715. av_strlcpy(key, info.uri, sizeof(key));
  716. } else if (av_strstart(line, "#EXT-X-MEDIA:", &ptr)) {
  717. struct rendition_info info = {{0}};
  718. ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_rendition_args,
  719. &info);
  720. new_rendition(c, &info, url);
  721. } else if (av_strstart(line, "#EXT-X-TARGETDURATION:", &ptr)) {
  722. ret = ensure_playlist(c, &pls, url);
  723. if (ret < 0)
  724. goto fail;
  725. pls->target_duration = strtoll(ptr, NULL, 10) * AV_TIME_BASE;
  726. } else if (av_strstart(line, "#EXT-X-MEDIA-SEQUENCE:", &ptr)) {
  727. ret = ensure_playlist(c, &pls, url);
  728. if (ret < 0)
  729. goto fail;
  730. pls->start_seq_no = atoi(ptr);
  731. } else if (av_strstart(line, "#EXT-X-PLAYLIST-TYPE:", &ptr)) {
  732. ret = ensure_playlist(c, &pls, url);
  733. if (ret < 0)
  734. goto fail;
  735. if (!strcmp(ptr, "EVENT"))
  736. pls->type = PLS_TYPE_EVENT;
  737. else if (!strcmp(ptr, "VOD"))
  738. pls->type = PLS_TYPE_VOD;
  739. } else if (av_strstart(line, "#EXT-X-MAP:", &ptr)) {
  740. struct init_section_info info = {{0}};
  741. ret = ensure_playlist(c, &pls, url);
  742. if (ret < 0)
  743. goto fail;
  744. ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_init_section_args,
  745. &info);
  746. cur_init_section = new_init_section(pls, &info, url);
  747. } else if (av_strstart(line, "#EXT-X-ENDLIST", &ptr)) {
  748. if (pls)
  749. pls->finished = 1;
  750. } else if (av_strstart(line, "#EXTINF:", &ptr)) {
  751. is_segment = 1;
  752. duration = atof(ptr) * AV_TIME_BASE;
  753. } else if (av_strstart(line, "#EXT-X-BYTERANGE:", &ptr)) {
  754. seg_size = strtoll(ptr, NULL, 10);
  755. ptr = strchr(ptr, '@');
  756. if (ptr)
  757. seg_offset = strtoll(ptr+1, NULL, 10);
  758. } else if (av_strstart(line, "#", NULL)) {
  759. continue;
  760. } else if (line[0]) {
  761. if (is_variant) {
  762. if (!new_variant(c, &variant_info, line, url)) {
  763. ret = AVERROR(ENOMEM);
  764. goto fail;
  765. }
  766. is_variant = 0;
  767. }
  768. if (is_segment) {
  769. struct segment *seg;
  770. if (!pls) {
  771. if (!new_variant(c, 0, url, NULL)) {
  772. ret = AVERROR(ENOMEM);
  773. goto fail;
  774. }
  775. pls = c->playlists[c->n_playlists - 1];
  776. }
  777. seg = av_malloc(sizeof(struct segment));
  778. if (!seg) {
  779. ret = AVERROR(ENOMEM);
  780. goto fail;
  781. }
  782. seg->duration = duration;
  783. seg->key_type = key_type;
  784. if (has_iv) {
  785. memcpy(seg->iv, iv, sizeof(iv));
  786. } else {
  787. int seq = pls->start_seq_no + pls->n_segments;
  788. memset(seg->iv, 0, sizeof(seg->iv));
  789. AV_WB32(seg->iv + 12, seq);
  790. }
  791. if (key_type != KEY_NONE) {
  792. ff_make_absolute_url(tmp_str, sizeof(tmp_str), url, key);
  793. seg->key = av_strdup(tmp_str);
  794. if (!seg->key) {
  795. av_free(seg);
  796. ret = AVERROR(ENOMEM);
  797. goto fail;
  798. }
  799. } else {
  800. seg->key = NULL;
  801. }
  802. ff_make_absolute_url(tmp_str, sizeof(tmp_str), url, line);
  803. seg->url = av_strdup(tmp_str);
  804. if (!seg->url) {
  805. av_free(seg->key);
  806. av_free(seg);
  807. ret = AVERROR(ENOMEM);
  808. goto fail;
  809. }
  810. dynarray_add(&pls->segments, &pls->n_segments, seg);
  811. is_segment = 0;
  812. seg->size = seg_size;
  813. if (seg_size >= 0) {
  814. seg->url_offset = seg_offset;
  815. seg_offset += seg_size;
  816. seg_size = -1;
  817. } else {
  818. seg->url_offset = 0;
  819. seg_offset = 0;
  820. }
  821. seg->init_section = cur_init_section;
  822. }
  823. }
  824. }
  825. if (pls)
  826. pls->last_load_time = av_gettime_relative();
  827. fail:
  828. av_free(new_url);
  829. if (close_in)
  830. ff_format_io_close(c->ctx, &in);
  831. c->ctx->ctx_flags = c->ctx->ctx_flags & ~(unsigned)AVFMTCTX_UNSEEKABLE;
  832. if (!c->n_variants || !c->variants[0]->n_playlists ||
  833. !(c->variants[0]->playlists[0]->finished ||
  834. c->variants[0]->playlists[0]->type == PLS_TYPE_EVENT))
  835. c->ctx->ctx_flags |= AVFMTCTX_UNSEEKABLE;
  836. return ret;
  837. }
  838. static struct segment *current_segment(struct playlist *pls)
  839. {
  840. return pls->segments[pls->cur_seq_no - pls->start_seq_no];
  841. }
  842. static struct segment *next_segment(struct playlist *pls)
  843. {
  844. int n = pls->cur_seq_no - pls->start_seq_no + 1;
  845. if (n >= pls->n_segments)
  846. return NULL;
  847. return pls->segments[n];
  848. }
  849. enum ReadFromURLMode {
  850. READ_NORMAL,
  851. READ_COMPLETE,
  852. };
  853. static int read_from_url(struct playlist *pls, struct segment *seg,
  854. uint8_t *buf, int buf_size,
  855. enum ReadFromURLMode mode)
  856. {
  857. int ret;
  858. /* limit read if the segment was only a part of a file */
  859. if (seg->size >= 0)
  860. buf_size = FFMIN(buf_size, seg->size - pls->cur_seg_offset);
  861. if (mode == READ_COMPLETE) {
  862. ret = avio_read(pls->input, buf, buf_size);
  863. if (ret != buf_size)
  864. av_log(NULL, AV_LOG_ERROR, "Could not read complete segment.\n");
  865. } else
  866. ret = avio_read(pls->input, buf, buf_size);
  867. if (ret > 0)
  868. pls->cur_seg_offset += ret;
  869. return ret;
  870. }
  871. /* Parse the raw ID3 data and pass contents to caller */
  872. static void parse_id3(AVFormatContext *s, AVIOContext *pb,
  873. AVDictionary **metadata, int64_t *dts,
  874. ID3v2ExtraMetaAPIC **apic, ID3v2ExtraMeta **extra_meta)
  875. {
  876. static const char id3_priv_owner_ts[] = "com.apple.streaming.transportStreamTimestamp";
  877. ID3v2ExtraMeta *meta;
  878. ff_id3v2_read_dict(pb, metadata, ID3v2_DEFAULT_MAGIC, extra_meta);
  879. for (meta = *extra_meta; meta; meta = meta->next) {
  880. if (!strcmp(meta->tag, "PRIV")) {
  881. ID3v2ExtraMetaPRIV *priv = meta->data;
  882. if (priv->datasize == 8 && !strcmp(priv->owner, id3_priv_owner_ts)) {
  883. /* 33-bit MPEG timestamp */
  884. int64_t ts = AV_RB64(priv->data);
  885. av_log(s, AV_LOG_DEBUG, "HLS ID3 audio timestamp %"PRId64"\n", ts);
  886. if ((ts & ~((1ULL << 33) - 1)) == 0)
  887. *dts = ts;
  888. else
  889. av_log(s, AV_LOG_ERROR, "Invalid HLS ID3 audio timestamp %"PRId64"\n", ts);
  890. }
  891. } else if (!strcmp(meta->tag, "APIC") && apic)
  892. *apic = meta->data;
  893. }
  894. }
  895. /* Check if the ID3 metadata contents have changed */
  896. static int id3_has_changed_values(struct playlist *pls, AVDictionary *metadata,
  897. ID3v2ExtraMetaAPIC *apic)
  898. {
  899. AVDictionaryEntry *entry = NULL;
  900. AVDictionaryEntry *oldentry;
  901. /* check that no keys have changed values */
  902. while ((entry = av_dict_get(metadata, "", entry, AV_DICT_IGNORE_SUFFIX))) {
  903. oldentry = av_dict_get(pls->id3_initial, entry->key, NULL, AV_DICT_MATCH_CASE);
  904. if (!oldentry || strcmp(oldentry->value, entry->value) != 0)
  905. return 1;
  906. }
  907. /* check if apic appeared */
  908. if (apic && (pls->ctx->nb_streams != 2 || !pls->ctx->streams[1]->attached_pic.data))
  909. return 1;
  910. if (apic) {
  911. int size = pls->ctx->streams[1]->attached_pic.size;
  912. if (size != apic->buf->size - AV_INPUT_BUFFER_PADDING_SIZE)
  913. return 1;
  914. if (memcmp(apic->buf->data, pls->ctx->streams[1]->attached_pic.data, size) != 0)
  915. return 1;
  916. }
  917. return 0;
  918. }
  919. /* Parse ID3 data and handle the found data */
  920. static void handle_id3(AVIOContext *pb, struct playlist *pls)
  921. {
  922. AVDictionary *metadata = NULL;
  923. ID3v2ExtraMetaAPIC *apic = NULL;
  924. ID3v2ExtraMeta *extra_meta = NULL;
  925. int64_t timestamp = AV_NOPTS_VALUE;
  926. parse_id3(pls->ctx, pb, &metadata, &timestamp, &apic, &extra_meta);
  927. if (timestamp != AV_NOPTS_VALUE) {
  928. pls->id3_mpegts_timestamp = timestamp;
  929. pls->id3_offset = 0;
  930. }
  931. if (!pls->id3_found) {
  932. /* initial ID3 tags */
  933. av_assert0(!pls->id3_deferred_extra);
  934. pls->id3_found = 1;
  935. /* get picture attachment and set text metadata */
  936. if (pls->ctx->nb_streams)
  937. ff_id3v2_parse_apic(pls->ctx, &extra_meta);
  938. else
  939. /* demuxer not yet opened, defer picture attachment */
  940. pls->id3_deferred_extra = extra_meta;
  941. av_dict_copy(&pls->ctx->metadata, metadata, 0);
  942. pls->id3_initial = metadata;
  943. } else {
  944. if (!pls->id3_changed && id3_has_changed_values(pls, metadata, apic)) {
  945. avpriv_report_missing_feature(pls->ctx, "Changing ID3 metadata in HLS audio elementary stream");
  946. pls->id3_changed = 1;
  947. }
  948. av_dict_free(&metadata);
  949. }
  950. if (!pls->id3_deferred_extra)
  951. ff_id3v2_free_extra_meta(&extra_meta);
  952. }
  953. static void intercept_id3(struct playlist *pls, uint8_t *buf,
  954. int buf_size, int *len)
  955. {
  956. /* intercept id3 tags, we do not want to pass them to the raw
  957. * demuxer on all segment switches */
  958. int bytes;
  959. int id3_buf_pos = 0;
  960. int fill_buf = 0;
  961. struct segment *seg = current_segment(pls);
  962. /* gather all the id3 tags */
  963. while (1) {
  964. /* see if we can retrieve enough data for ID3 header */
  965. if (*len < ID3v2_HEADER_SIZE && buf_size >= ID3v2_HEADER_SIZE) {
  966. bytes = read_from_url(pls, seg, buf + *len, ID3v2_HEADER_SIZE - *len, READ_COMPLETE);
  967. if (bytes > 0) {
  968. if (bytes == ID3v2_HEADER_SIZE - *len)
  969. /* no EOF yet, so fill the caller buffer again after
  970. * we have stripped the ID3 tags */
  971. fill_buf = 1;
  972. *len += bytes;
  973. } else if (*len <= 0) {
  974. /* error/EOF */
  975. *len = bytes;
  976. fill_buf = 0;
  977. }
  978. }
  979. if (*len < ID3v2_HEADER_SIZE)
  980. break;
  981. if (ff_id3v2_match(buf, ID3v2_DEFAULT_MAGIC)) {
  982. int64_t maxsize = seg->size >= 0 ? seg->size : 1024*1024;
  983. int taglen = ff_id3v2_tag_len(buf);
  984. int tag_got_bytes = FFMIN(taglen, *len);
  985. int remaining = taglen - tag_got_bytes;
  986. if (taglen > maxsize) {
  987. av_log(pls->ctx, AV_LOG_ERROR, "Too large HLS ID3 tag (%d > %"PRId64" bytes)\n",
  988. taglen, maxsize);
  989. break;
  990. }
  991. /*
  992. * Copy the id3 tag to our temporary id3 buffer.
  993. * We could read a small id3 tag directly without memcpy, but
  994. * we would still need to copy the large tags, and handling
  995. * both of those cases together with the possibility for multiple
  996. * tags would make the handling a bit complex.
  997. */
  998. pls->id3_buf = av_fast_realloc(pls->id3_buf, &pls->id3_buf_size, id3_buf_pos + taglen);
  999. if (!pls->id3_buf)
  1000. break;
  1001. memcpy(pls->id3_buf + id3_buf_pos, buf, tag_got_bytes);
  1002. id3_buf_pos += tag_got_bytes;
  1003. /* strip the intercepted bytes */
  1004. *len -= tag_got_bytes;
  1005. memmove(buf, buf + tag_got_bytes, *len);
  1006. av_log(pls->ctx, AV_LOG_DEBUG, "Stripped %d HLS ID3 bytes\n", tag_got_bytes);
  1007. if (remaining > 0) {
  1008. /* read the rest of the tag in */
  1009. if (read_from_url(pls, seg, pls->id3_buf + id3_buf_pos, remaining, READ_COMPLETE) != remaining)
  1010. break;
  1011. id3_buf_pos += remaining;
  1012. av_log(pls->ctx, AV_LOG_DEBUG, "Stripped additional %d HLS ID3 bytes\n", remaining);
  1013. }
  1014. } else {
  1015. /* no more ID3 tags */
  1016. break;
  1017. }
  1018. }
  1019. /* re-fill buffer for the caller unless EOF */
  1020. if (*len >= 0 && (fill_buf || *len == 0)) {
  1021. bytes = read_from_url(pls, seg, buf + *len, buf_size - *len, READ_NORMAL);
  1022. /* ignore error if we already had some data */
  1023. if (bytes >= 0)
  1024. *len += bytes;
  1025. else if (*len == 0)
  1026. *len = bytes;
  1027. }
  1028. if (pls->id3_buf) {
  1029. /* Now parse all the ID3 tags */
  1030. AVIOContext id3ioctx;
  1031. ffio_init_context(&id3ioctx, pls->id3_buf, id3_buf_pos, 0, NULL, NULL, NULL, NULL);
  1032. handle_id3(&id3ioctx, pls);
  1033. }
  1034. if (pls->is_id3_timestamped == -1)
  1035. pls->is_id3_timestamped = (pls->id3_mpegts_timestamp != AV_NOPTS_VALUE);
  1036. }
  1037. static int open_input(HLSContext *c, struct playlist *pls, struct segment *seg, AVIOContext **in)
  1038. {
  1039. AVDictionary *opts = NULL;
  1040. int ret;
  1041. int is_http = 0;
  1042. // broker prior HTTP options that should be consistent across requests
  1043. av_dict_set(&opts, "user_agent", c->user_agent, 0);
  1044. av_dict_set(&opts, "cookies", c->cookies, 0);
  1045. av_dict_set(&opts, "headers", c->headers, 0);
  1046. av_dict_set(&opts, "http_proxy", c->http_proxy, 0);
  1047. av_dict_set(&opts, "seekable", "0", 0);
  1048. if (c->http_persistent)
  1049. av_dict_set(&opts, "multiple_requests", "1", 0);
  1050. if (seg->size >= 0) {
  1051. /* try to restrict the HTTP request to the part we want
  1052. * (if this is in fact a HTTP request) */
  1053. av_dict_set_int(&opts, "offset", seg->url_offset, 0);
  1054. av_dict_set_int(&opts, "end_offset", seg->url_offset + seg->size, 0);
  1055. }
  1056. av_log(pls->parent, AV_LOG_VERBOSE, "HLS request for url '%s', offset %"PRId64", playlist %d\n",
  1057. seg->url, seg->url_offset, pls->index);
  1058. if (seg->key_type == KEY_NONE) {
  1059. ret = open_url(pls->parent, in, seg->url, c->avio_opts, opts, &is_http);
  1060. } else if (seg->key_type == KEY_AES_128) {
  1061. AVDictionary *opts2 = NULL;
  1062. char iv[33], key[33], url[MAX_URL_SIZE];
  1063. if (strcmp(seg->key, pls->key_url)) {
  1064. AVIOContext *pb = NULL;
  1065. if (open_url(pls->parent, &pb, seg->key, c->avio_opts, opts, NULL) == 0) {
  1066. ret = avio_read(pb, pls->key, sizeof(pls->key));
  1067. if (ret != sizeof(pls->key)) {
  1068. av_log(NULL, AV_LOG_ERROR, "Unable to read key file %s\n",
  1069. seg->key);
  1070. }
  1071. ff_format_io_close(pls->parent, &pb);
  1072. } else {
  1073. av_log(NULL, AV_LOG_ERROR, "Unable to open key file %s\n",
  1074. seg->key);
  1075. }
  1076. av_strlcpy(pls->key_url, seg->key, sizeof(pls->key_url));
  1077. }
  1078. ff_data_to_hex(iv, seg->iv, sizeof(seg->iv), 0);
  1079. ff_data_to_hex(key, pls->key, sizeof(pls->key), 0);
  1080. iv[32] = key[32] = '\0';
  1081. if (strstr(seg->url, "://"))
  1082. snprintf(url, sizeof(url), "crypto+%s", seg->url);
  1083. else
  1084. snprintf(url, sizeof(url), "crypto:%s", seg->url);
  1085. av_dict_copy(&opts2, c->avio_opts, 0);
  1086. av_dict_set(&opts2, "key", key, 0);
  1087. av_dict_set(&opts2, "iv", iv, 0);
  1088. ret = open_url(pls->parent, in, url, opts2, opts, &is_http);
  1089. av_dict_free(&opts2);
  1090. if (ret < 0) {
  1091. goto cleanup;
  1092. }
  1093. ret = 0;
  1094. } else if (seg->key_type == KEY_SAMPLE_AES) {
  1095. av_log(pls->parent, AV_LOG_ERROR,
  1096. "SAMPLE-AES encryption is not supported yet\n");
  1097. ret = AVERROR_PATCHWELCOME;
  1098. }
  1099. else
  1100. ret = AVERROR(ENOSYS);
  1101. /* Seek to the requested position. If this was a HTTP request, the offset
  1102. * should already be where want it to, but this allows e.g. local testing
  1103. * without a HTTP server.
  1104. *
  1105. * This is not done for HTTP at all as avio_seek() does internal bookkeeping
  1106. * of file offset which is out-of-sync with the actual offset when "offset"
  1107. * AVOption is used with http protocol, causing the seek to not be a no-op
  1108. * as would be expected. Wrong offset received from the server will not be
  1109. * noticed without the call, though.
  1110. */
  1111. if (ret == 0 && !is_http && seg->key_type == KEY_NONE && seg->url_offset) {
  1112. int64_t seekret = avio_seek(*in, seg->url_offset, SEEK_SET);
  1113. if (seekret < 0) {
  1114. av_log(pls->parent, AV_LOG_ERROR, "Unable to seek to offset %"PRId64" of HLS segment '%s'\n", seg->url_offset, seg->url);
  1115. ret = seekret;
  1116. ff_format_io_close(pls->parent, in);
  1117. }
  1118. }
  1119. cleanup:
  1120. av_dict_free(&opts);
  1121. pls->cur_seg_offset = 0;
  1122. return ret;
  1123. }
  1124. static int update_init_section(struct playlist *pls, struct segment *seg)
  1125. {
  1126. static const int max_init_section_size = 1024*1024;
  1127. HLSContext *c = pls->parent->priv_data;
  1128. int64_t sec_size;
  1129. int64_t urlsize;
  1130. int ret;
  1131. if (seg->init_section == pls->cur_init_section)
  1132. return 0;
  1133. pls->cur_init_section = NULL;
  1134. if (!seg->init_section)
  1135. return 0;
  1136. ret = open_input(c, pls, seg->init_section, &pls->input);
  1137. if (ret < 0) {
  1138. av_log(pls->parent, AV_LOG_WARNING,
  1139. "Failed to open an initialization section in playlist %d\n",
  1140. pls->index);
  1141. return ret;
  1142. }
  1143. if (seg->init_section->size >= 0)
  1144. sec_size = seg->init_section->size;
  1145. else if ((urlsize = avio_size(pls->input)) >= 0)
  1146. sec_size = urlsize;
  1147. else
  1148. sec_size = max_init_section_size;
  1149. av_log(pls->parent, AV_LOG_DEBUG,
  1150. "Downloading an initialization section of size %"PRId64"\n",
  1151. sec_size);
  1152. sec_size = FFMIN(sec_size, max_init_section_size);
  1153. av_fast_malloc(&pls->init_sec_buf, &pls->init_sec_buf_size, sec_size);
  1154. ret = read_from_url(pls, seg->init_section, pls->init_sec_buf,
  1155. pls->init_sec_buf_size, READ_COMPLETE);
  1156. ff_format_io_close(pls->parent, &pls->input);
  1157. if (ret < 0)
  1158. return ret;
  1159. pls->cur_init_section = seg->init_section;
  1160. pls->init_sec_data_len = ret;
  1161. pls->init_sec_buf_read_offset = 0;
  1162. /* spec says audio elementary streams do not have media initialization
  1163. * sections, so there should be no ID3 timestamps */
  1164. pls->is_id3_timestamped = 0;
  1165. return 0;
  1166. }
  1167. static int64_t default_reload_interval(struct playlist *pls)
  1168. {
  1169. return pls->n_segments > 0 ?
  1170. pls->segments[pls->n_segments - 1]->duration :
  1171. pls->target_duration;
  1172. }
  1173. static int playlist_needed(struct playlist *pls)
  1174. {
  1175. AVFormatContext *s = pls->parent;
  1176. int i, j;
  1177. int stream_needed = 0;
  1178. int first_st;
  1179. /* If there is no context or streams yet, the playlist is needed */
  1180. if (!pls->ctx || !pls->n_main_streams)
  1181. return 1;
  1182. /* check if any of the streams in the playlist are needed */
  1183. for (i = 0; i < pls->n_main_streams; i++) {
  1184. if (pls->main_streams[i]->discard < AVDISCARD_ALL) {
  1185. stream_needed = 1;
  1186. break;
  1187. }
  1188. }
  1189. /* If all streams in the playlist were discarded, the playlist is not
  1190. * needed (regardless of whether whole programs are discarded or not). */
  1191. if (!stream_needed)
  1192. return 0;
  1193. /* Otherwise, check if all the programs (variants) this playlist is in are
  1194. * discarded. Since all streams in the playlist are part of the same programs
  1195. * we can just check the programs of the first stream. */
  1196. first_st = pls->main_streams[0]->index;
  1197. for (i = 0; i < s->nb_programs; i++) {
  1198. AVProgram *program = s->programs[i];
  1199. if (program->discard < AVDISCARD_ALL) {
  1200. for (j = 0; j < program->nb_stream_indexes; j++) {
  1201. if (program->stream_index[j] == first_st) {
  1202. /* playlist is in an undiscarded program */
  1203. return 1;
  1204. }
  1205. }
  1206. }
  1207. }
  1208. /* some streams were not discarded but all the programs were */
  1209. return 0;
  1210. }
  1211. static int read_data(void *opaque, uint8_t *buf, int buf_size)
  1212. {
  1213. struct playlist *v = opaque;
  1214. HLSContext *c = v->parent->priv_data;
  1215. int ret;
  1216. int just_opened = 0;
  1217. int reload_count = 0;
  1218. struct segment *seg;
  1219. restart:
  1220. if (!v->needed)
  1221. return AVERROR_EOF;
  1222. if (!v->input || (c->http_persistent && v->input_read_done)) {
  1223. int64_t reload_interval;
  1224. /* Check that the playlist is still needed before opening a new
  1225. * segment. */
  1226. v->needed = playlist_needed(v);
  1227. if (!v->needed) {
  1228. av_log(v->parent, AV_LOG_INFO, "No longer receiving playlist %d\n",
  1229. v->index);
  1230. return AVERROR_EOF;
  1231. }
  1232. /* If this is a live stream and the reload interval has elapsed since
  1233. * the last playlist reload, reload the playlists now. */
  1234. reload_interval = default_reload_interval(v);
  1235. reload:
  1236. reload_count++;
  1237. if (reload_count > c->max_reload)
  1238. return AVERROR_EOF;
  1239. if (!v->finished &&
  1240. av_gettime_relative() - v->last_load_time >= reload_interval) {
  1241. if ((ret = parse_playlist(c, v->url, v, NULL)) < 0) {
  1242. if (ret != AVERROR_EXIT)
  1243. av_log(v->parent, AV_LOG_WARNING, "Failed to reload playlist %d\n",
  1244. v->index);
  1245. return ret;
  1246. }
  1247. /* If we need to reload the playlist again below (if
  1248. * there's still no more segments), switch to a reload
  1249. * interval of half the target duration. */
  1250. reload_interval = v->target_duration / 2;
  1251. }
  1252. if (v->cur_seq_no < v->start_seq_no) {
  1253. av_log(NULL, AV_LOG_WARNING,
  1254. "skipping %d segments ahead, expired from playlists\n",
  1255. v->start_seq_no - v->cur_seq_no);
  1256. v->cur_seq_no = v->start_seq_no;
  1257. }
  1258. if (v->cur_seq_no >= v->start_seq_no + v->n_segments) {
  1259. if (v->finished)
  1260. return AVERROR_EOF;
  1261. while (av_gettime_relative() - v->last_load_time < reload_interval) {
  1262. if (ff_check_interrupt(c->interrupt_callback))
  1263. return AVERROR_EXIT;
  1264. av_usleep(100*1000);
  1265. }
  1266. /* Enough time has elapsed since the last reload */
  1267. goto reload;
  1268. }
  1269. v->input_read_done = 0;
  1270. seg = current_segment(v);
  1271. /* load/update Media Initialization Section, if any */
  1272. ret = update_init_section(v, seg);
  1273. if (ret)
  1274. return ret;
  1275. if (c->http_multiple == 1 && v->input_next_requested) {
  1276. FFSWAP(AVIOContext *, v->input, v->input_next);
  1277. v->input_next_requested = 0;
  1278. ret = 0;
  1279. } else {
  1280. ret = open_input(c, v, seg, &v->input);
  1281. }
  1282. if (ret < 0) {
  1283. if (ff_check_interrupt(c->interrupt_callback))
  1284. return AVERROR_EXIT;
  1285. av_log(v->parent, AV_LOG_WARNING, "Failed to open segment %d of playlist %d\n",
  1286. v->cur_seq_no,
  1287. v->index);
  1288. v->cur_seq_no += 1;
  1289. goto reload;
  1290. }
  1291. just_opened = 1;
  1292. }
  1293. if (c->http_multiple == -1) {
  1294. uint8_t *http_version_opt = NULL;
  1295. int r = av_opt_get(v->input, "http_version", AV_OPT_SEARCH_CHILDREN, &http_version_opt);
  1296. if (r >= 0) {
  1297. c->http_multiple = strncmp((const char *)http_version_opt, "1.1", 3) == 0;
  1298. av_freep(&http_version_opt);
  1299. }
  1300. }
  1301. seg = next_segment(v);
  1302. if (c->http_multiple == 1 && !v->input_next_requested &&
  1303. seg && seg->key_type == KEY_NONE && av_strstart(seg->url, "http", NULL)) {
  1304. ret = open_input(c, v, seg, &v->input_next);
  1305. if (ret < 0) {
  1306. if (ff_check_interrupt(c->interrupt_callback))
  1307. return AVERROR_EXIT;
  1308. av_log(v->parent, AV_LOG_WARNING, "Failed to open segment %d of playlist %d\n",
  1309. v->cur_seq_no + 1,
  1310. v->index);
  1311. } else {
  1312. v->input_next_requested = 1;
  1313. }
  1314. }
  1315. if (v->init_sec_buf_read_offset < v->init_sec_data_len) {
  1316. /* Push init section out first before first actual segment */
  1317. int copy_size = FFMIN(v->init_sec_data_len - v->init_sec_buf_read_offset, buf_size);
  1318. memcpy(buf, v->init_sec_buf, copy_size);
  1319. v->init_sec_buf_read_offset += copy_size;
  1320. return copy_size;
  1321. }
  1322. seg = current_segment(v);
  1323. ret = read_from_url(v, seg, buf, buf_size, READ_NORMAL);
  1324. if (ret > 0) {
  1325. if (just_opened && v->is_id3_timestamped != 0) {
  1326. /* Intercept ID3 tags here, elementary audio streams are required
  1327. * to convey timestamps using them in the beginning of each segment. */
  1328. intercept_id3(v, buf, buf_size, &ret);
  1329. }
  1330. return ret;
  1331. }
  1332. if (c->http_persistent &&
  1333. seg->key_type == KEY_NONE && av_strstart(seg->url, "http", NULL)) {
  1334. v->input_read_done = 1;
  1335. } else {
  1336. ff_format_io_close(v->parent, &v->input);
  1337. }
  1338. v->cur_seq_no++;
  1339. c->cur_seq_no = v->cur_seq_no;
  1340. goto restart;
  1341. }
  1342. static void add_renditions_to_variant(HLSContext *c, struct variant *var,
  1343. enum AVMediaType type, const char *group_id)
  1344. {
  1345. int i;
  1346. for (i = 0; i < c->n_renditions; i++) {
  1347. struct rendition *rend = c->renditions[i];
  1348. if (rend->type == type && !strcmp(rend->group_id, group_id)) {
  1349. if (rend->playlist)
  1350. /* rendition is an external playlist
  1351. * => add the playlist to the variant */
  1352. dynarray_add(&var->playlists, &var->n_playlists, rend->playlist);
  1353. else
  1354. /* rendition is part of the variant main Media Playlist
  1355. * => add the rendition to the main Media Playlist */
  1356. dynarray_add(&var->playlists[0]->renditions,
  1357. &var->playlists[0]->n_renditions,
  1358. rend);
  1359. }
  1360. }
  1361. }
  1362. static void add_metadata_from_renditions(AVFormatContext *s, struct playlist *pls,
  1363. enum AVMediaType type)
  1364. {
  1365. int rend_idx = 0;
  1366. int i;
  1367. for (i = 0; i < pls->n_main_streams; i++) {
  1368. AVStream *st = pls->main_streams[i];
  1369. if (st->codecpar->codec_type != type)
  1370. continue;
  1371. for (; rend_idx < pls->n_renditions; rend_idx++) {
  1372. struct rendition *rend = pls->renditions[rend_idx];
  1373. if (rend->type != type)
  1374. continue;
  1375. if (rend->language[0])
  1376. av_dict_set(&st->metadata, "language", rend->language, 0);
  1377. if (rend->name[0])
  1378. av_dict_set(&st->metadata, "comment", rend->name, 0);
  1379. st->disposition |= rend->disposition;
  1380. }
  1381. if (rend_idx >=pls->n_renditions)
  1382. break;
  1383. }
  1384. }
  1385. /* if timestamp was in valid range: returns 1 and sets seq_no
  1386. * if not: returns 0 and sets seq_no to closest segment */
  1387. static int find_timestamp_in_playlist(HLSContext *c, struct playlist *pls,
  1388. int64_t timestamp, int *seq_no)
  1389. {
  1390. int i;
  1391. int64_t pos = c->first_timestamp == AV_NOPTS_VALUE ?
  1392. 0 : c->first_timestamp;
  1393. if (timestamp < pos) {
  1394. *seq_no = pls->start_seq_no;
  1395. return 0;
  1396. }
  1397. for (i = 0; i < pls->n_segments; i++) {
  1398. int64_t diff = pos + pls->segments[i]->duration - timestamp;
  1399. if (diff > 0) {
  1400. *seq_no = pls->start_seq_no + i;
  1401. return 1;
  1402. }
  1403. pos += pls->segments[i]->duration;
  1404. }
  1405. *seq_no = pls->start_seq_no + pls->n_segments - 1;
  1406. return 0;
  1407. }
  1408. static int select_cur_seq_no(HLSContext *c, struct playlist *pls)
  1409. {
  1410. int seq_no;
  1411. if (!pls->finished && !c->first_packet &&
  1412. av_gettime_relative() - pls->last_load_time >= default_reload_interval(pls))
  1413. /* reload the playlist since it was suspended */
  1414. parse_playlist(c, pls->url, pls, NULL);
  1415. /* If playback is already in progress (we are just selecting a new
  1416. * playlist) and this is a complete file, find the matching segment
  1417. * by counting durations. */
  1418. if (pls->finished && c->cur_timestamp != AV_NOPTS_VALUE) {
  1419. find_timestamp_in_playlist(c, pls, c->cur_timestamp, &seq_no);
  1420. return seq_no;
  1421. }
  1422. if (!pls->finished) {
  1423. if (!c->first_packet && /* we are doing a segment selection during playback */
  1424. c->cur_seq_no >= pls->start_seq_no &&
  1425. c->cur_seq_no < pls->start_seq_no + pls->n_segments)
  1426. /* While spec 3.4.3 says that we cannot assume anything about the
  1427. * content at the same sequence number on different playlists,
  1428. * in practice this seems to work and doing it otherwise would
  1429. * require us to download a segment to inspect its timestamps. */
  1430. return c->cur_seq_no;
  1431. /* If this is a live stream, start live_start_index segments from the
  1432. * start or end */
  1433. if (c->live_start_index < 0)
  1434. return pls->start_seq_no + FFMAX(pls->n_segments + c->live_start_index, 0);
  1435. else
  1436. return pls->start_seq_no + FFMIN(c->live_start_index, pls->n_segments - 1);
  1437. }
  1438. /* Otherwise just start on the first segment. */
  1439. return pls->start_seq_no;
  1440. }
  1441. static int save_avio_options(AVFormatContext *s)
  1442. {
  1443. HLSContext *c = s->priv_data;
  1444. static const char * const opts[] = {
  1445. "headers", "http_proxy", "user_agent", "user-agent", "cookies", NULL };
  1446. const char * const * opt = opts;
  1447. uint8_t *buf;
  1448. int ret = 0;
  1449. while (*opt) {
  1450. if (av_opt_get(s->pb, *opt, AV_OPT_SEARCH_CHILDREN | AV_OPT_ALLOW_NULL, &buf) >= 0) {
  1451. ret = av_dict_set(&c->avio_opts, *opt, buf,
  1452. AV_DICT_DONT_STRDUP_VAL);
  1453. if (ret < 0)
  1454. return ret;
  1455. }
  1456. opt++;
  1457. }
  1458. return ret;
  1459. }
  1460. static int nested_io_open(AVFormatContext *s, AVIOContext **pb, const char *url,
  1461. int flags, AVDictionary **opts)
  1462. {
  1463. av_log(s, AV_LOG_ERROR,
  1464. "A HLS playlist item '%s' referred to an external file '%s'. "
  1465. "Opening this file was forbidden for security reasons\n",
  1466. s->filename, url);
  1467. return AVERROR(EPERM);
  1468. }
  1469. static void add_stream_to_programs(AVFormatContext *s, struct playlist *pls, AVStream *stream)
  1470. {
  1471. HLSContext *c = s->priv_data;
  1472. int i, j;
  1473. int bandwidth = -1;
  1474. for (i = 0; i < c->n_variants; i++) {
  1475. struct variant *v = c->variants[i];
  1476. for (j = 0; j < v->n_playlists; j++) {
  1477. if (v->playlists[j] != pls)
  1478. continue;
  1479. av_program_add_stream_index(s, i, stream->index);
  1480. if (bandwidth < 0)
  1481. bandwidth = v->bandwidth;
  1482. else if (bandwidth != v->bandwidth)
  1483. bandwidth = -1; /* stream in multiple variants with different bandwidths */
  1484. }
  1485. }
  1486. if (bandwidth >= 0)
  1487. av_dict_set_int(&stream->metadata, "variant_bitrate", bandwidth, 0);
  1488. }
  1489. static int set_stream_info_from_input_stream(AVStream *st, struct playlist *pls, AVStream *ist)
  1490. {
  1491. int err;
  1492. err = avcodec_parameters_copy(st->codecpar, ist->codecpar);
  1493. if (err < 0)
  1494. return err;
  1495. if (pls->is_id3_timestamped) /* custom timestamps via id3 */
  1496. avpriv_set_pts_info(st, 33, 1, MPEG_TIME_BASE);
  1497. else
  1498. avpriv_set_pts_info(st, ist->pts_wrap_bits, ist->time_base.num, ist->time_base.den);
  1499. st->internal->need_context_update = 1;
  1500. return 0;
  1501. }
  1502. /* add new subdemuxer streams to our context, if any */
  1503. static int update_streams_from_subdemuxer(AVFormatContext *s, struct playlist *pls)
  1504. {
  1505. int err;
  1506. while (pls->n_main_streams < pls->ctx->nb_streams) {
  1507. int ist_idx = pls->n_main_streams;
  1508. AVStream *st = avformat_new_stream(s, NULL);
  1509. AVStream *ist = pls->ctx->streams[ist_idx];
  1510. if (!st)
  1511. return AVERROR(ENOMEM);
  1512. st->id = pls->index;
  1513. dynarray_add(&pls->main_streams, &pls->n_main_streams, st);
  1514. add_stream_to_programs(s, pls, st);
  1515. err = set_stream_info_from_input_stream(st, pls, ist);
  1516. if (err < 0)
  1517. return err;
  1518. }
  1519. return 0;
  1520. }
  1521. static void update_noheader_flag(AVFormatContext *s)
  1522. {
  1523. HLSContext *c = s->priv_data;
  1524. int flag_needed = 0;
  1525. int i;
  1526. for (i = 0; i < c->n_playlists; i++) {
  1527. struct playlist *pls = c->playlists[i];
  1528. if (pls->has_noheader_flag) {
  1529. flag_needed = 1;
  1530. break;
  1531. }
  1532. }
  1533. if (flag_needed)
  1534. s->ctx_flags |= AVFMTCTX_NOHEADER;
  1535. else
  1536. s->ctx_flags &= ~AVFMTCTX_NOHEADER;
  1537. }
  1538. static int hls_close(AVFormatContext *s)
  1539. {
  1540. HLSContext *c = s->priv_data;
  1541. free_playlist_list(c);
  1542. free_variant_list(c);
  1543. free_rendition_list(c);
  1544. av_dict_free(&c->avio_opts);
  1545. ff_format_io_close(c->ctx, &c->playlist_pb);
  1546. return 0;
  1547. }
  1548. static int hls_read_header(AVFormatContext *s)
  1549. {
  1550. void *u = (s->flags & AVFMT_FLAG_CUSTOM_IO) ? NULL : s->pb;
  1551. HLSContext *c = s->priv_data;
  1552. int ret = 0, i;
  1553. int highest_cur_seq_no = 0;
  1554. c->ctx = s;
  1555. c->interrupt_callback = &s->interrupt_callback;
  1556. c->strict_std_compliance = s->strict_std_compliance;
  1557. c->first_packet = 1;
  1558. c->first_timestamp = AV_NOPTS_VALUE;
  1559. c->cur_timestamp = AV_NOPTS_VALUE;
  1560. if (u) {
  1561. // get the previous user agent & set back to null if string size is zero
  1562. update_options(&c->user_agent, "user_agent", u);
  1563. // get the previous cookies & set back to null if string size is zero
  1564. update_options(&c->cookies, "cookies", u);
  1565. // get the previous headers & set back to null if string size is zero
  1566. update_options(&c->headers, "headers", u);
  1567. // get the previous http proxt & set back to null if string size is zero
  1568. update_options(&c->http_proxy, "http_proxy", u);
  1569. }
  1570. if ((ret = parse_playlist(c, s->filename, NULL, s->pb)) < 0)
  1571. goto fail;
  1572. if ((ret = save_avio_options(s)) < 0)
  1573. goto fail;
  1574. /* Some HLS servers don't like being sent the range header */
  1575. av_dict_set(&c->avio_opts, "seekable", "0", 0);
  1576. if (c->n_variants == 0) {
  1577. av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");
  1578. ret = AVERROR_EOF;
  1579. goto fail;
  1580. }
  1581. /* If the playlist only contained playlists (Master Playlist),
  1582. * parse each individual playlist. */
  1583. if (c->n_playlists > 1 || c->playlists[0]->n_segments == 0) {
  1584. for (i = 0; i < c->n_playlists; i++) {
  1585. struct playlist *pls = c->playlists[i];
  1586. if ((ret = parse_playlist(c, pls->url, pls, NULL)) < 0)
  1587. goto fail;
  1588. }
  1589. }
  1590. if (c->variants[0]->playlists[0]->n_segments == 0) {
  1591. av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");
  1592. ret = AVERROR_EOF;
  1593. goto fail;
  1594. }
  1595. /* If this isn't a live stream, calculate the total duration of the
  1596. * stream. */
  1597. if (c->variants[0]->playlists[0]->finished) {
  1598. int64_t duration = 0;
  1599. for (i = 0; i < c->variants[0]->playlists[0]->n_segments; i++)
  1600. duration += c->variants[0]->playlists[0]->segments[i]->duration;
  1601. s->duration = duration;
  1602. }
  1603. /* Associate renditions with variants */
  1604. for (i = 0; i < c->n_variants; i++) {
  1605. struct variant *var = c->variants[i];
  1606. if (var->audio_group[0])
  1607. add_renditions_to_variant(c, var, AVMEDIA_TYPE_AUDIO, var->audio_group);
  1608. if (var->video_group[0])
  1609. add_renditions_to_variant(c, var, AVMEDIA_TYPE_VIDEO, var->video_group);
  1610. if (var->subtitles_group[0])
  1611. add_renditions_to_variant(c, var, AVMEDIA_TYPE_SUBTITLE, var->subtitles_group);
  1612. }
  1613. /* Create a program for each variant */
  1614. for (i = 0; i < c->n_variants; i++) {
  1615. struct variant *v = c->variants[i];
  1616. AVProgram *program;
  1617. program = av_new_program(s, i);
  1618. if (!program)
  1619. goto fail;
  1620. av_dict_set_int(&program->metadata, "variant_bitrate", v->bandwidth, 0);
  1621. }
  1622. /* Select the starting segments */
  1623. for (i = 0; i < c->n_playlists; i++) {
  1624. struct playlist *pls = c->playlists[i];
  1625. if (pls->n_segments == 0)
  1626. continue;
  1627. pls->cur_seq_no = select_cur_seq_no(c, pls);
  1628. highest_cur_seq_no = FFMAX(highest_cur_seq_no, pls->cur_seq_no);
  1629. }
  1630. /* Open the demuxer for each playlist */
  1631. for (i = 0; i < c->n_playlists; i++) {
  1632. struct playlist *pls = c->playlists[i];
  1633. AVInputFormat *in_fmt = NULL;
  1634. if (!(pls->ctx = avformat_alloc_context())) {
  1635. ret = AVERROR(ENOMEM);
  1636. goto fail;
  1637. }
  1638. if (pls->n_segments == 0)
  1639. continue;
  1640. pls->index = i;
  1641. pls->needed = 1;
  1642. pls->parent = s;
  1643. /*
  1644. * If this is a live stream and this playlist looks like it is one segment
  1645. * behind, try to sync it up so that every substream starts at the same
  1646. * time position (so e.g. avformat_find_stream_info() will see packets from
  1647. * all active streams within the first few seconds). This is not very generic,
  1648. * though, as the sequence numbers are technically independent.
  1649. */
  1650. if (!pls->finished && pls->cur_seq_no == highest_cur_seq_no - 1 &&
  1651. highest_cur_seq_no < pls->start_seq_no + pls->n_segments) {
  1652. pls->cur_seq_no = highest_cur_seq_no;
  1653. }
  1654. pls->read_buffer = av_malloc(INITIAL_BUFFER_SIZE);
  1655. if (!pls->read_buffer){
  1656. ret = AVERROR(ENOMEM);
  1657. avformat_free_context(pls->ctx);
  1658. pls->ctx = NULL;
  1659. goto fail;
  1660. }
  1661. ffio_init_context(&pls->pb, pls->read_buffer, INITIAL_BUFFER_SIZE, 0, pls,
  1662. read_data, NULL, NULL);
  1663. pls->pb.seekable = 0;
  1664. ret = av_probe_input_buffer(&pls->pb, &in_fmt, pls->segments[0]->url,
  1665. NULL, 0, 0);
  1666. if (ret < 0) {
  1667. /* Free the ctx - it isn't initialized properly at this point,
  1668. * so avformat_close_input shouldn't be called. If
  1669. * avformat_open_input fails below, it frees and zeros the
  1670. * context, so it doesn't need any special treatment like this. */
  1671. av_log(s, AV_LOG_ERROR, "Error when loading first segment '%s'\n", pls->segments[0]->url);
  1672. avformat_free_context(pls->ctx);
  1673. pls->ctx = NULL;
  1674. goto fail;
  1675. }
  1676. pls->ctx->pb = &pls->pb;
  1677. pls->ctx->io_open = nested_io_open;
  1678. pls->ctx->flags |= s->flags & ~AVFMT_FLAG_CUSTOM_IO;
  1679. if ((ret = ff_copy_whiteblacklists(pls->ctx, s)) < 0)
  1680. goto fail;
  1681. ret = avformat_open_input(&pls->ctx, pls->segments[0]->url, in_fmt, NULL);
  1682. if (ret < 0)
  1683. goto fail;
  1684. if (pls->id3_deferred_extra && pls->ctx->nb_streams == 1) {
  1685. ff_id3v2_parse_apic(pls->ctx, &pls->id3_deferred_extra);
  1686. avformat_queue_attached_pictures(pls->ctx);
  1687. ff_id3v2_free_extra_meta(&pls->id3_deferred_extra);
  1688. pls->id3_deferred_extra = NULL;
  1689. }
  1690. if (pls->is_id3_timestamped == -1)
  1691. av_log(s, AV_LOG_WARNING, "No expected HTTP requests have been made\n");
  1692. /*
  1693. * For ID3 timestamped raw audio streams we need to detect the packet
  1694. * durations to calculate timestamps in fill_timing_for_id3_timestamped_stream(),
  1695. * but for other streams we can rely on our user calling avformat_find_stream_info()
  1696. * on us if they want to.
  1697. */
  1698. if (pls->is_id3_timestamped) {
  1699. ret = avformat_find_stream_info(pls->ctx, NULL);
  1700. if (ret < 0)
  1701. goto fail;
  1702. }
  1703. pls->has_noheader_flag = !!(pls->ctx->ctx_flags & AVFMTCTX_NOHEADER);
  1704. /* Create new AVStreams for each stream in this playlist */
  1705. ret = update_streams_from_subdemuxer(s, pls);
  1706. if (ret < 0)
  1707. goto fail;
  1708. add_metadata_from_renditions(s, pls, AVMEDIA_TYPE_AUDIO);
  1709. add_metadata_from_renditions(s, pls, AVMEDIA_TYPE_VIDEO);
  1710. add_metadata_from_renditions(s, pls, AVMEDIA_TYPE_SUBTITLE);
  1711. }
  1712. update_noheader_flag(s);
  1713. return 0;
  1714. fail:
  1715. hls_close(s);
  1716. return ret;
  1717. }
  1718. static int recheck_discard_flags(AVFormatContext *s, int first)
  1719. {
  1720. HLSContext *c = s->priv_data;
  1721. int i, changed = 0;
  1722. int cur_needed;
  1723. /* Check if any new streams are needed */
  1724. for (i = 0; i < c->n_playlists; i++) {
  1725. struct playlist *pls = c->playlists[i];
  1726. cur_needed = playlist_needed(c->playlists[i]);
  1727. if (cur_needed && !pls->needed) {
  1728. pls->needed = 1;
  1729. changed = 1;
  1730. pls->cur_seq_no = select_cur_seq_no(c, pls);
  1731. pls->pb.eof_reached = 0;
  1732. if (c->cur_timestamp != AV_NOPTS_VALUE) {
  1733. /* catch up */
  1734. pls->seek_timestamp = c->cur_timestamp;
  1735. pls->seek_flags = AVSEEK_FLAG_ANY;
  1736. pls->seek_stream_index = -1;
  1737. }
  1738. av_log(s, AV_LOG_INFO, "Now receiving playlist %d, segment %d\n", i, pls->cur_seq_no);
  1739. } else if (first && !cur_needed && pls->needed) {
  1740. if (pls->input)
  1741. ff_format_io_close(pls->parent, &pls->input);
  1742. pls->input_read_done = 0;
  1743. if (pls->input_next)
  1744. ff_format_io_close(pls->parent, &pls->input_next);
  1745. pls->input_next_requested = 0;
  1746. pls->needed = 0;
  1747. changed = 1;
  1748. av_log(s, AV_LOG_INFO, "No longer receiving playlist %d\n", i);
  1749. }
  1750. }
  1751. return changed;
  1752. }
  1753. static void fill_timing_for_id3_timestamped_stream(struct playlist *pls)
  1754. {
  1755. if (pls->id3_offset >= 0) {
  1756. pls->pkt.dts = pls->id3_mpegts_timestamp +
  1757. av_rescale_q(pls->id3_offset,
  1758. pls->ctx->streams[pls->pkt.stream_index]->time_base,
  1759. MPEG_TIME_BASE_Q);
  1760. if (pls->pkt.duration)
  1761. pls->id3_offset += pls->pkt.duration;
  1762. else
  1763. pls->id3_offset = -1;
  1764. } else {
  1765. /* there have been packets with unknown duration
  1766. * since the last id3 tag, should not normally happen */
  1767. pls->pkt.dts = AV_NOPTS_VALUE;
  1768. }
  1769. if (pls->pkt.duration)
  1770. pls->pkt.duration = av_rescale_q(pls->pkt.duration,
  1771. pls->ctx->streams[pls->pkt.stream_index]->time_base,
  1772. MPEG_TIME_BASE_Q);
  1773. pls->pkt.pts = AV_NOPTS_VALUE;
  1774. }
  1775. static AVRational get_timebase(struct playlist *pls)
  1776. {
  1777. if (pls->is_id3_timestamped)
  1778. return MPEG_TIME_BASE_Q;
  1779. return pls->ctx->streams[pls->pkt.stream_index]->time_base;
  1780. }
  1781. static int compare_ts_with_wrapdetect(int64_t ts_a, struct playlist *pls_a,
  1782. int64_t ts_b, struct playlist *pls_b)
  1783. {
  1784. int64_t scaled_ts_a = av_rescale_q(ts_a, get_timebase(pls_a), MPEG_TIME_BASE_Q);
  1785. int64_t scaled_ts_b = av_rescale_q(ts_b, get_timebase(pls_b), MPEG_TIME_BASE_Q);
  1786. return av_compare_mod(scaled_ts_a, scaled_ts_b, 1LL << 33);
  1787. }
  1788. static int hls_read_packet(AVFormatContext *s, AVPacket *pkt)
  1789. {
  1790. HLSContext *c = s->priv_data;
  1791. int ret, i, minplaylist = -1;
  1792. recheck_discard_flags(s, c->first_packet);
  1793. c->first_packet = 0;
  1794. for (i = 0; i < c->n_playlists; i++) {
  1795. struct playlist *pls = c->playlists[i];
  1796. /* Make sure we've got one buffered packet from each open playlist
  1797. * stream */
  1798. if (pls->needed && !pls->pkt.data) {
  1799. while (1) {
  1800. int64_t ts_diff;
  1801. AVRational tb;
  1802. ret = av_read_frame(pls->ctx, &pls->pkt);
  1803. if (ret < 0) {
  1804. if (!avio_feof(&pls->pb) && ret != AVERROR_EOF)
  1805. return ret;
  1806. reset_packet(&pls->pkt);
  1807. break;
  1808. } else {
  1809. /* stream_index check prevents matching picture attachments etc. */
  1810. if (pls->is_id3_timestamped && pls->pkt.stream_index == 0) {
  1811. /* audio elementary streams are id3 timestamped */
  1812. fill_timing_for_id3_timestamped_stream(pls);
  1813. }
  1814. if (c->first_timestamp == AV_NOPTS_VALUE &&
  1815. pls->pkt.dts != AV_NOPTS_VALUE)
  1816. c->first_timestamp = av_rescale_q(pls->pkt.dts,
  1817. get_timebase(pls), AV_TIME_BASE_Q);
  1818. }
  1819. if (pls->seek_timestamp == AV_NOPTS_VALUE)
  1820. break;
  1821. if (pls->seek_stream_index < 0 ||
  1822. pls->seek_stream_index == pls->pkt.stream_index) {
  1823. if (pls->pkt.dts == AV_NOPTS_VALUE) {
  1824. pls->seek_timestamp = AV_NOPTS_VALUE;
  1825. break;
  1826. }
  1827. tb = get_timebase(pls);
  1828. ts_diff = av_rescale_rnd(pls->pkt.dts, AV_TIME_BASE,
  1829. tb.den, AV_ROUND_DOWN) -
  1830. pls->seek_timestamp;
  1831. if (ts_diff >= 0 && (pls->seek_flags & AVSEEK_FLAG_ANY ||
  1832. pls->pkt.flags & AV_PKT_FLAG_KEY)) {
  1833. pls->seek_timestamp = AV_NOPTS_VALUE;
  1834. break;
  1835. }
  1836. }
  1837. av_packet_unref(&pls->pkt);
  1838. reset_packet(&pls->pkt);
  1839. }
  1840. }
  1841. /* Check if this stream has the packet with the lowest dts */
  1842. if (pls->pkt.data) {
  1843. struct playlist *minpls = minplaylist < 0 ?
  1844. NULL : c->playlists[minplaylist];
  1845. if (minplaylist < 0) {
  1846. minplaylist = i;
  1847. } else {
  1848. int64_t dts = pls->pkt.dts;
  1849. int64_t mindts = minpls->pkt.dts;
  1850. if (dts == AV_NOPTS_VALUE ||
  1851. (mindts != AV_NOPTS_VALUE && compare_ts_with_wrapdetect(dts, pls, mindts, minpls) < 0))
  1852. minplaylist = i;
  1853. }
  1854. }
  1855. }
  1856. /* If we got a packet, return it */
  1857. if (minplaylist >= 0) {
  1858. struct playlist *pls = c->playlists[minplaylist];
  1859. AVStream *ist;
  1860. AVStream *st;
  1861. ret = update_streams_from_subdemuxer(s, pls);
  1862. if (ret < 0) {
  1863. av_packet_unref(&pls->pkt);
  1864. reset_packet(&pls->pkt);
  1865. return ret;
  1866. }
  1867. /* check if noheader flag has been cleared by the subdemuxer */
  1868. if (pls->has_noheader_flag && !(pls->ctx->ctx_flags & AVFMTCTX_NOHEADER)) {
  1869. pls->has_noheader_flag = 0;
  1870. update_noheader_flag(s);
  1871. }
  1872. if (pls->pkt.stream_index >= pls->n_main_streams) {
  1873. av_log(s, AV_LOG_ERROR, "stream index inconsistency: index %d, %d main streams, %d subdemuxer streams\n",
  1874. pls->pkt.stream_index, pls->n_main_streams, pls->ctx->nb_streams);
  1875. av_packet_unref(&pls->pkt);
  1876. reset_packet(&pls->pkt);
  1877. return AVERROR_BUG;
  1878. }
  1879. ist = pls->ctx->streams[pls->pkt.stream_index];
  1880. st = pls->main_streams[pls->pkt.stream_index];
  1881. *pkt = pls->pkt;
  1882. pkt->stream_index = st->index;
  1883. reset_packet(&c->playlists[minplaylist]->pkt);
  1884. if (pkt->dts != AV_NOPTS_VALUE)
  1885. c->cur_timestamp = av_rescale_q(pkt->dts,
  1886. ist->time_base,
  1887. AV_TIME_BASE_Q);
  1888. /* There may be more situations where this would be useful, but this at least
  1889. * handles newly probed codecs properly (i.e. request_probe by mpegts). */
  1890. if (ist->codecpar->codec_id != st->codecpar->codec_id) {
  1891. ret = set_stream_info_from_input_stream(st, pls, ist);
  1892. if (ret < 0) {
  1893. av_packet_unref(pkt);
  1894. return ret;
  1895. }
  1896. }
  1897. return 0;
  1898. }
  1899. return AVERROR_EOF;
  1900. }
  1901. static int hls_read_seek(AVFormatContext *s, int stream_index,
  1902. int64_t timestamp, int flags)
  1903. {
  1904. HLSContext *c = s->priv_data;
  1905. struct playlist *seek_pls = NULL;
  1906. int i, seq_no;
  1907. int j;
  1908. int stream_subdemuxer_index;
  1909. int64_t first_timestamp, seek_timestamp, duration;
  1910. if ((flags & AVSEEK_FLAG_BYTE) || (c->ctx->ctx_flags & AVFMTCTX_UNSEEKABLE))
  1911. return AVERROR(ENOSYS);
  1912. first_timestamp = c->first_timestamp == AV_NOPTS_VALUE ?
  1913. 0 : c->first_timestamp;
  1914. seek_timestamp = av_rescale_rnd(timestamp, AV_TIME_BASE,
  1915. s->streams[stream_index]->time_base.den,
  1916. flags & AVSEEK_FLAG_BACKWARD ?
  1917. AV_ROUND_DOWN : AV_ROUND_UP);
  1918. duration = s->duration == AV_NOPTS_VALUE ?
  1919. 0 : s->duration;
  1920. if (0 < duration && duration < seek_timestamp - first_timestamp)
  1921. return AVERROR(EIO);
  1922. /* find the playlist with the specified stream */
  1923. for (i = 0; i < c->n_playlists; i++) {
  1924. struct playlist *pls = c->playlists[i];
  1925. for (j = 0; j < pls->n_main_streams; j++) {
  1926. if (pls->main_streams[j] == s->streams[stream_index]) {
  1927. seek_pls = pls;
  1928. stream_subdemuxer_index = j;
  1929. break;
  1930. }
  1931. }
  1932. }
  1933. /* check if the timestamp is valid for the playlist with the
  1934. * specified stream index */
  1935. if (!seek_pls || !find_timestamp_in_playlist(c, seek_pls, seek_timestamp, &seq_no))
  1936. return AVERROR(EIO);
  1937. /* set segment now so we do not need to search again below */
  1938. seek_pls->cur_seq_no = seq_no;
  1939. seek_pls->seek_stream_index = stream_subdemuxer_index;
  1940. for (i = 0; i < c->n_playlists; i++) {
  1941. /* Reset reading */
  1942. struct playlist *pls = c->playlists[i];
  1943. if (pls->input)
  1944. ff_format_io_close(pls->parent, &pls->input);
  1945. pls->input_read_done = 0;
  1946. if (pls->input_next)
  1947. ff_format_io_close(pls->parent, &pls->input_next);
  1948. pls->input_next_requested = 0;
  1949. av_packet_unref(&pls->pkt);
  1950. reset_packet(&pls->pkt);
  1951. pls->pb.eof_reached = 0;
  1952. /* Clear any buffered data */
  1953. pls->pb.buf_end = pls->pb.buf_ptr = pls->pb.buffer;
  1954. /* Reset the pos, to let the mpegts demuxer know we've seeked. */
  1955. pls->pb.pos = 0;
  1956. /* Flush the packet queue of the subdemuxer. */
  1957. ff_read_frame_flush(pls->ctx);
  1958. pls->seek_timestamp = seek_timestamp;
  1959. pls->seek_flags = flags;
  1960. if (pls != seek_pls) {
  1961. /* set closest segment seq_no for playlists not handled above */
  1962. find_timestamp_in_playlist(c, pls, seek_timestamp, &pls->cur_seq_no);
  1963. /* seek the playlist to the given position without taking
  1964. * keyframes into account since this playlist does not have the
  1965. * specified stream where we should look for the keyframes */
  1966. pls->seek_stream_index = -1;
  1967. pls->seek_flags |= AVSEEK_FLAG_ANY;
  1968. }
  1969. }
  1970. c->cur_timestamp = seek_timestamp;
  1971. return 0;
  1972. }
  1973. static int hls_probe(AVProbeData *p)
  1974. {
  1975. /* Require #EXTM3U at the start, and either one of the ones below
  1976. * somewhere for a proper match. */
  1977. if (strncmp(p->buf, "#EXTM3U", 7))
  1978. return 0;
  1979. if (strstr(p->buf, "#EXT-X-STREAM-INF:") ||
  1980. strstr(p->buf, "#EXT-X-TARGETDURATION:") ||
  1981. strstr(p->buf, "#EXT-X-MEDIA-SEQUENCE:"))
  1982. return AVPROBE_SCORE_MAX;
  1983. return 0;
  1984. }
  1985. #define OFFSET(x) offsetof(HLSContext, x)
  1986. #define FLAGS AV_OPT_FLAG_DECODING_PARAM
  1987. static const AVOption hls_options[] = {
  1988. {"live_start_index", "segment index to start live streams at (negative values are from the end)",
  1989. OFFSET(live_start_index), AV_OPT_TYPE_INT, {.i64 = -3}, INT_MIN, INT_MAX, FLAGS},
  1990. {"allowed_extensions", "List of file extensions that hls is allowed to access",
  1991. OFFSET(allowed_extensions), AV_OPT_TYPE_STRING,
  1992. {.str = "3gp,aac,avi,flac,mkv,m3u8,m4a,m4s,m4v,mpg,mov,mp2,mp3,mp4,mpeg,mpegts,ogg,ogv,oga,ts,vob,wav"},
  1993. INT_MIN, INT_MAX, FLAGS},
  1994. {"max_reload", "Maximum number of times a insufficient list is attempted to be reloaded",
  1995. OFFSET(max_reload), AV_OPT_TYPE_INT, {.i64 = 1000}, 0, INT_MAX, FLAGS},
  1996. {"http_persistent", "Use persistent HTTP connections",
  1997. OFFSET(http_persistent), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, FLAGS },
  1998. {"http_multiple", "Use multiple HTTP connections for fetching segments",
  1999. OFFSET(http_multiple), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, FLAGS},
  2000. {NULL}
  2001. };
  2002. static const AVClass hls_class = {
  2003. .class_name = "hls,applehttp",
  2004. .item_name = av_default_item_name,
  2005. .option = hls_options,
  2006. .version = LIBAVUTIL_VERSION_INT,
  2007. };
  2008. AVInputFormat ff_hls_demuxer = {
  2009. .name = "hls,applehttp",
  2010. .long_name = NULL_IF_CONFIG_SMALL("Apple HTTP Live Streaming"),
  2011. .priv_class = &hls_class,
  2012. .priv_data_size = sizeof(HLSContext),
  2013. .flags = AVFMT_NOGENSEARCH,
  2014. .read_probe = hls_probe,
  2015. .read_header = hls_read_header,
  2016. .read_packet = hls_read_packet,
  2017. .read_close = hls_close,
  2018. .read_seek = hls_read_seek,
  2019. };