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.

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