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.

2230 lines
75KB

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