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.

1993 lines
68KB

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