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.

2260 lines
77KB

  1. /*
  2. * Dynamic Adaptive Streaming over HTTP demux
  3. * Copyright (c) 2017 samsamsam@o2.pl based on HLS demux
  4. * Copyright (c) 2017 Steven Liu
  5. *
  6. * This file is part of FFmpeg.
  7. *
  8. * FFmpeg is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU Lesser General Public
  10. * License as published by the Free Software Foundation; either
  11. * version 2.1 of the License, or (at your option) any later version.
  12. *
  13. * FFmpeg is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  16. * Lesser General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU Lesser General Public
  19. * License along with FFmpeg; if not, write to the Free Software
  20. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  21. */
  22. #include <libxml/parser.h>
  23. #include "libavutil/intreadwrite.h"
  24. #include "libavutil/opt.h"
  25. #include "libavutil/time.h"
  26. #include "libavutil/parseutils.h"
  27. #include "internal.h"
  28. #include "avio_internal.h"
  29. #include "dash.h"
  30. #define INITIAL_BUFFER_SIZE 32768
  31. struct fragment {
  32. int64_t url_offset;
  33. int64_t size;
  34. char *url;
  35. };
  36. /*
  37. * reference to : ISO_IEC_23009-1-DASH-2012
  38. * Section: 5.3.9.6.2
  39. * Table: Table 17 — Semantics of SegmentTimeline element
  40. * */
  41. struct timeline {
  42. /* starttime: Element or Attribute Name
  43. * specifies the MPD start time, in @timescale units,
  44. * the first Segment in the series starts relative to the beginning of the Period.
  45. * The value of this attribute must be equal to or greater than the sum of the previous S
  46. * element earliest presentation time and the sum of the contiguous Segment durations.
  47. * If the value of the attribute is greater than what is expressed by the previous S element,
  48. * it expresses discontinuities in the timeline.
  49. * If not present then the value shall be assumed to be zero for the first S element
  50. * and for the subsequent S elements, the value shall be assumed to be the sum of
  51. * the previous S element's earliest presentation time and contiguous duration
  52. * (i.e. previous S@starttime + @duration * (@repeat + 1)).
  53. * */
  54. int64_t starttime;
  55. /* repeat: Element or Attribute Name
  56. * specifies the repeat count of the number of following contiguous Segments with
  57. * the same duration expressed by the value of @duration. This value is zero-based
  58. * (e.g. a value of three means four Segments in the contiguous series).
  59. * */
  60. int64_t repeat;
  61. /* duration: Element or Attribute Name
  62. * specifies the Segment duration, in units of the value of the @timescale.
  63. * */
  64. int64_t duration;
  65. };
  66. /*
  67. * Each playlist has its own demuxer. If it is currently active,
  68. * it has an opened AVIOContext too, and potentially an AVPacket
  69. * containing the next packet from this stream.
  70. */
  71. struct representation {
  72. char *url_template;
  73. AVIOContext pb;
  74. AVIOContext *input;
  75. AVFormatContext *parent;
  76. AVFormatContext *ctx;
  77. AVPacket pkt;
  78. int rep_idx;
  79. int rep_count;
  80. int stream_index;
  81. enum AVMediaType type;
  82. char id[20];
  83. int bandwidth;
  84. AVRational framerate;
  85. AVStream *assoc_stream; /* demuxer stream associated with this representation */
  86. int n_fragments;
  87. struct fragment **fragments; /* VOD list of fragment for profile */
  88. int n_timelines;
  89. struct timeline **timelines;
  90. int64_t first_seq_no;
  91. int64_t last_seq_no;
  92. int64_t start_number; /* used in case when we have dynamic list of segment to know which segments are new one*/
  93. int64_t fragment_duration;
  94. int64_t fragment_timescale;
  95. int64_t presentation_timeoffset;
  96. int64_t cur_seq_no;
  97. int64_t cur_seg_offset;
  98. int64_t cur_seg_size;
  99. struct fragment *cur_seg;
  100. /* Currently active Media Initialization Section */
  101. struct fragment *init_section;
  102. uint8_t *init_sec_buf;
  103. uint32_t init_sec_buf_size;
  104. uint32_t init_sec_data_len;
  105. uint32_t init_sec_buf_read_offset;
  106. int64_t cur_timestamp;
  107. int is_restart_needed;
  108. };
  109. typedef struct DASHContext {
  110. const AVClass *class;
  111. char *base_url;
  112. 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. xmlFree(presentation_timeoffset_val);
  815. }
  816. if (duration_val) {
  817. rep->fragment_duration = (int64_t) strtoll(duration_val, NULL, 10);
  818. xmlFree(duration_val);
  819. }
  820. if (timescale_val) {
  821. rep->fragment_timescale = (int64_t) strtoll(timescale_val, NULL, 10);
  822. xmlFree(timescale_val);
  823. }
  824. if (startnumber_val) {
  825. rep->first_seq_no = (int64_t) strtoll(startnumber_val, NULL, 10);
  826. xmlFree(startnumber_val);
  827. }
  828. if (adaptionset_supplementalproperty_node) {
  829. if (!av_strcasecmp(xmlGetProp(adaptionset_supplementalproperty_node,"schemeIdUri"), "http://dashif.org/guidelines/last-segment-number")) {
  830. val = xmlGetProp(adaptionset_supplementalproperty_node,"value");
  831. if (!val) {
  832. av_log(s, AV_LOG_ERROR, "Missing value attribute in adaptionset_supplementalproperty_node\n");
  833. } else {
  834. rep->last_seq_no =(int64_t) strtoll(val, NULL, 10) - 1;
  835. xmlFree(val);
  836. }
  837. }
  838. }
  839. fragment_timeline_node = find_child_node_by_name(representation_segmenttemplate_node, "SegmentTimeline");
  840. if (!fragment_timeline_node)
  841. fragment_timeline_node = find_child_node_by_name(fragment_template_node, "SegmentTimeline");
  842. if (!fragment_timeline_node)
  843. fragment_timeline_node = find_child_node_by_name(adaptionset_segmentlist_node, "SegmentTimeline");
  844. if (!fragment_timeline_node)
  845. fragment_timeline_node = find_child_node_by_name(period_segmentlist_node, "SegmentTimeline");
  846. if (fragment_timeline_node) {
  847. fragment_timeline_node = xmlFirstElementChild(fragment_timeline_node);
  848. while (fragment_timeline_node) {
  849. ret = parse_manifest_segmenttimeline(s, rep, fragment_timeline_node);
  850. if (ret < 0) {
  851. return ret;
  852. }
  853. fragment_timeline_node = xmlNextElementSibling(fragment_timeline_node);
  854. }
  855. }
  856. } else if (representation_baseurl_node && !representation_segmentlist_node) {
  857. seg = av_mallocz(sizeof(struct fragment));
  858. if (!seg) {
  859. ret = AVERROR(ENOMEM);
  860. goto end;
  861. }
  862. seg->url = get_content_url(baseurl_nodes, 4, c->max_url_size, rep_id_val, rep_bandwidth_val, NULL);
  863. if (!seg->url) {
  864. av_free(seg);
  865. ret = AVERROR(ENOMEM);
  866. goto end;
  867. }
  868. seg->size = -1;
  869. dynarray_add(&rep->fragments, &rep->n_fragments, seg);
  870. } else if (representation_segmentlist_node) {
  871. // TODO: https://www.brendanlong.com/the-structure-of-an-mpeg-dash-mpd.html
  872. // http://www-itec.uni-klu.ac.at/dash/ddash/mpdGenerator.php?fragmentlength=15&type=full
  873. xmlNodePtr fragmenturl_node = NULL;
  874. segmentlists_tab[0] = representation_segmentlist_node;
  875. segmentlists_tab[1] = adaptionset_segmentlist_node;
  876. duration_val = get_val_from_nodes_tab(segmentlists_tab, 2, "duration");
  877. timescale_val = get_val_from_nodes_tab(segmentlists_tab, 2, "timescale");
  878. if (duration_val) {
  879. rep->fragment_duration = (int64_t) strtoll(duration_val, NULL, 10);
  880. xmlFree(duration_val);
  881. }
  882. if (timescale_val) {
  883. rep->fragment_timescale = (int64_t) strtoll(timescale_val, NULL, 10);
  884. xmlFree(timescale_val);
  885. }
  886. fragmenturl_node = xmlFirstElementChild(representation_segmentlist_node);
  887. while (fragmenturl_node) {
  888. ret = parse_manifest_segmenturlnode(s, rep, fragmenturl_node,
  889. baseurl_nodes,
  890. rep_id_val,
  891. rep_bandwidth_val);
  892. if (ret < 0) {
  893. return ret;
  894. }
  895. fragmenturl_node = xmlNextElementSibling(fragmenturl_node);
  896. }
  897. fragment_timeline_node = find_child_node_by_name(representation_segmenttemplate_node, "SegmentTimeline");
  898. if (!fragment_timeline_node)
  899. fragment_timeline_node = find_child_node_by_name(fragment_template_node, "SegmentTimeline");
  900. if (!fragment_timeline_node)
  901. fragment_timeline_node = find_child_node_by_name(adaptionset_segmentlist_node, "SegmentTimeline");
  902. if (!fragment_timeline_node)
  903. fragment_timeline_node = find_child_node_by_name(period_segmentlist_node, "SegmentTimeline");
  904. if (fragment_timeline_node) {
  905. fragment_timeline_node = xmlFirstElementChild(fragment_timeline_node);
  906. while (fragment_timeline_node) {
  907. ret = parse_manifest_segmenttimeline(s, rep, fragment_timeline_node);
  908. if (ret < 0) {
  909. return ret;
  910. }
  911. fragment_timeline_node = xmlNextElementSibling(fragment_timeline_node);
  912. }
  913. }
  914. } else {
  915. free_representation(rep);
  916. rep = NULL;
  917. av_log(s, AV_LOG_ERROR, "Unknown format of Representation node id[%s] \n", (const char *)rep_id_val);
  918. }
  919. if (rep) {
  920. if (rep->fragment_duration > 0 && !rep->fragment_timescale)
  921. rep->fragment_timescale = 1;
  922. rep->bandwidth = rep_bandwidth_val ? atoi(rep_bandwidth_val) : 0;
  923. strncpy(rep->id, rep_id_val ? rep_id_val : "", sizeof(rep->id));
  924. rep->framerate = av_make_q(0, 0);
  925. if (type == AVMEDIA_TYPE_VIDEO && rep_framerate_val) {
  926. ret = av_parse_video_rate(&rep->framerate, rep_framerate_val);
  927. if (ret < 0)
  928. av_log(s, AV_LOG_VERBOSE, "Ignoring invalid frame rate '%s'\n", rep_framerate_val);
  929. }
  930. if (type == AVMEDIA_TYPE_VIDEO) {
  931. rep->rep_idx = video_rep_idx;
  932. dynarray_add(&c->videos, &c->n_videos, rep);
  933. } else {
  934. rep->rep_idx = audio_rep_idx;
  935. dynarray_add(&c->audios, &c->n_audios, rep);
  936. }
  937. }
  938. }
  939. video_rep_idx += type == AVMEDIA_TYPE_VIDEO;
  940. audio_rep_idx += type == AVMEDIA_TYPE_AUDIO;
  941. end:
  942. if (rep_id_val)
  943. xmlFree(rep_id_val);
  944. if (rep_bandwidth_val)
  945. xmlFree(rep_bandwidth_val);
  946. if (rep_framerate_val)
  947. xmlFree(rep_framerate_val);
  948. return ret;
  949. }
  950. static int parse_manifest_adaptationset(AVFormatContext *s, const char *url,
  951. xmlNodePtr adaptionset_node,
  952. xmlNodePtr mpd_baseurl_node,
  953. xmlNodePtr period_baseurl_node,
  954. xmlNodePtr period_segmenttemplate_node,
  955. xmlNodePtr period_segmentlist_node)
  956. {
  957. int ret = 0;
  958. DASHContext *c = s->priv_data;
  959. xmlNodePtr fragment_template_node = NULL;
  960. xmlNodePtr content_component_node = NULL;
  961. xmlNodePtr adaptionset_baseurl_node = NULL;
  962. xmlNodePtr adaptionset_segmentlist_node = NULL;
  963. xmlNodePtr adaptionset_supplementalproperty_node = NULL;
  964. xmlNodePtr node = NULL;
  965. c->adaptionset_contenttype_val = xmlGetProp(adaptionset_node, "contentType");
  966. c->adaptionset_par_val = xmlGetProp(adaptionset_node, "par");
  967. c->adaptionset_lang_val = xmlGetProp(adaptionset_node, "lang");
  968. c->adaptionset_minbw_val = xmlGetProp(adaptionset_node, "minBandwidth");
  969. c->adaptionset_maxbw_val = xmlGetProp(adaptionset_node, "maxBandwidth");
  970. c->adaptionset_minwidth_val = xmlGetProp(adaptionset_node, "minWidth");
  971. c->adaptionset_maxwidth_val = xmlGetProp(adaptionset_node, "maxWidth");
  972. c->adaptionset_minheight_val = xmlGetProp(adaptionset_node, "minHeight");
  973. c->adaptionset_maxheight_val = xmlGetProp(adaptionset_node, "maxHeight");
  974. c->adaptionset_minframerate_val = xmlGetProp(adaptionset_node, "minFrameRate");
  975. c->adaptionset_maxframerate_val = xmlGetProp(adaptionset_node, "maxFrameRate");
  976. c->adaptionset_segmentalignment_val = xmlGetProp(adaptionset_node, "segmentAlignment");
  977. c->adaptionset_bitstreamswitching_val = xmlGetProp(adaptionset_node, "bitstreamSwitching");
  978. node = xmlFirstElementChild(adaptionset_node);
  979. while (node) {
  980. if (!av_strcasecmp(node->name, (const char *)"SegmentTemplate")) {
  981. fragment_template_node = node;
  982. } else if (!av_strcasecmp(node->name, (const char *)"ContentComponent")) {
  983. content_component_node = node;
  984. } else if (!av_strcasecmp(node->name, (const char *)"BaseURL")) {
  985. adaptionset_baseurl_node = node;
  986. } else if (!av_strcasecmp(node->name, (const char *)"SegmentList")) {
  987. adaptionset_segmentlist_node = node;
  988. } else if (!av_strcasecmp(node->name, (const char *)"SupplementalProperty")) {
  989. adaptionset_supplementalproperty_node = node;
  990. } else if (!av_strcasecmp(node->name, (const char *)"Representation")) {
  991. ret = parse_manifest_representation(s, url, node,
  992. adaptionset_node,
  993. mpd_baseurl_node,
  994. period_baseurl_node,
  995. period_segmenttemplate_node,
  996. period_segmentlist_node,
  997. fragment_template_node,
  998. content_component_node,
  999. adaptionset_baseurl_node,
  1000. adaptionset_segmentlist_node,
  1001. adaptionset_supplementalproperty_node);
  1002. if (ret < 0) {
  1003. return ret;
  1004. }
  1005. }
  1006. node = xmlNextElementSibling(node);
  1007. }
  1008. return 0;
  1009. }
  1010. static int parse_manifest(AVFormatContext *s, const char *url, AVIOContext *in)
  1011. {
  1012. DASHContext *c = s->priv_data;
  1013. int ret = 0;
  1014. int close_in = 0;
  1015. uint8_t *new_url = NULL;
  1016. int64_t filesize = 0;
  1017. char *buffer = NULL;
  1018. AVDictionary *opts = NULL;
  1019. xmlDoc *doc = NULL;
  1020. xmlNodePtr root_element = NULL;
  1021. xmlNodePtr node = NULL;
  1022. xmlNodePtr period_node = NULL;
  1023. xmlNodePtr tmp_node = NULL;
  1024. xmlNodePtr mpd_baseurl_node = NULL;
  1025. xmlNodePtr period_baseurl_node = NULL;
  1026. xmlNodePtr period_segmenttemplate_node = NULL;
  1027. xmlNodePtr period_segmentlist_node = NULL;
  1028. xmlNodePtr adaptionset_node = NULL;
  1029. xmlAttrPtr attr = NULL;
  1030. char *val = NULL;
  1031. uint32_t period_duration_sec = 0;
  1032. uint32_t period_start_sec = 0;
  1033. if (!in) {
  1034. close_in = 1;
  1035. av_dict_copy(&opts, c->avio_opts, 0);
  1036. ret = avio_open2(&in, url, AVIO_FLAG_READ, c->interrupt_callback, &opts);
  1037. av_dict_free(&opts);
  1038. if (ret < 0)
  1039. return ret;
  1040. }
  1041. if (av_opt_get(in, "location", AV_OPT_SEARCH_CHILDREN, &new_url) >= 0) {
  1042. c->base_url = av_strdup(new_url);
  1043. } else {
  1044. c->base_url = av_strdup(url);
  1045. }
  1046. filesize = avio_size(in);
  1047. if (filesize <= 0) {
  1048. filesize = 8 * 1024;
  1049. }
  1050. buffer = av_mallocz(filesize);
  1051. if (!buffer) {
  1052. av_free(c->base_url);
  1053. return AVERROR(ENOMEM);
  1054. }
  1055. filesize = avio_read(in, buffer, filesize);
  1056. if (filesize <= 0) {
  1057. av_log(s, AV_LOG_ERROR, "Unable to read to offset '%s'\n", url);
  1058. ret = AVERROR_INVALIDDATA;
  1059. } else {
  1060. LIBXML_TEST_VERSION
  1061. doc = xmlReadMemory(buffer, filesize, c->base_url, NULL, 0);
  1062. root_element = xmlDocGetRootElement(doc);
  1063. node = root_element;
  1064. if (!node) {
  1065. ret = AVERROR_INVALIDDATA;
  1066. av_log(s, AV_LOG_ERROR, "Unable to parse '%s' - missing root node\n", url);
  1067. goto cleanup;
  1068. }
  1069. if (node->type != XML_ELEMENT_NODE ||
  1070. av_strcasecmp(node->name, (const char *)"MPD")) {
  1071. ret = AVERROR_INVALIDDATA;
  1072. av_log(s, AV_LOG_ERROR, "Unable to parse '%s' - wrong root node name[%s] type[%d]\n", url, node->name, (int)node->type);
  1073. goto cleanup;
  1074. }
  1075. val = xmlGetProp(node, "type");
  1076. if (!val) {
  1077. av_log(s, AV_LOG_ERROR, "Unable to parse '%s' - missing type attrib\n", url);
  1078. ret = AVERROR_INVALIDDATA;
  1079. goto cleanup;
  1080. }
  1081. if (!av_strcasecmp(val, (const char *)"dynamic"))
  1082. c->is_live = 1;
  1083. xmlFree(val);
  1084. attr = node->properties;
  1085. while (attr) {
  1086. val = xmlGetProp(node, attr->name);
  1087. if (!av_strcasecmp(attr->name, (const char *)"availabilityStartTime")) {
  1088. c->availability_start_time = get_utc_date_time_insec(s, (const char *)val);
  1089. } else if (!av_strcasecmp(attr->name, (const char *)"availabilityEndTime")) {
  1090. c->availability_end_time = get_utc_date_time_insec(s, (const char *)val);
  1091. } else if (!av_strcasecmp(attr->name, (const char *)"publishTime")) {
  1092. c->publish_time = get_utc_date_time_insec(s, (const char *)val);
  1093. } else if (!av_strcasecmp(attr->name, (const char *)"minimumUpdatePeriod")) {
  1094. c->minimum_update_period = get_duration_insec(s, (const char *)val);
  1095. } else if (!av_strcasecmp(attr->name, (const char *)"timeShiftBufferDepth")) {
  1096. c->time_shift_buffer_depth = get_duration_insec(s, (const char *)val);
  1097. } else if (!av_strcasecmp(attr->name, (const char *)"minBufferTime")) {
  1098. c->min_buffer_time = get_duration_insec(s, (const char *)val);
  1099. } else if (!av_strcasecmp(attr->name, (const char *)"suggestedPresentationDelay")) {
  1100. c->suggested_presentation_delay = get_duration_insec(s, (const char *)val);
  1101. } else if (!av_strcasecmp(attr->name, (const char *)"mediaPresentationDuration")) {
  1102. c->media_presentation_duration = get_duration_insec(s, (const char *)val);
  1103. }
  1104. attr = attr->next;
  1105. xmlFree(val);
  1106. }
  1107. tmp_node = find_child_node_by_name(node, "BaseURL");
  1108. if (tmp_node) {
  1109. mpd_baseurl_node = xmlCopyNode(tmp_node,1);
  1110. } else {
  1111. mpd_baseurl_node = xmlNewNode(NULL, "BaseURL");
  1112. }
  1113. // at now we can handle only one period, with the longest duration
  1114. node = xmlFirstElementChild(node);
  1115. while (node) {
  1116. if (!av_strcasecmp(node->name, (const char *)"Period")) {
  1117. period_duration_sec = 0;
  1118. period_start_sec = 0;
  1119. attr = node->properties;
  1120. while (attr) {
  1121. val = xmlGetProp(node, attr->name);
  1122. if (!av_strcasecmp(attr->name, (const char *)"duration")) {
  1123. period_duration_sec = get_duration_insec(s, (const char *)val);
  1124. } else if (!av_strcasecmp(attr->name, (const char *)"start")) {
  1125. period_start_sec = get_duration_insec(s, (const char *)val);
  1126. }
  1127. attr = attr->next;
  1128. xmlFree(val);
  1129. }
  1130. if ((period_duration_sec) >= (c->period_duration)) {
  1131. period_node = node;
  1132. c->period_duration = period_duration_sec;
  1133. c->period_start = period_start_sec;
  1134. if (c->period_start > 0)
  1135. c->media_presentation_duration = c->period_duration;
  1136. }
  1137. }
  1138. node = xmlNextElementSibling(node);
  1139. }
  1140. if (!period_node) {
  1141. av_log(s, AV_LOG_ERROR, "Unable to parse '%s' - missing Period node\n", url);
  1142. ret = AVERROR_INVALIDDATA;
  1143. goto cleanup;
  1144. }
  1145. adaptionset_node = xmlFirstElementChild(period_node);
  1146. while (adaptionset_node) {
  1147. if (!av_strcasecmp(adaptionset_node->name, (const char *)"BaseURL")) {
  1148. period_baseurl_node = adaptionset_node;
  1149. } else if (!av_strcasecmp(adaptionset_node->name, (const char *)"SegmentTemplate")) {
  1150. period_segmenttemplate_node = adaptionset_node;
  1151. } else if (!av_strcasecmp(adaptionset_node->name, (const char *)"SegmentList")) {
  1152. period_segmentlist_node = adaptionset_node;
  1153. } else if (!av_strcasecmp(adaptionset_node->name, (const char *)"AdaptationSet")) {
  1154. parse_manifest_adaptationset(s, url, adaptionset_node, mpd_baseurl_node, period_baseurl_node, period_segmenttemplate_node, period_segmentlist_node);
  1155. }
  1156. adaptionset_node = xmlNextElementSibling(adaptionset_node);
  1157. }
  1158. cleanup:
  1159. /*free the document */
  1160. xmlFreeDoc(doc);
  1161. xmlCleanupParser();
  1162. xmlFreeNode(mpd_baseurl_node);
  1163. }
  1164. av_free(new_url);
  1165. av_free(buffer);
  1166. if (close_in) {
  1167. avio_close(in);
  1168. }
  1169. return ret;
  1170. }
  1171. static int64_t calc_cur_seg_no(AVFormatContext *s, struct representation *pls)
  1172. {
  1173. DASHContext *c = s->priv_data;
  1174. int64_t num = 0;
  1175. int64_t start_time_offset = 0;
  1176. if (c->is_live) {
  1177. if (pls->n_fragments) {
  1178. num = pls->first_seq_no;
  1179. } else if (pls->n_timelines) {
  1180. start_time_offset = get_segment_start_time_based_on_timeline(pls, 0xFFFFFFFF) - 60 * pls->fragment_timescale; // 60 seconds before end
  1181. num = calc_next_seg_no_from_timelines(pls, start_time_offset);
  1182. if (num == -1)
  1183. num = pls->first_seq_no;
  1184. else
  1185. num += pls->first_seq_no;
  1186. } else if (pls->fragment_duration){
  1187. if (pls->presentation_timeoffset) {
  1188. num = pls->presentation_timeoffset * pls->fragment_timescale / pls->fragment_duration;
  1189. } else if (c->publish_time > 0 && !c->availability_start_time) {
  1190. 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;
  1191. } else {
  1192. num = pls->first_seq_no + (((get_current_time_in_sec() - c->availability_start_time) - c->suggested_presentation_delay) * pls->fragment_timescale) / pls->fragment_duration;
  1193. }
  1194. }
  1195. } else {
  1196. num = pls->first_seq_no;
  1197. }
  1198. return num;
  1199. }
  1200. static int64_t calc_min_seg_no(AVFormatContext *s, struct representation *pls)
  1201. {
  1202. DASHContext *c = s->priv_data;
  1203. int64_t num = 0;
  1204. if (c->is_live && pls->fragment_duration) {
  1205. 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;
  1206. } else {
  1207. num = pls->first_seq_no;
  1208. }
  1209. return num;
  1210. }
  1211. static int64_t calc_max_seg_no(struct representation *pls, DASHContext *c)
  1212. {
  1213. int64_t num = 0;
  1214. if (pls->n_fragments) {
  1215. num = pls->first_seq_no + pls->n_fragments - 1;
  1216. } else if (pls->n_timelines) {
  1217. int i = 0;
  1218. num = pls->first_seq_no + pls->n_timelines - 1;
  1219. for (i = 0; i < pls->n_timelines; i++) {
  1220. if (pls->timelines[i]->repeat == -1) {
  1221. int length_of_each_segment = pls->timelines[i]->duration / pls->fragment_timescale;
  1222. num = c->period_duration / length_of_each_segment;
  1223. } else {
  1224. num += pls->timelines[i]->repeat;
  1225. }
  1226. }
  1227. } else if (c->is_live && pls->fragment_duration) {
  1228. num = pls->first_seq_no + (((get_current_time_in_sec() - c->availability_start_time)) * pls->fragment_timescale) / pls->fragment_duration;
  1229. } else if (pls->fragment_duration) {
  1230. num = pls->first_seq_no + (c->media_presentation_duration * pls->fragment_timescale) / pls->fragment_duration;
  1231. }
  1232. return num;
  1233. }
  1234. static void move_timelines(struct representation *rep_src, struct representation *rep_dest, DASHContext *c)
  1235. {
  1236. if (rep_dest && rep_src ) {
  1237. free_timelines_list(rep_dest);
  1238. rep_dest->timelines = rep_src->timelines;
  1239. rep_dest->n_timelines = rep_src->n_timelines;
  1240. rep_dest->first_seq_no = rep_src->first_seq_no;
  1241. rep_dest->last_seq_no = calc_max_seg_no(rep_dest, c);
  1242. rep_src->timelines = NULL;
  1243. rep_src->n_timelines = 0;
  1244. rep_dest->cur_seq_no = rep_src->cur_seq_no;
  1245. }
  1246. }
  1247. static void move_segments(struct representation *rep_src, struct representation *rep_dest, DASHContext *c)
  1248. {
  1249. if (rep_dest && rep_src ) {
  1250. free_fragment_list(rep_dest);
  1251. if (rep_src->start_number > (rep_dest->start_number + rep_dest->n_fragments))
  1252. rep_dest->cur_seq_no = 0;
  1253. else
  1254. rep_dest->cur_seq_no += rep_src->start_number - rep_dest->start_number;
  1255. rep_dest->fragments = rep_src->fragments;
  1256. rep_dest->n_fragments = rep_src->n_fragments;
  1257. rep_dest->parent = rep_src->parent;
  1258. rep_dest->last_seq_no = calc_max_seg_no(rep_dest, c);
  1259. rep_src->fragments = NULL;
  1260. rep_src->n_fragments = 0;
  1261. }
  1262. }
  1263. static int refresh_manifest(AVFormatContext *s)
  1264. {
  1265. int ret = 0, i;
  1266. DASHContext *c = s->priv_data;
  1267. // save current context
  1268. int n_videos = c->n_videos;
  1269. struct representation **videos = c->videos;
  1270. int n_audios = c->n_audios;
  1271. struct representation **audios = c->audios;
  1272. char *base_url = c->base_url;
  1273. c->base_url = NULL;
  1274. c->n_videos = 0;
  1275. c->videos = NULL;
  1276. c->n_audios = 0;
  1277. c->audios = NULL;
  1278. ret = parse_manifest(s, s->url, NULL);
  1279. if (ret)
  1280. goto finish;
  1281. if (c->n_videos != n_videos) {
  1282. av_log(c, AV_LOG_ERROR,
  1283. "new manifest has mismatched no. of video representations, %d -> %d\n",
  1284. n_videos, c->n_videos);
  1285. return AVERROR_INVALIDDATA;
  1286. }
  1287. if (c->n_audios != n_audios) {
  1288. av_log(c, AV_LOG_ERROR,
  1289. "new manifest has mismatched no. of audio representations, %d -> %d\n",
  1290. n_audios, c->n_audios);
  1291. return AVERROR_INVALIDDATA;
  1292. }
  1293. for (i = 0; i < n_videos; i++) {
  1294. struct representation *cur_video = videos[i];
  1295. struct representation *ccur_video = c->videos[i];
  1296. if (cur_video->timelines) {
  1297. // calc current time
  1298. int64_t currentTime = get_segment_start_time_based_on_timeline(cur_video, cur_video->cur_seq_no) / cur_video->fragment_timescale;
  1299. // update segments
  1300. ccur_video->cur_seq_no = calc_next_seg_no_from_timelines(ccur_video, currentTime * cur_video->fragment_timescale - 1);
  1301. if (ccur_video->cur_seq_no >= 0) {
  1302. move_timelines(ccur_video, cur_video, c);
  1303. }
  1304. }
  1305. if (cur_video->fragments) {
  1306. move_segments(ccur_video, cur_video, c);
  1307. }
  1308. }
  1309. for (i = 0; i < n_audios; i++) {
  1310. struct representation *cur_audio = audios[i];
  1311. struct representation *ccur_audio = c->audios[i];
  1312. if (cur_audio->timelines) {
  1313. // calc current time
  1314. int64_t currentTime = get_segment_start_time_based_on_timeline(cur_audio, cur_audio->cur_seq_no) / cur_audio->fragment_timescale;
  1315. // update segments
  1316. ccur_audio->cur_seq_no = calc_next_seg_no_from_timelines(ccur_audio, currentTime * cur_audio->fragment_timescale - 1);
  1317. if (ccur_audio->cur_seq_no >= 0) {
  1318. move_timelines(ccur_audio, cur_audio, c);
  1319. }
  1320. }
  1321. if (cur_audio->fragments) {
  1322. move_segments(ccur_audio, cur_audio, c);
  1323. }
  1324. }
  1325. finish:
  1326. // restore context
  1327. if (c->base_url)
  1328. av_free(base_url);
  1329. else
  1330. c->base_url = base_url;
  1331. if (c->audios)
  1332. free_audio_list(c);
  1333. if (c->videos)
  1334. free_video_list(c);
  1335. c->n_audios = n_audios;
  1336. c->audios = audios;
  1337. c->n_videos = n_videos;
  1338. c->videos = videos;
  1339. return ret;
  1340. }
  1341. static struct fragment *get_current_fragment(struct representation *pls)
  1342. {
  1343. int64_t min_seq_no = 0;
  1344. int64_t max_seq_no = 0;
  1345. struct fragment *seg = NULL;
  1346. struct fragment *seg_ptr = NULL;
  1347. DASHContext *c = pls->parent->priv_data;
  1348. while (( !ff_check_interrupt(c->interrupt_callback)&& pls->n_fragments > 0)) {
  1349. if (pls->cur_seq_no < pls->n_fragments) {
  1350. seg_ptr = pls->fragments[pls->cur_seq_no];
  1351. seg = av_mallocz(sizeof(struct fragment));
  1352. if (!seg) {
  1353. return NULL;
  1354. }
  1355. seg->url = av_strdup(seg_ptr->url);
  1356. if (!seg->url) {
  1357. av_free(seg);
  1358. return NULL;
  1359. }
  1360. seg->size = seg_ptr->size;
  1361. seg->url_offset = seg_ptr->url_offset;
  1362. return seg;
  1363. } else if (c->is_live) {
  1364. refresh_manifest(pls->parent);
  1365. } else {
  1366. break;
  1367. }
  1368. }
  1369. if (c->is_live) {
  1370. min_seq_no = calc_min_seg_no(pls->parent, pls);
  1371. max_seq_no = calc_max_seg_no(pls, c);
  1372. if (pls->timelines || pls->fragments) {
  1373. refresh_manifest(pls->parent);
  1374. }
  1375. if (pls->cur_seq_no <= min_seq_no) {
  1376. 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);
  1377. pls->cur_seq_no = calc_cur_seg_no(pls->parent, pls);
  1378. } else if (pls->cur_seq_no > max_seq_no) {
  1379. 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);
  1380. }
  1381. seg = av_mallocz(sizeof(struct fragment));
  1382. if (!seg) {
  1383. return NULL;
  1384. }
  1385. } else if (pls->cur_seq_no <= pls->last_seq_no) {
  1386. seg = av_mallocz(sizeof(struct fragment));
  1387. if (!seg) {
  1388. return NULL;
  1389. }
  1390. }
  1391. if (seg) {
  1392. char *tmpfilename= av_mallocz(c->max_url_size);
  1393. if (!tmpfilename) {
  1394. return NULL;
  1395. }
  1396. 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));
  1397. seg->url = av_strireplace(pls->url_template, pls->url_template, tmpfilename);
  1398. if (!seg->url) {
  1399. av_log(pls->parent, AV_LOG_WARNING, "Unable to resolve template url '%s', try to use origin template\n", pls->url_template);
  1400. seg->url = av_strdup(pls->url_template);
  1401. if (!seg->url) {
  1402. av_log(pls->parent, AV_LOG_ERROR, "Cannot resolve template url '%s'\n", pls->url_template);
  1403. av_free(tmpfilename);
  1404. return NULL;
  1405. }
  1406. }
  1407. av_free(tmpfilename);
  1408. seg->size = -1;
  1409. }
  1410. return seg;
  1411. }
  1412. enum ReadFromURLMode {
  1413. READ_NORMAL,
  1414. READ_COMPLETE,
  1415. };
  1416. static int read_from_url(struct representation *pls, struct fragment *seg,
  1417. uint8_t *buf, int buf_size,
  1418. enum ReadFromURLMode mode)
  1419. {
  1420. int ret;
  1421. /* limit read if the fragment was only a part of a file */
  1422. if (seg->size >= 0)
  1423. buf_size = FFMIN(buf_size, pls->cur_seg_size - pls->cur_seg_offset);
  1424. if (mode == READ_COMPLETE) {
  1425. ret = avio_read(pls->input, buf, buf_size);
  1426. if (ret < buf_size) {
  1427. av_log(pls->parent, AV_LOG_WARNING, "Could not read complete fragment.\n");
  1428. }
  1429. } else {
  1430. ret = avio_read(pls->input, buf, buf_size);
  1431. }
  1432. if (ret > 0)
  1433. pls->cur_seg_offset += ret;
  1434. return ret;
  1435. }
  1436. static int open_input(DASHContext *c, struct representation *pls, struct fragment *seg)
  1437. {
  1438. AVDictionary *opts = NULL;
  1439. char *url = NULL;
  1440. int ret = 0;
  1441. url = av_mallocz(c->max_url_size);
  1442. if (!url) {
  1443. goto cleanup;
  1444. }
  1445. if (seg->size >= 0) {
  1446. /* try to restrict the HTTP request to the part we want
  1447. * (if this is in fact a HTTP request) */
  1448. av_dict_set_int(&opts, "offset", seg->url_offset, 0);
  1449. av_dict_set_int(&opts, "end_offset", seg->url_offset + seg->size, 0);
  1450. }
  1451. ff_make_absolute_url(url, c->max_url_size, c->base_url, seg->url);
  1452. av_log(pls->parent, AV_LOG_VERBOSE, "DASH request for url '%s', offset %"PRId64", playlist %d\n",
  1453. url, seg->url_offset, pls->rep_idx);
  1454. ret = open_url(pls->parent, &pls->input, url, c->avio_opts, opts, NULL);
  1455. if (ret < 0) {
  1456. goto cleanup;
  1457. }
  1458. cleanup:
  1459. av_free(url);
  1460. av_dict_free(&opts);
  1461. pls->cur_seg_offset = 0;
  1462. pls->cur_seg_size = seg->size;
  1463. return ret;
  1464. }
  1465. static int update_init_section(struct representation *pls)
  1466. {
  1467. static const int max_init_section_size = 1024 * 1024;
  1468. DASHContext *c = pls->parent->priv_data;
  1469. int64_t sec_size;
  1470. int64_t urlsize;
  1471. int ret;
  1472. if (!pls->init_section || pls->init_sec_buf)
  1473. return 0;
  1474. ret = open_input(c, pls, pls->init_section);
  1475. if (ret < 0) {
  1476. av_log(pls->parent, AV_LOG_WARNING,
  1477. "Failed to open an initialization section in playlist %d\n",
  1478. pls->rep_idx);
  1479. return ret;
  1480. }
  1481. if (pls->init_section->size >= 0)
  1482. sec_size = pls->init_section->size;
  1483. else if ((urlsize = avio_size(pls->input)) >= 0)
  1484. sec_size = urlsize;
  1485. else
  1486. sec_size = max_init_section_size;
  1487. av_log(pls->parent, AV_LOG_DEBUG,
  1488. "Downloading an initialization section of size %"PRId64"\n",
  1489. sec_size);
  1490. sec_size = FFMIN(sec_size, max_init_section_size);
  1491. av_fast_malloc(&pls->init_sec_buf, &pls->init_sec_buf_size, sec_size);
  1492. ret = read_from_url(pls, pls->init_section, pls->init_sec_buf,
  1493. pls->init_sec_buf_size, READ_COMPLETE);
  1494. ff_format_io_close(pls->parent, &pls->input);
  1495. if (ret < 0)
  1496. return ret;
  1497. pls->init_sec_data_len = ret;
  1498. pls->init_sec_buf_read_offset = 0;
  1499. return 0;
  1500. }
  1501. static int64_t seek_data(void *opaque, int64_t offset, int whence)
  1502. {
  1503. struct representation *v = opaque;
  1504. if (v->n_fragments && !v->init_sec_data_len) {
  1505. return avio_seek(v->input, offset, whence);
  1506. }
  1507. return AVERROR(ENOSYS);
  1508. }
  1509. static int read_data(void *opaque, uint8_t *buf, int buf_size)
  1510. {
  1511. int ret = 0;
  1512. struct representation *v = opaque;
  1513. DASHContext *c = v->parent->priv_data;
  1514. restart:
  1515. if (!v->input) {
  1516. free_fragment(&v->cur_seg);
  1517. v->cur_seg = get_current_fragment(v);
  1518. if (!v->cur_seg) {
  1519. ret = AVERROR_EOF;
  1520. goto end;
  1521. }
  1522. /* load/update Media Initialization Section, if any */
  1523. ret = update_init_section(v);
  1524. if (ret)
  1525. goto end;
  1526. ret = open_input(c, v, v->cur_seg);
  1527. if (ret < 0) {
  1528. if (ff_check_interrupt(c->interrupt_callback)) {
  1529. goto end;
  1530. ret = AVERROR_EXIT;
  1531. }
  1532. av_log(v->parent, AV_LOG_WARNING, "Failed to open fragment of playlist %d\n", v->rep_idx);
  1533. v->cur_seq_no++;
  1534. goto restart;
  1535. }
  1536. }
  1537. if (v->init_sec_buf_read_offset < v->init_sec_data_len) {
  1538. /* Push init section out first before first actual fragment */
  1539. int copy_size = FFMIN(v->init_sec_data_len - v->init_sec_buf_read_offset, buf_size);
  1540. memcpy(buf, v->init_sec_buf, copy_size);
  1541. v->init_sec_buf_read_offset += copy_size;
  1542. ret = copy_size;
  1543. goto end;
  1544. }
  1545. /* check the v->cur_seg, if it is null, get current and double check if the new v->cur_seg*/
  1546. if (!v->cur_seg) {
  1547. v->cur_seg = get_current_fragment(v);
  1548. }
  1549. if (!v->cur_seg) {
  1550. ret = AVERROR_EOF;
  1551. goto end;
  1552. }
  1553. ret = read_from_url(v, v->cur_seg, buf, buf_size, READ_NORMAL);
  1554. if (ret > 0)
  1555. goto end;
  1556. if (c->is_live || v->cur_seq_no < v->last_seq_no) {
  1557. if (!v->is_restart_needed)
  1558. v->cur_seq_no++;
  1559. v->is_restart_needed = 1;
  1560. }
  1561. end:
  1562. return ret;
  1563. }
  1564. static int save_avio_options(AVFormatContext *s)
  1565. {
  1566. DASHContext *c = s->priv_data;
  1567. const char *opts[] = { "headers", "user_agent", "cookies", NULL }, **opt = opts;
  1568. uint8_t *buf = NULL;
  1569. int ret = 0;
  1570. while (*opt) {
  1571. if (av_opt_get(s->pb, *opt, AV_OPT_SEARCH_CHILDREN, &buf) >= 0) {
  1572. if (buf[0] != '\0') {
  1573. ret = av_dict_set(&c->avio_opts, *opt, buf, AV_DICT_DONT_STRDUP_VAL);
  1574. if (ret < 0) {
  1575. av_freep(&buf);
  1576. return ret;
  1577. }
  1578. } else {
  1579. av_freep(&buf);
  1580. }
  1581. }
  1582. opt++;
  1583. }
  1584. return ret;
  1585. }
  1586. static int nested_io_open(AVFormatContext *s, AVIOContext **pb, const char *url,
  1587. int flags, AVDictionary **opts)
  1588. {
  1589. av_log(s, AV_LOG_ERROR,
  1590. "A DASH playlist item '%s' referred to an external file '%s'. "
  1591. "Opening this file was forbidden for security reasons\n",
  1592. s->url, url);
  1593. return AVERROR(EPERM);
  1594. }
  1595. static void close_demux_for_component(struct representation *pls)
  1596. {
  1597. /* note: the internal buffer could have changed */
  1598. av_freep(&pls->pb.buffer);
  1599. memset(&pls->pb, 0x00, sizeof(AVIOContext));
  1600. pls->ctx->pb = NULL;
  1601. avformat_close_input(&pls->ctx);
  1602. pls->ctx = NULL;
  1603. }
  1604. static int reopen_demux_for_component(AVFormatContext *s, struct representation *pls)
  1605. {
  1606. DASHContext *c = s->priv_data;
  1607. AVInputFormat *in_fmt = NULL;
  1608. AVDictionary *in_fmt_opts = NULL;
  1609. uint8_t *avio_ctx_buffer = NULL;
  1610. int ret = 0, i;
  1611. if (pls->ctx) {
  1612. close_demux_for_component(pls);
  1613. }
  1614. if (ff_check_interrupt(&s->interrupt_callback)) {
  1615. ret = AVERROR_EXIT;
  1616. goto fail;
  1617. }
  1618. if (!(pls->ctx = avformat_alloc_context())) {
  1619. ret = AVERROR(ENOMEM);
  1620. goto fail;
  1621. }
  1622. avio_ctx_buffer = av_malloc(INITIAL_BUFFER_SIZE);
  1623. if (!avio_ctx_buffer ) {
  1624. ret = AVERROR(ENOMEM);
  1625. avformat_free_context(pls->ctx);
  1626. pls->ctx = NULL;
  1627. goto fail;
  1628. }
  1629. if (c->is_live) {
  1630. ffio_init_context(&pls->pb, avio_ctx_buffer , INITIAL_BUFFER_SIZE, 0, pls, read_data, NULL, NULL);
  1631. } else {
  1632. ffio_init_context(&pls->pb, avio_ctx_buffer , INITIAL_BUFFER_SIZE, 0, pls, read_data, NULL, seek_data);
  1633. }
  1634. pls->pb.seekable = 0;
  1635. if ((ret = ff_copy_whiteblacklists(pls->ctx, s)) < 0)
  1636. goto fail;
  1637. pls->ctx->flags = AVFMT_FLAG_CUSTOM_IO;
  1638. pls->ctx->probesize = 1024 * 4;
  1639. pls->ctx->max_analyze_duration = 4 * AV_TIME_BASE;
  1640. ret = av_probe_input_buffer(&pls->pb, &in_fmt, "", NULL, 0, 0);
  1641. if (ret < 0) {
  1642. av_log(s, AV_LOG_ERROR, "Error when loading first fragment, playlist %d\n", (int)pls->rep_idx);
  1643. avformat_free_context(pls->ctx);
  1644. pls->ctx = NULL;
  1645. goto fail;
  1646. }
  1647. pls->ctx->pb = &pls->pb;
  1648. pls->ctx->io_open = nested_io_open;
  1649. // provide additional information from mpd if available
  1650. ret = avformat_open_input(&pls->ctx, "", in_fmt, &in_fmt_opts); //pls->init_section->url
  1651. av_dict_free(&in_fmt_opts);
  1652. if (ret < 0)
  1653. goto fail;
  1654. if (pls->n_fragments) {
  1655. #if FF_API_R_FRAME_RATE
  1656. if (pls->framerate.den) {
  1657. for (i = 0; i < pls->ctx->nb_streams; i++)
  1658. pls->ctx->streams[i]->r_frame_rate = pls->framerate;
  1659. }
  1660. #endif
  1661. ret = avformat_find_stream_info(pls->ctx, NULL);
  1662. if (ret < 0)
  1663. goto fail;
  1664. }
  1665. fail:
  1666. return ret;
  1667. }
  1668. static int open_demux_for_component(AVFormatContext *s, struct representation *pls)
  1669. {
  1670. int ret = 0;
  1671. int i;
  1672. pls->parent = s;
  1673. pls->cur_seq_no = calc_cur_seg_no(s, pls);
  1674. if (!pls->last_seq_no) {
  1675. pls->last_seq_no = calc_max_seg_no(pls, s->priv_data);
  1676. }
  1677. ret = reopen_demux_for_component(s, pls);
  1678. if (ret < 0) {
  1679. goto fail;
  1680. }
  1681. for (i = 0; i < pls->ctx->nb_streams; i++) {
  1682. AVStream *st = avformat_new_stream(s, NULL);
  1683. AVStream *ist = pls->ctx->streams[i];
  1684. if (!st) {
  1685. ret = AVERROR(ENOMEM);
  1686. goto fail;
  1687. }
  1688. st->id = i;
  1689. avcodec_parameters_copy(st->codecpar, pls->ctx->streams[i]->codecpar);
  1690. avpriv_set_pts_info(st, ist->pts_wrap_bits, ist->time_base.num, ist->time_base.den);
  1691. }
  1692. return 0;
  1693. fail:
  1694. return ret;
  1695. }
  1696. static int is_common_init_section_exist(struct representation **pls, int n_pls)
  1697. {
  1698. struct fragment *first_init_section = pls[0]->init_section;
  1699. char *url =NULL;
  1700. int64_t url_offset = -1;
  1701. int64_t size = -1;
  1702. int i = 0;
  1703. if (first_init_section == NULL || n_pls == 0)
  1704. return 0;
  1705. url = first_init_section->url;
  1706. url_offset = first_init_section->url_offset;
  1707. size = pls[0]->init_section->size;
  1708. for (i=0;i<n_pls;i++) {
  1709. if (av_strcasecmp(pls[i]->init_section->url,url) || pls[i]->init_section->url_offset != url_offset || pls[i]->init_section->size != size) {
  1710. return 0;
  1711. }
  1712. }
  1713. return 1;
  1714. }
  1715. static void copy_init_section(struct representation *rep_dest, struct representation *rep_src)
  1716. {
  1717. rep_dest->init_sec_buf = av_mallocz(rep_src->init_sec_buf_size);
  1718. memcpy(rep_dest->init_sec_buf, rep_src->init_sec_buf, rep_src->init_sec_data_len);
  1719. rep_dest->init_sec_buf_size = rep_src->init_sec_buf_size;
  1720. rep_dest->init_sec_data_len = rep_src->init_sec_data_len;
  1721. rep_dest->cur_timestamp = rep_src->cur_timestamp;
  1722. }
  1723. static int dash_read_header(AVFormatContext *s)
  1724. {
  1725. DASHContext *c = s->priv_data;
  1726. int ret = 0;
  1727. int stream_index = 0;
  1728. int i;
  1729. c->interrupt_callback = &s->interrupt_callback;
  1730. if ((ret = save_avio_options(s)) < 0)
  1731. goto fail;
  1732. av_dict_set(&c->avio_opts, "seekable", "0", 0);
  1733. if ((ret = parse_manifest(s, s->url, s->pb)) < 0)
  1734. goto fail;
  1735. /* If this isn't a live stream, fill the total duration of the
  1736. * stream. */
  1737. if (!c->is_live) {
  1738. s->duration = (int64_t) c->media_presentation_duration * AV_TIME_BASE;
  1739. }
  1740. if(c->n_videos)
  1741. c->is_init_section_common_video = is_common_init_section_exist(c->videos, c->n_videos);
  1742. /* Open the demuxer for video and audio components if available */
  1743. for (i = 0; i < c->n_videos; i++) {
  1744. struct representation *cur_video = c->videos[i];
  1745. if (i > 0 && c->is_init_section_common_video) {
  1746. copy_init_section(cur_video,c->videos[0]);
  1747. }
  1748. ret = open_demux_for_component(s, cur_video);
  1749. if (ret)
  1750. goto fail;
  1751. cur_video->stream_index = stream_index;
  1752. ++stream_index;
  1753. }
  1754. if(c->n_audios)
  1755. c->is_init_section_common_audio = is_common_init_section_exist(c->audios, c->n_audios);
  1756. for (i = 0; i < c->n_audios; i++) {
  1757. struct representation *cur_audio = c->audios[i];
  1758. if (i > 0 && c->is_init_section_common_audio) {
  1759. copy_init_section(cur_audio,c->audios[0]);
  1760. }
  1761. ret = open_demux_for_component(s, cur_audio);
  1762. if (ret)
  1763. goto fail;
  1764. cur_audio->stream_index = stream_index;
  1765. ++stream_index;
  1766. }
  1767. if (!stream_index) {
  1768. ret = AVERROR_INVALIDDATA;
  1769. goto fail;
  1770. }
  1771. /* Create a program */
  1772. if (!ret) {
  1773. AVProgram *program;
  1774. program = av_new_program(s, 0);
  1775. if (!program) {
  1776. goto fail;
  1777. }
  1778. for (i = 0; i < c->n_videos; i++) {
  1779. struct representation *pls = c->videos[i];
  1780. av_program_add_stream_index(s, 0, pls->stream_index);
  1781. pls->assoc_stream = s->streams[pls->stream_index];
  1782. if (pls->bandwidth > 0)
  1783. av_dict_set_int(&pls->assoc_stream->metadata, "variant_bitrate", pls->bandwidth, 0);
  1784. if (pls->id[0])
  1785. av_dict_set(&pls->assoc_stream->metadata, "id", pls->id, 0);
  1786. }
  1787. for (i = 0; i < c->n_audios; i++) {
  1788. struct representation *pls = c->audios[i];
  1789. av_program_add_stream_index(s, 0, pls->stream_index);
  1790. pls->assoc_stream = s->streams[pls->stream_index];
  1791. if (pls->bandwidth > 0)
  1792. av_dict_set_int(&pls->assoc_stream->metadata, "variant_bitrate", pls->bandwidth, 0);
  1793. if (pls->id[0])
  1794. av_dict_set(&pls->assoc_stream->metadata, "id", pls->id, 0);
  1795. }
  1796. }
  1797. return 0;
  1798. fail:
  1799. return ret;
  1800. }
  1801. static void recheck_discard_flags(AVFormatContext *s, struct representation **p, int n)
  1802. {
  1803. int i, j;
  1804. for (i = 0; i < n; i++) {
  1805. struct representation *pls = p[i];
  1806. int needed = !pls->assoc_stream || pls->assoc_stream->discard < AVDISCARD_ALL;
  1807. if (needed && !pls->ctx) {
  1808. pls->cur_seg_offset = 0;
  1809. pls->init_sec_buf_read_offset = 0;
  1810. /* Catch up */
  1811. for (j = 0; j < n; j++) {
  1812. pls->cur_seq_no = FFMAX(pls->cur_seq_no, p[j]->cur_seq_no);
  1813. }
  1814. reopen_demux_for_component(s, pls);
  1815. av_log(s, AV_LOG_INFO, "Now receiving stream_index %d\n", pls->stream_index);
  1816. } else if (!needed && pls->ctx) {
  1817. close_demux_for_component(pls);
  1818. if (pls->input)
  1819. ff_format_io_close(pls->parent, &pls->input);
  1820. av_log(s, AV_LOG_INFO, "No longer receiving stream_index %d\n", pls->stream_index);
  1821. }
  1822. }
  1823. }
  1824. static int dash_read_packet(AVFormatContext *s, AVPacket *pkt)
  1825. {
  1826. DASHContext *c = s->priv_data;
  1827. int ret = 0, i;
  1828. int64_t mints = 0;
  1829. struct representation *cur = NULL;
  1830. recheck_discard_flags(s, c->videos, c->n_videos);
  1831. recheck_discard_flags(s, c->audios, c->n_audios);
  1832. for (i = 0; i < c->n_videos; i++) {
  1833. struct representation *pls = c->videos[i];
  1834. if (!pls->ctx)
  1835. continue;
  1836. if (!cur || pls->cur_timestamp < mints) {
  1837. cur = pls;
  1838. mints = pls->cur_timestamp;
  1839. }
  1840. }
  1841. for (i = 0; i < c->n_audios; i++) {
  1842. struct representation *pls = c->audios[i];
  1843. if (!pls->ctx)
  1844. continue;
  1845. if (!cur || pls->cur_timestamp < mints) {
  1846. cur = pls;
  1847. mints = pls->cur_timestamp;
  1848. }
  1849. }
  1850. if (!cur) {
  1851. return AVERROR_INVALIDDATA;
  1852. }
  1853. while (!ff_check_interrupt(c->interrupt_callback) && !ret) {
  1854. ret = av_read_frame(cur->ctx, pkt);
  1855. if (ret >= 0) {
  1856. /* If we got a packet, return it */
  1857. cur->cur_timestamp = av_rescale(pkt->pts, (int64_t)cur->ctx->streams[0]->time_base.num * 90000, cur->ctx->streams[0]->time_base.den);
  1858. pkt->stream_index = cur->stream_index;
  1859. return 0;
  1860. }
  1861. if (cur->is_restart_needed) {
  1862. cur->cur_seg_offset = 0;
  1863. cur->init_sec_buf_read_offset = 0;
  1864. if (cur->input)
  1865. ff_format_io_close(cur->parent, &cur->input);
  1866. ret = reopen_demux_for_component(s, cur);
  1867. cur->is_restart_needed = 0;
  1868. }
  1869. }
  1870. return AVERROR_EOF;
  1871. }
  1872. static int dash_close(AVFormatContext *s)
  1873. {
  1874. DASHContext *c = s->priv_data;
  1875. free_audio_list(c);
  1876. free_video_list(c);
  1877. av_dict_free(&c->avio_opts);
  1878. av_freep(&c->base_url);
  1879. return 0;
  1880. }
  1881. static int dash_seek(AVFormatContext *s, struct representation *pls, int64_t seek_pos_msec, int flags, int dry_run)
  1882. {
  1883. int ret = 0;
  1884. int i = 0;
  1885. int j = 0;
  1886. int64_t duration = 0;
  1887. av_log(pls->parent, AV_LOG_VERBOSE, "DASH seek pos[%"PRId64"ms], playlist %d%s\n",
  1888. seek_pos_msec, pls->rep_idx, dry_run ? " (dry)" : "");
  1889. // single fragment mode
  1890. if (pls->n_fragments == 1) {
  1891. pls->cur_timestamp = 0;
  1892. pls->cur_seg_offset = 0;
  1893. if (dry_run)
  1894. return 0;
  1895. ff_read_frame_flush(pls->ctx);
  1896. return av_seek_frame(pls->ctx, -1, seek_pos_msec * 1000, flags);
  1897. }
  1898. if (pls->input)
  1899. ff_format_io_close(pls->parent, &pls->input);
  1900. // find the nearest fragment
  1901. if (pls->n_timelines > 0 && pls->fragment_timescale > 0) {
  1902. int64_t num = pls->first_seq_no;
  1903. av_log(pls->parent, AV_LOG_VERBOSE, "dash_seek with SegmentTimeline start n_timelines[%d] "
  1904. "last_seq_no[%"PRId64"], playlist %d.\n",
  1905. (int)pls->n_timelines, (int64_t)pls->last_seq_no, (int)pls->rep_idx);
  1906. for (i = 0; i < pls->n_timelines; i++) {
  1907. if (pls->timelines[i]->starttime > 0) {
  1908. duration = pls->timelines[i]->starttime;
  1909. }
  1910. duration += pls->timelines[i]->duration;
  1911. if (seek_pos_msec < ((duration * 1000) / pls->fragment_timescale)) {
  1912. goto set_seq_num;
  1913. }
  1914. for (j = 0; j < pls->timelines[i]->repeat; j++) {
  1915. duration += pls->timelines[i]->duration;
  1916. num++;
  1917. if (seek_pos_msec < ((duration * 1000) / pls->fragment_timescale)) {
  1918. goto set_seq_num;
  1919. }
  1920. }
  1921. num++;
  1922. }
  1923. set_seq_num:
  1924. pls->cur_seq_no = num > pls->last_seq_no ? pls->last_seq_no : num;
  1925. av_log(pls->parent, AV_LOG_VERBOSE, "dash_seek with SegmentTimeline end cur_seq_no[%"PRId64"], playlist %d.\n",
  1926. (int64_t)pls->cur_seq_no, (int)pls->rep_idx);
  1927. } else if (pls->fragment_duration > 0) {
  1928. pls->cur_seq_no = pls->first_seq_no + ((seek_pos_msec * pls->fragment_timescale) / pls->fragment_duration) / 1000;
  1929. } else {
  1930. av_log(pls->parent, AV_LOG_ERROR, "dash_seek missing timeline or fragment_duration\n");
  1931. pls->cur_seq_no = pls->first_seq_no;
  1932. }
  1933. pls->cur_timestamp = 0;
  1934. pls->cur_seg_offset = 0;
  1935. pls->init_sec_buf_read_offset = 0;
  1936. ret = dry_run ? 0 : reopen_demux_for_component(s, pls);
  1937. return ret;
  1938. }
  1939. static int dash_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
  1940. {
  1941. int ret = 0, i;
  1942. DASHContext *c = s->priv_data;
  1943. int64_t seek_pos_msec = av_rescale_rnd(timestamp, 1000,
  1944. s->streams[stream_index]->time_base.den,
  1945. flags & AVSEEK_FLAG_BACKWARD ?
  1946. AV_ROUND_DOWN : AV_ROUND_UP);
  1947. if ((flags & AVSEEK_FLAG_BYTE) || c->is_live)
  1948. return AVERROR(ENOSYS);
  1949. /* Seek in discarded streams with dry_run=1 to avoid reopening them */
  1950. for (i = 0; i < c->n_videos; i++) {
  1951. if (!ret)
  1952. ret = dash_seek(s, c->videos[i], seek_pos_msec, flags, !c->videos[i]->ctx);
  1953. }
  1954. for (i = 0; i < c->n_audios; i++) {
  1955. if (!ret)
  1956. ret = dash_seek(s, c->audios[i], seek_pos_msec, flags, !c->audios[i]->ctx);
  1957. }
  1958. return ret;
  1959. }
  1960. static int dash_probe(AVProbeData *p)
  1961. {
  1962. if (!av_stristr(p->buf, "<MPD"))
  1963. return 0;
  1964. if (av_stristr(p->buf, "dash:profile:isoff-on-demand:2011") ||
  1965. av_stristr(p->buf, "dash:profile:isoff-live:2011") ||
  1966. av_stristr(p->buf, "dash:profile:isoff-live:2012") ||
  1967. av_stristr(p->buf, "dash:profile:isoff-main:2011")) {
  1968. return AVPROBE_SCORE_MAX;
  1969. }
  1970. if (av_stristr(p->buf, "dash:profile")) {
  1971. return AVPROBE_SCORE_MAX;
  1972. }
  1973. return 0;
  1974. }
  1975. #define OFFSET(x) offsetof(DASHContext, x)
  1976. #define FLAGS AV_OPT_FLAG_DECODING_PARAM
  1977. static const AVOption dash_options[] = {
  1978. {"allowed_extensions", "List of file extensions that dash is allowed to access",
  1979. OFFSET(allowed_extensions), AV_OPT_TYPE_STRING,
  1980. {.str = "aac,m4a,m4s,m4v,mov,mp4"},
  1981. INT_MIN, INT_MAX, FLAGS},
  1982. {NULL}
  1983. };
  1984. static const AVClass dash_class = {
  1985. .class_name = "dash",
  1986. .item_name = av_default_item_name,
  1987. .option = dash_options,
  1988. .version = LIBAVUTIL_VERSION_INT,
  1989. };
  1990. AVInputFormat ff_dash_demuxer = {
  1991. .name = "dash",
  1992. .long_name = NULL_IF_CONFIG_SMALL("Dynamic Adaptive Streaming over HTTP"),
  1993. .priv_class = &dash_class,
  1994. .priv_data_size = sizeof(DASHContext),
  1995. .read_probe = dash_probe,
  1996. .read_header = dash_read_header,
  1997. .read_packet = dash_read_packet,
  1998. .read_close = dash_close,
  1999. .read_seek = dash_read_seek,
  2000. .flags = AVFMT_NO_BYTE_SEEK,
  2001. };