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

566 lines
18KB

  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 finished;
  59. int target_duration;
  60. int start_seq_no;
  61. int n_segments;
  62. struct segment **segments;
  63. int needed;
  64. };
  65. typedef struct AppleHTTPContext {
  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. var->finished = 0;
  158. }
  159. while (!in->eof_reached) {
  160. read_chomp_line(in, line, sizeof(line));
  161. if (av_strstart(line, "#EXT-X-STREAM-INF:", &ptr)) {
  162. struct variant_info info = {{0}};
  163. is_variant = 1;
  164. ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_variant_args,
  165. &info);
  166. bandwidth = atoi(info.bandwidth);
  167. } else if (av_strstart(line, "#EXT-X-TARGETDURATION:", &ptr)) {
  168. if (!var) {
  169. var = new_variant(c, 0, url, NULL);
  170. if (!var) {
  171. ret = AVERROR(ENOMEM);
  172. goto fail;
  173. }
  174. }
  175. var->target_duration = atoi(ptr);
  176. } else if (av_strstart(line, "#EXT-X-MEDIA-SEQUENCE:", &ptr)) {
  177. if (!var) {
  178. var = new_variant(c, 0, url, NULL);
  179. if (!var) {
  180. ret = AVERROR(ENOMEM);
  181. goto fail;
  182. }
  183. }
  184. var->start_seq_no = atoi(ptr);
  185. } else if (av_strstart(line, "#EXT-X-ENDLIST", &ptr)) {
  186. if (var)
  187. var->finished = 1;
  188. } else if (av_strstart(line, "#EXTINF:", &ptr)) {
  189. is_segment = 1;
  190. duration = atoi(ptr);
  191. } else if (av_strstart(line, "#", NULL)) {
  192. continue;
  193. } else if (line[0]) {
  194. if (is_variant) {
  195. if (!new_variant(c, bandwidth, line, url)) {
  196. ret = AVERROR(ENOMEM);
  197. goto fail;
  198. }
  199. is_variant = 0;
  200. bandwidth = 0;
  201. }
  202. if (is_segment) {
  203. struct segment *seg;
  204. if (!var) {
  205. var = new_variant(c, 0, url, NULL);
  206. if (!var) {
  207. ret = AVERROR(ENOMEM);
  208. goto fail;
  209. }
  210. }
  211. seg = av_malloc(sizeof(struct segment));
  212. if (!seg) {
  213. ret = AVERROR(ENOMEM);
  214. goto fail;
  215. }
  216. seg->duration = duration;
  217. ff_make_absolute_url(seg->url, sizeof(seg->url), url, line);
  218. dynarray_add(&var->segments, &var->n_segments, seg);
  219. is_segment = 0;
  220. }
  221. }
  222. }
  223. c->last_load_time = av_gettime();
  224. fail:
  225. if (close_in)
  226. avio_close(in);
  227. return ret;
  228. }
  229. static int applehttp_read_header(AVFormatContext *s, AVFormatParameters *ap)
  230. {
  231. AppleHTTPContext *c = s->priv_data;
  232. int ret = 0, i, j, stream_offset = 0;
  233. if ((ret = parse_playlist(c, s->filename, NULL, s->pb)) < 0)
  234. goto fail;
  235. if (c->n_variants == 0) {
  236. av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");
  237. ret = AVERROR_EOF;
  238. goto fail;
  239. }
  240. /* If the playlist only contained variants, parse each individual
  241. * variant playlist. */
  242. if (c->n_variants > 1 || c->variants[0]->n_segments == 0) {
  243. for (i = 0; i < c->n_variants; i++) {
  244. struct variant *v = c->variants[i];
  245. if ((ret = parse_playlist(c, v->url, v, NULL)) < 0)
  246. goto fail;
  247. }
  248. }
  249. if (c->variants[0]->n_segments == 0) {
  250. av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");
  251. ret = AVERROR_EOF;
  252. goto fail;
  253. }
  254. /* If this isn't a live stream, calculate the total duration of the
  255. * stream. */
  256. if (c->variants[0]->finished) {
  257. int64_t duration = 0;
  258. for (i = 0; i < c->variants[0]->n_segments; i++)
  259. duration += c->variants[0]->segments[i]->duration;
  260. s->duration = duration * AV_TIME_BASE;
  261. }
  262. c->min_end_seq = INT_MAX;
  263. /* Open the demuxer for each variant */
  264. for (i = 0; i < c->n_variants; i++) {
  265. struct variant *v = c->variants[i];
  266. if (v->n_segments == 0)
  267. continue;
  268. c->max_start_seq = FFMAX(c->max_start_seq, v->start_seq_no);
  269. c->min_end_seq = FFMIN(c->min_end_seq, v->start_seq_no +
  270. v->n_segments);
  271. ret = av_open_input_file(&v->ctx, v->segments[0]->url, NULL, 0, NULL);
  272. if (ret < 0)
  273. goto fail;
  274. avio_close(v->ctx->pb);
  275. v->ctx->pb = NULL;
  276. v->stream_offset = stream_offset;
  277. /* Create new AVStreams for each stream in this variant */
  278. for (j = 0; j < v->ctx->nb_streams; j++) {
  279. AVStream *st = av_new_stream(s, i);
  280. if (!st) {
  281. ret = AVERROR(ENOMEM);
  282. goto fail;
  283. }
  284. avcodec_copy_context(st->codec, v->ctx->streams[j]->codec);
  285. }
  286. stream_offset += v->ctx->nb_streams;
  287. }
  288. c->last_packet_dts = AV_NOPTS_VALUE;
  289. c->cur_seq_no = c->max_start_seq;
  290. /* If this is a live stream with more than 3 segments, start at the
  291. * third last segment. */
  292. if (!c->variants[0]->finished && c->min_end_seq - c->max_start_seq > 3)
  293. c->cur_seq_no = c->min_end_seq - 2;
  294. return 0;
  295. fail:
  296. free_variant_list(c);
  297. return ret;
  298. }
  299. static int open_variant(AppleHTTPContext *c, struct variant *var, int skip)
  300. {
  301. int ret;
  302. if (c->cur_seq_no < var->start_seq_no) {
  303. av_log(NULL, AV_LOG_WARNING,
  304. "seq %d not available in variant %s, skipping\n",
  305. var->start_seq_no, var->url);
  306. return 0;
  307. }
  308. if (c->cur_seq_no - var->start_seq_no >= var->n_segments)
  309. return c->variants[0]->finished ? AVERROR_EOF : 0;
  310. ret = avio_open(&var->pb,
  311. var->segments[c->cur_seq_no - var->start_seq_no]->url,
  312. URL_RDONLY);
  313. if (ret < 0)
  314. return ret;
  315. var->ctx->pb = var->pb;
  316. /* If this is a new segment in parallel with another one already opened,
  317. * skip ahead so they're all at the same dts. */
  318. if (skip && c->last_packet_dts != AV_NOPTS_VALUE) {
  319. while (1) {
  320. ret = av_read_frame(var->ctx, &var->pkt);
  321. if (ret < 0) {
  322. if (ret == AVERROR_EOF) {
  323. reset_packet(&var->pkt);
  324. return 0;
  325. }
  326. return ret;
  327. }
  328. if (var->pkt.dts >= c->last_packet_dts)
  329. break;
  330. av_free_packet(&var->pkt);
  331. }
  332. }
  333. return 0;
  334. }
  335. static int applehttp_read_packet(AVFormatContext *s, AVPacket *pkt)
  336. {
  337. AppleHTTPContext *c = s->priv_data;
  338. int ret, i, minvariant = -1, first = 1, needed = 0, changed = 0,
  339. variants = 0;
  340. /* Recheck the discard flags - which streams are desired at the moment */
  341. for (i = 0; i < c->n_variants; i++)
  342. c->variants[i]->needed = 0;
  343. for (i = 0; i < s->nb_streams; i++) {
  344. AVStream *st = s->streams[i];
  345. struct variant *var = c->variants[s->streams[i]->id];
  346. if (st->discard < AVDISCARD_ALL) {
  347. var->needed = 1;
  348. needed++;
  349. }
  350. /* Copy the discard flag to the chained demuxer, to indicate which
  351. * streams are desired. */
  352. var->ctx->streams[i - var->stream_offset]->discard = st->discard;
  353. }
  354. if (!needed)
  355. return AVERROR_EOF;
  356. start:
  357. for (i = 0; i < c->n_variants; i++) {
  358. struct variant *var = c->variants[i];
  359. /* Close unneeded streams, open newly requested streams */
  360. if (var->pb && !var->needed) {
  361. av_log(s, AV_LOG_DEBUG,
  362. "Closing variant stream %d, no longer needed\n", i);
  363. av_free_packet(&var->pkt);
  364. reset_packet(&var->pkt);
  365. avio_close(var->pb);
  366. var->pb = NULL;
  367. changed = 1;
  368. } else if (!var->pb && var->needed) {
  369. if (first)
  370. av_log(s, AV_LOG_DEBUG, "Opening variant stream %d\n", i);
  371. if (first && !var->finished)
  372. if ((ret = parse_playlist(c, var->url, var, NULL)) < 0)
  373. return ret;
  374. ret = open_variant(c, var, first);
  375. if (ret < 0)
  376. return ret;
  377. changed = 1;
  378. }
  379. /* Count the number of open variants */
  380. if (var->pb)
  381. variants++;
  382. /* Make sure we've got one buffered packet from each open variant
  383. * stream */
  384. if (var->pb && !var->pkt.data) {
  385. ret = av_read_frame(var->ctx, &var->pkt);
  386. if (ret < 0) {
  387. if (!var->pb->eof_reached)
  388. return ret;
  389. reset_packet(&var->pkt);
  390. }
  391. }
  392. /* Check if this stream has the packet with the lowest dts */
  393. if (var->pkt.data) {
  394. if (minvariant < 0 ||
  395. var->pkt.dts < c->variants[minvariant]->pkt.dts)
  396. minvariant = i;
  397. }
  398. }
  399. if (first && changed)
  400. av_log(s, AV_LOG_INFO, "Receiving %d variant streams\n", variants);
  401. /* If we got a packet, return it */
  402. if (minvariant >= 0) {
  403. *pkt = c->variants[minvariant]->pkt;
  404. pkt->stream_index += c->variants[minvariant]->stream_offset;
  405. reset_packet(&c->variants[minvariant]->pkt);
  406. c->last_packet_dts = pkt->dts;
  407. return 0;
  408. }
  409. /* No more packets - eof reached in all variant streams, close the
  410. * current segments. */
  411. for (i = 0; i < c->n_variants; i++) {
  412. struct variant *var = c->variants[i];
  413. if (var->pb) {
  414. avio_close(var->pb);
  415. var->pb = NULL;
  416. }
  417. }
  418. /* Indicate that we're opening the next segment, not opening a new
  419. * variant stream in parallel, so we shouldn't try to skip ahead. */
  420. first = 0;
  421. c->cur_seq_no++;
  422. reload:
  423. if (!c->variants[0]->finished) {
  424. /* If this is a live stream and target_duration has elapsed since
  425. * the last playlist reload, reload the variant playlists now. */
  426. int64_t now = av_gettime();
  427. if (now - c->last_load_time >= c->variants[0]->target_duration*1000000) {
  428. c->max_start_seq = 0;
  429. c->min_end_seq = INT_MAX;
  430. for (i = 0; i < c->n_variants; i++) {
  431. struct variant *var = c->variants[i];
  432. if (var->needed) {
  433. if ((ret = parse_playlist(c, var->url, var, NULL)) < 0)
  434. return ret;
  435. c->max_start_seq = FFMAX(c->max_start_seq,
  436. var->start_seq_no);
  437. c->min_end_seq = FFMIN(c->min_end_seq,
  438. var->start_seq_no + var->n_segments);
  439. }
  440. }
  441. }
  442. }
  443. if (c->cur_seq_no < c->max_start_seq) {
  444. av_log(NULL, AV_LOG_WARNING,
  445. "skipping %d segments ahead, expired from playlists\n",
  446. c->max_start_seq - c->cur_seq_no);
  447. c->cur_seq_no = c->max_start_seq;
  448. }
  449. /* If more segments exist, open the next one */
  450. if (c->cur_seq_no < c->min_end_seq)
  451. goto start;
  452. /* We've reached the end of the playlists - return eof if this is a
  453. * non-live stream, wait until the next playlist reload if it is live. */
  454. if (c->variants[0]->finished)
  455. return AVERROR_EOF;
  456. while (av_gettime() - c->last_load_time <
  457. c->variants[0]->target_duration*1000000) {
  458. if (url_interrupt_cb())
  459. return AVERROR_EXIT;
  460. usleep(100*1000);
  461. }
  462. /* Enough time has elapsed since the last reload */
  463. goto reload;
  464. }
  465. static int applehttp_close(AVFormatContext *s)
  466. {
  467. AppleHTTPContext *c = s->priv_data;
  468. free_variant_list(c);
  469. return 0;
  470. }
  471. static int applehttp_read_seek(AVFormatContext *s, int stream_index,
  472. int64_t timestamp, int flags)
  473. {
  474. AppleHTTPContext *c = s->priv_data;
  475. int64_t pos = 0;
  476. int i;
  477. struct variant *var = c->variants[0];
  478. if ((flags & AVSEEK_FLAG_BYTE) || !c->variants[0]->finished)
  479. return AVERROR(ENOSYS);
  480. /* Reset the variants */
  481. c->last_packet_dts = AV_NOPTS_VALUE;
  482. for (i = 0; i < c->n_variants; i++) {
  483. struct variant *var = c->variants[i];
  484. if (var->pb) {
  485. avio_close(var->pb);
  486. var->pb = NULL;
  487. }
  488. av_free_packet(&var->pkt);
  489. reset_packet(&var->pkt);
  490. }
  491. timestamp = av_rescale_rnd(timestamp, 1, stream_index >= 0 ?
  492. s->streams[stream_index]->time_base.den :
  493. AV_TIME_BASE, flags & AVSEEK_FLAG_BACKWARD ?
  494. AV_ROUND_DOWN : AV_ROUND_UP);
  495. /* Locate the segment that contains the target timestamp */
  496. for (i = 0; i < var->n_segments; i++) {
  497. if (timestamp >= pos && timestamp < pos + var->segments[i]->duration) {
  498. c->cur_seq_no = var->start_seq_no + i;
  499. return 0;
  500. }
  501. pos += var->segments[i]->duration;
  502. }
  503. return AVERROR(EIO);
  504. }
  505. static int applehttp_probe(AVProbeData *p)
  506. {
  507. /* Require #EXTM3U at the start, and either one of the ones below
  508. * somewhere for a proper match. */
  509. if (strncmp(p->buf, "#EXTM3U", 7))
  510. return 0;
  511. if (strstr(p->buf, "#EXT-X-STREAM-INF:") ||
  512. strstr(p->buf, "#EXT-X-TARGETDURATION:") ||
  513. strstr(p->buf, "#EXT-X-MEDIA-SEQUENCE:"))
  514. return AVPROBE_SCORE_MAX;
  515. return 0;
  516. }
  517. AVInputFormat ff_applehttp_demuxer = {
  518. "applehttp",
  519. NULL_IF_CONFIG_SMALL("Apple HTTP Live Streaming format"),
  520. sizeof(AppleHTTPContext),
  521. applehttp_probe,
  522. applehttp_read_header,
  523. applehttp_read_packet,
  524. applehttp_close,
  525. applehttp_read_seek,
  526. };