applehttp.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. /*
  2. * Apple HTTP Live Streaming demuxer
  3. * Copyright (c) 2010 Martin Storsjo
  4. *
  5. * This file is part of Libav.
  6. *
  7. * Libav is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * Libav is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with Libav; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. /**
  22. * @file
  23. * Apple HTTP Live Streaming demuxer
  24. * http://tools.ietf.org/html/draft-pantos-http-live-streaming
  25. */
  26. #define _XOPEN_SOURCE 600
  27. #include "libavutil/avstring.h"
  28. #include "avformat.h"
  29. #include "internal.h"
  30. #include <unistd.h>
  31. /*
  32. * An apple http stream consists of a playlist with media segment files,
  33. * played sequentially. There may be several playlists with the same
  34. * video content, in different bandwidth variants, that are played in
  35. * parallel (preferrably only one bandwidth variant at a time). In this case,
  36. * the user supplied the url to a main playlist that only lists the variant
  37. * playlists.
  38. *
  39. * If the main playlist doesn't point at any variants, we still create
  40. * one anonymous toplevel variant for this, to maintain the structure.
  41. */
  42. struct segment {
  43. int duration;
  44. char url[MAX_URL_SIZE];
  45. };
  46. /*
  47. * Each variant has its own demuxer. If it currently is active,
  48. * it has an open AVIOContext too, and potentially an AVPacket
  49. * containing the next packet from this stream.
  50. */
  51. struct variant {
  52. int bandwidth;
  53. char url[MAX_URL_SIZE];
  54. AVIOContext *pb;
  55. AVFormatContext *ctx;
  56. AVPacket pkt;
  57. int stream_offset;
  58. int start_seq_no;
  59. int n_segments;
  60. struct segment **segments;
  61. int needed;
  62. };
  63. typedef struct AppleHTTPContext {
  64. int target_duration;
  65. int finished;
  66. int n_variants;
  67. struct variant **variants;
  68. int cur_seq_no;
  69. int64_t last_load_time;
  70. int64_t last_packet_dts;
  71. int max_start_seq, min_end_seq;
  72. } AppleHTTPContext;
  73. static int read_chomp_line(AVIOContext *s, char *buf, int maxlen)
  74. {
  75. int len = ff_get_line(s, buf, maxlen);
  76. while (len > 0 && isspace(buf[len - 1]))
  77. buf[--len] = '\0';
  78. return len;
  79. }
  80. static void free_segment_list(struct variant *var)
  81. {
  82. int i;
  83. for (i = 0; i < var->n_segments; i++)
  84. av_free(var->segments[i]);
  85. av_freep(&var->segments);
  86. var->n_segments = 0;
  87. }
  88. static void free_variant_list(AppleHTTPContext *c)
  89. {
  90. int i;
  91. for (i = 0; i < c->n_variants; i++) {
  92. struct variant *var = c->variants[i];
  93. free_segment_list(var);
  94. av_free_packet(&var->pkt);
  95. if (var->pb)
  96. avio_close(var->pb);
  97. if (var->ctx) {
  98. var->ctx->pb = NULL;
  99. av_close_input_file(var->ctx);
  100. }
  101. av_free(var);
  102. }
  103. av_freep(&c->variants);
  104. c->n_variants = 0;
  105. }
  106. /*
  107. * Used to reset a statically allocated AVPacket to a clean slate,
  108. * containing no data.
  109. */
  110. static void reset_packet(AVPacket *pkt)
  111. {
  112. av_init_packet(pkt);
  113. pkt->data = NULL;
  114. }
  115. static struct variant *new_variant(AppleHTTPContext *c, int bandwidth,
  116. const char *url, const char *base)
  117. {
  118. struct variant *var = av_mallocz(sizeof(struct variant));
  119. if (!var)
  120. return NULL;
  121. reset_packet(&var->pkt);
  122. var->bandwidth = bandwidth;
  123. ff_make_absolute_url(var->url, sizeof(var->url), base, url);
  124. dynarray_add(&c->variants, &c->n_variants, var);
  125. return var;
  126. }
  127. struct variant_info {
  128. char bandwidth[20];
  129. };
  130. static void handle_variant_args(struct variant_info *info, const char *key,
  131. int key_len, char **dest, int *dest_len)
  132. {
  133. if (!strncmp(key, "BANDWIDTH=", key_len)) {
  134. *dest = info->bandwidth;
  135. *dest_len = sizeof(info->bandwidth);
  136. }
  137. }
  138. static int parse_playlist(AppleHTTPContext *c, const char *url,
  139. struct variant *var, AVIOContext *in)
  140. {
  141. int ret = 0, duration = 0, is_segment = 0, is_variant = 0, bandwidth = 0;
  142. char line[1024];
  143. const char *ptr;
  144. int close_in = 0;
  145. if (!in) {
  146. close_in = 1;
  147. if ((ret = avio_open(&in, url, URL_RDONLY)) < 0)
  148. return ret;
  149. }
  150. read_chomp_line(in, line, sizeof(line));
  151. if (strcmp(line, "#EXTM3U")) {
  152. ret = AVERROR_INVALIDDATA;
  153. goto fail;
  154. }
  155. if (var)
  156. free_segment_list(var);
  157. c->finished = 0;
  158. while (!in->eof_reached) {
  159. read_chomp_line(in, line, sizeof(line));
  160. if (av_strstart(line, "#EXT-X-STREAM-INF:", &ptr)) {
  161. struct variant_info info = {{0}};
  162. is_variant = 1;
  163. ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_variant_args,
  164. &info);
  165. bandwidth = atoi(info.bandwidth);
  166. } else if (av_strstart(line, "#EXT-X-TARGETDURATION:", &ptr)) {
  167. c->target_duration = atoi(ptr);
  168. } else if (av_strstart(line, "#EXT-X-MEDIA-SEQUENCE:", &ptr)) {
  169. if (!var) {
  170. var = new_variant(c, 0, url, NULL);
  171. if (!var) {
  172. ret = AVERROR(ENOMEM);
  173. goto fail;
  174. }
  175. }
  176. var->start_seq_no = atoi(ptr);
  177. } else if (av_strstart(line, "#EXT-X-ENDLIST", &ptr)) {
  178. c->finished = 1;
  179. } else if (av_strstart(line, "#EXTINF:", &ptr)) {
  180. is_segment = 1;
  181. duration = atoi(ptr);
  182. } else if (av_strstart(line, "#", NULL)) {
  183. continue;
  184. } else if (line[0]) {
  185. if (is_variant) {
  186. if (!new_variant(c, bandwidth, line, url)) {
  187. ret = AVERROR(ENOMEM);
  188. goto fail;
  189. }
  190. is_variant = 0;
  191. bandwidth = 0;
  192. }
  193. if (is_segment) {
  194. struct segment *seg;
  195. if (!var) {
  196. var = new_variant(c, 0, url, NULL);
  197. if (!var) {
  198. ret = AVERROR(ENOMEM);
  199. goto fail;
  200. }
  201. }
  202. seg = av_malloc(sizeof(struct segment));
  203. if (!seg) {
  204. ret = AVERROR(ENOMEM);
  205. goto fail;
  206. }
  207. seg->duration = duration;
  208. ff_make_absolute_url(seg->url, sizeof(seg->url), url, line);
  209. dynarray_add(&var->segments, &var->n_segments, seg);
  210. is_segment = 0;
  211. }
  212. }
  213. }
  214. c->last_load_time = av_gettime();
  215. fail:
  216. if (close_in)
  217. avio_close(in);
  218. return ret;
  219. }
  220. static int applehttp_read_header(AVFormatContext *s, AVFormatParameters *ap)
  221. {
  222. AppleHTTPContext *c = s->priv_data;
  223. int ret = 0, i, j, stream_offset = 0;
  224. if ((ret = parse_playlist(c, s->filename, NULL, s->pb)) < 0)
  225. goto fail;
  226. if (c->n_variants == 0) {
  227. av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");
  228. ret = AVERROR_EOF;
  229. goto fail;
  230. }
  231. /* If the playlist only contained variants, parse each individual
  232. * variant playlist. */
  233. if (c->n_variants > 1 || c->variants[0]->n_segments == 0) {
  234. for (i = 0; i < c->n_variants; i++) {
  235. struct variant *v = c->variants[i];
  236. if ((ret = parse_playlist(c, v->url, v, NULL)) < 0)
  237. goto fail;
  238. }
  239. }
  240. if (c->variants[0]->n_segments == 0) {
  241. av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");
  242. ret = AVERROR_EOF;
  243. goto fail;
  244. }
  245. /* If this isn't a live stream, calculate the total duration of the
  246. * stream. */
  247. if (c->finished) {
  248. int64_t duration = 0;
  249. for (i = 0; i < c->variants[0]->n_segments; i++)
  250. duration += c->variants[0]->segments[i]->duration;
  251. s->duration = duration * AV_TIME_BASE;
  252. }
  253. c->min_end_seq = INT_MAX;
  254. /* Open the demuxer for each variant */
  255. for (i = 0; i < c->n_variants; i++) {
  256. struct variant *v = c->variants[i];
  257. if (v->n_segments == 0)
  258. continue;
  259. c->max_start_seq = FFMAX(c->max_start_seq, v->start_seq_no);
  260. c->min_end_seq = FFMIN(c->min_end_seq, v->start_seq_no +
  261. v->n_segments);
  262. ret = av_open_input_file(&v->ctx, v->segments[0]->url, NULL, 0, NULL);
  263. if (ret < 0)
  264. goto fail;
  265. avio_close(v->ctx->pb);
  266. v->ctx->pb = NULL;
  267. v->stream_offset = stream_offset;
  268. /* Create new AVStreams for each stream in this variant */
  269. for (j = 0; j < v->ctx->nb_streams; j++) {
  270. AVStream *st = av_new_stream(s, i);
  271. if (!st) {
  272. ret = AVERROR(ENOMEM);
  273. goto fail;
  274. }
  275. avcodec_copy_context(st->codec, v->ctx->streams[j]->codec);
  276. }
  277. stream_offset += v->ctx->nb_streams;
  278. }
  279. c->last_packet_dts = AV_NOPTS_VALUE;
  280. c->cur_seq_no = c->max_start_seq;
  281. /* If this is a live stream with more than 3 segments, start at the
  282. * third last segment. */
  283. if (!c->finished && c->min_end_seq - c->max_start_seq > 3)
  284. c->cur_seq_no = c->min_end_seq - 2;
  285. return 0;
  286. fail:
  287. free_variant_list(c);
  288. return ret;
  289. }
  290. static int open_variant(AppleHTTPContext *c, struct variant *var, int skip)
  291. {
  292. int ret;
  293. if (c->cur_seq_no < var->start_seq_no) {
  294. av_log(NULL, AV_LOG_WARNING,
  295. "seq %d not available in variant %s, skipping\n",
  296. var->start_seq_no, var->url);
  297. return 0;
  298. }
  299. if (c->cur_seq_no - var->start_seq_no >= var->n_segments)
  300. return c->finished ? AVERROR_EOF : 0;
  301. ret = avio_open(&var->pb,
  302. var->segments[c->cur_seq_no - var->start_seq_no]->url,
  303. URL_RDONLY);
  304. if (ret < 0)
  305. return ret;
  306. var->ctx->pb = var->pb;
  307. /* If this is a new segment in parallel with another one already opened,
  308. * skip ahead so they're all at the same dts. */
  309. if (skip && c->last_packet_dts != AV_NOPTS_VALUE) {
  310. while (1) {
  311. ret = av_read_frame(var->ctx, &var->pkt);
  312. if (ret < 0) {
  313. if (ret == AVERROR_EOF) {
  314. reset_packet(&var->pkt);
  315. return 0;
  316. }
  317. return ret;
  318. }
  319. if (var->pkt.dts >= c->last_packet_dts)
  320. break;
  321. av_free_packet(&var->pkt);
  322. }
  323. }
  324. return 0;
  325. }
  326. static int applehttp_read_packet(AVFormatContext *s, AVPacket *pkt)
  327. {
  328. AppleHTTPContext *c = s->priv_data;
  329. int ret, i, minvariant = -1, first = 1, needed = 0, changed = 0,
  330. variants = 0;
  331. /* Recheck the discard flags - which streams are desired at the moment */
  332. for (i = 0; i < c->n_variants; i++)
  333. c->variants[i]->needed = 0;
  334. for (i = 0; i < s->nb_streams; i++) {
  335. AVStream *st = s->streams[i];
  336. struct variant *var = c->variants[s->streams[i]->id];
  337. if (st->discard < AVDISCARD_ALL) {
  338. var->needed = 1;
  339. needed++;
  340. }
  341. /* Copy the discard flag to the chained demuxer, to indicate which
  342. * streams are desired. */
  343. var->ctx->streams[i - var->stream_offset]->discard = st->discard;
  344. }
  345. if (!needed)
  346. return AVERROR_EOF;
  347. start:
  348. for (i = 0; i < c->n_variants; i++) {
  349. struct variant *var = c->variants[i];
  350. /* Close unneeded streams, open newly requested streams */
  351. if (var->pb && !var->needed) {
  352. av_log(s, AV_LOG_DEBUG,
  353. "Closing variant stream %d, no longer needed\n", i);
  354. av_free_packet(&var->pkt);
  355. reset_packet(&var->pkt);
  356. avio_close(var->pb);
  357. var->pb = NULL;
  358. changed = 1;
  359. } else if (!var->pb && var->needed) {
  360. if (first)
  361. av_log(s, AV_LOG_DEBUG, "Opening variant stream %d\n", i);
  362. if (first && !c->finished)
  363. if ((ret = parse_playlist(c, var->url, var, NULL)) < 0)
  364. return ret;
  365. ret = open_variant(c, var, first);
  366. if (ret < 0)
  367. return ret;
  368. changed = 1;
  369. }
  370. /* Count the number of open variants */
  371. if (var->pb)
  372. variants++;
  373. /* Make sure we've got one buffered packet from each open variant
  374. * stream */
  375. if (var->pb && !var->pkt.data) {
  376. ret = av_read_frame(var->ctx, &var->pkt);
  377. if (ret < 0) {
  378. if (!var->pb->eof_reached)
  379. return ret;
  380. reset_packet(&var->pkt);
  381. }
  382. }
  383. /* Check if this stream has the packet with the lowest dts */
  384. if (var->pkt.data) {
  385. if (minvariant < 0 ||
  386. var->pkt.dts < c->variants[minvariant]->pkt.dts)
  387. minvariant = i;
  388. }
  389. }
  390. if (first && changed)
  391. av_log(s, AV_LOG_INFO, "Receiving %d variant streams\n", variants);
  392. /* If we got a packet, return it */
  393. if (minvariant >= 0) {
  394. *pkt = c->variants[minvariant]->pkt;
  395. pkt->stream_index += c->variants[minvariant]->stream_offset;
  396. reset_packet(&c->variants[minvariant]->pkt);
  397. c->last_packet_dts = pkt->dts;
  398. return 0;
  399. }
  400. /* No more packets - eof reached in all variant streams, close the
  401. * current segments. */
  402. for (i = 0; i < c->n_variants; i++) {
  403. struct variant *var = c->variants[i];
  404. if (var->pb) {
  405. avio_close(var->pb);
  406. var->pb = NULL;
  407. }
  408. }
  409. /* Indicate that we're opening the next segment, not opening a new
  410. * variant stream in parallel, so we shouldn't try to skip ahead. */
  411. first = 0;
  412. c->cur_seq_no++;
  413. reload:
  414. if (!c->finished) {
  415. /* If this is a live stream and target_duration has elapsed since
  416. * the last playlist reload, reload the variant playlists now. */
  417. int64_t now = av_gettime();
  418. if (now - c->last_load_time >= c->target_duration*1000000) {
  419. c->max_start_seq = 0;
  420. c->min_end_seq = INT_MAX;
  421. for (i = 0; i < c->n_variants; i++) {
  422. struct variant *var = c->variants[i];
  423. if (var->needed) {
  424. if ((ret = parse_playlist(c, var->url, var, NULL)) < 0)
  425. return ret;
  426. c->max_start_seq = FFMAX(c->max_start_seq,
  427. var->start_seq_no);
  428. c->min_end_seq = FFMIN(c->min_end_seq,
  429. var->start_seq_no + var->n_segments);
  430. }
  431. }
  432. }
  433. }
  434. if (c->cur_seq_no < c->max_start_seq) {
  435. av_log(NULL, AV_LOG_WARNING,
  436. "skipping %d segments ahead, expired from playlists\n",
  437. c->max_start_seq - c->cur_seq_no);
  438. c->cur_seq_no = c->max_start_seq;
  439. }
  440. /* If more segments exist, open the next one */
  441. if (c->cur_seq_no < c->min_end_seq)
  442. goto start;
  443. /* We've reached the end of the playlists - return eof if this is a
  444. * non-live stream, wait until the next playlist reload if it is live. */
  445. if (c->finished)
  446. return AVERROR_EOF;
  447. while (av_gettime() - c->last_load_time < c->target_duration*1000000) {
  448. if (url_interrupt_cb())
  449. return AVERROR_EXIT;
  450. usleep(100*1000);
  451. }
  452. /* Enough time has elapsed since the last reload */
  453. goto reload;
  454. }
  455. static int applehttp_close(AVFormatContext *s)
  456. {
  457. AppleHTTPContext *c = s->priv_data;
  458. free_variant_list(c);
  459. return 0;
  460. }
  461. static int applehttp_read_seek(AVFormatContext *s, int stream_index,
  462. int64_t timestamp, int flags)
  463. {
  464. AppleHTTPContext *c = s->priv_data;
  465. int64_t pos = 0;
  466. int i;
  467. struct variant *var = c->variants[0];
  468. if ((flags & AVSEEK_FLAG_BYTE) || !c->finished)
  469. return AVERROR(ENOSYS);
  470. /* Reset the variants */
  471. c->last_packet_dts = AV_NOPTS_VALUE;
  472. for (i = 0; i < c->n_variants; i++) {
  473. struct variant *var = c->variants[i];
  474. if (var->pb) {
  475. avio_close(var->pb);
  476. var->pb = NULL;
  477. }
  478. av_free_packet(&var->pkt);
  479. reset_packet(&var->pkt);
  480. }
  481. timestamp = av_rescale_rnd(timestamp, 1, stream_index >= 0 ?
  482. s->streams[stream_index]->time_base.den :
  483. AV_TIME_BASE, flags & AVSEEK_FLAG_BACKWARD ?
  484. AV_ROUND_DOWN : AV_ROUND_UP);
  485. /* Locate the segment that contains the target timestamp */
  486. for (i = 0; i < var->n_segments; i++) {
  487. if (timestamp >= pos && timestamp < pos + var->segments[i]->duration) {
  488. c->cur_seq_no = var->start_seq_no + i;
  489. return 0;
  490. }
  491. pos += var->segments[i]->duration;
  492. }
  493. return AVERROR(EIO);
  494. }
  495. static int applehttp_probe(AVProbeData *p)
  496. {
  497. /* Require #EXTM3U at the start, and either one of the ones below
  498. * somewhere for a proper match. */
  499. if (strncmp(p->buf, "#EXTM3U", 7))
  500. return 0;
  501. if (strstr(p->buf, "#EXT-X-STREAM-INF:") ||
  502. strstr(p->buf, "#EXT-X-TARGETDURATION:") ||
  503. strstr(p->buf, "#EXT-X-MEDIA-SEQUENCE:"))
  504. return AVPROBE_SCORE_MAX;
  505. return 0;
  506. }
  507. AVInputFormat ff_applehttp_demuxer = {
  508. "applehttp",
  509. NULL_IF_CONFIG_SMALL("Apple HTTP Live Streaming format"),
  510. sizeof(AppleHTTPContext),
  511. applehttp_probe,
  512. applehttp_read_header,
  513. applehttp_read_packet,
  514. applehttp_close,
  515. applehttp_read_seek,
  516. };