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.

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