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.

2179 lines
74KB

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