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.

2242 lines
76KB

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