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.

2239 lines
76KB

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