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.

1967 lines
67KB

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