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.

2405 lines
80KB

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