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.

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