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.

2148 lines
72KB

  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 fragment_template_node,
  707. xmlNodePtr content_component_node,
  708. xmlNodePtr adaptionset_baseurl_node,
  709. xmlNodePtr adaptionset_segmentlist_node)
  710. {
  711. int32_t ret = 0;
  712. int32_t audio_rep_idx = 0;
  713. int32_t video_rep_idx = 0;
  714. DASHContext *c = s->priv_data;
  715. struct representation *rep = NULL;
  716. struct fragment *seg = NULL;
  717. xmlNodePtr representation_segmenttemplate_node = NULL;
  718. xmlNodePtr representation_baseurl_node = NULL;
  719. xmlNodePtr representation_segmentlist_node = NULL;
  720. xmlNodePtr segmentlists_tab[2];
  721. xmlNodePtr fragment_timeline_node = NULL;
  722. xmlNodePtr fragment_templates_tab[4];
  723. char *duration_val = NULL;
  724. char *presentation_timeoffset_val = NULL;
  725. char *startnumber_val = NULL;
  726. char *timescale_val = NULL;
  727. char *initialization_val = NULL;
  728. char *media_val = NULL;
  729. xmlNodePtr baseurl_nodes[4];
  730. xmlNodePtr representation_node = node;
  731. char *rep_id_val = xmlGetProp(representation_node, "id");
  732. char *rep_bandwidth_val = xmlGetProp(representation_node, "bandwidth");
  733. char *rep_framerate_val = xmlGetProp(representation_node, "frameRate");
  734. enum AVMediaType type = AVMEDIA_TYPE_UNKNOWN;
  735. // try get information from representation
  736. if (type == AVMEDIA_TYPE_UNKNOWN)
  737. type = get_content_type(representation_node);
  738. // try get information from contentComponen
  739. if (type == AVMEDIA_TYPE_UNKNOWN)
  740. type = get_content_type(content_component_node);
  741. // try get information from adaption set
  742. if (type == AVMEDIA_TYPE_UNKNOWN)
  743. type = get_content_type(adaptionset_node);
  744. if (type == AVMEDIA_TYPE_UNKNOWN) {
  745. av_log(s, AV_LOG_VERBOSE, "Parsing '%s' - skipp not supported representation type\n", url);
  746. } else if (type == AVMEDIA_TYPE_VIDEO || type == AVMEDIA_TYPE_AUDIO) {
  747. // convert selected representation to our internal struct
  748. rep = av_mallocz(sizeof(struct representation));
  749. if (!rep) {
  750. ret = AVERROR(ENOMEM);
  751. goto end;
  752. }
  753. representation_segmenttemplate_node = find_child_node_by_name(representation_node, "SegmentTemplate");
  754. representation_baseurl_node = find_child_node_by_name(representation_node, "BaseURL");
  755. representation_segmentlist_node = find_child_node_by_name(representation_node, "SegmentList");
  756. baseurl_nodes[0] = mpd_baseurl_node;
  757. baseurl_nodes[1] = period_baseurl_node;
  758. baseurl_nodes[2] = adaptionset_baseurl_node;
  759. baseurl_nodes[3] = representation_baseurl_node;
  760. ret = resolve_content_path(s, url, &c->max_url_size, baseurl_nodes, 4);
  761. c->max_url_size = aligned(c->max_url_size + strlen(rep_id_val) + strlen(rep_bandwidth_val));
  762. if (ret == AVERROR(ENOMEM) || ret == 0) {
  763. goto end;
  764. }
  765. if (representation_segmenttemplate_node || fragment_template_node || period_segmenttemplate_node) {
  766. fragment_timeline_node = NULL;
  767. fragment_templates_tab[0] = representation_segmenttemplate_node;
  768. fragment_templates_tab[1] = adaptionset_segmentlist_node;
  769. fragment_templates_tab[2] = fragment_template_node;
  770. fragment_templates_tab[3] = period_segmenttemplate_node;
  771. presentation_timeoffset_val = get_val_from_nodes_tab(fragment_templates_tab, 4, "presentationTimeOffset");
  772. duration_val = get_val_from_nodes_tab(fragment_templates_tab, 4, "duration");
  773. startnumber_val = get_val_from_nodes_tab(fragment_templates_tab, 4, "startNumber");
  774. timescale_val = get_val_from_nodes_tab(fragment_templates_tab, 4, "timescale");
  775. initialization_val = get_val_from_nodes_tab(fragment_templates_tab, 4, "initialization");
  776. media_val = get_val_from_nodes_tab(fragment_templates_tab, 4, "media");
  777. if (initialization_val) {
  778. rep->init_section = av_mallocz(sizeof(struct fragment));
  779. if (!rep->init_section) {
  780. av_free(rep);
  781. ret = AVERROR(ENOMEM);
  782. goto end;
  783. }
  784. c->max_url_size = aligned(c->max_url_size + strlen(initialization_val));
  785. rep->init_section->url = get_content_url(baseurl_nodes, 4, c->max_url_size, rep_id_val, rep_bandwidth_val, initialization_val);
  786. if (!rep->init_section->url) {
  787. av_free(rep->init_section);
  788. av_free(rep);
  789. ret = AVERROR(ENOMEM);
  790. goto end;
  791. }
  792. rep->init_section->size = -1;
  793. xmlFree(initialization_val);
  794. }
  795. if (media_val) {
  796. c->max_url_size = aligned(c->max_url_size + strlen(media_val));
  797. rep->url_template = get_content_url(baseurl_nodes, 4, c->max_url_size, rep_id_val, rep_bandwidth_val, media_val);
  798. xmlFree(media_val);
  799. }
  800. if (presentation_timeoffset_val) {
  801. rep->presentation_timeoffset = (int64_t) strtoll(presentation_timeoffset_val, NULL, 10);
  802. xmlFree(presentation_timeoffset_val);
  803. }
  804. if (duration_val) {
  805. rep->fragment_duration = (int64_t) strtoll(duration_val, NULL, 10);
  806. xmlFree(duration_val);
  807. }
  808. if (timescale_val) {
  809. rep->fragment_timescale = (int64_t) strtoll(timescale_val, NULL, 10);
  810. xmlFree(timescale_val);
  811. }
  812. if (startnumber_val) {
  813. rep->first_seq_no = (int64_t) strtoll(startnumber_val, NULL, 10);
  814. xmlFree(startnumber_val);
  815. }
  816. fragment_timeline_node = find_child_node_by_name(representation_segmenttemplate_node, "SegmentTimeline");
  817. if (!fragment_timeline_node)
  818. fragment_timeline_node = find_child_node_by_name(fragment_template_node, "SegmentTimeline");
  819. if (!fragment_timeline_node)
  820. fragment_timeline_node = find_child_node_by_name(adaptionset_segmentlist_node, "SegmentTimeline");
  821. if (fragment_timeline_node) {
  822. fragment_timeline_node = xmlFirstElementChild(fragment_timeline_node);
  823. while (fragment_timeline_node) {
  824. ret = parse_manifest_segmenttimeline(s, rep, fragment_timeline_node);
  825. if (ret < 0) {
  826. return ret;
  827. }
  828. fragment_timeline_node = xmlNextElementSibling(fragment_timeline_node);
  829. }
  830. }
  831. } else if (representation_baseurl_node && !representation_segmentlist_node) {
  832. seg = av_mallocz(sizeof(struct fragment));
  833. if (!seg) {
  834. ret = AVERROR(ENOMEM);
  835. goto end;
  836. }
  837. seg->url = get_content_url(baseurl_nodes, 4, c->max_url_size, rep_id_val, rep_bandwidth_val, NULL);
  838. if (!seg->url) {
  839. av_free(seg);
  840. ret = AVERROR(ENOMEM);
  841. goto end;
  842. }
  843. seg->size = -1;
  844. dynarray_add(&rep->fragments, &rep->n_fragments, seg);
  845. } else if (representation_segmentlist_node) {
  846. // TODO: https://www.brendanlong.com/the-structure-of-an-mpeg-dash-mpd.html
  847. // http://www-itec.uni-klu.ac.at/dash/ddash/mpdGenerator.php?fragmentlength=15&type=full
  848. xmlNodePtr fragmenturl_node = NULL;
  849. segmentlists_tab[0] = representation_segmentlist_node;
  850. segmentlists_tab[1] = adaptionset_segmentlist_node;
  851. duration_val = get_val_from_nodes_tab(segmentlists_tab, 2, "duration");
  852. timescale_val = get_val_from_nodes_tab(segmentlists_tab, 2, "timescale");
  853. if (duration_val) {
  854. rep->fragment_duration = (int64_t) strtoll(duration_val, NULL, 10);
  855. xmlFree(duration_val);
  856. }
  857. if (timescale_val) {
  858. rep->fragment_timescale = (int64_t) strtoll(timescale_val, NULL, 10);
  859. xmlFree(timescale_val);
  860. }
  861. fragmenturl_node = xmlFirstElementChild(representation_segmentlist_node);
  862. while (fragmenturl_node) {
  863. ret = parse_manifest_segmenturlnode(s, rep, fragmenturl_node,
  864. baseurl_nodes,
  865. rep_id_val,
  866. rep_bandwidth_val);
  867. if (ret < 0) {
  868. return ret;
  869. }
  870. fragmenturl_node = xmlNextElementSibling(fragmenturl_node);
  871. }
  872. fragment_timeline_node = find_child_node_by_name(representation_segmenttemplate_node, "SegmentTimeline");
  873. if (!fragment_timeline_node)
  874. fragment_timeline_node = find_child_node_by_name(fragment_template_node, "SegmentTimeline");
  875. if (!fragment_timeline_node)
  876. fragment_timeline_node = find_child_node_by_name(adaptionset_segmentlist_node, "SegmentTimeline");
  877. if (fragment_timeline_node) {
  878. fragment_timeline_node = xmlFirstElementChild(fragment_timeline_node);
  879. while (fragment_timeline_node) {
  880. ret = parse_manifest_segmenttimeline(s, rep, fragment_timeline_node);
  881. if (ret < 0) {
  882. return ret;
  883. }
  884. fragment_timeline_node = xmlNextElementSibling(fragment_timeline_node);
  885. }
  886. }
  887. } else {
  888. free_representation(rep);
  889. rep = NULL;
  890. av_log(s, AV_LOG_ERROR, "Unknown format of Representation node id[%s] \n", (const char *)rep_id_val);
  891. }
  892. if (rep) {
  893. if (rep->fragment_duration > 0 && !rep->fragment_timescale)
  894. rep->fragment_timescale = 1;
  895. rep->bandwidth = rep_bandwidth_val ? atoi(rep_bandwidth_val) : 0;
  896. strncpy(rep->id, rep_id_val ? rep_id_val : "", sizeof(rep->id));
  897. rep->framerate = av_make_q(0, 0);
  898. if (type == AVMEDIA_TYPE_VIDEO && rep_framerate_val) {
  899. ret = av_parse_video_rate(&rep->framerate, rep_framerate_val);
  900. if (ret < 0)
  901. av_log(s, AV_LOG_VERBOSE, "Ignoring invalid frame rate '%s'\n", rep_framerate_val);
  902. }
  903. if (type == AVMEDIA_TYPE_VIDEO) {
  904. rep->rep_idx = video_rep_idx;
  905. dynarray_add(&c->videos, &c->n_videos, rep);
  906. } else {
  907. rep->rep_idx = audio_rep_idx;
  908. dynarray_add(&c->audios, &c->n_audios, rep);
  909. }
  910. }
  911. }
  912. video_rep_idx += type == AVMEDIA_TYPE_VIDEO;
  913. audio_rep_idx += type == AVMEDIA_TYPE_AUDIO;
  914. end:
  915. if (rep_id_val)
  916. xmlFree(rep_id_val);
  917. if (rep_bandwidth_val)
  918. xmlFree(rep_bandwidth_val);
  919. if (rep_framerate_val)
  920. xmlFree(rep_framerate_val);
  921. return ret;
  922. }
  923. static int parse_manifest_adaptationset(AVFormatContext *s, const char *url,
  924. xmlNodePtr adaptionset_node,
  925. xmlNodePtr mpd_baseurl_node,
  926. xmlNodePtr period_baseurl_node,
  927. xmlNodePtr period_segmenttemplate_node)
  928. {
  929. int ret = 0;
  930. xmlNodePtr fragment_template_node = NULL;
  931. xmlNodePtr content_component_node = NULL;
  932. xmlNodePtr adaptionset_baseurl_node = NULL;
  933. xmlNodePtr adaptionset_segmentlist_node = NULL;
  934. xmlNodePtr node = NULL;
  935. node = xmlFirstElementChild(adaptionset_node);
  936. while (node) {
  937. if (!av_strcasecmp(node->name, (const char *)"SegmentTemplate")) {
  938. fragment_template_node = node;
  939. } else if (!av_strcasecmp(node->name, (const char *)"ContentComponent")) {
  940. content_component_node = node;
  941. } else if (!av_strcasecmp(node->name, (const char *)"BaseURL")) {
  942. adaptionset_baseurl_node = node;
  943. } else if (!av_strcasecmp(node->name, (const char *)"SegmentList")) {
  944. adaptionset_segmentlist_node = node;
  945. } else if (!av_strcasecmp(node->name, (const char *)"Representation")) {
  946. ret = parse_manifest_representation(s, url, node,
  947. adaptionset_node,
  948. mpd_baseurl_node,
  949. period_baseurl_node,
  950. period_segmenttemplate_node,
  951. fragment_template_node,
  952. content_component_node,
  953. adaptionset_baseurl_node,
  954. adaptionset_segmentlist_node);
  955. if (ret < 0) {
  956. return ret;
  957. }
  958. }
  959. node = xmlNextElementSibling(node);
  960. }
  961. return 0;
  962. }
  963. static int parse_manifest(AVFormatContext *s, const char *url, AVIOContext *in)
  964. {
  965. DASHContext *c = s->priv_data;
  966. int ret = 0;
  967. int close_in = 0;
  968. uint8_t *new_url = NULL;
  969. int64_t filesize = 0;
  970. char *buffer = NULL;
  971. AVDictionary *opts = NULL;
  972. xmlDoc *doc = NULL;
  973. xmlNodePtr root_element = NULL;
  974. xmlNodePtr node = NULL;
  975. xmlNodePtr period_node = NULL;
  976. xmlNodePtr mpd_baseurl_node = NULL;
  977. xmlNodePtr period_baseurl_node = NULL;
  978. xmlNodePtr period_segmenttemplate_node = NULL;
  979. xmlNodePtr adaptionset_node = NULL;
  980. xmlAttrPtr attr = NULL;
  981. char *val = NULL;
  982. uint32_t perdiod_duration_sec = 0;
  983. uint32_t perdiod_start_sec = 0;
  984. if (!in) {
  985. close_in = 1;
  986. set_httpheader_options(c, &opts);
  987. ret = avio_open2(&in, url, AVIO_FLAG_READ, c->interrupt_callback, &opts);
  988. av_dict_free(&opts);
  989. if (ret < 0)
  990. return ret;
  991. }
  992. if (av_opt_get(in, "location", AV_OPT_SEARCH_CHILDREN, &new_url) >= 0) {
  993. c->base_url = av_strdup(new_url);
  994. } else {
  995. c->base_url = av_strdup(url);
  996. }
  997. filesize = avio_size(in);
  998. if (filesize <= 0) {
  999. filesize = 8 * 1024;
  1000. }
  1001. buffer = av_mallocz(filesize);
  1002. if (!buffer) {
  1003. av_free(c->base_url);
  1004. return AVERROR(ENOMEM);
  1005. }
  1006. filesize = avio_read(in, buffer, filesize);
  1007. if (filesize <= 0) {
  1008. av_log(s, AV_LOG_ERROR, "Unable to read to offset '%s'\n", url);
  1009. ret = AVERROR_INVALIDDATA;
  1010. } else {
  1011. LIBXML_TEST_VERSION
  1012. doc = xmlReadMemory(buffer, filesize, c->base_url, NULL, 0);
  1013. root_element = xmlDocGetRootElement(doc);
  1014. node = root_element;
  1015. if (!node) {
  1016. ret = AVERROR_INVALIDDATA;
  1017. av_log(s, AV_LOG_ERROR, "Unable to parse '%s' - missing root node\n", url);
  1018. goto cleanup;
  1019. }
  1020. if (node->type != XML_ELEMENT_NODE ||
  1021. av_strcasecmp(node->name, (const char *)"MPD")) {
  1022. ret = AVERROR_INVALIDDATA;
  1023. av_log(s, AV_LOG_ERROR, "Unable to parse '%s' - wrong root node name[%s] type[%d]\n", url, node->name, (int)node->type);
  1024. goto cleanup;
  1025. }
  1026. val = xmlGetProp(node, "type");
  1027. if (!val) {
  1028. av_log(s, AV_LOG_ERROR, "Unable to parse '%s' - missing type attrib\n", url);
  1029. ret = AVERROR_INVALIDDATA;
  1030. goto cleanup;
  1031. }
  1032. if (!av_strcasecmp(val, (const char *)"dynamic"))
  1033. c->is_live = 1;
  1034. xmlFree(val);
  1035. attr = node->properties;
  1036. while (attr) {
  1037. val = xmlGetProp(node, attr->name);
  1038. if (!av_strcasecmp(attr->name, (const char *)"availabilityStartTime")) {
  1039. c->availability_start_time = get_utc_date_time_insec(s, (const char *)val);
  1040. } else if (!av_strcasecmp(attr->name, (const char *)"publishTime")) {
  1041. c->publish_time = get_utc_date_time_insec(s, (const char *)val);
  1042. } else if (!av_strcasecmp(attr->name, (const char *)"minimumUpdatePeriod")) {
  1043. c->minimum_update_period = get_duration_insec(s, (const char *)val);
  1044. } else if (!av_strcasecmp(attr->name, (const char *)"timeShiftBufferDepth")) {
  1045. c->time_shift_buffer_depth = get_duration_insec(s, (const char *)val);
  1046. } else if (!av_strcasecmp(attr->name, (const char *)"minBufferTime")) {
  1047. c->min_buffer_time = get_duration_insec(s, (const char *)val);
  1048. } else if (!av_strcasecmp(attr->name, (const char *)"suggestedPresentationDelay")) {
  1049. c->suggested_presentation_delay = get_duration_insec(s, (const char *)val);
  1050. } else if (!av_strcasecmp(attr->name, (const char *)"mediaPresentationDuration")) {
  1051. c->media_presentation_duration = get_duration_insec(s, (const char *)val);
  1052. }
  1053. attr = attr->next;
  1054. xmlFree(val);
  1055. }
  1056. mpd_baseurl_node = find_child_node_by_name(node, "BaseURL");
  1057. if (!mpd_baseurl_node) {
  1058. mpd_baseurl_node = xmlNewNode(NULL, "BaseURL");
  1059. }
  1060. // at now we can handle only one period, with the longest duration
  1061. node = xmlFirstElementChild(node);
  1062. while (node) {
  1063. if (!av_strcasecmp(node->name, (const char *)"Period")) {
  1064. perdiod_duration_sec = 0;
  1065. perdiod_start_sec = 0;
  1066. attr = node->properties;
  1067. while (attr) {
  1068. val = xmlGetProp(node, attr->name);
  1069. if (!av_strcasecmp(attr->name, (const char *)"duration")) {
  1070. perdiod_duration_sec = get_duration_insec(s, (const char *)val);
  1071. } else if (!av_strcasecmp(attr->name, (const char *)"start")) {
  1072. perdiod_start_sec = get_duration_insec(s, (const char *)val);
  1073. }
  1074. attr = attr->next;
  1075. xmlFree(val);
  1076. }
  1077. if ((perdiod_duration_sec) >= (c->period_duration)) {
  1078. period_node = node;
  1079. c->period_duration = perdiod_duration_sec;
  1080. c->period_start = perdiod_start_sec;
  1081. if (c->period_start > 0)
  1082. c->media_presentation_duration = c->period_duration;
  1083. }
  1084. }
  1085. node = xmlNextElementSibling(node);
  1086. }
  1087. if (!period_node) {
  1088. av_log(s, AV_LOG_ERROR, "Unable to parse '%s' - missing Period node\n", url);
  1089. ret = AVERROR_INVALIDDATA;
  1090. goto cleanup;
  1091. }
  1092. adaptionset_node = xmlFirstElementChild(period_node);
  1093. while (adaptionset_node) {
  1094. if (!av_strcasecmp(adaptionset_node->name, (const char *)"BaseURL")) {
  1095. period_baseurl_node = adaptionset_node;
  1096. } else if (!av_strcasecmp(adaptionset_node->name, (const char *)"SegmentTemplate")) {
  1097. period_segmenttemplate_node = adaptionset_node;
  1098. } else if (!av_strcasecmp(adaptionset_node->name, (const char *)"AdaptationSet")) {
  1099. parse_manifest_adaptationset(s, url, adaptionset_node, mpd_baseurl_node, period_baseurl_node, period_segmenttemplate_node);
  1100. }
  1101. adaptionset_node = xmlNextElementSibling(adaptionset_node);
  1102. }
  1103. cleanup:
  1104. /*free the document */
  1105. xmlFreeDoc(doc);
  1106. xmlCleanupParser();
  1107. }
  1108. av_free(new_url);
  1109. av_free(buffer);
  1110. if (close_in) {
  1111. avio_close(in);
  1112. }
  1113. return ret;
  1114. }
  1115. static int64_t calc_cur_seg_no(AVFormatContext *s, struct representation *pls)
  1116. {
  1117. DASHContext *c = s->priv_data;
  1118. int64_t num = 0;
  1119. int64_t start_time_offset = 0;
  1120. if (c->is_live) {
  1121. if (pls->n_fragments) {
  1122. num = pls->first_seq_no;
  1123. } else if (pls->n_timelines) {
  1124. start_time_offset = get_segment_start_time_based_on_timeline(pls, 0xFFFFFFFF) - 60 * pls->fragment_timescale; // 60 seconds before end
  1125. num = calc_next_seg_no_from_timelines(pls, start_time_offset);
  1126. if (num == -1)
  1127. num = pls->first_seq_no;
  1128. else
  1129. num += pls->first_seq_no;
  1130. } else if (pls->fragment_duration){
  1131. if (pls->presentation_timeoffset) {
  1132. num = pls->presentation_timeoffset * pls->fragment_timescale / pls->fragment_duration;
  1133. } else if (c->publish_time > 0 && !c->availability_start_time) {
  1134. num = pls->first_seq_no + (((c->publish_time - c->availability_start_time) - c->suggested_presentation_delay) * pls->fragment_timescale) / pls->fragment_duration;
  1135. } else {
  1136. num = pls->first_seq_no + (((get_current_time_in_sec() - c->availability_start_time) - c->suggested_presentation_delay) * pls->fragment_timescale) / pls->fragment_duration;
  1137. }
  1138. }
  1139. } else {
  1140. num = pls->first_seq_no;
  1141. }
  1142. return num;
  1143. }
  1144. static int64_t calc_min_seg_no(AVFormatContext *s, struct representation *pls)
  1145. {
  1146. DASHContext *c = s->priv_data;
  1147. int64_t num = 0;
  1148. if (c->is_live && pls->fragment_duration) {
  1149. 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;
  1150. } else {
  1151. num = pls->first_seq_no;
  1152. }
  1153. return num;
  1154. }
  1155. static int64_t calc_max_seg_no(struct representation *pls, DASHContext *c)
  1156. {
  1157. int64_t num = 0;
  1158. if (pls->n_fragments) {
  1159. num = pls->first_seq_no + pls->n_fragments - 1;
  1160. } else if (pls->n_timelines) {
  1161. int i = 0;
  1162. num = pls->first_seq_no + pls->n_timelines - 1;
  1163. for (i = 0; i < pls->n_timelines; i++) {
  1164. num += pls->timelines[i]->repeat;
  1165. }
  1166. } else if (c->is_live && pls->fragment_duration) {
  1167. num = pls->first_seq_no + (((get_current_time_in_sec() - c->availability_start_time)) * pls->fragment_timescale) / pls->fragment_duration;
  1168. } else if (pls->fragment_duration) {
  1169. num = pls->first_seq_no + (c->media_presentation_duration * pls->fragment_timescale) / pls->fragment_duration;
  1170. }
  1171. return num;
  1172. }
  1173. static void move_timelines(struct representation *rep_src, struct representation *rep_dest, DASHContext *c)
  1174. {
  1175. if (rep_dest && rep_src ) {
  1176. free_timelines_list(rep_dest);
  1177. rep_dest->timelines = rep_src->timelines;
  1178. rep_dest->n_timelines = rep_src->n_timelines;
  1179. rep_dest->first_seq_no = rep_src->first_seq_no;
  1180. rep_dest->last_seq_no = calc_max_seg_no(rep_dest, c);
  1181. rep_src->timelines = NULL;
  1182. rep_src->n_timelines = 0;
  1183. rep_dest->cur_seq_no = rep_src->cur_seq_no;
  1184. }
  1185. }
  1186. static void move_segments(struct representation *rep_src, struct representation *rep_dest, DASHContext *c)
  1187. {
  1188. if (rep_dest && rep_src ) {
  1189. free_fragment_list(rep_dest);
  1190. if (rep_src->start_number > (rep_dest->start_number + rep_dest->n_fragments))
  1191. rep_dest->cur_seq_no = 0;
  1192. else
  1193. rep_dest->cur_seq_no += rep_src->start_number - rep_dest->start_number;
  1194. rep_dest->fragments = rep_src->fragments;
  1195. rep_dest->n_fragments = rep_src->n_fragments;
  1196. rep_dest->parent = rep_src->parent;
  1197. rep_dest->last_seq_no = calc_max_seg_no(rep_dest, c);
  1198. rep_src->fragments = NULL;
  1199. rep_src->n_fragments = 0;
  1200. }
  1201. }
  1202. static int refresh_manifest(AVFormatContext *s)
  1203. {
  1204. int ret = 0, i;
  1205. DASHContext *c = s->priv_data;
  1206. // save current context
  1207. int n_videos = c->n_videos;
  1208. struct representation **videos = c->videos;
  1209. int n_audios = c->n_audios;
  1210. struct representation **audios = c->audios;
  1211. char *base_url = c->base_url;
  1212. c->base_url = NULL;
  1213. c->n_videos = 0;
  1214. c->videos = NULL;
  1215. c->n_audios = 0;
  1216. c->audios = NULL;
  1217. ret = parse_manifest(s, s->filename, NULL);
  1218. if (ret)
  1219. goto finish;
  1220. if (c->n_videos != n_videos) {
  1221. av_log(c, AV_LOG_ERROR,
  1222. "new manifest has mismatched no. of video representations, %d -> %d\n",
  1223. n_videos, c->n_videos);
  1224. return AVERROR_INVALIDDATA;
  1225. }
  1226. if (c->n_audios != n_audios) {
  1227. av_log(c, AV_LOG_ERROR,
  1228. "new manifest has mismatched no. of audio representations, %d -> %d\n",
  1229. n_audios, c->n_audios);
  1230. return AVERROR_INVALIDDATA;
  1231. }
  1232. for (i = 0; i < n_videos; i++) {
  1233. struct representation *cur_video = videos[i];
  1234. struct representation *ccur_video = c->videos[i];
  1235. if (cur_video->timelines) {
  1236. // calc current time
  1237. int64_t currentTime = get_segment_start_time_based_on_timeline(cur_video, cur_video->cur_seq_no) / cur_video->fragment_timescale;
  1238. // update segments
  1239. ccur_video->cur_seq_no = calc_next_seg_no_from_timelines(ccur_video, currentTime * cur_video->fragment_timescale - 1);
  1240. if (ccur_video->cur_seq_no >= 0) {
  1241. move_timelines(ccur_video, cur_video, c);
  1242. }
  1243. }
  1244. if (cur_video->fragments) {
  1245. move_segments(ccur_video, cur_video, c);
  1246. }
  1247. }
  1248. for (i = 0; i < n_audios; i++) {
  1249. struct representation *cur_audio = audios[i];
  1250. struct representation *ccur_audio = c->audios[i];
  1251. if (cur_audio->timelines) {
  1252. // calc current time
  1253. int64_t currentTime = get_segment_start_time_based_on_timeline(cur_audio, cur_audio->cur_seq_no) / cur_audio->fragment_timescale;
  1254. // update segments
  1255. ccur_audio->cur_seq_no = calc_next_seg_no_from_timelines(ccur_audio, currentTime * cur_audio->fragment_timescale - 1);
  1256. if (ccur_audio->cur_seq_no >= 0) {
  1257. move_timelines(ccur_audio, cur_audio, c);
  1258. }
  1259. }
  1260. if (cur_audio->fragments) {
  1261. move_segments(ccur_audio, cur_audio, c);
  1262. }
  1263. }
  1264. finish:
  1265. // restore context
  1266. if (c->base_url)
  1267. av_free(base_url);
  1268. else
  1269. c->base_url = base_url;
  1270. if (c->audios)
  1271. free_audio_list(c);
  1272. if (c->videos)
  1273. free_video_list(c);
  1274. c->n_audios = n_audios;
  1275. c->audios = audios;
  1276. c->n_videos = n_videos;
  1277. c->videos = videos;
  1278. return ret;
  1279. }
  1280. static struct fragment *get_current_fragment(struct representation *pls)
  1281. {
  1282. int64_t min_seq_no = 0;
  1283. int64_t max_seq_no = 0;
  1284. struct fragment *seg = NULL;
  1285. struct fragment *seg_ptr = NULL;
  1286. DASHContext *c = pls->parent->priv_data;
  1287. while (( !ff_check_interrupt(c->interrupt_callback)&& pls->n_fragments > 0)) {
  1288. if (pls->cur_seq_no < pls->n_fragments) {
  1289. seg_ptr = pls->fragments[pls->cur_seq_no];
  1290. seg = av_mallocz(sizeof(struct fragment));
  1291. if (!seg) {
  1292. return NULL;
  1293. }
  1294. seg->url = av_strdup(seg_ptr->url);
  1295. if (!seg->url) {
  1296. av_free(seg);
  1297. return NULL;
  1298. }
  1299. seg->size = seg_ptr->size;
  1300. seg->url_offset = seg_ptr->url_offset;
  1301. return seg;
  1302. } else if (c->is_live) {
  1303. refresh_manifest(pls->parent);
  1304. } else {
  1305. break;
  1306. }
  1307. }
  1308. if (c->is_live) {
  1309. min_seq_no = calc_min_seg_no(pls->parent, pls);
  1310. max_seq_no = calc_max_seg_no(pls, c);
  1311. if (pls->timelines || pls->fragments) {
  1312. refresh_manifest(pls->parent);
  1313. }
  1314. if (pls->cur_seq_no <= min_seq_no) {
  1315. 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);
  1316. pls->cur_seq_no = calc_cur_seg_no(pls->parent, pls);
  1317. } else if (pls->cur_seq_no > max_seq_no) {
  1318. 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);
  1319. }
  1320. seg = av_mallocz(sizeof(struct fragment));
  1321. if (!seg) {
  1322. return NULL;
  1323. }
  1324. } else if (pls->cur_seq_no <= pls->last_seq_no) {
  1325. seg = av_mallocz(sizeof(struct fragment));
  1326. if (!seg) {
  1327. return NULL;
  1328. }
  1329. }
  1330. if (seg) {
  1331. char *tmpfilename= av_mallocz(c->max_url_size);
  1332. if (!tmpfilename) {
  1333. return NULL;
  1334. }
  1335. 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));
  1336. seg->url = av_strireplace(pls->url_template, pls->url_template, tmpfilename);
  1337. if (!seg->url) {
  1338. av_log(pls->parent, AV_LOG_WARNING, "Unable to resolve template url '%s', try to use origin template\n", pls->url_template);
  1339. seg->url = av_strdup(pls->url_template);
  1340. if (!seg->url) {
  1341. av_log(pls->parent, AV_LOG_ERROR, "Cannot resolve template url '%s'\n", pls->url_template);
  1342. av_free(tmpfilename);
  1343. return NULL;
  1344. }
  1345. }
  1346. av_free(tmpfilename);
  1347. seg->size = -1;
  1348. }
  1349. return seg;
  1350. }
  1351. enum ReadFromURLMode {
  1352. READ_NORMAL,
  1353. READ_COMPLETE,
  1354. };
  1355. static int read_from_url(struct representation *pls, struct fragment *seg,
  1356. uint8_t *buf, int buf_size,
  1357. enum ReadFromURLMode mode)
  1358. {
  1359. int ret;
  1360. /* limit read if the fragment was only a part of a file */
  1361. if (seg->size >= 0)
  1362. buf_size = FFMIN(buf_size, pls->cur_seg_size - pls->cur_seg_offset);
  1363. if (mode == READ_COMPLETE) {
  1364. ret = avio_read(pls->input, buf, buf_size);
  1365. if (ret < buf_size) {
  1366. av_log(pls->parent, AV_LOG_WARNING, "Could not read complete fragment.\n");
  1367. }
  1368. } else {
  1369. ret = avio_read(pls->input, buf, buf_size);
  1370. }
  1371. if (ret > 0)
  1372. pls->cur_seg_offset += ret;
  1373. return ret;
  1374. }
  1375. static int open_input(DASHContext *c, struct representation *pls, struct fragment *seg)
  1376. {
  1377. AVDictionary *opts = NULL;
  1378. char *url = NULL;
  1379. int ret = 0;
  1380. url = av_mallocz(c->max_url_size);
  1381. if (!url) {
  1382. goto cleanup;
  1383. }
  1384. set_httpheader_options(c, &opts);
  1385. if (seg->size >= 0) {
  1386. /* try to restrict the HTTP request to the part we want
  1387. * (if this is in fact a HTTP request) */
  1388. av_dict_set_int(&opts, "offset", seg->url_offset, 0);
  1389. av_dict_set_int(&opts, "end_offset", seg->url_offset + seg->size, 0);
  1390. }
  1391. ff_make_absolute_url(url, c->max_url_size, c->base_url, seg->url);
  1392. av_log(pls->parent, AV_LOG_VERBOSE, "DASH request for url '%s', offset %"PRId64", playlist %d\n",
  1393. url, seg->url_offset, pls->rep_idx);
  1394. ret = open_url(pls->parent, &pls->input, url, c->avio_opts, opts, NULL);
  1395. if (ret < 0) {
  1396. goto cleanup;
  1397. }
  1398. cleanup:
  1399. av_free(url);
  1400. av_dict_free(&opts);
  1401. pls->cur_seg_offset = 0;
  1402. pls->cur_seg_size = seg->size;
  1403. return ret;
  1404. }
  1405. static int update_init_section(struct representation *pls)
  1406. {
  1407. static const int max_init_section_size = 1024 * 1024;
  1408. DASHContext *c = pls->parent->priv_data;
  1409. int64_t sec_size;
  1410. int64_t urlsize;
  1411. int ret;
  1412. if (!pls->init_section || pls->init_sec_buf)
  1413. return 0;
  1414. ret = open_input(c, pls, pls->init_section);
  1415. if (ret < 0) {
  1416. av_log(pls->parent, AV_LOG_WARNING,
  1417. "Failed to open an initialization section in playlist %d\n",
  1418. pls->rep_idx);
  1419. return ret;
  1420. }
  1421. if (pls->init_section->size >= 0)
  1422. sec_size = pls->init_section->size;
  1423. else if ((urlsize = avio_size(pls->input)) >= 0)
  1424. sec_size = urlsize;
  1425. else
  1426. sec_size = max_init_section_size;
  1427. av_log(pls->parent, AV_LOG_DEBUG,
  1428. "Downloading an initialization section of size %"PRId64"\n",
  1429. sec_size);
  1430. sec_size = FFMIN(sec_size, max_init_section_size);
  1431. av_fast_malloc(&pls->init_sec_buf, &pls->init_sec_buf_size, sec_size);
  1432. ret = read_from_url(pls, pls->init_section, pls->init_sec_buf,
  1433. pls->init_sec_buf_size, READ_COMPLETE);
  1434. ff_format_io_close(pls->parent, &pls->input);
  1435. if (ret < 0)
  1436. return ret;
  1437. pls->init_sec_data_len = ret;
  1438. pls->init_sec_buf_read_offset = 0;
  1439. return 0;
  1440. }
  1441. static int64_t seek_data(void *opaque, int64_t offset, int whence)
  1442. {
  1443. struct representation *v = opaque;
  1444. if (v->n_fragments && !v->init_sec_data_len) {
  1445. return avio_seek(v->input, offset, whence);
  1446. }
  1447. return AVERROR(ENOSYS);
  1448. }
  1449. static int read_data(void *opaque, uint8_t *buf, int buf_size)
  1450. {
  1451. int ret = 0;
  1452. struct representation *v = opaque;
  1453. DASHContext *c = v->parent->priv_data;
  1454. restart:
  1455. if (!v->input) {
  1456. free_fragment(&v->cur_seg);
  1457. v->cur_seg = get_current_fragment(v);
  1458. if (!v->cur_seg) {
  1459. ret = AVERROR_EOF;
  1460. goto end;
  1461. }
  1462. /* load/update Media Initialization Section, if any */
  1463. ret = update_init_section(v);
  1464. if (ret)
  1465. goto end;
  1466. ret = open_input(c, v, v->cur_seg);
  1467. if (ret < 0) {
  1468. if (ff_check_interrupt(c->interrupt_callback)) {
  1469. goto end;
  1470. ret = AVERROR_EXIT;
  1471. }
  1472. av_log(v->parent, AV_LOG_WARNING, "Failed to open fragment of playlist %d\n", v->rep_idx);
  1473. v->cur_seq_no++;
  1474. goto restart;
  1475. }
  1476. }
  1477. if (v->init_sec_buf_read_offset < v->init_sec_data_len) {
  1478. /* Push init section out first before first actual fragment */
  1479. int copy_size = FFMIN(v->init_sec_data_len - v->init_sec_buf_read_offset, buf_size);
  1480. memcpy(buf, v->init_sec_buf, copy_size);
  1481. v->init_sec_buf_read_offset += copy_size;
  1482. ret = copy_size;
  1483. goto end;
  1484. }
  1485. /* check the v->cur_seg, if it is null, get current and double check if the new v->cur_seg*/
  1486. if (!v->cur_seg) {
  1487. v->cur_seg = get_current_fragment(v);
  1488. }
  1489. if (!v->cur_seg) {
  1490. ret = AVERROR_EOF;
  1491. goto end;
  1492. }
  1493. ret = read_from_url(v, v->cur_seg, buf, buf_size, READ_NORMAL);
  1494. if (ret > 0)
  1495. goto end;
  1496. if (c->is_live || v->cur_seq_no < v->last_seq_no) {
  1497. if (!v->is_restart_needed)
  1498. v->cur_seq_no++;
  1499. v->is_restart_needed = 1;
  1500. }
  1501. end:
  1502. return ret;
  1503. }
  1504. static int save_avio_options(AVFormatContext *s)
  1505. {
  1506. DASHContext *c = s->priv_data;
  1507. const char *opts[] = { "headers", "user_agent", "user-agent", "cookies", NULL }, **opt = opts;
  1508. uint8_t *buf = NULL;
  1509. int ret = 0;
  1510. while (*opt) {
  1511. if (av_opt_get(s->pb, *opt, AV_OPT_SEARCH_CHILDREN, &buf) >= 0) {
  1512. if (buf[0] != '\0') {
  1513. ret = av_dict_set(&c->avio_opts, *opt, buf, AV_DICT_DONT_STRDUP_VAL);
  1514. if (ret < 0) {
  1515. av_freep(&buf);
  1516. return ret;
  1517. }
  1518. } else {
  1519. av_freep(&buf);
  1520. }
  1521. }
  1522. opt++;
  1523. }
  1524. return ret;
  1525. }
  1526. static int nested_io_open(AVFormatContext *s, AVIOContext **pb, const char *url,
  1527. int flags, AVDictionary **opts)
  1528. {
  1529. av_log(s, AV_LOG_ERROR,
  1530. "A DASH playlist item '%s' referred to an external file '%s'. "
  1531. "Opening this file was forbidden for security reasons\n",
  1532. s->filename, url);
  1533. return AVERROR(EPERM);
  1534. }
  1535. static void close_demux_for_component(struct representation *pls)
  1536. {
  1537. /* note: the internal buffer could have changed */
  1538. av_freep(&pls->pb.buffer);
  1539. memset(&pls->pb, 0x00, sizeof(AVIOContext));
  1540. pls->ctx->pb = NULL;
  1541. avformat_close_input(&pls->ctx);
  1542. pls->ctx = NULL;
  1543. }
  1544. static int reopen_demux_for_component(AVFormatContext *s, struct representation *pls)
  1545. {
  1546. DASHContext *c = s->priv_data;
  1547. AVInputFormat *in_fmt = NULL;
  1548. AVDictionary *in_fmt_opts = NULL;
  1549. uint8_t *avio_ctx_buffer = NULL;
  1550. int ret = 0, i;
  1551. if (pls->ctx) {
  1552. close_demux_for_component(pls);
  1553. }
  1554. if (!(pls->ctx = avformat_alloc_context())) {
  1555. ret = AVERROR(ENOMEM);
  1556. goto fail;
  1557. }
  1558. avio_ctx_buffer = av_malloc(INITIAL_BUFFER_SIZE);
  1559. if (!avio_ctx_buffer ) {
  1560. ret = AVERROR(ENOMEM);
  1561. avformat_free_context(pls->ctx);
  1562. pls->ctx = NULL;
  1563. goto fail;
  1564. }
  1565. if (c->is_live) {
  1566. ffio_init_context(&pls->pb, avio_ctx_buffer , INITIAL_BUFFER_SIZE, 0, pls, read_data, NULL, NULL);
  1567. } else {
  1568. ffio_init_context(&pls->pb, avio_ctx_buffer , INITIAL_BUFFER_SIZE, 0, pls, read_data, NULL, seek_data);
  1569. }
  1570. pls->pb.seekable = 0;
  1571. if ((ret = ff_copy_whiteblacklists(pls->ctx, s)) < 0)
  1572. goto fail;
  1573. pls->ctx->flags = AVFMT_FLAG_CUSTOM_IO;
  1574. pls->ctx->probesize = 1024 * 4;
  1575. pls->ctx->max_analyze_duration = 4 * AV_TIME_BASE;
  1576. ret = av_probe_input_buffer(&pls->pb, &in_fmt, "", NULL, 0, 0);
  1577. if (ret < 0) {
  1578. av_log(s, AV_LOG_ERROR, "Error when loading first fragment, playlist %d\n", (int)pls->rep_idx);
  1579. avformat_free_context(pls->ctx);
  1580. pls->ctx = NULL;
  1581. goto fail;
  1582. }
  1583. pls->ctx->pb = &pls->pb;
  1584. pls->ctx->io_open = nested_io_open;
  1585. // provide additional information from mpd if available
  1586. ret = avformat_open_input(&pls->ctx, "", in_fmt, &in_fmt_opts); //pls->init_section->url
  1587. av_dict_free(&in_fmt_opts);
  1588. if (ret < 0)
  1589. goto fail;
  1590. if (pls->n_fragments) {
  1591. #if FF_API_R_FRAME_RATE
  1592. if (pls->framerate.den) {
  1593. for (i = 0; i < pls->ctx->nb_streams; i++)
  1594. pls->ctx->streams[i]->r_frame_rate = pls->framerate;
  1595. }
  1596. #endif
  1597. ret = avformat_find_stream_info(pls->ctx, NULL);
  1598. if (ret < 0)
  1599. goto fail;
  1600. }
  1601. fail:
  1602. return ret;
  1603. }
  1604. static int open_demux_for_component(AVFormatContext *s, struct representation *pls)
  1605. {
  1606. int ret = 0;
  1607. int i;
  1608. pls->parent = s;
  1609. pls->cur_seq_no = calc_cur_seg_no(s, pls);
  1610. pls->last_seq_no = calc_max_seg_no(pls, s->priv_data);
  1611. ret = reopen_demux_for_component(s, pls);
  1612. if (ret < 0) {
  1613. goto fail;
  1614. }
  1615. for (i = 0; i < pls->ctx->nb_streams; i++) {
  1616. AVStream *st = avformat_new_stream(s, NULL);
  1617. AVStream *ist = pls->ctx->streams[i];
  1618. if (!st) {
  1619. ret = AVERROR(ENOMEM);
  1620. goto fail;
  1621. }
  1622. st->id = i;
  1623. avcodec_parameters_copy(st->codecpar, pls->ctx->streams[i]->codecpar);
  1624. avpriv_set_pts_info(st, ist->pts_wrap_bits, ist->time_base.num, ist->time_base.den);
  1625. }
  1626. return 0;
  1627. fail:
  1628. return ret;
  1629. }
  1630. static int dash_read_header(AVFormatContext *s)
  1631. {
  1632. void *u = (s->flags & AVFMT_FLAG_CUSTOM_IO) ? NULL : s->pb;
  1633. DASHContext *c = s->priv_data;
  1634. int ret = 0;
  1635. int stream_index = 0;
  1636. int i;
  1637. c->interrupt_callback = &s->interrupt_callback;
  1638. // if the URL context is good, read important options we must broker later
  1639. if (u) {
  1640. update_options(&c->user_agent, "user-agent", u);
  1641. update_options(&c->cookies, "cookies", u);
  1642. update_options(&c->headers, "headers", u);
  1643. }
  1644. if ((ret = parse_manifest(s, s->filename, s->pb)) < 0)
  1645. goto fail;
  1646. if ((ret = save_avio_options(s)) < 0)
  1647. goto fail;
  1648. /* If this isn't a live stream, fill the total duration of the
  1649. * stream. */
  1650. if (!c->is_live) {
  1651. s->duration = (int64_t) c->media_presentation_duration * AV_TIME_BASE;
  1652. }
  1653. /* Open the demuxer for video and audio components if available */
  1654. for (i = 0; i < c->n_videos; i++) {
  1655. struct representation *cur_video = c->videos[i];
  1656. ret = open_demux_for_component(s, cur_video);
  1657. if (ret)
  1658. goto fail;
  1659. cur_video->stream_index = stream_index;
  1660. ++stream_index;
  1661. }
  1662. for (i = 0; i < c->n_audios; i++) {
  1663. struct representation *cur_audio = c->audios[i];
  1664. ret = open_demux_for_component(s, cur_audio);
  1665. if (ret)
  1666. goto fail;
  1667. cur_audio->stream_index = stream_index;
  1668. ++stream_index;
  1669. }
  1670. if (!stream_index) {
  1671. ret = AVERROR_INVALIDDATA;
  1672. goto fail;
  1673. }
  1674. /* Create a program */
  1675. if (!ret) {
  1676. AVProgram *program;
  1677. program = av_new_program(s, 0);
  1678. if (!program) {
  1679. goto fail;
  1680. }
  1681. for (i = 0; i < c->n_videos; i++) {
  1682. struct representation *pls = c->videos[i];
  1683. av_program_add_stream_index(s, 0, pls->stream_index);
  1684. pls->assoc_stream = s->streams[pls->stream_index];
  1685. if (pls->bandwidth > 0)
  1686. av_dict_set_int(&pls->assoc_stream->metadata, "variant_bitrate", pls->bandwidth, 0);
  1687. if (pls->id[0])
  1688. av_dict_set(&pls->assoc_stream->metadata, "id", pls->id, 0);
  1689. }
  1690. for (i = 0; i < c->n_audios; i++) {
  1691. struct representation *pls = c->audios[i];
  1692. av_program_add_stream_index(s, 0, pls->stream_index);
  1693. pls->assoc_stream = s->streams[pls->stream_index];
  1694. if (pls->bandwidth > 0)
  1695. av_dict_set_int(&pls->assoc_stream->metadata, "variant_bitrate", pls->bandwidth, 0);
  1696. if (pls->id[0])
  1697. av_dict_set(&pls->assoc_stream->metadata, "id", pls->id, 0);
  1698. }
  1699. }
  1700. return 0;
  1701. fail:
  1702. return ret;
  1703. }
  1704. static void recheck_discard_flags(AVFormatContext *s, struct representation **p, int n)
  1705. {
  1706. int i, j;
  1707. for (i = 0; i < n; i++) {
  1708. struct representation *pls = p[i];
  1709. int needed = !pls->assoc_stream || pls->assoc_stream->discard < AVDISCARD_ALL;
  1710. if (needed && !pls->ctx) {
  1711. pls->cur_seg_offset = 0;
  1712. pls->init_sec_buf_read_offset = 0;
  1713. /* Catch up */
  1714. for (j = 0; j < n; j++) {
  1715. pls->cur_seq_no = FFMAX(pls->cur_seq_no, p[j]->cur_seq_no);
  1716. }
  1717. reopen_demux_for_component(s, pls);
  1718. av_log(s, AV_LOG_INFO, "Now receiving stream_index %d\n", pls->stream_index);
  1719. } else if (!needed && pls->ctx) {
  1720. close_demux_for_component(pls);
  1721. if (pls->input)
  1722. ff_format_io_close(pls->parent, &pls->input);
  1723. av_log(s, AV_LOG_INFO, "No longer receiving stream_index %d\n", pls->stream_index);
  1724. }
  1725. }
  1726. }
  1727. static int dash_read_packet(AVFormatContext *s, AVPacket *pkt)
  1728. {
  1729. DASHContext *c = s->priv_data;
  1730. int ret = 0, i;
  1731. int64_t mints = 0;
  1732. struct representation *cur = NULL;
  1733. recheck_discard_flags(s, c->videos, c->n_videos);
  1734. recheck_discard_flags(s, c->audios, c->n_audios);
  1735. for (i = 0; i < c->n_videos; i++) {
  1736. struct representation *pls = c->videos[i];
  1737. if (!pls->ctx)
  1738. continue;
  1739. if (!cur || pls->cur_timestamp < mints) {
  1740. cur = pls;
  1741. mints = pls->cur_timestamp;
  1742. }
  1743. }
  1744. for (i = 0; i < c->n_audios; i++) {
  1745. struct representation *pls = c->audios[i];
  1746. if (!pls->ctx)
  1747. continue;
  1748. if (!cur || pls->cur_timestamp < mints) {
  1749. cur = pls;
  1750. mints = pls->cur_timestamp;
  1751. }
  1752. }
  1753. if (!cur) {
  1754. return AVERROR_INVALIDDATA;
  1755. }
  1756. while (!ff_check_interrupt(c->interrupt_callback) && !ret) {
  1757. ret = av_read_frame(cur->ctx, pkt);
  1758. if (ret >= 0) {
  1759. /* If we got a packet, return it */
  1760. cur->cur_timestamp = av_rescale(pkt->pts, (int64_t)cur->ctx->streams[0]->time_base.num * 90000, cur->ctx->streams[0]->time_base.den);
  1761. pkt->stream_index = cur->stream_index;
  1762. return 0;
  1763. }
  1764. if (cur->is_restart_needed) {
  1765. cur->cur_seg_offset = 0;
  1766. cur->init_sec_buf_read_offset = 0;
  1767. if (cur->input)
  1768. ff_format_io_close(cur->parent, &cur->input);
  1769. ret = reopen_demux_for_component(s, cur);
  1770. cur->is_restart_needed = 0;
  1771. }
  1772. }
  1773. return AVERROR_EOF;
  1774. }
  1775. static int dash_close(AVFormatContext *s)
  1776. {
  1777. DASHContext *c = s->priv_data;
  1778. free_audio_list(c);
  1779. free_video_list(c);
  1780. av_freep(&c->cookies);
  1781. av_freep(&c->user_agent);
  1782. av_dict_free(&c->avio_opts);
  1783. av_freep(&c->base_url);
  1784. return 0;
  1785. }
  1786. static int dash_seek(AVFormatContext *s, struct representation *pls, int64_t seek_pos_msec, int flags, int dry_run)
  1787. {
  1788. int ret = 0;
  1789. int i = 0;
  1790. int j = 0;
  1791. int64_t duration = 0;
  1792. av_log(pls->parent, AV_LOG_VERBOSE, "DASH seek pos[%"PRId64"ms], playlist %d%s\n",
  1793. seek_pos_msec, pls->rep_idx, dry_run ? " (dry)" : "");
  1794. // single fragment mode
  1795. if (pls->n_fragments == 1) {
  1796. pls->cur_timestamp = 0;
  1797. pls->cur_seg_offset = 0;
  1798. if (dry_run)
  1799. return 0;
  1800. ff_read_frame_flush(pls->ctx);
  1801. return av_seek_frame(pls->ctx, -1, seek_pos_msec * 1000, flags);
  1802. }
  1803. if (pls->input)
  1804. ff_format_io_close(pls->parent, &pls->input);
  1805. // find the nearest fragment
  1806. if (pls->n_timelines > 0 && pls->fragment_timescale > 0) {
  1807. int64_t num = pls->first_seq_no;
  1808. av_log(pls->parent, AV_LOG_VERBOSE, "dash_seek with SegmentTimeline start n_timelines[%d] "
  1809. "last_seq_no[%"PRId64"], playlist %d.\n",
  1810. (int)pls->n_timelines, (int64_t)pls->last_seq_no, (int)pls->rep_idx);
  1811. for (i = 0; i < pls->n_timelines; i++) {
  1812. if (pls->timelines[i]->starttime > 0) {
  1813. duration = pls->timelines[i]->starttime;
  1814. }
  1815. duration += pls->timelines[i]->duration;
  1816. if (seek_pos_msec < ((duration * 1000) / pls->fragment_timescale)) {
  1817. goto set_seq_num;
  1818. }
  1819. for (j = 0; j < pls->timelines[i]->repeat; j++) {
  1820. duration += pls->timelines[i]->duration;
  1821. num++;
  1822. if (seek_pos_msec < ((duration * 1000) / pls->fragment_timescale)) {
  1823. goto set_seq_num;
  1824. }
  1825. }
  1826. num++;
  1827. }
  1828. set_seq_num:
  1829. pls->cur_seq_no = num > pls->last_seq_no ? pls->last_seq_no : num;
  1830. av_log(pls->parent, AV_LOG_VERBOSE, "dash_seek with SegmentTimeline end cur_seq_no[%"PRId64"], playlist %d.\n",
  1831. (int64_t)pls->cur_seq_no, (int)pls->rep_idx);
  1832. } else if (pls->fragment_duration > 0) {
  1833. pls->cur_seq_no = pls->first_seq_no + ((seek_pos_msec * pls->fragment_timescale) / pls->fragment_duration) / 1000;
  1834. } else {
  1835. av_log(pls->parent, AV_LOG_ERROR, "dash_seek missing timeline or fragment_duration\n");
  1836. pls->cur_seq_no = pls->first_seq_no;
  1837. }
  1838. pls->cur_timestamp = 0;
  1839. pls->cur_seg_offset = 0;
  1840. pls->init_sec_buf_read_offset = 0;
  1841. ret = dry_run ? 0 : reopen_demux_for_component(s, pls);
  1842. return ret;
  1843. }
  1844. static int dash_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
  1845. {
  1846. int ret = 0, i;
  1847. DASHContext *c = s->priv_data;
  1848. int64_t seek_pos_msec = av_rescale_rnd(timestamp, 1000,
  1849. s->streams[stream_index]->time_base.den,
  1850. flags & AVSEEK_FLAG_BACKWARD ?
  1851. AV_ROUND_DOWN : AV_ROUND_UP);
  1852. if ((flags & AVSEEK_FLAG_BYTE) || c->is_live)
  1853. return AVERROR(ENOSYS);
  1854. /* Seek in discarded streams with dry_run=1 to avoid reopening them */
  1855. for (i = 0; i < c->n_videos; i++) {
  1856. if (!ret)
  1857. ret = dash_seek(s, c->videos[i], seek_pos_msec, flags, !c->videos[i]->ctx);
  1858. }
  1859. for (i = 0; i < c->n_audios; i++) {
  1860. if (!ret)
  1861. ret = dash_seek(s, c->audios[i], seek_pos_msec, flags, !c->audios[i]->ctx);
  1862. }
  1863. return ret;
  1864. }
  1865. static int dash_probe(AVProbeData *p)
  1866. {
  1867. if (!av_stristr(p->buf, "<MPD"))
  1868. return 0;
  1869. if (av_stristr(p->buf, "dash:profile:isoff-on-demand:2011") ||
  1870. av_stristr(p->buf, "dash:profile:isoff-live:2011") ||
  1871. av_stristr(p->buf, "dash:profile:isoff-live:2012") ||
  1872. av_stristr(p->buf, "dash:profile:isoff-main:2011")) {
  1873. return AVPROBE_SCORE_MAX;
  1874. }
  1875. if (av_stristr(p->buf, "dash:profile")) {
  1876. return AVPROBE_SCORE_MAX;
  1877. }
  1878. return 0;
  1879. }
  1880. #define OFFSET(x) offsetof(DASHContext, x)
  1881. #define FLAGS AV_OPT_FLAG_DECODING_PARAM
  1882. static const AVOption dash_options[] = {
  1883. {"allowed_extensions", "List of file extensions that dash is allowed to access",
  1884. OFFSET(allowed_extensions), AV_OPT_TYPE_STRING,
  1885. {.str = "aac,m4a,m4s,m4v,mov,mp4"},
  1886. INT_MIN, INT_MAX, FLAGS},
  1887. {NULL}
  1888. };
  1889. static const AVClass dash_class = {
  1890. .class_name = "dash",
  1891. .item_name = av_default_item_name,
  1892. .option = dash_options,
  1893. .version = LIBAVUTIL_VERSION_INT,
  1894. };
  1895. AVInputFormat ff_dash_demuxer = {
  1896. .name = "dash",
  1897. .long_name = NULL_IF_CONFIG_SMALL("Dynamic Adaptive Streaming over HTTP"),
  1898. .priv_class = &dash_class,
  1899. .priv_data_size = sizeof(DASHContext),
  1900. .read_probe = dash_probe,
  1901. .read_header = dash_read_header,
  1902. .read_packet = dash_read_packet,
  1903. .read_close = dash_close,
  1904. .read_seek = dash_read_seek,
  1905. .flags = AVFMT_NO_BYTE_SEEK,
  1906. };