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.

2017 lines
69KB

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