00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00028 #include "libavutil/avstring.h"
00029 #include "libavutil/intreadwrite.h"
00030 #include "libavutil/opt.h"
00031 #include "libavutil/dict.h"
00032 #include "avformat.h"
00033 #include "internal.h"
00034 #include <unistd.h>
00035 #include "avio_internal.h"
00036 #include "url.h"
00037
00038 #define INITIAL_BUFFER_SIZE 32768
00039
00040
00041
00042
00043
00044
00045
00046
00047
00048
00049
00050
00051
00052 enum KeyType {
00053 KEY_NONE,
00054 KEY_AES_128,
00055 };
00056
00057 struct segment {
00058 int duration;
00059 char url[MAX_URL_SIZE];
00060 char key[MAX_URL_SIZE];
00061 enum KeyType key_type;
00062 uint8_t iv[16];
00063 };
00064
00065
00066
00067
00068
00069
00070 struct variant {
00071 int bandwidth;
00072 char url[MAX_URL_SIZE];
00073 AVIOContext pb;
00074 uint8_t* read_buffer;
00075 URLContext *input;
00076 AVFormatContext *parent;
00077 int index;
00078 AVFormatContext *ctx;
00079 AVPacket pkt;
00080 int stream_offset;
00081
00082 int finished;
00083 int target_duration;
00084 int start_seq_no;
00085 int n_segments;
00086 struct segment **segments;
00087 int needed, cur_needed;
00088 int cur_seq_no;
00089 int64_t last_load_time;
00090
00091 char key_url[MAX_URL_SIZE];
00092 uint8_t key[16];
00093 };
00094
00095 typedef struct AppleHTTPContext {
00096 int n_variants;
00097 struct variant **variants;
00098 int cur_seq_no;
00099 int end_of_segment;
00100 int first_packet;
00101 } AppleHTTPContext;
00102
00103 static int read_chomp_line(AVIOContext *s, char *buf, int maxlen)
00104 {
00105 int len = ff_get_line(s, buf, maxlen);
00106 while (len > 0 && isspace(buf[len - 1]))
00107 buf[--len] = '\0';
00108 return len;
00109 }
00110
00111 static void free_segment_list(struct variant *var)
00112 {
00113 int i;
00114 for (i = 0; i < var->n_segments; i++)
00115 av_free(var->segments[i]);
00116 av_freep(&var->segments);
00117 var->n_segments = 0;
00118 }
00119
00120 static void free_variant_list(AppleHTTPContext *c)
00121 {
00122 int i;
00123 for (i = 0; i < c->n_variants; i++) {
00124 struct variant *var = c->variants[i];
00125 free_segment_list(var);
00126 av_free_packet(&var->pkt);
00127 av_free(var->pb.buffer);
00128 if (var->input)
00129 ffurl_close(var->input);
00130 if (var->ctx) {
00131 var->ctx->pb = NULL;
00132 av_close_input_file(var->ctx);
00133 }
00134 av_free(var);
00135 }
00136 av_freep(&c->variants);
00137 c->n_variants = 0;
00138 }
00139
00140
00141
00142
00143
00144 static void reset_packet(AVPacket *pkt)
00145 {
00146 av_init_packet(pkt);
00147 pkt->data = NULL;
00148 }
00149
00150 static struct variant *new_variant(AppleHTTPContext *c, int bandwidth,
00151 const char *url, const char *base)
00152 {
00153 struct variant *var = av_mallocz(sizeof(struct variant));
00154 if (!var)
00155 return NULL;
00156 reset_packet(&var->pkt);
00157 var->bandwidth = bandwidth;
00158 ff_make_absolute_url(var->url, sizeof(var->url), base, url);
00159 dynarray_add(&c->variants, &c->n_variants, var);
00160 return var;
00161 }
00162
00163 struct variant_info {
00164 char bandwidth[20];
00165 };
00166
00167 static void handle_variant_args(struct variant_info *info, const char *key,
00168 int key_len, char **dest, int *dest_len)
00169 {
00170 if (!strncmp(key, "BANDWIDTH=", key_len)) {
00171 *dest = info->bandwidth;
00172 *dest_len = sizeof(info->bandwidth);
00173 }
00174 }
00175
00176 struct key_info {
00177 char uri[MAX_URL_SIZE];
00178 char method[10];
00179 char iv[35];
00180 };
00181
00182 static void handle_key_args(struct key_info *info, const char *key,
00183 int key_len, char **dest, int *dest_len)
00184 {
00185 if (!strncmp(key, "METHOD=", key_len)) {
00186 *dest = info->method;
00187 *dest_len = sizeof(info->method);
00188 } else if (!strncmp(key, "URI=", key_len)) {
00189 *dest = info->uri;
00190 *dest_len = sizeof(info->uri);
00191 } else if (!strncmp(key, "IV=", key_len)) {
00192 *dest = info->iv;
00193 *dest_len = sizeof(info->iv);
00194 }
00195 }
00196
00197 static int parse_playlist(AppleHTTPContext *c, const char *url,
00198 struct variant *var, AVIOContext *in)
00199 {
00200 int ret = 0, duration = 0, is_segment = 0, is_variant = 0, bandwidth = 0;
00201 enum KeyType key_type = KEY_NONE;
00202 uint8_t iv[16] = "";
00203 int has_iv = 0;
00204 char key[MAX_URL_SIZE];
00205 char line[1024];
00206 const char *ptr;
00207 int close_in = 0;
00208
00209 if (!in) {
00210 close_in = 1;
00211 if ((ret = avio_open(&in, url, AVIO_RDONLY)) < 0)
00212 return ret;
00213 }
00214
00215 read_chomp_line(in, line, sizeof(line));
00216 if (strcmp(line, "#EXTM3U")) {
00217 ret = AVERROR_INVALIDDATA;
00218 goto fail;
00219 }
00220
00221 if (var) {
00222 free_segment_list(var);
00223 var->finished = 0;
00224 }
00225 while (!url_feof(in)) {
00226 read_chomp_line(in, line, sizeof(line));
00227 if (av_strstart(line, "#EXT-X-STREAM-INF:", &ptr)) {
00228 struct variant_info info = {{0}};
00229 is_variant = 1;
00230 ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_variant_args,
00231 &info);
00232 bandwidth = atoi(info.bandwidth);
00233 } else if (av_strstart(line, "#EXT-X-KEY:", &ptr)) {
00234 struct key_info info = {{0}};
00235 ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_key_args,
00236 &info);
00237 key_type = KEY_NONE;
00238 has_iv = 0;
00239 if (!strcmp(info.method, "AES-128"))
00240 key_type = KEY_AES_128;
00241 if (!strncmp(info.iv, "0x", 2) || !strncmp(info.iv, "0X", 2)) {
00242 ff_hex_to_data(iv, info.iv + 2);
00243 has_iv = 1;
00244 }
00245 av_strlcpy(key, info.uri, sizeof(key));
00246 } else if (av_strstart(line, "#EXT-X-TARGETDURATION:", &ptr)) {
00247 if (!var) {
00248 var = new_variant(c, 0, url, NULL);
00249 if (!var) {
00250 ret = AVERROR(ENOMEM);
00251 goto fail;
00252 }
00253 }
00254 var->target_duration = atoi(ptr);
00255 } else if (av_strstart(line, "#EXT-X-MEDIA-SEQUENCE:", &ptr)) {
00256 if (!var) {
00257 var = new_variant(c, 0, url, NULL);
00258 if (!var) {
00259 ret = AVERROR(ENOMEM);
00260 goto fail;
00261 }
00262 }
00263 var->start_seq_no = atoi(ptr);
00264 } else if (av_strstart(line, "#EXT-X-ENDLIST", &ptr)) {
00265 if (var)
00266 var->finished = 1;
00267 } else if (av_strstart(line, "#EXTINF:", &ptr)) {
00268 is_segment = 1;
00269 duration = atoi(ptr);
00270 } else if (av_strstart(line, "#", NULL)) {
00271 continue;
00272 } else if (line[0]) {
00273 if (is_variant) {
00274 if (!new_variant(c, bandwidth, line, url)) {
00275 ret = AVERROR(ENOMEM);
00276 goto fail;
00277 }
00278 is_variant = 0;
00279 bandwidth = 0;
00280 }
00281 if (is_segment) {
00282 struct segment *seg;
00283 if (!var) {
00284 var = new_variant(c, 0, url, NULL);
00285 if (!var) {
00286 ret = AVERROR(ENOMEM);
00287 goto fail;
00288 }
00289 }
00290 seg = av_malloc(sizeof(struct segment));
00291 if (!seg) {
00292 ret = AVERROR(ENOMEM);
00293 goto fail;
00294 }
00295 seg->duration = duration;
00296 seg->key_type = key_type;
00297 if (has_iv) {
00298 memcpy(seg->iv, iv, sizeof(iv));
00299 } else {
00300 int seq = var->start_seq_no + var->n_segments;
00301 memset(seg->iv, 0, sizeof(seg->iv));
00302 AV_WB32(seg->iv + 12, seq);
00303 }
00304 ff_make_absolute_url(seg->key, sizeof(seg->key), url, key);
00305 ff_make_absolute_url(seg->url, sizeof(seg->url), url, line);
00306 dynarray_add(&var->segments, &var->n_segments, seg);
00307 is_segment = 0;
00308 }
00309 }
00310 }
00311 if (var)
00312 var->last_load_time = av_gettime();
00313
00314 fail:
00315 if (close_in)
00316 avio_close(in);
00317 return ret;
00318 }
00319
00320 static int open_input(struct variant *var)
00321 {
00322 struct segment *seg = var->segments[var->cur_seq_no - var->start_seq_no];
00323 if (seg->key_type == KEY_NONE) {
00324 return ffurl_open(&var->input, seg->url, AVIO_RDONLY);
00325 } else if (seg->key_type == KEY_AES_128) {
00326 char iv[33], key[33], url[MAX_URL_SIZE];
00327 int ret;
00328 if (strcmp(seg->key, var->key_url)) {
00329 URLContext *uc;
00330 if (ffurl_open(&uc, seg->key, AVIO_RDONLY) == 0) {
00331 if (ffurl_read_complete(uc, var->key, sizeof(var->key))
00332 != sizeof(var->key)) {
00333 av_log(NULL, AV_LOG_ERROR, "Unable to read key file %s\n",
00334 seg->key);
00335 }
00336 ffurl_close(uc);
00337 } else {
00338 av_log(NULL, AV_LOG_ERROR, "Unable to open key file %s\n",
00339 seg->key);
00340 }
00341 av_strlcpy(var->key_url, seg->key, sizeof(var->key_url));
00342 }
00343 ff_data_to_hex(iv, seg->iv, sizeof(seg->iv), 0);
00344 ff_data_to_hex(key, var->key, sizeof(var->key), 0);
00345 iv[32] = key[32] = '\0';
00346 if (strstr(seg->url, "://"))
00347 snprintf(url, sizeof(url), "crypto+%s", seg->url);
00348 else
00349 snprintf(url, sizeof(url), "crypto:%s", seg->url);
00350 if ((ret = ffurl_alloc(&var->input, url, AVIO_RDONLY)) < 0)
00351 return ret;
00352 av_set_string3(var->input->priv_data, "key", key, 0, NULL);
00353 av_set_string3(var->input->priv_data, "iv", iv, 0, NULL);
00354 if ((ret = ffurl_connect(var->input)) < 0) {
00355 ffurl_close(var->input);
00356 var->input = NULL;
00357 return ret;
00358 }
00359 return 0;
00360 }
00361 return AVERROR(ENOSYS);
00362 }
00363
00364 static int read_data(void *opaque, uint8_t *buf, int buf_size)
00365 {
00366 struct variant *v = opaque;
00367 AppleHTTPContext *c = v->parent->priv_data;
00368 int ret, i;
00369
00370 restart:
00371 if (!v->input) {
00372 reload:
00373
00374
00375 if (!v->finished &&
00376 av_gettime() - v->last_load_time >= v->target_duration*1000000 &&
00377 (ret = parse_playlist(c, v->url, v, NULL)) < 0)
00378 return ret;
00379 if (v->cur_seq_no < v->start_seq_no) {
00380 av_log(NULL, AV_LOG_WARNING,
00381 "skipping %d segments ahead, expired from playlists\n",
00382 v->start_seq_no - v->cur_seq_no);
00383 v->cur_seq_no = v->start_seq_no;
00384 }
00385 if (v->cur_seq_no >= v->start_seq_no + v->n_segments) {
00386 if (v->finished)
00387 return AVERROR_EOF;
00388 while (av_gettime() - v->last_load_time <
00389 v->target_duration*1000000) {
00390 if (url_interrupt_cb())
00391 return AVERROR_EXIT;
00392 usleep(100*1000);
00393 }
00394
00395 goto reload;
00396 }
00397
00398 ret = ffurl_open(&v->input,
00399 v->segments[v->cur_seq_no - v->start_seq_no]->url,
00400 AVIO_RDONLY);
00401 if (ret < 0)
00402 return ret;
00403 }
00404 ret = ffurl_read(v->input, buf, buf_size);
00405 if (ret > 0)
00406 return ret;
00407 if (ret < 0 && ret != AVERROR_EOF)
00408 return ret;
00409 ffurl_close(v->input);
00410 v->input = NULL;
00411 v->cur_seq_no++;
00412
00413 c->end_of_segment = 1;
00414 c->cur_seq_no = v->cur_seq_no;
00415
00416 if (v->ctx) {
00417 v->needed = 0;
00418 for (i = v->stream_offset; i < v->stream_offset + v->ctx->nb_streams;
00419 i++) {
00420 if (v->parent->streams[i]->discard < AVDISCARD_ALL)
00421 v->needed = 1;
00422 }
00423 }
00424 if (!v->needed) {
00425 av_log(v->parent, AV_LOG_INFO, "No longer receiving variant %d\n",
00426 v->index);
00427 return AVERROR_EOF;
00428 }
00429 goto restart;
00430 }
00431
00432 static int applehttp_read_header(AVFormatContext *s, AVFormatParameters *ap)
00433 {
00434 AppleHTTPContext *c = s->priv_data;
00435 int ret = 0, i, j, stream_offset = 0;
00436
00437 if ((ret = parse_playlist(c, s->filename, NULL, s->pb)) < 0)
00438 goto fail;
00439
00440 if (c->n_variants == 0) {
00441 av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");
00442 ret = AVERROR_EOF;
00443 goto fail;
00444 }
00445
00446
00447 if (c->n_variants > 1 || c->variants[0]->n_segments == 0) {
00448 for (i = 0; i < c->n_variants; i++) {
00449 struct variant *v = c->variants[i];
00450 if ((ret = parse_playlist(c, v->url, v, NULL)) < 0)
00451 goto fail;
00452 }
00453 }
00454
00455 if (c->variants[0]->n_segments == 0) {
00456 av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");
00457 ret = AVERROR_EOF;
00458 goto fail;
00459 }
00460
00461
00462
00463 if (c->variants[0]->finished) {
00464 int64_t duration = 0;
00465 for (i = 0; i < c->variants[0]->n_segments; i++)
00466 duration += c->variants[0]->segments[i]->duration;
00467 s->duration = duration * AV_TIME_BASE;
00468 }
00469
00470
00471 for (i = 0; i < c->n_variants; i++) {
00472 struct variant *v = c->variants[i];
00473 AVInputFormat *in_fmt = NULL;
00474 char bitrate_str[20];
00475 if (v->n_segments == 0)
00476 continue;
00477
00478 if (!(v->ctx = avformat_alloc_context())) {
00479 ret = AVERROR(ENOMEM);
00480 goto fail;
00481 }
00482
00483 v->index = i;
00484 v->needed = 1;
00485 v->parent = s;
00486
00487
00488
00489 v->cur_seq_no = v->start_seq_no;
00490 if (!v->finished && v->n_segments > 3)
00491 v->cur_seq_no = v->start_seq_no + v->n_segments - 3;
00492
00493 v->read_buffer = av_malloc(INITIAL_BUFFER_SIZE);
00494 ffio_init_context(&v->pb, v->read_buffer, INITIAL_BUFFER_SIZE, 0, v,
00495 read_data, NULL, NULL);
00496 v->pb.seekable = 0;
00497 ret = av_probe_input_buffer(&v->pb, &in_fmt, v->segments[0]->url,
00498 NULL, 0, 0);
00499 if (ret < 0)
00500 goto fail;
00501 v->ctx->pb = &v->pb;
00502 ret = avformat_open_input(&v->ctx, v->segments[0]->url, in_fmt, NULL);
00503 if (ret < 0)
00504 goto fail;
00505 v->stream_offset = stream_offset;
00506 snprintf(bitrate_str, sizeof(bitrate_str), "%d", v->bandwidth);
00507
00508 for (j = 0; j < v->ctx->nb_streams; j++) {
00509 AVStream *st = av_new_stream(s, i);
00510 if (!st) {
00511 ret = AVERROR(ENOMEM);
00512 goto fail;
00513 }
00514 avcodec_copy_context(st->codec, v->ctx->streams[j]->codec);
00515 if (v->bandwidth)
00516 av_dict_set(&st->metadata, "variant_bitrate", bitrate_str,
00517 0);
00518 }
00519 stream_offset += v->ctx->nb_streams;
00520 }
00521
00522 c->first_packet = 1;
00523
00524 return 0;
00525 fail:
00526 free_variant_list(c);
00527 return ret;
00528 }
00529
00530 static int recheck_discard_flags(AVFormatContext *s, int first)
00531 {
00532 AppleHTTPContext *c = s->priv_data;
00533 int i, changed = 0;
00534
00535
00536 for (i = 0; i < c->n_variants; i++)
00537 c->variants[i]->cur_needed = 0;;
00538
00539 for (i = 0; i < s->nb_streams; i++) {
00540 AVStream *st = s->streams[i];
00541 struct variant *var = c->variants[s->streams[i]->id];
00542 if (st->discard < AVDISCARD_ALL)
00543 var->cur_needed = 1;
00544 }
00545 for (i = 0; i < c->n_variants; i++) {
00546 struct variant *v = c->variants[i];
00547 if (v->cur_needed && !v->needed) {
00548 v->needed = 1;
00549 changed = 1;
00550 v->cur_seq_no = c->cur_seq_no;
00551 v->pb.eof_reached = 0;
00552 av_log(s, AV_LOG_INFO, "Now receiving variant %d\n", i);
00553 } else if (first && !v->cur_needed && v->needed) {
00554 if (v->input)
00555 ffurl_close(v->input);
00556 v->input = NULL;
00557 v->needed = 0;
00558 changed = 1;
00559 av_log(s, AV_LOG_INFO, "No longer receiving variant %d\n", i);
00560 }
00561 }
00562 return changed;
00563 }
00564
00565 static int applehttp_read_packet(AVFormatContext *s, AVPacket *pkt)
00566 {
00567 AppleHTTPContext *c = s->priv_data;
00568 int ret, i, minvariant = -1;
00569
00570 if (c->first_packet) {
00571 recheck_discard_flags(s, 1);
00572 c->first_packet = 0;
00573 }
00574
00575 start:
00576 c->end_of_segment = 0;
00577 for (i = 0; i < c->n_variants; i++) {
00578 struct variant *var = c->variants[i];
00579
00580
00581 if (var->needed && !var->pkt.data) {
00582 ret = av_read_frame(var->ctx, &var->pkt);
00583 if (ret < 0) {
00584 if (!url_feof(&var->pb))
00585 return ret;
00586 reset_packet(&var->pkt);
00587 }
00588 }
00589
00590 if (var->pkt.data) {
00591 if (minvariant < 0 ||
00592 var->pkt.dts < c->variants[minvariant]->pkt.dts)
00593 minvariant = i;
00594 }
00595 }
00596 if (c->end_of_segment) {
00597 if (recheck_discard_flags(s, 0))
00598 goto start;
00599 }
00600
00601 if (minvariant >= 0) {
00602 *pkt = c->variants[minvariant]->pkt;
00603 pkt->stream_index += c->variants[minvariant]->stream_offset;
00604 reset_packet(&c->variants[minvariant]->pkt);
00605 return 0;
00606 }
00607 return AVERROR_EOF;
00608 }
00609
00610 static int applehttp_close(AVFormatContext *s)
00611 {
00612 AppleHTTPContext *c = s->priv_data;
00613
00614 free_variant_list(c);
00615 return 0;
00616 }
00617
00618 static int applehttp_read_seek(AVFormatContext *s, int stream_index,
00619 int64_t timestamp, int flags)
00620 {
00621 AppleHTTPContext *c = s->priv_data;
00622 int i, j, ret;
00623
00624 if ((flags & AVSEEK_FLAG_BYTE) || !c->variants[0]->finished)
00625 return AVERROR(ENOSYS);
00626
00627 timestamp = av_rescale_rnd(timestamp, 1, stream_index >= 0 ?
00628 s->streams[stream_index]->time_base.den :
00629 AV_TIME_BASE, flags & AVSEEK_FLAG_BACKWARD ?
00630 AV_ROUND_DOWN : AV_ROUND_UP);
00631 ret = AVERROR(EIO);
00632 for (i = 0; i < c->n_variants; i++) {
00633
00634 struct variant *var = c->variants[i];
00635 int64_t pos = 0;
00636 if (var->input) {
00637 ffurl_close(var->input);
00638 var->input = NULL;
00639 }
00640 av_free_packet(&var->pkt);
00641 reset_packet(&var->pkt);
00642 var->pb.eof_reached = 0;
00643
00644
00645 for (j = 0; j < var->n_segments; j++) {
00646 if (timestamp >= pos &&
00647 timestamp < pos + var->segments[j]->duration) {
00648 var->cur_seq_no = var->start_seq_no + j;
00649 ret = 0;
00650 break;
00651 }
00652 pos += var->segments[j]->duration;
00653 }
00654 }
00655 return ret;
00656 }
00657
00658 static int applehttp_probe(AVProbeData *p)
00659 {
00660
00661
00662 if (strncmp(p->buf, "#EXTM3U", 7))
00663 return 0;
00664 if (strstr(p->buf, "#EXT-X-STREAM-INF:") ||
00665 strstr(p->buf, "#EXT-X-TARGETDURATION:") ||
00666 strstr(p->buf, "#EXT-X-MEDIA-SEQUENCE:"))
00667 return AVPROBE_SCORE_MAX;
00668 return 0;
00669 }
00670
00671 AVInputFormat ff_applehttp_demuxer = {
00672 "applehttp",
00673 NULL_IF_CONFIG_SMALL("Apple HTTP Live Streaming format"),
00674 sizeof(AppleHTTPContext),
00675 applehttp_probe,
00676 applehttp_read_header,
00677 applehttp_read_packet,
00678 applehttp_close,
00679 applehttp_read_seek,
00680 };