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.

2269 lines
78KB

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