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.

2242 lines
77KB

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