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.

2159 lines
73KB

  1. /*
  2. * Dynamic Adaptive Streaming over HTTP demux
  3. * Copyright (c) 2017 samsamsam@o2.pl based on HLS demux
  4. * Copyright (c) 2017 Steven Liu
  5. *
  6. * This file is part of FFmpeg.
  7. *
  8. * FFmpeg is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU Lesser General Public
  10. * License as published by the Free Software Foundation; either
  11. * version 2.1 of the License, or (at your option) any later version.
  12. *
  13. * FFmpeg is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  16. * Lesser General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU Lesser General Public
  19. * License along with FFmpeg; if not, write to the Free Software
  20. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  21. */
  22. #include <libxml/parser.h>
  23. #include "libavutil/intreadwrite.h"
  24. #include "libavutil/opt.h"
  25. #include "libavutil/time.h"
  26. #include "libavutil/parseutils.h"
  27. #include "internal.h"
  28. #include "avio_internal.h"
  29. #include "dash.h"
  30. #define INITIAL_BUFFER_SIZE 32768
  31. struct fragment {
  32. int64_t url_offset;
  33. int64_t size;
  34. char *url;
  35. };
  36. /*
  37. * reference to : ISO_IEC_23009-1-DASH-2012
  38. * Section: 5.3.9.6.2
  39. * Table: Table 17 — Semantics of SegmentTimeline element
  40. * */
  41. struct timeline {
  42. /* starttime: Element or Attribute Name
  43. * specifies the MPD start time, in @timescale units,
  44. * the first Segment in the series starts relative to the beginning of the Period.
  45. * The value of this attribute must be equal to or greater than the sum of the previous S
  46. * element earliest presentation time and the sum of the contiguous Segment durations.
  47. * If the value of the attribute is greater than what is expressed by the previous S element,
  48. * it expresses discontinuities in the timeline.
  49. * If not present then the value shall be assumed to be zero for the first S element
  50. * and for the subsequent S elements, the value shall be assumed to be the sum of
  51. * the previous S element's earliest presentation time and contiguous duration
  52. * (i.e. previous S@starttime + @duration * (@repeat + 1)).
  53. * */
  54. int64_t starttime;
  55. /* repeat: Element or Attribute Name
  56. * specifies the repeat count of the number of following contiguous Segments with
  57. * the same duration expressed by the value of @duration. This value is zero-based
  58. * (e.g. a value of three means four Segments in the contiguous series).
  59. * */
  60. int64_t repeat;
  61. /* duration: Element or Attribute Name
  62. * specifies the Segment duration, in units of the value of the @timescale.
  63. * */
  64. int64_t duration;
  65. };
  66. /*
  67. * Each playlist has its own demuxer. If it is currently active,
  68. * it has an opened AVIOContext too, and potentially an AVPacket
  69. * containing the next packet from this stream.
  70. */
  71. struct representation {
  72. char *url_template;
  73. AVIOContext pb;
  74. AVIOContext *input;
  75. AVFormatContext *parent;
  76. AVFormatContext *ctx;
  77. AVPacket pkt;
  78. int rep_idx;
  79. int rep_count;
  80. int stream_index;
  81. enum AVMediaType type;
  82. char id[20];
  83. int bandwidth;
  84. AVRational framerate;
  85. AVStream *assoc_stream; /* demuxer stream associated with this representation */
  86. int n_fragments;
  87. struct fragment **fragments; /* VOD list of fragment for profile */
  88. int n_timelines;
  89. struct timeline **timelines;
  90. int64_t first_seq_no;
  91. int64_t last_seq_no;
  92. int64_t start_number; /* used in case when we have dynamic list of segment to know which segments are new one*/
  93. int64_t fragment_duration;
  94. int64_t fragment_timescale;
  95. int64_t presentation_timeoffset;
  96. int64_t cur_seq_no;
  97. int64_t cur_seg_offset;
  98. int64_t cur_seg_size;
  99. struct fragment *cur_seg;
  100. /* Currently active Media Initialization Section */
  101. struct fragment *init_section;
  102. uint8_t *init_sec_buf;
  103. uint32_t init_sec_buf_size;
  104. uint32_t init_sec_data_len;
  105. uint32_t init_sec_buf_read_offset;
  106. int64_t cur_timestamp;
  107. int is_restart_needed;
  108. };
  109. typedef struct DASHContext {
  110. const AVClass *class;
  111. char *base_url;
  112. int n_videos;
  113. struct representation **videos;
  114. int n_audios;
  115. struct representation **audios;
  116. /* MediaPresentationDescription Attribute */
  117. uint64_t media_presentation_duration;
  118. uint64_t suggested_presentation_delay;
  119. uint64_t availability_start_time;
  120. uint64_t publish_time;
  121. uint64_t minimum_update_period;
  122. uint64_t time_shift_buffer_depth;
  123. uint64_t min_buffer_time;
  124. /* Period Attribute */
  125. uint64_t period_duration;
  126. uint64_t period_start;
  127. int is_live;
  128. AVIOInterruptCB *interrupt_callback;
  129. char *user_agent; ///< holds HTTP user agent set as an AVOption to the HTTP protocol context
  130. char *cookies; ///< holds HTTP cookie values set in either the initial response or as an AVOption to the HTTP protocol context
  131. char *headers; ///< holds HTTP headers set as an AVOption to the HTTP protocol context
  132. char *allowed_extensions;
  133. AVDictionary *avio_opts;
  134. int max_url_size;
  135. } DASHContext;
  136. static int ishttp(char *url)
  137. {
  138. const char *proto_name = avio_find_protocol_name(url);
  139. return av_strstart(proto_name, "http", NULL);
  140. }
  141. static int aligned(int val)
  142. {
  143. return ((val + 0x3F) >> 6) << 6;
  144. }
  145. static uint64_t get_current_time_in_sec(void)
  146. {
  147. return av_gettime() / 1000000;
  148. }
  149. static uint64_t get_utc_date_time_insec(AVFormatContext *s, const char *datetime)
  150. {
  151. struct tm timeinfo;
  152. int year = 0;
  153. int month = 0;
  154. int day = 0;
  155. int hour = 0;
  156. int minute = 0;
  157. int ret = 0;
  158. float second = 0.0;
  159. /* ISO-8601 date parser */
  160. if (!datetime)
  161. return 0;
  162. ret = sscanf(datetime, "%d-%d-%dT%d:%d:%fZ", &year, &month, &day, &hour, &minute, &second);
  163. /* year, month, day, hour, minute, second 6 arguments */
  164. if (ret != 6) {
  165. av_log(s, AV_LOG_WARNING, "get_utc_date_time_insec get a wrong time format\n");
  166. }
  167. timeinfo.tm_year = year - 1900;
  168. timeinfo.tm_mon = month - 1;
  169. timeinfo.tm_mday = day;
  170. timeinfo.tm_hour = hour;
  171. timeinfo.tm_min = minute;
  172. timeinfo.tm_sec = (int)second;
  173. return av_timegm(&timeinfo);
  174. }
  175. static uint32_t get_duration_insec(AVFormatContext *s, const char *duration)
  176. {
  177. /* ISO-8601 duration parser */
  178. uint32_t days = 0;
  179. uint32_t hours = 0;
  180. uint32_t mins = 0;
  181. uint32_t secs = 0;
  182. int size = 0;
  183. float value = 0;
  184. char type = '\0';
  185. const char *ptr = duration;
  186. while (*ptr) {
  187. if (*ptr == 'P' || *ptr == 'T') {
  188. ptr++;
  189. continue;
  190. }
  191. if (sscanf(ptr, "%f%c%n", &value, &type, &size) != 2) {
  192. av_log(s, AV_LOG_WARNING, "get_duration_insec get a wrong time format\n");
  193. return 0; /* parser error */
  194. }
  195. switch (type) {
  196. case 'D':
  197. days = (uint32_t)value;
  198. break;
  199. case 'H':
  200. hours = (uint32_t)value;
  201. break;
  202. case 'M':
  203. mins = (uint32_t)value;
  204. break;
  205. case 'S':
  206. secs = (uint32_t)value;
  207. break;
  208. default:
  209. // handle invalid type
  210. break;
  211. }
  212. ptr += size;
  213. }
  214. return ((days * 24 + hours) * 60 + mins) * 60 + secs;
  215. }
  216. static int64_t get_segment_start_time_based_on_timeline(struct representation *pls, int64_t cur_seq_no)
  217. {
  218. int64_t start_time = 0;
  219. int64_t i = 0;
  220. int64_t j = 0;
  221. int64_t num = 0;
  222. if (pls->n_timelines) {
  223. for (i = 0; i < pls->n_timelines; i++) {
  224. if (pls->timelines[i]->starttime > 0) {
  225. start_time = pls->timelines[i]->starttime;
  226. }
  227. if (num == cur_seq_no)
  228. goto finish;
  229. start_time += pls->timelines[i]->duration;
  230. for (j = 0; j < pls->timelines[i]->repeat; j++) {
  231. num++;
  232. if (num == cur_seq_no)
  233. goto finish;
  234. start_time += pls->timelines[i]->duration;
  235. }
  236. num++;
  237. }
  238. }
  239. finish:
  240. return start_time;
  241. }
  242. static int64_t calc_next_seg_no_from_timelines(struct representation *pls, int64_t cur_time)
  243. {
  244. int64_t i = 0;
  245. int64_t j = 0;
  246. int64_t num = 0;
  247. int64_t start_time = 0;
  248. for (i = 0; i < pls->n_timelines; i++) {
  249. if (pls->timelines[i]->starttime > 0) {
  250. start_time = pls->timelines[i]->starttime;
  251. }
  252. if (start_time > cur_time)
  253. goto finish;
  254. start_time += pls->timelines[i]->duration;
  255. for (j = 0; j < pls->timelines[i]->repeat; j++) {
  256. num++;
  257. if (start_time > cur_time)
  258. goto finish;
  259. start_time += pls->timelines[i]->duration;
  260. }
  261. num++;
  262. }
  263. return -1;
  264. finish:
  265. return num;
  266. }
  267. static void free_fragment(struct fragment **seg)
  268. {
  269. if (!(*seg)) {
  270. return;
  271. }
  272. av_freep(&(*seg)->url);
  273. av_freep(seg);
  274. }
  275. static void free_fragment_list(struct representation *pls)
  276. {
  277. int i;
  278. for (i = 0; i < pls->n_fragments; i++) {
  279. free_fragment(&pls->fragments[i]);
  280. }
  281. av_freep(&pls->fragments);
  282. pls->n_fragments = 0;
  283. }
  284. static void free_timelines_list(struct representation *pls)
  285. {
  286. int i;
  287. for (i = 0; i < pls->n_timelines; i++) {
  288. av_freep(&pls->timelines[i]);
  289. }
  290. av_freep(&pls->timelines);
  291. pls->n_timelines = 0;
  292. }
  293. static void free_representation(struct representation *pls)
  294. {
  295. free_fragment_list(pls);
  296. free_timelines_list(pls);
  297. free_fragment(&pls->cur_seg);
  298. free_fragment(&pls->init_section);
  299. av_freep(&pls->init_sec_buf);
  300. av_freep(&pls->pb.buffer);
  301. if (pls->input)
  302. ff_format_io_close(pls->parent, &pls->input);
  303. if (pls->ctx) {
  304. pls->ctx->pb = NULL;
  305. avformat_close_input(&pls->ctx);
  306. }
  307. av_freep(&pls->url_template);
  308. av_freep(&pls);
  309. }
  310. static void free_video_list(DASHContext *c)
  311. {
  312. int i;
  313. for (i = 0; i < c->n_videos; i++) {
  314. struct representation *pls = c->videos[i];
  315. free_representation(pls);
  316. }
  317. av_freep(&c->videos);
  318. c->n_videos = 0;
  319. }
  320. static void free_audio_list(DASHContext *c)
  321. {
  322. int i;
  323. for (i = 0; i < c->n_audios; i++) {
  324. struct representation *pls = c->audios[i];
  325. free_representation(pls);
  326. }
  327. av_freep(&c->audios);
  328. c->n_audios = 0;
  329. }
  330. static void set_httpheader_options(DASHContext *c, AVDictionary **opts)
  331. {
  332. // broker prior HTTP options that should be consistent across requests
  333. av_dict_set(opts, "user-agent", c->user_agent, 0);
  334. av_dict_set(opts, "cookies", c->cookies, 0);
  335. av_dict_set(opts, "headers", c->headers, 0);
  336. if (c->is_live) {
  337. av_dict_set(opts, "seekable", "0", 0);
  338. }
  339. }
  340. static void update_options(char **dest, const char *name, void *src)
  341. {
  342. av_freep(dest);
  343. av_opt_get(src, name, AV_OPT_SEARCH_CHILDREN, (uint8_t**)dest);
  344. if (*dest)
  345. av_freep(dest);
  346. }
  347. static int open_url(AVFormatContext *s, AVIOContext **pb, const char *url,
  348. AVDictionary *opts, AVDictionary *opts2, int *is_http)
  349. {
  350. DASHContext *c = s->priv_data;
  351. AVDictionary *tmp = NULL;
  352. const char *proto_name = NULL;
  353. int ret;
  354. av_dict_copy(&tmp, opts, 0);
  355. av_dict_copy(&tmp, opts2, 0);
  356. if (av_strstart(url, "crypto", NULL)) {
  357. if (url[6] == '+' || url[6] == ':')
  358. proto_name = avio_find_protocol_name(url + 7);
  359. }
  360. if (!proto_name)
  361. proto_name = avio_find_protocol_name(url);
  362. if (!proto_name)
  363. return AVERROR_INVALIDDATA;
  364. // only http(s) & file are allowed
  365. if (av_strstart(proto_name, "file", NULL)) {
  366. if (strcmp(c->allowed_extensions, "ALL") && !av_match_ext(url, c->allowed_extensions)) {
  367. av_log(s, AV_LOG_ERROR,
  368. "Filename extension of \'%s\' is not a common multimedia extension, blocked for security reasons.\n"
  369. "If you wish to override this adjust allowed_extensions, you can set it to \'ALL\' to allow all\n",
  370. url);
  371. return AVERROR_INVALIDDATA;
  372. }
  373. } else if (av_strstart(proto_name, "http", NULL)) {
  374. ;
  375. } else
  376. return AVERROR_INVALIDDATA;
  377. if (!strncmp(proto_name, url, strlen(proto_name)) && url[strlen(proto_name)] == ':')
  378. ;
  379. else if (av_strstart(url, "crypto", NULL) && !strncmp(proto_name, url + 7, strlen(proto_name)) && url[7 + strlen(proto_name)] == ':')
  380. ;
  381. else if (strcmp(proto_name, "file") || !strncmp(url, "file,", 5))
  382. return AVERROR_INVALIDDATA;
  383. av_freep(pb);
  384. ret = avio_open2(pb, url, AVIO_FLAG_READ, c->interrupt_callback, &tmp);
  385. if (ret >= 0) {
  386. // update cookies on http response with setcookies.
  387. char *new_cookies = NULL;
  388. if (!(s->flags & AVFMT_FLAG_CUSTOM_IO))
  389. av_opt_get(*pb, "cookies", AV_OPT_SEARCH_CHILDREN, (uint8_t**)&new_cookies);
  390. if (new_cookies) {
  391. av_free(c->cookies);
  392. c->cookies = new_cookies;
  393. }
  394. av_dict_set(&opts, "cookies", c->cookies, 0);
  395. }
  396. av_dict_free(&tmp);
  397. if (is_http)
  398. *is_http = av_strstart(proto_name, "http", NULL);
  399. return ret;
  400. }
  401. static char *get_content_url(xmlNodePtr *baseurl_nodes,
  402. int n_baseurl_nodes,
  403. int max_url_size,
  404. char *rep_id_val,
  405. char *rep_bandwidth_val,
  406. char *val)
  407. {
  408. int i;
  409. char *text;
  410. char *url = NULL;
  411. char *tmp_str = av_mallocz(max_url_size);
  412. char *tmp_str_2 = av_mallocz(max_url_size);
  413. if (!tmp_str || !tmp_str_2) {
  414. return NULL;
  415. }
  416. for (i = 0; i < n_baseurl_nodes; ++i) {
  417. if (baseurl_nodes[i] &&
  418. baseurl_nodes[i]->children &&
  419. baseurl_nodes[i]->children->type == XML_TEXT_NODE) {
  420. text = xmlNodeGetContent(baseurl_nodes[i]->children);
  421. if (text) {
  422. memset(tmp_str, 0, max_url_size);
  423. memset(tmp_str_2, 0, max_url_size);
  424. ff_make_absolute_url(tmp_str_2, max_url_size, tmp_str, text);
  425. av_strlcpy(tmp_str, tmp_str_2, max_url_size);
  426. xmlFree(text);
  427. }
  428. }
  429. }
  430. if (val)
  431. av_strlcat(tmp_str, (const char*)val, max_url_size);
  432. if (rep_id_val) {
  433. url = av_strireplace(tmp_str, "$RepresentationID$", (const char*)rep_id_val);
  434. if (!url) {
  435. goto end;
  436. }
  437. av_strlcpy(tmp_str, url, max_url_size);
  438. }
  439. if (rep_bandwidth_val && tmp_str[0] != '\0') {
  440. // free any previously assigned url before reassigning
  441. av_free(url);
  442. url = av_strireplace(tmp_str, "$Bandwidth$", (const char*)rep_bandwidth_val);
  443. if (!url) {
  444. goto end;
  445. }
  446. }
  447. end:
  448. av_free(tmp_str);
  449. av_free(tmp_str_2);
  450. return url;
  451. }
  452. static char *get_val_from_nodes_tab(xmlNodePtr *nodes, const int n_nodes, const char *attrname)
  453. {
  454. int i;
  455. char *val;
  456. for (i = 0; i < n_nodes; ++i) {
  457. if (nodes[i]) {
  458. val = xmlGetProp(nodes[i], attrname);
  459. if (val)
  460. return val;
  461. }
  462. }
  463. return NULL;
  464. }
  465. static xmlNodePtr find_child_node_by_name(xmlNodePtr rootnode, const char *nodename)
  466. {
  467. xmlNodePtr node = rootnode;
  468. if (!node) {
  469. return NULL;
  470. }
  471. node = xmlFirstElementChild(node);
  472. while (node) {
  473. if (!av_strcasecmp(node->name, nodename)) {
  474. return node;
  475. }
  476. node = xmlNextElementSibling(node);
  477. }
  478. return NULL;
  479. }
  480. static enum AVMediaType get_content_type(xmlNodePtr node)
  481. {
  482. enum AVMediaType type = AVMEDIA_TYPE_UNKNOWN;
  483. int i = 0;
  484. const char *attr;
  485. char *val = NULL;
  486. if (node) {
  487. for (i = 0; i < 2; i++) {
  488. attr = i ? "mimeType" : "contentType";
  489. val = xmlGetProp(node, attr);
  490. if (val) {
  491. if (av_stristr((const char *)val, "video")) {
  492. type = AVMEDIA_TYPE_VIDEO;
  493. } else if (av_stristr((const char *)val, "audio")) {
  494. type = AVMEDIA_TYPE_AUDIO;
  495. }
  496. xmlFree(val);
  497. }
  498. }
  499. }
  500. return type;
  501. }
  502. static struct fragment * get_Fragment(char *range)
  503. {
  504. struct fragment * seg = av_mallocz(sizeof(struct fragment));
  505. if (!seg)
  506. return NULL;
  507. seg->size = -1;
  508. if (range) {
  509. char *str_end_offset;
  510. char *str_offset = av_strtok(range, "-", &str_end_offset);
  511. seg->url_offset = strtoll(str_offset, NULL, 10);
  512. seg->size = strtoll(str_end_offset, NULL, 10) - seg->url_offset;
  513. }
  514. return seg;
  515. }
  516. static int parse_manifest_segmenturlnode(AVFormatContext *s, struct representation *rep,
  517. xmlNodePtr fragmenturl_node,
  518. xmlNodePtr *baseurl_nodes,
  519. char *rep_id_val,
  520. char *rep_bandwidth_val)
  521. {
  522. DASHContext *c = s->priv_data;
  523. char *initialization_val = NULL;
  524. char *media_val = NULL;
  525. char *range_val = NULL;
  526. int max_url_size = c ? c->max_url_size: MAX_URL_SIZE;
  527. if (!av_strcasecmp(fragmenturl_node->name, (const char *)"Initialization")) {
  528. initialization_val = xmlGetProp(fragmenturl_node, "sourceURL");
  529. range_val = xmlGetProp(fragmenturl_node, "range");
  530. if (initialization_val || range_val) {
  531. rep->init_section = get_Fragment(range_val);
  532. if (!rep->init_section) {
  533. xmlFree(initialization_val);
  534. xmlFree(range_val);
  535. return AVERROR(ENOMEM);
  536. }
  537. rep->init_section->url = get_content_url(baseurl_nodes, 4,
  538. max_url_size,
  539. rep_id_val,
  540. rep_bandwidth_val,
  541. initialization_val);
  542. if (!rep->init_section->url) {
  543. av_free(rep->init_section);
  544. xmlFree(initialization_val);
  545. xmlFree(range_val);
  546. return AVERROR(ENOMEM);
  547. }
  548. xmlFree(initialization_val);
  549. xmlFree(range_val);
  550. }
  551. } else if (!av_strcasecmp(fragmenturl_node->name, (const char *)"SegmentURL")) {
  552. media_val = xmlGetProp(fragmenturl_node, "media");
  553. range_val = xmlGetProp(fragmenturl_node, "mediaRange");
  554. if (media_val || range_val) {
  555. struct fragment *seg = get_Fragment(range_val);
  556. if (!seg) {
  557. xmlFree(media_val);
  558. xmlFree(range_val);
  559. return AVERROR(ENOMEM);
  560. }
  561. seg->url = get_content_url(baseurl_nodes, 4,
  562. max_url_size,
  563. rep_id_val,
  564. rep_bandwidth_val,
  565. media_val);
  566. if (!seg->url) {
  567. av_free(seg);
  568. xmlFree(media_val);
  569. xmlFree(range_val);
  570. return AVERROR(ENOMEM);
  571. }
  572. dynarray_add(&rep->fragments, &rep->n_fragments, seg);
  573. xmlFree(media_val);
  574. xmlFree(range_val);
  575. }
  576. }
  577. return 0;
  578. }
  579. static int parse_manifest_segmenttimeline(AVFormatContext *s, struct representation *rep,
  580. xmlNodePtr fragment_timeline_node)
  581. {
  582. xmlAttrPtr attr = NULL;
  583. char *val = NULL;
  584. if (!av_strcasecmp(fragment_timeline_node->name, (const char *)"S")) {
  585. struct timeline *tml = av_mallocz(sizeof(struct timeline));
  586. if (!tml) {
  587. return AVERROR(ENOMEM);
  588. }
  589. attr = fragment_timeline_node->properties;
  590. while (attr) {
  591. val = xmlGetProp(fragment_timeline_node, attr->name);
  592. if (!val) {
  593. av_log(s, AV_LOG_WARNING, "parse_manifest_segmenttimeline attr->name = %s val is NULL\n", attr->name);
  594. continue;
  595. }
  596. if (!av_strcasecmp(attr->name, (const char *)"t")) {
  597. tml->starttime = (int64_t)strtoll(val, NULL, 10);
  598. } else if (!av_strcasecmp(attr->name, (const char *)"r")) {
  599. tml->repeat =(int64_t) strtoll(val, NULL, 10);
  600. } else if (!av_strcasecmp(attr->name, (const char *)"d")) {
  601. tml->duration = (int64_t)strtoll(val, NULL, 10);
  602. }
  603. attr = attr->next;
  604. xmlFree(val);
  605. }
  606. dynarray_add(&rep->timelines, &rep->n_timelines, tml);
  607. }
  608. return 0;
  609. }
  610. static int resolve_content_path(AVFormatContext *s, const char *url, int *max_url_size, xmlNodePtr *baseurl_nodes, int n_baseurl_nodes) {
  611. char *tmp_str = NULL;
  612. char *path = NULL;
  613. char *mpdName = NULL;
  614. xmlNodePtr node = NULL;
  615. char *baseurl = NULL;
  616. char *root_url = NULL;
  617. char *text = NULL;
  618. int isRootHttp = 0;
  619. char token ='/';
  620. int start = 0;
  621. int rootId = 0;
  622. int updated = 0;
  623. int size = 0;
  624. int i;
  625. int tmp_max_url_size = strlen(url);
  626. for (i = n_baseurl_nodes-1; i >= 0 ; i--) {
  627. text = xmlNodeGetContent(baseurl_nodes[i]);
  628. if (!text)
  629. continue;
  630. tmp_max_url_size += strlen(text);
  631. if (ishttp(text)) {
  632. xmlFree(text);
  633. break;
  634. }
  635. xmlFree(text);
  636. }
  637. tmp_max_url_size = aligned(tmp_max_url_size);
  638. text = av_mallocz(tmp_max_url_size);
  639. if (!text) {
  640. updated = AVERROR(ENOMEM);
  641. goto end;
  642. }
  643. av_strlcpy(text, url, strlen(url)+1);
  644. while (mpdName = av_strtok(text, "/", &text)) {
  645. size = strlen(mpdName);
  646. }
  647. path = av_mallocz(tmp_max_url_size);
  648. tmp_str = av_mallocz(tmp_max_url_size);
  649. if (!tmp_str || !path) {
  650. updated = AVERROR(ENOMEM);
  651. goto end;
  652. }
  653. av_strlcpy (path, url, strlen(url) - size + 1);
  654. for (rootId = n_baseurl_nodes - 1; rootId > 0; rootId --) {
  655. if (!(node = baseurl_nodes[rootId])) {
  656. continue;
  657. }
  658. if (ishttp(xmlNodeGetContent(node))) {
  659. break;
  660. }
  661. }
  662. node = baseurl_nodes[rootId];
  663. baseurl = xmlNodeGetContent(node);
  664. root_url = (av_strcasecmp(baseurl, "")) ? baseurl : path;
  665. if (node) {
  666. xmlNodeSetContent(node, root_url);
  667. updated = 1;
  668. }
  669. size = strlen(root_url);
  670. isRootHttp = ishttp(root_url);
  671. if (root_url[size - 1] != token) {
  672. av_strlcat(root_url, "/", size + 2);
  673. size += 2;
  674. }
  675. for (i = 0; i < n_baseurl_nodes; ++i) {
  676. if (i == rootId) {
  677. continue;
  678. }
  679. text = xmlNodeGetContent(baseurl_nodes[i]);
  680. if (text) {
  681. memset(tmp_str, 0, strlen(tmp_str));
  682. if (!ishttp(text) && isRootHttp) {
  683. av_strlcpy(tmp_str, root_url, size + 1);
  684. }
  685. start = (text[0] == token);
  686. av_strlcat(tmp_str, text + start, tmp_max_url_size);
  687. xmlNodeSetContent(baseurl_nodes[i], tmp_str);
  688. updated = 1;
  689. xmlFree(text);
  690. }
  691. }
  692. end:
  693. if (tmp_max_url_size > *max_url_size) {
  694. *max_url_size = tmp_max_url_size;
  695. }
  696. av_free(path);
  697. av_free(tmp_str);
  698. return updated;
  699. }
  700. static int parse_manifest_representation(AVFormatContext *s, const char *url,
  701. xmlNodePtr node,
  702. xmlNodePtr adaptionset_node,
  703. xmlNodePtr mpd_baseurl_node,
  704. xmlNodePtr period_baseurl_node,
  705. xmlNodePtr period_segmenttemplate_node,
  706. xmlNodePtr period_segmentlist_node,
  707. xmlNodePtr fragment_template_node,
  708. xmlNodePtr content_component_node,
  709. xmlNodePtr adaptionset_baseurl_node,
  710. xmlNodePtr adaptionset_segmentlist_node)
  711. {
  712. int32_t ret = 0;
  713. int32_t audio_rep_idx = 0;
  714. int32_t video_rep_idx = 0;
  715. DASHContext *c = s->priv_data;
  716. struct representation *rep = NULL;
  717. struct fragment *seg = NULL;
  718. xmlNodePtr representation_segmenttemplate_node = NULL;
  719. xmlNodePtr representation_baseurl_node = NULL;
  720. xmlNodePtr representation_segmentlist_node = NULL;
  721. xmlNodePtr segmentlists_tab[2];
  722. xmlNodePtr fragment_timeline_node = NULL;
  723. xmlNodePtr fragment_templates_tab[5];
  724. char *duration_val = NULL;
  725. char *presentation_timeoffset_val = NULL;
  726. char *startnumber_val = NULL;
  727. char *timescale_val = NULL;
  728. char *initialization_val = NULL;
  729. char *media_val = NULL;
  730. xmlNodePtr baseurl_nodes[4];
  731. xmlNodePtr representation_node = node;
  732. char *rep_id_val = xmlGetProp(representation_node, "id");
  733. char *rep_bandwidth_val = xmlGetProp(representation_node, "bandwidth");
  734. char *rep_framerate_val = xmlGetProp(representation_node, "frameRate");
  735. enum AVMediaType type = AVMEDIA_TYPE_UNKNOWN;
  736. // try get information from representation
  737. if (type == AVMEDIA_TYPE_UNKNOWN)
  738. type = get_content_type(representation_node);
  739. // try get information from contentComponen
  740. if (type == AVMEDIA_TYPE_UNKNOWN)
  741. type = get_content_type(content_component_node);
  742. // try get information from adaption set
  743. if (type == AVMEDIA_TYPE_UNKNOWN)
  744. type = get_content_type(adaptionset_node);
  745. if (type == AVMEDIA_TYPE_UNKNOWN) {
  746. av_log(s, AV_LOG_VERBOSE, "Parsing '%s' - skipp not supported representation type\n", url);
  747. } else if (type == AVMEDIA_TYPE_VIDEO || type == AVMEDIA_TYPE_AUDIO) {
  748. // convert selected representation to our internal struct
  749. rep = av_mallocz(sizeof(struct representation));
  750. if (!rep) {
  751. ret = AVERROR(ENOMEM);
  752. goto end;
  753. }
  754. representation_segmenttemplate_node = find_child_node_by_name(representation_node, "SegmentTemplate");
  755. representation_baseurl_node = find_child_node_by_name(representation_node, "BaseURL");
  756. representation_segmentlist_node = find_child_node_by_name(representation_node, "SegmentList");
  757. baseurl_nodes[0] = mpd_baseurl_node;
  758. baseurl_nodes[1] = period_baseurl_node;
  759. baseurl_nodes[2] = adaptionset_baseurl_node;
  760. baseurl_nodes[3] = representation_baseurl_node;
  761. ret = resolve_content_path(s, url, &c->max_url_size, baseurl_nodes, 4);
  762. c->max_url_size = aligned(c->max_url_size + strlen(rep_id_val) + strlen(rep_bandwidth_val));
  763. if (ret == AVERROR(ENOMEM) || ret == 0) {
  764. goto end;
  765. }
  766. if (representation_segmenttemplate_node || fragment_template_node || period_segmenttemplate_node) {
  767. fragment_timeline_node = NULL;
  768. fragment_templates_tab[0] = representation_segmenttemplate_node;
  769. fragment_templates_tab[1] = adaptionset_segmentlist_node;
  770. fragment_templates_tab[2] = fragment_template_node;
  771. fragment_templates_tab[3] = period_segmenttemplate_node;
  772. fragment_templates_tab[4] = period_segmentlist_node;
  773. presentation_timeoffset_val = get_val_from_nodes_tab(fragment_templates_tab, 4, "presentationTimeOffset");
  774. duration_val = get_val_from_nodes_tab(fragment_templates_tab, 4, "duration");
  775. startnumber_val = get_val_from_nodes_tab(fragment_templates_tab, 4, "startNumber");
  776. timescale_val = get_val_from_nodes_tab(fragment_templates_tab, 4, "timescale");
  777. initialization_val = get_val_from_nodes_tab(fragment_templates_tab, 4, "initialization");
  778. media_val = get_val_from_nodes_tab(fragment_templates_tab, 4, "media");
  779. if (initialization_val) {
  780. rep->init_section = av_mallocz(sizeof(struct fragment));
  781. if (!rep->init_section) {
  782. av_free(rep);
  783. ret = AVERROR(ENOMEM);
  784. goto end;
  785. }
  786. c->max_url_size = aligned(c->max_url_size + strlen(initialization_val));
  787. rep->init_section->url = get_content_url(baseurl_nodes, 4, c->max_url_size, rep_id_val, rep_bandwidth_val, initialization_val);
  788. if (!rep->init_section->url) {
  789. av_free(rep->init_section);
  790. av_free(rep);
  791. ret = AVERROR(ENOMEM);
  792. goto end;
  793. }
  794. rep->init_section->size = -1;
  795. xmlFree(initialization_val);
  796. }
  797. if (media_val) {
  798. c->max_url_size = aligned(c->max_url_size + strlen(media_val));
  799. rep->url_template = get_content_url(baseurl_nodes, 4, c->max_url_size, rep_id_val, rep_bandwidth_val, media_val);
  800. xmlFree(media_val);
  801. }
  802. if (presentation_timeoffset_val) {
  803. rep->presentation_timeoffset = (int64_t) strtoll(presentation_timeoffset_val, NULL, 10);
  804. xmlFree(presentation_timeoffset_val);
  805. }
  806. if (duration_val) {
  807. rep->fragment_duration = (int64_t) strtoll(duration_val, NULL, 10);
  808. xmlFree(duration_val);
  809. }
  810. if (timescale_val) {
  811. rep->fragment_timescale = (int64_t) strtoll(timescale_val, NULL, 10);
  812. xmlFree(timescale_val);
  813. }
  814. if (startnumber_val) {
  815. rep->first_seq_no = (int64_t) strtoll(startnumber_val, NULL, 10);
  816. xmlFree(startnumber_val);
  817. }
  818. fragment_timeline_node = find_child_node_by_name(representation_segmenttemplate_node, "SegmentTimeline");
  819. if (!fragment_timeline_node)
  820. fragment_timeline_node = find_child_node_by_name(fragment_template_node, "SegmentTimeline");
  821. if (!fragment_timeline_node)
  822. fragment_timeline_node = find_child_node_by_name(adaptionset_segmentlist_node, "SegmentTimeline");
  823. if (!fragment_timeline_node)
  824. fragment_timeline_node = find_child_node_by_name(period_segmentlist_node, "SegmentTimeline");
  825. if (fragment_timeline_node) {
  826. fragment_timeline_node = xmlFirstElementChild(fragment_timeline_node);
  827. while (fragment_timeline_node) {
  828. ret = parse_manifest_segmenttimeline(s, rep, fragment_timeline_node);
  829. if (ret < 0) {
  830. return ret;
  831. }
  832. fragment_timeline_node = xmlNextElementSibling(fragment_timeline_node);
  833. }
  834. }
  835. } else if (representation_baseurl_node && !representation_segmentlist_node) {
  836. seg = av_mallocz(sizeof(struct fragment));
  837. if (!seg) {
  838. ret = AVERROR(ENOMEM);
  839. goto end;
  840. }
  841. seg->url = get_content_url(baseurl_nodes, 4, c->max_url_size, rep_id_val, rep_bandwidth_val, NULL);
  842. if (!seg->url) {
  843. av_free(seg);
  844. ret = AVERROR(ENOMEM);
  845. goto end;
  846. }
  847. seg->size = -1;
  848. dynarray_add(&rep->fragments, &rep->n_fragments, seg);
  849. } else if (representation_segmentlist_node) {
  850. // TODO: https://www.brendanlong.com/the-structure-of-an-mpeg-dash-mpd.html
  851. // http://www-itec.uni-klu.ac.at/dash/ddash/mpdGenerator.php?fragmentlength=15&type=full
  852. xmlNodePtr fragmenturl_node = NULL;
  853. segmentlists_tab[0] = representation_segmentlist_node;
  854. segmentlists_tab[1] = adaptionset_segmentlist_node;
  855. duration_val = get_val_from_nodes_tab(segmentlists_tab, 2, "duration");
  856. timescale_val = get_val_from_nodes_tab(segmentlists_tab, 2, "timescale");
  857. if (duration_val) {
  858. rep->fragment_duration = (int64_t) strtoll(duration_val, NULL, 10);
  859. xmlFree(duration_val);
  860. }
  861. if (timescale_val) {
  862. rep->fragment_timescale = (int64_t) strtoll(timescale_val, NULL, 10);
  863. xmlFree(timescale_val);
  864. }
  865. fragmenturl_node = xmlFirstElementChild(representation_segmentlist_node);
  866. while (fragmenturl_node) {
  867. ret = parse_manifest_segmenturlnode(s, rep, fragmenturl_node,
  868. baseurl_nodes,
  869. rep_id_val,
  870. rep_bandwidth_val);
  871. if (ret < 0) {
  872. return ret;
  873. }
  874. fragmenturl_node = xmlNextElementSibling(fragmenturl_node);
  875. }
  876. fragment_timeline_node = find_child_node_by_name(representation_segmenttemplate_node, "SegmentTimeline");
  877. if (!fragment_timeline_node)
  878. fragment_timeline_node = find_child_node_by_name(fragment_template_node, "SegmentTimeline");
  879. if (!fragment_timeline_node)
  880. fragment_timeline_node = find_child_node_by_name(adaptionset_segmentlist_node, "SegmentTimeline");
  881. if (!fragment_timeline_node)
  882. fragment_timeline_node = find_child_node_by_name(period_segmentlist_node, "SegmentTimeline");
  883. if (fragment_timeline_node) {
  884. fragment_timeline_node = xmlFirstElementChild(fragment_timeline_node);
  885. while (fragment_timeline_node) {
  886. ret = parse_manifest_segmenttimeline(s, rep, fragment_timeline_node);
  887. if (ret < 0) {
  888. return ret;
  889. }
  890. fragment_timeline_node = xmlNextElementSibling(fragment_timeline_node);
  891. }
  892. }
  893. } else {
  894. free_representation(rep);
  895. rep = NULL;
  896. av_log(s, AV_LOG_ERROR, "Unknown format of Representation node id[%s] \n", (const char *)rep_id_val);
  897. }
  898. if (rep) {
  899. if (rep->fragment_duration > 0 && !rep->fragment_timescale)
  900. rep->fragment_timescale = 1;
  901. rep->bandwidth = rep_bandwidth_val ? atoi(rep_bandwidth_val) : 0;
  902. strncpy(rep->id, rep_id_val ? rep_id_val : "", sizeof(rep->id));
  903. rep->framerate = av_make_q(0, 0);
  904. if (type == AVMEDIA_TYPE_VIDEO && rep_framerate_val) {
  905. ret = av_parse_video_rate(&rep->framerate, rep_framerate_val);
  906. if (ret < 0)
  907. av_log(s, AV_LOG_VERBOSE, "Ignoring invalid frame rate '%s'\n", rep_framerate_val);
  908. }
  909. if (type == AVMEDIA_TYPE_VIDEO) {
  910. rep->rep_idx = video_rep_idx;
  911. dynarray_add(&c->videos, &c->n_videos, rep);
  912. } else {
  913. rep->rep_idx = audio_rep_idx;
  914. dynarray_add(&c->audios, &c->n_audios, rep);
  915. }
  916. }
  917. }
  918. video_rep_idx += type == AVMEDIA_TYPE_VIDEO;
  919. audio_rep_idx += type == AVMEDIA_TYPE_AUDIO;
  920. end:
  921. if (rep_id_val)
  922. xmlFree(rep_id_val);
  923. if (rep_bandwidth_val)
  924. xmlFree(rep_bandwidth_val);
  925. if (rep_framerate_val)
  926. xmlFree(rep_framerate_val);
  927. return ret;
  928. }
  929. static int parse_manifest_adaptationset(AVFormatContext *s, const char *url,
  930. xmlNodePtr adaptionset_node,
  931. xmlNodePtr mpd_baseurl_node,
  932. xmlNodePtr period_baseurl_node,
  933. xmlNodePtr period_segmenttemplate_node,
  934. xmlNodePtr period_segmentlist_node)
  935. {
  936. int ret = 0;
  937. xmlNodePtr fragment_template_node = NULL;
  938. xmlNodePtr content_component_node = NULL;
  939. xmlNodePtr adaptionset_baseurl_node = NULL;
  940. xmlNodePtr adaptionset_segmentlist_node = NULL;
  941. xmlNodePtr node = NULL;
  942. node = xmlFirstElementChild(adaptionset_node);
  943. while (node) {
  944. if (!av_strcasecmp(node->name, (const char *)"SegmentTemplate")) {
  945. fragment_template_node = node;
  946. } else if (!av_strcasecmp(node->name, (const char *)"ContentComponent")) {
  947. content_component_node = node;
  948. } else if (!av_strcasecmp(node->name, (const char *)"BaseURL")) {
  949. adaptionset_baseurl_node = node;
  950. } else if (!av_strcasecmp(node->name, (const char *)"SegmentList")) {
  951. adaptionset_segmentlist_node = node;
  952. } else if (!av_strcasecmp(node->name, (const char *)"Representation")) {
  953. ret = parse_manifest_representation(s, url, node,
  954. adaptionset_node,
  955. mpd_baseurl_node,
  956. period_baseurl_node,
  957. period_segmenttemplate_node,
  958. period_segmentlist_node,
  959. fragment_template_node,
  960. content_component_node,
  961. adaptionset_baseurl_node,
  962. adaptionset_segmentlist_node);
  963. if (ret < 0) {
  964. return ret;
  965. }
  966. }
  967. node = xmlNextElementSibling(node);
  968. }
  969. return 0;
  970. }
  971. static int parse_manifest(AVFormatContext *s, const char *url, AVIOContext *in)
  972. {
  973. DASHContext *c = s->priv_data;
  974. int ret = 0;
  975. int close_in = 0;
  976. uint8_t *new_url = NULL;
  977. int64_t filesize = 0;
  978. char *buffer = NULL;
  979. AVDictionary *opts = NULL;
  980. xmlDoc *doc = NULL;
  981. xmlNodePtr root_element = NULL;
  982. xmlNodePtr node = NULL;
  983. xmlNodePtr period_node = NULL;
  984. xmlNodePtr mpd_baseurl_node = NULL;
  985. xmlNodePtr period_baseurl_node = NULL;
  986. xmlNodePtr period_segmenttemplate_node = NULL;
  987. xmlNodePtr period_segmentlist_node = NULL;
  988. xmlNodePtr adaptionset_node = NULL;
  989. xmlAttrPtr attr = NULL;
  990. char *val = NULL;
  991. uint32_t perdiod_duration_sec = 0;
  992. uint32_t perdiod_start_sec = 0;
  993. if (!in) {
  994. close_in = 1;
  995. set_httpheader_options(c, &opts);
  996. ret = avio_open2(&in, url, AVIO_FLAG_READ, c->interrupt_callback, &opts);
  997. av_dict_free(&opts);
  998. if (ret < 0)
  999. return ret;
  1000. }
  1001. if (av_opt_get(in, "location", AV_OPT_SEARCH_CHILDREN, &new_url) >= 0) {
  1002. c->base_url = av_strdup(new_url);
  1003. } else {
  1004. c->base_url = av_strdup(url);
  1005. }
  1006. filesize = avio_size(in);
  1007. if (filesize <= 0) {
  1008. filesize = 8 * 1024;
  1009. }
  1010. buffer = av_mallocz(filesize);
  1011. if (!buffer) {
  1012. av_free(c->base_url);
  1013. return AVERROR(ENOMEM);
  1014. }
  1015. filesize = avio_read(in, buffer, filesize);
  1016. if (filesize <= 0) {
  1017. av_log(s, AV_LOG_ERROR, "Unable to read to offset '%s'\n", url);
  1018. ret = AVERROR_INVALIDDATA;
  1019. } else {
  1020. LIBXML_TEST_VERSION
  1021. doc = xmlReadMemory(buffer, filesize, c->base_url, NULL, 0);
  1022. root_element = xmlDocGetRootElement(doc);
  1023. node = root_element;
  1024. if (!node) {
  1025. ret = AVERROR_INVALIDDATA;
  1026. av_log(s, AV_LOG_ERROR, "Unable to parse '%s' - missing root node\n", url);
  1027. goto cleanup;
  1028. }
  1029. if (node->type != XML_ELEMENT_NODE ||
  1030. av_strcasecmp(node->name, (const char *)"MPD")) {
  1031. ret = AVERROR_INVALIDDATA;
  1032. av_log(s, AV_LOG_ERROR, "Unable to parse '%s' - wrong root node name[%s] type[%d]\n", url, node->name, (int)node->type);
  1033. goto cleanup;
  1034. }
  1035. val = xmlGetProp(node, "type");
  1036. if (!val) {
  1037. av_log(s, AV_LOG_ERROR, "Unable to parse '%s' - missing type attrib\n", url);
  1038. ret = AVERROR_INVALIDDATA;
  1039. goto cleanup;
  1040. }
  1041. if (!av_strcasecmp(val, (const char *)"dynamic"))
  1042. c->is_live = 1;
  1043. xmlFree(val);
  1044. attr = node->properties;
  1045. while (attr) {
  1046. val = xmlGetProp(node, attr->name);
  1047. if (!av_strcasecmp(attr->name, (const char *)"availabilityStartTime")) {
  1048. c->availability_start_time = get_utc_date_time_insec(s, (const char *)val);
  1049. } else if (!av_strcasecmp(attr->name, (const char *)"publishTime")) {
  1050. c->publish_time = get_utc_date_time_insec(s, (const char *)val);
  1051. } else if (!av_strcasecmp(attr->name, (const char *)"minimumUpdatePeriod")) {
  1052. c->minimum_update_period = get_duration_insec(s, (const char *)val);
  1053. } else if (!av_strcasecmp(attr->name, (const char *)"timeShiftBufferDepth")) {
  1054. c->time_shift_buffer_depth = get_duration_insec(s, (const char *)val);
  1055. } else if (!av_strcasecmp(attr->name, (const char *)"minBufferTime")) {
  1056. c->min_buffer_time = get_duration_insec(s, (const char *)val);
  1057. } else if (!av_strcasecmp(attr->name, (const char *)"suggestedPresentationDelay")) {
  1058. c->suggested_presentation_delay = get_duration_insec(s, (const char *)val);
  1059. } else if (!av_strcasecmp(attr->name, (const char *)"mediaPresentationDuration")) {
  1060. c->media_presentation_duration = get_duration_insec(s, (const char *)val);
  1061. }
  1062. attr = attr->next;
  1063. xmlFree(val);
  1064. }
  1065. mpd_baseurl_node = find_child_node_by_name(node, "BaseURL");
  1066. if (!mpd_baseurl_node) {
  1067. mpd_baseurl_node = xmlNewNode(NULL, "BaseURL");
  1068. }
  1069. // at now we can handle only one period, with the longest duration
  1070. node = xmlFirstElementChild(node);
  1071. while (node) {
  1072. if (!av_strcasecmp(node->name, (const char *)"Period")) {
  1073. perdiod_duration_sec = 0;
  1074. perdiod_start_sec = 0;
  1075. attr = node->properties;
  1076. while (attr) {
  1077. val = xmlGetProp(node, attr->name);
  1078. if (!av_strcasecmp(attr->name, (const char *)"duration")) {
  1079. perdiod_duration_sec = get_duration_insec(s, (const char *)val);
  1080. } else if (!av_strcasecmp(attr->name, (const char *)"start")) {
  1081. perdiod_start_sec = get_duration_insec(s, (const char *)val);
  1082. }
  1083. attr = attr->next;
  1084. xmlFree(val);
  1085. }
  1086. if ((perdiod_duration_sec) >= (c->period_duration)) {
  1087. period_node = node;
  1088. c->period_duration = perdiod_duration_sec;
  1089. c->period_start = perdiod_start_sec;
  1090. if (c->period_start > 0)
  1091. c->media_presentation_duration = c->period_duration;
  1092. }
  1093. }
  1094. node = xmlNextElementSibling(node);
  1095. }
  1096. if (!period_node) {
  1097. av_log(s, AV_LOG_ERROR, "Unable to parse '%s' - missing Period node\n", url);
  1098. ret = AVERROR_INVALIDDATA;
  1099. goto cleanup;
  1100. }
  1101. adaptionset_node = xmlFirstElementChild(period_node);
  1102. while (adaptionset_node) {
  1103. if (!av_strcasecmp(adaptionset_node->name, (const char *)"BaseURL")) {
  1104. period_baseurl_node = adaptionset_node;
  1105. } else if (!av_strcasecmp(adaptionset_node->name, (const char *)"SegmentTemplate")) {
  1106. period_segmenttemplate_node = adaptionset_node;
  1107. } else if (!av_strcasecmp(adaptionset_node->name, (const char *)"SegmentList")) {
  1108. period_segmentlist_node = adaptionset_node;
  1109. } else if (!av_strcasecmp(adaptionset_node->name, (const char *)"AdaptationSet")) {
  1110. parse_manifest_adaptationset(s, url, adaptionset_node, mpd_baseurl_node, period_baseurl_node, period_segmenttemplate_node, period_segmentlist_node);
  1111. }
  1112. adaptionset_node = xmlNextElementSibling(adaptionset_node);
  1113. }
  1114. cleanup:
  1115. /*free the document */
  1116. xmlFreeDoc(doc);
  1117. xmlCleanupParser();
  1118. }
  1119. av_free(new_url);
  1120. av_free(buffer);
  1121. if (close_in) {
  1122. avio_close(in);
  1123. }
  1124. return ret;
  1125. }
  1126. static int64_t calc_cur_seg_no(AVFormatContext *s, struct representation *pls)
  1127. {
  1128. DASHContext *c = s->priv_data;
  1129. int64_t num = 0;
  1130. int64_t start_time_offset = 0;
  1131. if (c->is_live) {
  1132. if (pls->n_fragments) {
  1133. num = pls->first_seq_no;
  1134. } else if (pls->n_timelines) {
  1135. start_time_offset = get_segment_start_time_based_on_timeline(pls, 0xFFFFFFFF) - 60 * pls->fragment_timescale; // 60 seconds before end
  1136. num = calc_next_seg_no_from_timelines(pls, start_time_offset);
  1137. if (num == -1)
  1138. num = pls->first_seq_no;
  1139. else
  1140. num += pls->first_seq_no;
  1141. } else if (pls->fragment_duration){
  1142. if (pls->presentation_timeoffset) {
  1143. num = pls->presentation_timeoffset * pls->fragment_timescale / pls->fragment_duration;
  1144. } else if (c->publish_time > 0 && !c->availability_start_time) {
  1145. num = pls->first_seq_no + (((c->publish_time - c->availability_start_time) - c->suggested_presentation_delay) * pls->fragment_timescale) / pls->fragment_duration;
  1146. } else {
  1147. num = pls->first_seq_no + (((get_current_time_in_sec() - c->availability_start_time) - c->suggested_presentation_delay) * pls->fragment_timescale) / pls->fragment_duration;
  1148. }
  1149. }
  1150. } else {
  1151. num = pls->first_seq_no;
  1152. }
  1153. return num;
  1154. }
  1155. static int64_t calc_min_seg_no(AVFormatContext *s, struct representation *pls)
  1156. {
  1157. DASHContext *c = s->priv_data;
  1158. int64_t num = 0;
  1159. if (c->is_live && pls->fragment_duration) {
  1160. num = pls->first_seq_no + (((get_current_time_in_sec() - c->availability_start_time) - c->time_shift_buffer_depth) * pls->fragment_timescale) / pls->fragment_duration;
  1161. } else {
  1162. num = pls->first_seq_no;
  1163. }
  1164. return num;
  1165. }
  1166. static int64_t calc_max_seg_no(struct representation *pls, DASHContext *c)
  1167. {
  1168. int64_t num = 0;
  1169. if (pls->n_fragments) {
  1170. num = pls->first_seq_no + pls->n_fragments - 1;
  1171. } else if (pls->n_timelines) {
  1172. int i = 0;
  1173. num = pls->first_seq_no + pls->n_timelines - 1;
  1174. for (i = 0; i < pls->n_timelines; i++) {
  1175. num += pls->timelines[i]->repeat;
  1176. }
  1177. } else if (c->is_live && pls->fragment_duration) {
  1178. num = pls->first_seq_no + (((get_current_time_in_sec() - c->availability_start_time)) * pls->fragment_timescale) / pls->fragment_duration;
  1179. } else if (pls->fragment_duration) {
  1180. num = pls->first_seq_no + (c->media_presentation_duration * pls->fragment_timescale) / pls->fragment_duration;
  1181. }
  1182. return num;
  1183. }
  1184. static void move_timelines(struct representation *rep_src, struct representation *rep_dest, DASHContext *c)
  1185. {
  1186. if (rep_dest && rep_src ) {
  1187. free_timelines_list(rep_dest);
  1188. rep_dest->timelines = rep_src->timelines;
  1189. rep_dest->n_timelines = rep_src->n_timelines;
  1190. rep_dest->first_seq_no = rep_src->first_seq_no;
  1191. rep_dest->last_seq_no = calc_max_seg_no(rep_dest, c);
  1192. rep_src->timelines = NULL;
  1193. rep_src->n_timelines = 0;
  1194. rep_dest->cur_seq_no = rep_src->cur_seq_no;
  1195. }
  1196. }
  1197. static void move_segments(struct representation *rep_src, struct representation *rep_dest, DASHContext *c)
  1198. {
  1199. if (rep_dest && rep_src ) {
  1200. free_fragment_list(rep_dest);
  1201. if (rep_src->start_number > (rep_dest->start_number + rep_dest->n_fragments))
  1202. rep_dest->cur_seq_no = 0;
  1203. else
  1204. rep_dest->cur_seq_no += rep_src->start_number - rep_dest->start_number;
  1205. rep_dest->fragments = rep_src->fragments;
  1206. rep_dest->n_fragments = rep_src->n_fragments;
  1207. rep_dest->parent = rep_src->parent;
  1208. rep_dest->last_seq_no = calc_max_seg_no(rep_dest, c);
  1209. rep_src->fragments = NULL;
  1210. rep_src->n_fragments = 0;
  1211. }
  1212. }
  1213. static int refresh_manifest(AVFormatContext *s)
  1214. {
  1215. int ret = 0, i;
  1216. DASHContext *c = s->priv_data;
  1217. // save current context
  1218. int n_videos = c->n_videos;
  1219. struct representation **videos = c->videos;
  1220. int n_audios = c->n_audios;
  1221. struct representation **audios = c->audios;
  1222. char *base_url = c->base_url;
  1223. c->base_url = NULL;
  1224. c->n_videos = 0;
  1225. c->videos = NULL;
  1226. c->n_audios = 0;
  1227. c->audios = NULL;
  1228. ret = parse_manifest(s, s->filename, NULL);
  1229. if (ret)
  1230. goto finish;
  1231. if (c->n_videos != n_videos) {
  1232. av_log(c, AV_LOG_ERROR,
  1233. "new manifest has mismatched no. of video representations, %d -> %d\n",
  1234. n_videos, c->n_videos);
  1235. return AVERROR_INVALIDDATA;
  1236. }
  1237. if (c->n_audios != n_audios) {
  1238. av_log(c, AV_LOG_ERROR,
  1239. "new manifest has mismatched no. of audio representations, %d -> %d\n",
  1240. n_audios, c->n_audios);
  1241. return AVERROR_INVALIDDATA;
  1242. }
  1243. for (i = 0; i < n_videos; i++) {
  1244. struct representation *cur_video = videos[i];
  1245. struct representation *ccur_video = c->videos[i];
  1246. if (cur_video->timelines) {
  1247. // calc current time
  1248. int64_t currentTime = get_segment_start_time_based_on_timeline(cur_video, cur_video->cur_seq_no) / cur_video->fragment_timescale;
  1249. // update segments
  1250. ccur_video->cur_seq_no = calc_next_seg_no_from_timelines(ccur_video, currentTime * cur_video->fragment_timescale - 1);
  1251. if (ccur_video->cur_seq_no >= 0) {
  1252. move_timelines(ccur_video, cur_video, c);
  1253. }
  1254. }
  1255. if (cur_video->fragments) {
  1256. move_segments(ccur_video, cur_video, c);
  1257. }
  1258. }
  1259. for (i = 0; i < n_audios; i++) {
  1260. struct representation *cur_audio = audios[i];
  1261. struct representation *ccur_audio = c->audios[i];
  1262. if (cur_audio->timelines) {
  1263. // calc current time
  1264. int64_t currentTime = get_segment_start_time_based_on_timeline(cur_audio, cur_audio->cur_seq_no) / cur_audio->fragment_timescale;
  1265. // update segments
  1266. ccur_audio->cur_seq_no = calc_next_seg_no_from_timelines(ccur_audio, currentTime * cur_audio->fragment_timescale - 1);
  1267. if (ccur_audio->cur_seq_no >= 0) {
  1268. move_timelines(ccur_audio, cur_audio, c);
  1269. }
  1270. }
  1271. if (cur_audio->fragments) {
  1272. move_segments(ccur_audio, cur_audio, c);
  1273. }
  1274. }
  1275. finish:
  1276. // restore context
  1277. if (c->base_url)
  1278. av_free(base_url);
  1279. else
  1280. c->base_url = base_url;
  1281. if (c->audios)
  1282. free_audio_list(c);
  1283. if (c->videos)
  1284. free_video_list(c);
  1285. c->n_audios = n_audios;
  1286. c->audios = audios;
  1287. c->n_videos = n_videos;
  1288. c->videos = videos;
  1289. return ret;
  1290. }
  1291. static struct fragment *get_current_fragment(struct representation *pls)
  1292. {
  1293. int64_t min_seq_no = 0;
  1294. int64_t max_seq_no = 0;
  1295. struct fragment *seg = NULL;
  1296. struct fragment *seg_ptr = NULL;
  1297. DASHContext *c = pls->parent->priv_data;
  1298. while (( !ff_check_interrupt(c->interrupt_callback)&& pls->n_fragments > 0)) {
  1299. if (pls->cur_seq_no < pls->n_fragments) {
  1300. seg_ptr = pls->fragments[pls->cur_seq_no];
  1301. seg = av_mallocz(sizeof(struct fragment));
  1302. if (!seg) {
  1303. return NULL;
  1304. }
  1305. seg->url = av_strdup(seg_ptr->url);
  1306. if (!seg->url) {
  1307. av_free(seg);
  1308. return NULL;
  1309. }
  1310. seg->size = seg_ptr->size;
  1311. seg->url_offset = seg_ptr->url_offset;
  1312. return seg;
  1313. } else if (c->is_live) {
  1314. refresh_manifest(pls->parent);
  1315. } else {
  1316. break;
  1317. }
  1318. }
  1319. if (c->is_live) {
  1320. min_seq_no = calc_min_seg_no(pls->parent, pls);
  1321. max_seq_no = calc_max_seg_no(pls, c);
  1322. if (pls->timelines || pls->fragments) {
  1323. refresh_manifest(pls->parent);
  1324. }
  1325. if (pls->cur_seq_no <= min_seq_no) {
  1326. av_log(pls->parent, AV_LOG_VERBOSE, "old fragment: cur[%"PRId64"] min[%"PRId64"] max[%"PRId64"], playlist %d\n", (int64_t)pls->cur_seq_no, min_seq_no, max_seq_no, (int)pls->rep_idx);
  1327. pls->cur_seq_no = calc_cur_seg_no(pls->parent, pls);
  1328. } else if (pls->cur_seq_no > max_seq_no) {
  1329. av_log(pls->parent, AV_LOG_VERBOSE, "new fragment: min[%"PRId64"] max[%"PRId64"], playlist %d\n", min_seq_no, max_seq_no, (int)pls->rep_idx);
  1330. }
  1331. seg = av_mallocz(sizeof(struct fragment));
  1332. if (!seg) {
  1333. return NULL;
  1334. }
  1335. } else if (pls->cur_seq_no <= pls->last_seq_no) {
  1336. seg = av_mallocz(sizeof(struct fragment));
  1337. if (!seg) {
  1338. return NULL;
  1339. }
  1340. }
  1341. if (seg) {
  1342. char *tmpfilename= av_mallocz(c->max_url_size);
  1343. if (!tmpfilename) {
  1344. return NULL;
  1345. }
  1346. ff_dash_fill_tmpl_params(tmpfilename, c->max_url_size, pls->url_template, 0, pls->cur_seq_no, 0, get_segment_start_time_based_on_timeline(pls, pls->cur_seq_no));
  1347. seg->url = av_strireplace(pls->url_template, pls->url_template, tmpfilename);
  1348. if (!seg->url) {
  1349. av_log(pls->parent, AV_LOG_WARNING, "Unable to resolve template url '%s', try to use origin template\n", pls->url_template);
  1350. seg->url = av_strdup(pls->url_template);
  1351. if (!seg->url) {
  1352. av_log(pls->parent, AV_LOG_ERROR, "Cannot resolve template url '%s'\n", pls->url_template);
  1353. av_free(tmpfilename);
  1354. return NULL;
  1355. }
  1356. }
  1357. av_free(tmpfilename);
  1358. seg->size = -1;
  1359. }
  1360. return seg;
  1361. }
  1362. enum ReadFromURLMode {
  1363. READ_NORMAL,
  1364. READ_COMPLETE,
  1365. };
  1366. static int read_from_url(struct representation *pls, struct fragment *seg,
  1367. uint8_t *buf, int buf_size,
  1368. enum ReadFromURLMode mode)
  1369. {
  1370. int ret;
  1371. /* limit read if the fragment was only a part of a file */
  1372. if (seg->size >= 0)
  1373. buf_size = FFMIN(buf_size, pls->cur_seg_size - pls->cur_seg_offset);
  1374. if (mode == READ_COMPLETE) {
  1375. ret = avio_read(pls->input, buf, buf_size);
  1376. if (ret < buf_size) {
  1377. av_log(pls->parent, AV_LOG_WARNING, "Could not read complete fragment.\n");
  1378. }
  1379. } else {
  1380. ret = avio_read(pls->input, buf, buf_size);
  1381. }
  1382. if (ret > 0)
  1383. pls->cur_seg_offset += ret;
  1384. return ret;
  1385. }
  1386. static int open_input(DASHContext *c, struct representation *pls, struct fragment *seg)
  1387. {
  1388. AVDictionary *opts = NULL;
  1389. char *url = NULL;
  1390. int ret = 0;
  1391. url = av_mallocz(c->max_url_size);
  1392. if (!url) {
  1393. goto cleanup;
  1394. }
  1395. set_httpheader_options(c, &opts);
  1396. if (seg->size >= 0) {
  1397. /* try to restrict the HTTP request to the part we want
  1398. * (if this is in fact a HTTP request) */
  1399. av_dict_set_int(&opts, "offset", seg->url_offset, 0);
  1400. av_dict_set_int(&opts, "end_offset", seg->url_offset + seg->size, 0);
  1401. }
  1402. ff_make_absolute_url(url, c->max_url_size, c->base_url, seg->url);
  1403. av_log(pls->parent, AV_LOG_VERBOSE, "DASH request for url '%s', offset %"PRId64", playlist %d\n",
  1404. url, seg->url_offset, pls->rep_idx);
  1405. ret = open_url(pls->parent, &pls->input, url, c->avio_opts, opts, NULL);
  1406. if (ret < 0) {
  1407. goto cleanup;
  1408. }
  1409. cleanup:
  1410. av_free(url);
  1411. av_dict_free(&opts);
  1412. pls->cur_seg_offset = 0;
  1413. pls->cur_seg_size = seg->size;
  1414. return ret;
  1415. }
  1416. static int update_init_section(struct representation *pls)
  1417. {
  1418. static const int max_init_section_size = 1024 * 1024;
  1419. DASHContext *c = pls->parent->priv_data;
  1420. int64_t sec_size;
  1421. int64_t urlsize;
  1422. int ret;
  1423. if (!pls->init_section || pls->init_sec_buf)
  1424. return 0;
  1425. ret = open_input(c, pls, pls->init_section);
  1426. if (ret < 0) {
  1427. av_log(pls->parent, AV_LOG_WARNING,
  1428. "Failed to open an initialization section in playlist %d\n",
  1429. pls->rep_idx);
  1430. return ret;
  1431. }
  1432. if (pls->init_section->size >= 0)
  1433. sec_size = pls->init_section->size;
  1434. else if ((urlsize = avio_size(pls->input)) >= 0)
  1435. sec_size = urlsize;
  1436. else
  1437. sec_size = max_init_section_size;
  1438. av_log(pls->parent, AV_LOG_DEBUG,
  1439. "Downloading an initialization section of size %"PRId64"\n",
  1440. sec_size);
  1441. sec_size = FFMIN(sec_size, max_init_section_size);
  1442. av_fast_malloc(&pls->init_sec_buf, &pls->init_sec_buf_size, sec_size);
  1443. ret = read_from_url(pls, pls->init_section, pls->init_sec_buf,
  1444. pls->init_sec_buf_size, READ_COMPLETE);
  1445. ff_format_io_close(pls->parent, &pls->input);
  1446. if (ret < 0)
  1447. return ret;
  1448. pls->init_sec_data_len = ret;
  1449. pls->init_sec_buf_read_offset = 0;
  1450. return 0;
  1451. }
  1452. static int64_t seek_data(void *opaque, int64_t offset, int whence)
  1453. {
  1454. struct representation *v = opaque;
  1455. if (v->n_fragments && !v->init_sec_data_len) {
  1456. return avio_seek(v->input, offset, whence);
  1457. }
  1458. return AVERROR(ENOSYS);
  1459. }
  1460. static int read_data(void *opaque, uint8_t *buf, int buf_size)
  1461. {
  1462. int ret = 0;
  1463. struct representation *v = opaque;
  1464. DASHContext *c = v->parent->priv_data;
  1465. restart:
  1466. if (!v->input) {
  1467. free_fragment(&v->cur_seg);
  1468. v->cur_seg = get_current_fragment(v);
  1469. if (!v->cur_seg) {
  1470. ret = AVERROR_EOF;
  1471. goto end;
  1472. }
  1473. /* load/update Media Initialization Section, if any */
  1474. ret = update_init_section(v);
  1475. if (ret)
  1476. goto end;
  1477. ret = open_input(c, v, v->cur_seg);
  1478. if (ret < 0) {
  1479. if (ff_check_interrupt(c->interrupt_callback)) {
  1480. goto end;
  1481. ret = AVERROR_EXIT;
  1482. }
  1483. av_log(v->parent, AV_LOG_WARNING, "Failed to open fragment of playlist %d\n", v->rep_idx);
  1484. v->cur_seq_no++;
  1485. goto restart;
  1486. }
  1487. }
  1488. if (v->init_sec_buf_read_offset < v->init_sec_data_len) {
  1489. /* Push init section out first before first actual fragment */
  1490. int copy_size = FFMIN(v->init_sec_data_len - v->init_sec_buf_read_offset, buf_size);
  1491. memcpy(buf, v->init_sec_buf, copy_size);
  1492. v->init_sec_buf_read_offset += copy_size;
  1493. ret = copy_size;
  1494. goto end;
  1495. }
  1496. /* check the v->cur_seg, if it is null, get current and double check if the new v->cur_seg*/
  1497. if (!v->cur_seg) {
  1498. v->cur_seg = get_current_fragment(v);
  1499. }
  1500. if (!v->cur_seg) {
  1501. ret = AVERROR_EOF;
  1502. goto end;
  1503. }
  1504. ret = read_from_url(v, v->cur_seg, buf, buf_size, READ_NORMAL);
  1505. if (ret > 0)
  1506. goto end;
  1507. if (c->is_live || v->cur_seq_no < v->last_seq_no) {
  1508. if (!v->is_restart_needed)
  1509. v->cur_seq_no++;
  1510. v->is_restart_needed = 1;
  1511. }
  1512. end:
  1513. return ret;
  1514. }
  1515. static int save_avio_options(AVFormatContext *s)
  1516. {
  1517. DASHContext *c = s->priv_data;
  1518. const char *opts[] = { "headers", "user_agent", "user-agent", "cookies", NULL }, **opt = opts;
  1519. uint8_t *buf = NULL;
  1520. int ret = 0;
  1521. while (*opt) {
  1522. if (av_opt_get(s->pb, *opt, AV_OPT_SEARCH_CHILDREN, &buf) >= 0) {
  1523. if (buf[0] != '\0') {
  1524. ret = av_dict_set(&c->avio_opts, *opt, buf, AV_DICT_DONT_STRDUP_VAL);
  1525. if (ret < 0) {
  1526. av_freep(&buf);
  1527. return ret;
  1528. }
  1529. } else {
  1530. av_freep(&buf);
  1531. }
  1532. }
  1533. opt++;
  1534. }
  1535. return ret;
  1536. }
  1537. static int nested_io_open(AVFormatContext *s, AVIOContext **pb, const char *url,
  1538. int flags, AVDictionary **opts)
  1539. {
  1540. av_log(s, AV_LOG_ERROR,
  1541. "A DASH playlist item '%s' referred to an external file '%s'. "
  1542. "Opening this file was forbidden for security reasons\n",
  1543. s->filename, url);
  1544. return AVERROR(EPERM);
  1545. }
  1546. static void close_demux_for_component(struct representation *pls)
  1547. {
  1548. /* note: the internal buffer could have changed */
  1549. av_freep(&pls->pb.buffer);
  1550. memset(&pls->pb, 0x00, sizeof(AVIOContext));
  1551. pls->ctx->pb = NULL;
  1552. avformat_close_input(&pls->ctx);
  1553. pls->ctx = NULL;
  1554. }
  1555. static int reopen_demux_for_component(AVFormatContext *s, struct representation *pls)
  1556. {
  1557. DASHContext *c = s->priv_data;
  1558. AVInputFormat *in_fmt = NULL;
  1559. AVDictionary *in_fmt_opts = NULL;
  1560. uint8_t *avio_ctx_buffer = NULL;
  1561. int ret = 0, i;
  1562. if (pls->ctx) {
  1563. close_demux_for_component(pls);
  1564. }
  1565. if (!(pls->ctx = avformat_alloc_context())) {
  1566. ret = AVERROR(ENOMEM);
  1567. goto fail;
  1568. }
  1569. avio_ctx_buffer = av_malloc(INITIAL_BUFFER_SIZE);
  1570. if (!avio_ctx_buffer ) {
  1571. ret = AVERROR(ENOMEM);
  1572. avformat_free_context(pls->ctx);
  1573. pls->ctx = NULL;
  1574. goto fail;
  1575. }
  1576. if (c->is_live) {
  1577. ffio_init_context(&pls->pb, avio_ctx_buffer , INITIAL_BUFFER_SIZE, 0, pls, read_data, NULL, NULL);
  1578. } else {
  1579. ffio_init_context(&pls->pb, avio_ctx_buffer , INITIAL_BUFFER_SIZE, 0, pls, read_data, NULL, seek_data);
  1580. }
  1581. pls->pb.seekable = 0;
  1582. if ((ret = ff_copy_whiteblacklists(pls->ctx, s)) < 0)
  1583. goto fail;
  1584. pls->ctx->flags = AVFMT_FLAG_CUSTOM_IO;
  1585. pls->ctx->probesize = 1024 * 4;
  1586. pls->ctx->max_analyze_duration = 4 * AV_TIME_BASE;
  1587. ret = av_probe_input_buffer(&pls->pb, &in_fmt, "", NULL, 0, 0);
  1588. if (ret < 0) {
  1589. av_log(s, AV_LOG_ERROR, "Error when loading first fragment, playlist %d\n", (int)pls->rep_idx);
  1590. avformat_free_context(pls->ctx);
  1591. pls->ctx = NULL;
  1592. goto fail;
  1593. }
  1594. pls->ctx->pb = &pls->pb;
  1595. pls->ctx->io_open = nested_io_open;
  1596. // provide additional information from mpd if available
  1597. ret = avformat_open_input(&pls->ctx, "", in_fmt, &in_fmt_opts); //pls->init_section->url
  1598. av_dict_free(&in_fmt_opts);
  1599. if (ret < 0)
  1600. goto fail;
  1601. if (pls->n_fragments) {
  1602. #if FF_API_R_FRAME_RATE
  1603. if (pls->framerate.den) {
  1604. for (i = 0; i < pls->ctx->nb_streams; i++)
  1605. pls->ctx->streams[i]->r_frame_rate = pls->framerate;
  1606. }
  1607. #endif
  1608. ret = avformat_find_stream_info(pls->ctx, NULL);
  1609. if (ret < 0)
  1610. goto fail;
  1611. }
  1612. fail:
  1613. return ret;
  1614. }
  1615. static int open_demux_for_component(AVFormatContext *s, struct representation *pls)
  1616. {
  1617. int ret = 0;
  1618. int i;
  1619. pls->parent = s;
  1620. pls->cur_seq_no = calc_cur_seg_no(s, pls);
  1621. pls->last_seq_no = calc_max_seg_no(pls, s->priv_data);
  1622. ret = reopen_demux_for_component(s, pls);
  1623. if (ret < 0) {
  1624. goto fail;
  1625. }
  1626. for (i = 0; i < pls->ctx->nb_streams; i++) {
  1627. AVStream *st = avformat_new_stream(s, NULL);
  1628. AVStream *ist = pls->ctx->streams[i];
  1629. if (!st) {
  1630. ret = AVERROR(ENOMEM);
  1631. goto fail;
  1632. }
  1633. st->id = i;
  1634. avcodec_parameters_copy(st->codecpar, pls->ctx->streams[i]->codecpar);
  1635. avpriv_set_pts_info(st, ist->pts_wrap_bits, ist->time_base.num, ist->time_base.den);
  1636. }
  1637. return 0;
  1638. fail:
  1639. return ret;
  1640. }
  1641. static int dash_read_header(AVFormatContext *s)
  1642. {
  1643. void *u = (s->flags & AVFMT_FLAG_CUSTOM_IO) ? NULL : s->pb;
  1644. DASHContext *c = s->priv_data;
  1645. int ret = 0;
  1646. int stream_index = 0;
  1647. int i;
  1648. c->interrupt_callback = &s->interrupt_callback;
  1649. // if the URL context is good, read important options we must broker later
  1650. if (u) {
  1651. update_options(&c->user_agent, "user-agent", u);
  1652. update_options(&c->cookies, "cookies", u);
  1653. update_options(&c->headers, "headers", u);
  1654. }
  1655. if ((ret = parse_manifest(s, s->filename, s->pb)) < 0)
  1656. goto fail;
  1657. if ((ret = save_avio_options(s)) < 0)
  1658. goto fail;
  1659. /* If this isn't a live stream, fill the total duration of the
  1660. * stream. */
  1661. if (!c->is_live) {
  1662. s->duration = (int64_t) c->media_presentation_duration * AV_TIME_BASE;
  1663. }
  1664. /* Open the demuxer for video and audio components if available */
  1665. for (i = 0; i < c->n_videos; i++) {
  1666. struct representation *cur_video = c->videos[i];
  1667. ret = open_demux_for_component(s, cur_video);
  1668. if (ret)
  1669. goto fail;
  1670. cur_video->stream_index = stream_index;
  1671. ++stream_index;
  1672. }
  1673. for (i = 0; i < c->n_audios; i++) {
  1674. struct representation *cur_audio = c->audios[i];
  1675. ret = open_demux_for_component(s, cur_audio);
  1676. if (ret)
  1677. goto fail;
  1678. cur_audio->stream_index = stream_index;
  1679. ++stream_index;
  1680. }
  1681. if (!stream_index) {
  1682. ret = AVERROR_INVALIDDATA;
  1683. goto fail;
  1684. }
  1685. /* Create a program */
  1686. if (!ret) {
  1687. AVProgram *program;
  1688. program = av_new_program(s, 0);
  1689. if (!program) {
  1690. goto fail;
  1691. }
  1692. for (i = 0; i < c->n_videos; i++) {
  1693. struct representation *pls = c->videos[i];
  1694. av_program_add_stream_index(s, 0, pls->stream_index);
  1695. pls->assoc_stream = s->streams[pls->stream_index];
  1696. if (pls->bandwidth > 0)
  1697. av_dict_set_int(&pls->assoc_stream->metadata, "variant_bitrate", pls->bandwidth, 0);
  1698. if (pls->id[0])
  1699. av_dict_set(&pls->assoc_stream->metadata, "id", pls->id, 0);
  1700. }
  1701. for (i = 0; i < c->n_audios; i++) {
  1702. struct representation *pls = c->audios[i];
  1703. av_program_add_stream_index(s, 0, pls->stream_index);
  1704. pls->assoc_stream = s->streams[pls->stream_index];
  1705. if (pls->bandwidth > 0)
  1706. av_dict_set_int(&pls->assoc_stream->metadata, "variant_bitrate", pls->bandwidth, 0);
  1707. if (pls->id[0])
  1708. av_dict_set(&pls->assoc_stream->metadata, "id", pls->id, 0);
  1709. }
  1710. }
  1711. return 0;
  1712. fail:
  1713. return ret;
  1714. }
  1715. static void recheck_discard_flags(AVFormatContext *s, struct representation **p, int n)
  1716. {
  1717. int i, j;
  1718. for (i = 0; i < n; i++) {
  1719. struct representation *pls = p[i];
  1720. int needed = !pls->assoc_stream || pls->assoc_stream->discard < AVDISCARD_ALL;
  1721. if (needed && !pls->ctx) {
  1722. pls->cur_seg_offset = 0;
  1723. pls->init_sec_buf_read_offset = 0;
  1724. /* Catch up */
  1725. for (j = 0; j < n; j++) {
  1726. pls->cur_seq_no = FFMAX(pls->cur_seq_no, p[j]->cur_seq_no);
  1727. }
  1728. reopen_demux_for_component(s, pls);
  1729. av_log(s, AV_LOG_INFO, "Now receiving stream_index %d\n", pls->stream_index);
  1730. } else if (!needed && pls->ctx) {
  1731. close_demux_for_component(pls);
  1732. if (pls->input)
  1733. ff_format_io_close(pls->parent, &pls->input);
  1734. av_log(s, AV_LOG_INFO, "No longer receiving stream_index %d\n", pls->stream_index);
  1735. }
  1736. }
  1737. }
  1738. static int dash_read_packet(AVFormatContext *s, AVPacket *pkt)
  1739. {
  1740. DASHContext *c = s->priv_data;
  1741. int ret = 0, i;
  1742. int64_t mints = 0;
  1743. struct representation *cur = NULL;
  1744. recheck_discard_flags(s, c->videos, c->n_videos);
  1745. recheck_discard_flags(s, c->audios, c->n_audios);
  1746. for (i = 0; i < c->n_videos; i++) {
  1747. struct representation *pls = c->videos[i];
  1748. if (!pls->ctx)
  1749. continue;
  1750. if (!cur || pls->cur_timestamp < mints) {
  1751. cur = pls;
  1752. mints = pls->cur_timestamp;
  1753. }
  1754. }
  1755. for (i = 0; i < c->n_audios; i++) {
  1756. struct representation *pls = c->audios[i];
  1757. if (!pls->ctx)
  1758. continue;
  1759. if (!cur || pls->cur_timestamp < mints) {
  1760. cur = pls;
  1761. mints = pls->cur_timestamp;
  1762. }
  1763. }
  1764. if (!cur) {
  1765. return AVERROR_INVALIDDATA;
  1766. }
  1767. while (!ff_check_interrupt(c->interrupt_callback) && !ret) {
  1768. ret = av_read_frame(cur->ctx, pkt);
  1769. if (ret >= 0) {
  1770. /* If we got a packet, return it */
  1771. cur->cur_timestamp = av_rescale(pkt->pts, (int64_t)cur->ctx->streams[0]->time_base.num * 90000, cur->ctx->streams[0]->time_base.den);
  1772. pkt->stream_index = cur->stream_index;
  1773. return 0;
  1774. }
  1775. if (cur->is_restart_needed) {
  1776. cur->cur_seg_offset = 0;
  1777. cur->init_sec_buf_read_offset = 0;
  1778. if (cur->input)
  1779. ff_format_io_close(cur->parent, &cur->input);
  1780. ret = reopen_demux_for_component(s, cur);
  1781. cur->is_restart_needed = 0;
  1782. }
  1783. }
  1784. return AVERROR_EOF;
  1785. }
  1786. static int dash_close(AVFormatContext *s)
  1787. {
  1788. DASHContext *c = s->priv_data;
  1789. free_audio_list(c);
  1790. free_video_list(c);
  1791. av_freep(&c->cookies);
  1792. av_freep(&c->user_agent);
  1793. av_dict_free(&c->avio_opts);
  1794. av_freep(&c->base_url);
  1795. return 0;
  1796. }
  1797. static int dash_seek(AVFormatContext *s, struct representation *pls, int64_t seek_pos_msec, int flags, int dry_run)
  1798. {
  1799. int ret = 0;
  1800. int i = 0;
  1801. int j = 0;
  1802. int64_t duration = 0;
  1803. av_log(pls->parent, AV_LOG_VERBOSE, "DASH seek pos[%"PRId64"ms], playlist %d%s\n",
  1804. seek_pos_msec, pls->rep_idx, dry_run ? " (dry)" : "");
  1805. // single fragment mode
  1806. if (pls->n_fragments == 1) {
  1807. pls->cur_timestamp = 0;
  1808. pls->cur_seg_offset = 0;
  1809. if (dry_run)
  1810. return 0;
  1811. ff_read_frame_flush(pls->ctx);
  1812. return av_seek_frame(pls->ctx, -1, seek_pos_msec * 1000, flags);
  1813. }
  1814. if (pls->input)
  1815. ff_format_io_close(pls->parent, &pls->input);
  1816. // find the nearest fragment
  1817. if (pls->n_timelines > 0 && pls->fragment_timescale > 0) {
  1818. int64_t num = pls->first_seq_no;
  1819. av_log(pls->parent, AV_LOG_VERBOSE, "dash_seek with SegmentTimeline start n_timelines[%d] "
  1820. "last_seq_no[%"PRId64"], playlist %d.\n",
  1821. (int)pls->n_timelines, (int64_t)pls->last_seq_no, (int)pls->rep_idx);
  1822. for (i = 0; i < pls->n_timelines; i++) {
  1823. if (pls->timelines[i]->starttime > 0) {
  1824. duration = pls->timelines[i]->starttime;
  1825. }
  1826. duration += pls->timelines[i]->duration;
  1827. if (seek_pos_msec < ((duration * 1000) / pls->fragment_timescale)) {
  1828. goto set_seq_num;
  1829. }
  1830. for (j = 0; j < pls->timelines[i]->repeat; j++) {
  1831. duration += pls->timelines[i]->duration;
  1832. num++;
  1833. if (seek_pos_msec < ((duration * 1000) / pls->fragment_timescale)) {
  1834. goto set_seq_num;
  1835. }
  1836. }
  1837. num++;
  1838. }
  1839. set_seq_num:
  1840. pls->cur_seq_no = num > pls->last_seq_no ? pls->last_seq_no : num;
  1841. av_log(pls->parent, AV_LOG_VERBOSE, "dash_seek with SegmentTimeline end cur_seq_no[%"PRId64"], playlist %d.\n",
  1842. (int64_t)pls->cur_seq_no, (int)pls->rep_idx);
  1843. } else if (pls->fragment_duration > 0) {
  1844. pls->cur_seq_no = pls->first_seq_no + ((seek_pos_msec * pls->fragment_timescale) / pls->fragment_duration) / 1000;
  1845. } else {
  1846. av_log(pls->parent, AV_LOG_ERROR, "dash_seek missing timeline or fragment_duration\n");
  1847. pls->cur_seq_no = pls->first_seq_no;
  1848. }
  1849. pls->cur_timestamp = 0;
  1850. pls->cur_seg_offset = 0;
  1851. pls->init_sec_buf_read_offset = 0;
  1852. ret = dry_run ? 0 : reopen_demux_for_component(s, pls);
  1853. return ret;
  1854. }
  1855. static int dash_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
  1856. {
  1857. int ret = 0, i;
  1858. DASHContext *c = s->priv_data;
  1859. int64_t seek_pos_msec = av_rescale_rnd(timestamp, 1000,
  1860. s->streams[stream_index]->time_base.den,
  1861. flags & AVSEEK_FLAG_BACKWARD ?
  1862. AV_ROUND_DOWN : AV_ROUND_UP);
  1863. if ((flags & AVSEEK_FLAG_BYTE) || c->is_live)
  1864. return AVERROR(ENOSYS);
  1865. /* Seek in discarded streams with dry_run=1 to avoid reopening them */
  1866. for (i = 0; i < c->n_videos; i++) {
  1867. if (!ret)
  1868. ret = dash_seek(s, c->videos[i], seek_pos_msec, flags, !c->videos[i]->ctx);
  1869. }
  1870. for (i = 0; i < c->n_audios; i++) {
  1871. if (!ret)
  1872. ret = dash_seek(s, c->audios[i], seek_pos_msec, flags, !c->audios[i]->ctx);
  1873. }
  1874. return ret;
  1875. }
  1876. static int dash_probe(AVProbeData *p)
  1877. {
  1878. if (!av_stristr(p->buf, "<MPD"))
  1879. return 0;
  1880. if (av_stristr(p->buf, "dash:profile:isoff-on-demand:2011") ||
  1881. av_stristr(p->buf, "dash:profile:isoff-live:2011") ||
  1882. av_stristr(p->buf, "dash:profile:isoff-live:2012") ||
  1883. av_stristr(p->buf, "dash:profile:isoff-main:2011")) {
  1884. return AVPROBE_SCORE_MAX;
  1885. }
  1886. if (av_stristr(p->buf, "dash:profile")) {
  1887. return AVPROBE_SCORE_MAX;
  1888. }
  1889. return 0;
  1890. }
  1891. #define OFFSET(x) offsetof(DASHContext, x)
  1892. #define FLAGS AV_OPT_FLAG_DECODING_PARAM
  1893. static const AVOption dash_options[] = {
  1894. {"allowed_extensions", "List of file extensions that dash is allowed to access",
  1895. OFFSET(allowed_extensions), AV_OPT_TYPE_STRING,
  1896. {.str = "aac,m4a,m4s,m4v,mov,mp4"},
  1897. INT_MIN, INT_MAX, FLAGS},
  1898. {NULL}
  1899. };
  1900. static const AVClass dash_class = {
  1901. .class_name = "dash",
  1902. .item_name = av_default_item_name,
  1903. .option = dash_options,
  1904. .version = LIBAVUTIL_VERSION_INT,
  1905. };
  1906. AVInputFormat ff_dash_demuxer = {
  1907. .name = "dash",
  1908. .long_name = NULL_IF_CONFIG_SMALL("Dynamic Adaptive Streaming over HTTP"),
  1909. .priv_class = &dash_class,
  1910. .priv_data_size = sizeof(DASHContext),
  1911. .read_probe = dash_probe,
  1912. .read_header = dash_read_header,
  1913. .read_packet = dash_read_packet,
  1914. .read_close = dash_close,
  1915. .read_seek = dash_read_seek,
  1916. .flags = AVFMT_NO_BYTE_SEEK,
  1917. };