hls.c 81 KB

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