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.

2352 lines
81KB

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