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.

580 lines
18KB

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