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.

2361 lines
81KB

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