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.

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