2 * Dynamic Adaptive Streaming over HTTP demux
3 * Copyright (c) 2017 samsamsam@o2.pl based on HLS demux
4 * Copyright (c) 2017 Steven Liu
6 * This file is part of FFmpeg.
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.
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.
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
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"
28 #include "avio_internal.h"
31 #define INITIAL_BUFFER_SIZE 32768
40 * reference to : ISO_IEC_23009-1-DASH-2012
42 * Table: Table 17 — Semantics of SegmentTimeline element
45 /* starttime: Element or Attribute Name
46 * specifies the MPD start time, in @timescale units,
47 * the first Segment in the series starts relative to the beginning of the Period.
48 * The value of this attribute must be equal to or greater than the sum of the previous S
49 * element earliest presentation time and the sum of the contiguous Segment durations.
50 * If the value of the attribute is greater than what is expressed by the previous S element,
51 * it expresses discontinuities in the timeline.
52 * If not present then the value shall be assumed to be zero for the first S element
53 * and for the subsequent S elements, the value shall be assumed to be the sum of
54 * the previous S element's earliest presentation time and contiguous duration
55 * (i.e. previous S@starttime + @duration * (@repeat + 1)).
58 /* repeat: Element or Attribute Name
59 * specifies the repeat count of the number of following contiguous Segments with
60 * the same duration expressed by the value of @duration. This value is zero-based
61 * (e.g. a value of three means four Segments in the contiguous series).
64 /* duration: Element or Attribute Name
65 * specifies the Segment duration, in units of the value of the @timescale.
71 * Each playlist has its own demuxer. If it is currently active,
72 * it has an opened AVIOContext too, and potentially an AVPacket
73 * containing the next packet from this stream.
75 struct representation {
79 AVFormatContext *parent;
86 enum AVMediaType type;
89 AVStream *assoc_stream; /* demuxer stream associated with this representation */
92 struct fragment **fragments; /* VOD list of fragment for profile */
95 struct timeline **timelines;
99 int64_t start_number; /* used in case when we have dynamic list of segment to know which segments are new one*/
101 int64_t fragment_duration;
102 int64_t fragment_timescale;
104 int64_t presentation_timeoffset;
107 int64_t cur_seg_offset;
108 int64_t cur_seg_size;
109 struct fragment *cur_seg;
111 /* Currently active Media Initialization Section */
112 struct fragment *init_section;
113 uint8_t *init_sec_buf;
114 uint32_t init_sec_buf_size;
115 uint32_t init_sec_data_len;
116 uint32_t init_sec_buf_read_offset;
117 int64_t cur_timestamp;
118 int is_restart_needed;
121 typedef struct DASHContext {
122 const AVClass *class;
126 struct representation **videos;
128 struct representation **audios;
130 /* MediaPresentationDescription Attribute */
131 uint64_t media_presentation_duration;
132 uint64_t suggested_presentation_delay;
133 uint64_t availability_start_time;
134 uint64_t publish_time;
135 uint64_t minimum_update_period;
136 uint64_t time_shift_buffer_depth;
137 uint64_t min_buffer_time;
139 /* Period Attribute */
140 uint64_t period_duration;
141 uint64_t period_start;
144 AVIOInterruptCB *interrupt_callback;
145 char *user_agent; ///< holds HTTP user agent set as an AVOption to the HTTP protocol context
146 char *cookies; ///< holds HTTP cookie values set in either the initial response or as an AVOption to the HTTP protocol context
147 char *headers; ///< holds HTTP headers set as an AVOption to the HTTP protocol context
148 char *allowed_extensions;
149 AVDictionary *avio_opts;
152 static uint64_t get_current_time_in_sec(void)
154 return av_gettime() / 1000000;
157 static uint64_t get_utc_date_time_insec(AVFormatContext *s, const char *datetime)
168 /* ISO-8601 date parser */
172 ret = sscanf(datetime, "%d-%d-%dT%d:%d:%fZ", &year, &month, &day, &hour, &minute, &second);
173 /* year, month, day, hour, minute, second 6 arguments */
175 av_log(s, AV_LOG_WARNING, "get_utc_date_time_insec get a wrong time format\n");
177 timeinfo.tm_year = year - 1900;
178 timeinfo.tm_mon = month - 1;
179 timeinfo.tm_mday = day;
180 timeinfo.tm_hour = hour;
181 timeinfo.tm_min = minute;
182 timeinfo.tm_sec = (int)second;
184 return av_timegm(&timeinfo);
187 static uint32_t get_duration_insec(AVFormatContext *s, const char *duration)
189 /* ISO-8601 duration parser */
197 const char *ptr = duration;
200 if (*ptr == 'P' || *ptr == 'T') {
205 if (sscanf(ptr, "%f%c%n", &value, &type, &size) != 2) {
206 av_log(s, AV_LOG_WARNING, "get_duration_insec get a wrong time format\n");
207 return 0; /* parser error */
211 days = (uint32_t)value;
214 hours = (uint32_t)value;
217 mins = (uint32_t)value;
220 secs = (uint32_t)value;
223 // handle invalid type
228 return ((days * 24 + hours) * 60 + mins) * 60 + secs;
231 static int64_t get_segment_start_time_based_on_timeline(struct representation *pls, int64_t cur_seq_no)
233 int64_t start_time = 0;
238 if (pls->n_timelines) {
239 for (i = 0; i < pls->n_timelines; i++) {
240 if (pls->timelines[i]->starttime > 0) {
241 start_time = pls->timelines[i]->starttime;
243 if (num == cur_seq_no)
246 start_time += pls->timelines[i]->duration;
247 for (j = 0; j < pls->timelines[i]->repeat; j++) {
249 if (num == cur_seq_no)
251 start_time += pls->timelines[i]->duration;
260 static int64_t calc_next_seg_no_from_timelines(struct representation *pls, int64_t cur_time)
265 int64_t start_time = 0;
267 for (i = 0; i < pls->n_timelines; i++) {
268 if (pls->timelines[i]->starttime > 0) {
269 start_time = pls->timelines[i]->starttime;
271 if (start_time > cur_time)
274 start_time += pls->timelines[i]->duration;
275 for (j = 0; j < pls->timelines[i]->repeat; j++) {
277 if (start_time > cur_time)
279 start_time += pls->timelines[i]->duration;
290 static void free_fragment(struct fragment **seg)
295 av_freep(&(*seg)->url);
299 static void free_fragment_list(struct representation *pls)
303 for (i = 0; i < pls->n_fragments; i++) {
304 free_fragment(&pls->fragments[i]);
306 av_freep(&pls->fragments);
307 pls->n_fragments = 0;
310 static void free_timelines_list(struct representation *pls)
314 for (i = 0; i < pls->n_timelines; i++) {
315 av_freep(&pls->timelines[i]);
317 av_freep(&pls->timelines);
318 pls->n_timelines = 0;
321 static void free_representation(struct representation *pls)
323 free_fragment_list(pls);
324 free_timelines_list(pls);
325 free_fragment(&pls->cur_seg);
326 free_fragment(&pls->init_section);
327 av_freep(&pls->init_sec_buf);
328 av_freep(&pls->pb.buffer);
330 ff_format_io_close(pls->parent, &pls->input);
333 avformat_close_input(&pls->ctx);
336 av_freep(&pls->url_template);
340 static void free_video_list(DASHContext *c)
343 for (i = 0; i < c->n_videos; i++) {
344 struct representation *pls = c->videos[i];
345 free_representation(pls);
347 av_freep(&c->videos);
351 static void free_audio_list(DASHContext *c)
354 for (i = 0; i < c->n_audios; i++) {
355 struct representation *pls = c->audios[i];
356 free_representation(pls);
358 av_freep(&c->audios);
362 static void set_httpheader_options(DASHContext *c, AVDictionary **opts)
364 // broker prior HTTP options that should be consistent across requests
365 av_dict_set(opts, "user-agent", c->user_agent, 0);
366 av_dict_set(opts, "cookies", c->cookies, 0);
367 av_dict_set(opts, "headers", c->headers, 0);
369 av_dict_set(opts, "seekable", "0", 0);
372 static void update_options(char **dest, const char *name, void *src)
375 av_opt_get(src, name, AV_OPT_SEARCH_CHILDREN, (uint8_t**)dest);
380 static int open_url(AVFormatContext *s, AVIOContext **pb, const char *url,
381 AVDictionary *opts, AVDictionary *opts2, int *is_http)
383 DASHContext *c = s->priv_data;
384 AVDictionary *tmp = NULL;
385 const char *proto_name = NULL;
388 av_dict_copy(&tmp, opts, 0);
389 av_dict_copy(&tmp, opts2, 0);
391 if (av_strstart(url, "crypto", NULL)) {
392 if (url[6] == '+' || url[6] == ':')
393 proto_name = avio_find_protocol_name(url + 7);
397 proto_name = avio_find_protocol_name(url);
400 return AVERROR_INVALIDDATA;
402 // only http(s) & file are allowed
403 if (av_strstart(proto_name, "file", NULL)) {
404 if (strcmp(c->allowed_extensions, "ALL") && !av_match_ext(url, c->allowed_extensions)) {
405 av_log(s, AV_LOG_ERROR,
406 "Filename extension of \'%s\' is not a common multimedia extension, blocked for security reasons.\n"
407 "If you wish to override this adjust allowed_extensions, you can set it to \'ALL\' to allow all\n",
409 return AVERROR_INVALIDDATA;
411 } else if (av_strstart(proto_name, "http", NULL)) {
414 return AVERROR_INVALIDDATA;
416 if (!strncmp(proto_name, url, strlen(proto_name)) && url[strlen(proto_name)] == ':')
418 else if (av_strstart(url, "crypto", NULL) && !strncmp(proto_name, url + 7, strlen(proto_name)) && url[7 + strlen(proto_name)] == ':')
420 else if (strcmp(proto_name, "file") || !strncmp(url, "file,", 5))
421 return AVERROR_INVALIDDATA;
423 ret = s->io_open(s, pb, url, AVIO_FLAG_READ, &tmp);
425 // update cookies on http response with setcookies.
426 char *new_cookies = NULL;
428 if (!(s->flags & AVFMT_FLAG_CUSTOM_IO))
429 av_opt_get(*pb, "cookies", AV_OPT_SEARCH_CHILDREN, (uint8_t**)&new_cookies);
433 c->cookies = new_cookies;
436 av_dict_set(&opts, "cookies", c->cookies, 0);
442 *is_http = av_strstart(proto_name, "http", NULL);
447 static char *get_content_url(xmlNodePtr *baseurl_nodes,
450 char *rep_bandwidth_val,
456 char tmp_str[MAX_URL_SIZE];
457 char tmp_str_2[MAX_URL_SIZE];
459 memset(tmp_str, 0, sizeof(tmp_str));
461 for (i = 0; i < n_baseurl_nodes; ++i) {
462 if (baseurl_nodes[i] &&
463 baseurl_nodes[i]->children &&
464 baseurl_nodes[i]->children->type == XML_TEXT_NODE) {
465 text = xmlNodeGetContent(baseurl_nodes[i]->children);
467 memset(tmp_str, 0, sizeof(tmp_str));
468 memset(tmp_str_2, 0, sizeof(tmp_str_2));
469 ff_make_absolute_url(tmp_str_2, MAX_URL_SIZE, tmp_str, text);
470 av_strlcpy(tmp_str, tmp_str_2, sizeof(tmp_str));
477 av_strlcat(tmp_str, (const char*)val, sizeof(tmp_str));
480 url = av_strireplace(tmp_str, "$RepresentationID$", (const char*)rep_id_val);
484 av_strlcpy(tmp_str, url, sizeof(tmp_str));
487 if (rep_bandwidth_val && tmp_str[0] != '\0') {
488 url = av_strireplace(tmp_str, "$Bandwidth$", (const char*)rep_bandwidth_val);
496 static char *get_val_from_nodes_tab(xmlNodePtr *nodes, const int n_nodes, const char *attrname)
501 for (i = 0; i < n_nodes; ++i) {
503 val = xmlGetProp(nodes[i], attrname);
512 static xmlNodePtr find_child_node_by_name(xmlNodePtr rootnode, const char *nodename)
514 xmlNodePtr node = rootnode;
519 node = xmlFirstElementChild(node);
521 if (!av_strcasecmp(node->name, nodename)) {
524 node = xmlNextElementSibling(node);
529 static enum AVMediaType get_content_type(xmlNodePtr node)
531 enum AVMediaType type = AVMEDIA_TYPE_UNKNOWN;
537 for (i = 0; i < 2; i++) {
538 attr = i ? "mimeType" : "contentType";
539 val = xmlGetProp(node, attr);
541 if (av_stristr((const char *)val, "video")) {
542 type = AVMEDIA_TYPE_VIDEO;
543 } else if (av_stristr((const char *)val, "audio")) {
544 type = AVMEDIA_TYPE_AUDIO;
553 static int parse_manifest_segmenturlnode(AVFormatContext *s, struct representation *rep,
554 xmlNodePtr fragmenturl_node,
555 xmlNodePtr *baseurl_nodes,
557 char *rep_bandwidth_val)
559 char *initialization_val = NULL;
560 char *media_val = NULL;
562 if (!av_strcasecmp(fragmenturl_node->name, (const char *)"Initialization")) {
563 initialization_val = xmlGetProp(fragmenturl_node, "sourceURL");
564 if (initialization_val) {
565 rep->init_section = av_mallocz(sizeof(struct fragment));
566 if (!rep->init_section) {
567 xmlFree(initialization_val);
568 return AVERROR(ENOMEM);
570 rep->init_section->url = get_content_url(baseurl_nodes, 4,
574 if (!rep->init_section->url) {
575 av_free(rep->init_section);
576 xmlFree(initialization_val);
577 return AVERROR(ENOMEM);
579 rep->init_section->size = -1;
580 xmlFree(initialization_val);
582 } else if (!av_strcasecmp(fragmenturl_node->name, (const char *)"SegmentURL")) {
583 media_val = xmlGetProp(fragmenturl_node, "media");
585 struct fragment *seg = av_mallocz(sizeof(struct fragment));
588 return AVERROR(ENOMEM);
590 seg->url = get_content_url(baseurl_nodes, 4,
597 return AVERROR(ENOMEM);
600 dynarray_add(&rep->fragments, &rep->n_fragments, seg);
608 static int parse_manifest_segmenttimeline(AVFormatContext *s, struct representation *rep,
609 xmlNodePtr fragment_timeline_node)
611 xmlAttrPtr attr = NULL;
614 if (!av_strcasecmp(fragment_timeline_node->name, (const char *)"S")) {
615 struct timeline *tml = av_mallocz(sizeof(struct timeline));
617 return AVERROR(ENOMEM);
619 attr = fragment_timeline_node->properties;
621 val = xmlGetProp(fragment_timeline_node, attr->name);
624 av_log(s, AV_LOG_WARNING, "parse_manifest_segmenttimeline attr->name = %s val is NULL\n", attr->name);
628 if (!av_strcasecmp(attr->name, (const char *)"t")) {
629 tml->starttime = (int64_t)strtoll(val, NULL, 10);
630 } else if (!av_strcasecmp(attr->name, (const char *)"r")) {
631 tml->repeat =(int64_t) strtoll(val, NULL, 10);
632 } else if (!av_strcasecmp(attr->name, (const char *)"d")) {
633 tml->duration = (int64_t)strtoll(val, NULL, 10);
638 dynarray_add(&rep->timelines, &rep->n_timelines, tml);
644 static int parse_manifest_representation(AVFormatContext *s, const char *url,
646 xmlNodePtr adaptionset_node,
647 xmlNodePtr mpd_baseurl_node,
648 xmlNodePtr period_baseurl_node,
649 xmlNodePtr fragment_template_node,
650 xmlNodePtr content_component_node,
651 xmlNodePtr adaptionset_baseurl_node)
654 int32_t audio_rep_idx = 0;
655 int32_t video_rep_idx = 0;
656 DASHContext *c = s->priv_data;
657 struct representation *rep = NULL;
658 struct fragment *seg = NULL;
659 xmlNodePtr representation_segmenttemplate_node = NULL;
660 xmlNodePtr representation_baseurl_node = NULL;
661 xmlNodePtr representation_segmentlist_node = NULL;
662 xmlNodePtr fragment_timeline_node = NULL;
663 xmlNodePtr fragment_templates_tab[2];
664 char *duration_val = NULL;
665 char *presentation_timeoffset_val = NULL;
666 char *startnumber_val = NULL;
667 char *timescale_val = NULL;
668 char *initialization_val = NULL;
669 char *media_val = NULL;
670 xmlNodePtr baseurl_nodes[4];
671 xmlNodePtr representation_node = node;
672 char *rep_id_val = xmlGetProp(representation_node, "id");
673 char *rep_bandwidth_val = xmlGetProp(representation_node, "bandwidth");
674 enum AVMediaType type = AVMEDIA_TYPE_UNKNOWN;
676 // try get information from representation
677 if (type == AVMEDIA_TYPE_UNKNOWN)
678 type = get_content_type(representation_node);
679 // try get information from contentComponen
680 if (type == AVMEDIA_TYPE_UNKNOWN)
681 type = get_content_type(content_component_node);
682 // try get information from adaption set
683 if (type == AVMEDIA_TYPE_UNKNOWN)
684 type = get_content_type(adaptionset_node);
685 if (type == AVMEDIA_TYPE_UNKNOWN) {
686 av_log(s, AV_LOG_VERBOSE, "Parsing '%s' - skipp not supported representation type\n", url);
687 } else if (type == AVMEDIA_TYPE_VIDEO || type == AVMEDIA_TYPE_AUDIO) {
688 // convert selected representation to our internal struct
689 rep = av_mallocz(sizeof(struct representation));
691 ret = AVERROR(ENOMEM);
694 representation_segmenttemplate_node = find_child_node_by_name(representation_node, "SegmentTemplate");
695 representation_baseurl_node = find_child_node_by_name(representation_node, "BaseURL");
696 representation_segmentlist_node = find_child_node_by_name(representation_node, "SegmentList");
698 baseurl_nodes[0] = mpd_baseurl_node;
699 baseurl_nodes[1] = period_baseurl_node;
700 baseurl_nodes[2] = adaptionset_baseurl_node;
701 baseurl_nodes[3] = representation_baseurl_node;
703 if (representation_segmenttemplate_node || fragment_template_node) {
704 fragment_timeline_node = NULL;
705 fragment_templates_tab[0] = representation_segmenttemplate_node;
706 fragment_templates_tab[1] = fragment_template_node;
708 presentation_timeoffset_val = get_val_from_nodes_tab(fragment_templates_tab, 2, "presentationTimeOffset");
709 duration_val = get_val_from_nodes_tab(fragment_templates_tab, 2, "duration");
710 startnumber_val = get_val_from_nodes_tab(fragment_templates_tab, 2, "startNumber");
711 timescale_val = get_val_from_nodes_tab(fragment_templates_tab, 2, "timescale");
712 initialization_val = get_val_from_nodes_tab(fragment_templates_tab, 2, "initialization");
713 media_val = get_val_from_nodes_tab(fragment_templates_tab, 2, "media");
715 if (initialization_val) {
716 rep->init_section = av_mallocz(sizeof(struct fragment));
717 if (!rep->init_section) {
719 ret = AVERROR(ENOMEM);
722 rep->init_section->url = get_content_url(baseurl_nodes, 4, rep_id_val, rep_bandwidth_val, initialization_val);
723 if (!rep->init_section->url) {
724 av_free(rep->init_section);
726 ret = AVERROR(ENOMEM);
729 rep->init_section->size = -1;
730 xmlFree(initialization_val);
734 rep->url_template = get_content_url(baseurl_nodes, 4, rep_id_val, rep_bandwidth_val, media_val);
738 if (presentation_timeoffset_val) {
739 rep->presentation_timeoffset = (int64_t) strtoll(presentation_timeoffset_val, NULL, 10);
740 xmlFree(presentation_timeoffset_val);
743 rep->fragment_duration = (int64_t) strtoll(duration_val, NULL, 10);
744 xmlFree(duration_val);
747 rep->fragment_timescale = (int64_t) strtoll(timescale_val, NULL, 10);
748 xmlFree(timescale_val);
750 if (startnumber_val) {
751 rep->first_seq_no = (int64_t) strtoll(startnumber_val, NULL, 10);
752 xmlFree(startnumber_val);
755 fragment_timeline_node = find_child_node_by_name(representation_segmenttemplate_node, "SegmentTimeline");
757 if (!fragment_timeline_node)
758 fragment_timeline_node = find_child_node_by_name(fragment_template_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);
766 fragment_timeline_node = xmlNextElementSibling(fragment_timeline_node);
769 } else if (representation_baseurl_node && !representation_segmentlist_node) {
770 seg = av_mallocz(sizeof(struct fragment));
772 ret = AVERROR(ENOMEM);
775 seg->url = get_content_url(baseurl_nodes, 4, rep_id_val, rep_bandwidth_val, NULL);
778 ret = AVERROR(ENOMEM);
782 dynarray_add(&rep->fragments, &rep->n_fragments, seg);
783 } else if (representation_segmentlist_node) {
784 // TODO: https://www.brendanlong.com/the-structure-of-an-mpeg-dash-mpd.html
785 // http://www-itec.uni-klu.ac.at/dash/ddash/mpdGenerator.php?fragmentlength=15&type=full
786 xmlNodePtr fragmenturl_node = NULL;
787 duration_val = xmlGetProp(representation_segmentlist_node, "duration");
788 timescale_val = xmlGetProp(representation_segmentlist_node, "timescale");
790 rep->fragment_duration = (int64_t) strtoll(duration_val, NULL, 10);
791 xmlFree(duration_val);
794 rep->fragment_timescale = (int64_t) strtoll(timescale_val, NULL, 10);
795 xmlFree(timescale_val);
797 fragmenturl_node = xmlFirstElementChild(representation_segmentlist_node);
798 while (fragmenturl_node) {
799 ret = parse_manifest_segmenturlnode(s, rep, fragmenturl_node,
806 fragmenturl_node = xmlNextElementSibling(fragmenturl_node);
809 fragment_timeline_node = find_child_node_by_name(representation_segmenttemplate_node, "SegmentTimeline");
811 if (!fragment_timeline_node)
812 fragment_timeline_node = find_child_node_by_name(fragment_template_node, "SegmentTimeline");
813 if (fragment_timeline_node) {
814 fragment_timeline_node = xmlFirstElementChild(fragment_timeline_node);
815 while (fragment_timeline_node) {
816 ret = parse_manifest_segmenttimeline(s, rep, fragment_timeline_node);
820 fragment_timeline_node = xmlNextElementSibling(fragment_timeline_node);
824 free_representation(rep);
826 av_log(s, AV_LOG_ERROR, "Unknown format of Representation node id[%s] \n", (const char *)rep_id_val);
830 if (rep->fragment_duration > 0 && !rep->fragment_timescale)
831 rep->fragment_timescale = 1;
832 rep->bandwidth = rep_bandwidth_val ? atoi(rep_bandwidth_val) : 0;
833 strncpy(rep->id, rep_id_val ? rep_id_val : "", sizeof(rep->id));
834 if (type == AVMEDIA_TYPE_VIDEO) {
835 rep->rep_idx = video_rep_idx;
836 dynarray_add(&c->videos, &c->n_videos, rep);
838 rep->rep_idx = audio_rep_idx;
839 dynarray_add(&c->audios, &c->n_audios, rep);
844 video_rep_idx += type == AVMEDIA_TYPE_VIDEO;
845 audio_rep_idx += type == AVMEDIA_TYPE_AUDIO;
850 if (rep_bandwidth_val)
851 xmlFree(rep_bandwidth_val);
856 static int parse_manifest_adaptationset(AVFormatContext *s, const char *url,
857 xmlNodePtr adaptionset_node,
858 xmlNodePtr mpd_baseurl_node,
859 xmlNodePtr period_baseurl_node)
862 xmlNodePtr fragment_template_node = NULL;
863 xmlNodePtr content_component_node = NULL;
864 xmlNodePtr adaptionset_baseurl_node = NULL;
865 xmlNodePtr node = NULL;
867 node = xmlFirstElementChild(adaptionset_node);
869 if (!av_strcasecmp(node->name, (const char *)"SegmentTemplate")) {
870 fragment_template_node = node;
871 } else if (!av_strcasecmp(node->name, (const char *)"ContentComponent")) {
872 content_component_node = node;
873 } else if (!av_strcasecmp(node->name, (const char *)"BaseURL")) {
874 adaptionset_baseurl_node = node;
875 } else if (!av_strcasecmp(node->name, (const char *)"Representation")) {
876 ret = parse_manifest_representation(s, url, node,
880 fragment_template_node,
881 content_component_node,
882 adaptionset_baseurl_node);
887 node = xmlNextElementSibling(node);
892 static int parse_manifest(AVFormatContext *s, const char *url, AVIOContext *in)
894 DASHContext *c = s->priv_data;
897 uint8_t *new_url = NULL;
898 int64_t filesize = 0;
900 AVDictionary *opts = NULL;
902 xmlNodePtr root_element = NULL;
903 xmlNodePtr node = NULL;
904 xmlNodePtr period_node = NULL;
905 xmlNodePtr mpd_baseurl_node = NULL;
906 xmlNodePtr period_baseurl_node = NULL;
907 xmlNodePtr adaptionset_node = NULL;
908 xmlAttrPtr attr = NULL;
910 uint32_t perdiod_duration_sec = 0;
911 uint32_t perdiod_start_sec = 0;
916 set_httpheader_options(c, &opts);
917 ret = avio_open2(&in, url, AVIO_FLAG_READ, c->interrupt_callback, &opts);
923 if (av_opt_get(in, "location", AV_OPT_SEARCH_CHILDREN, &new_url) >= 0) {
924 c->base_url = av_strdup(new_url);
926 c->base_url = av_strdup(url);
929 filesize = avio_size(in);
934 buffer = av_mallocz(filesize);
936 av_free(c->base_url);
937 return AVERROR(ENOMEM);
940 filesize = avio_read(in, buffer, filesize);
942 av_log(s, AV_LOG_ERROR, "Unable to read to offset '%s'\n", url);
943 ret = AVERROR_INVALIDDATA;
947 doc = xmlReadMemory(buffer, filesize, c->base_url, NULL, 0);
948 root_element = xmlDocGetRootElement(doc);
952 ret = AVERROR_INVALIDDATA;
953 av_log(s, AV_LOG_ERROR, "Unable to parse '%s' - missing root node\n", url);
957 if (node->type != XML_ELEMENT_NODE ||
958 av_strcasecmp(node->name, (const char *)"MPD")) {
959 ret = AVERROR_INVALIDDATA;
960 av_log(s, AV_LOG_ERROR, "Unable to parse '%s' - wrong root node name[%s] type[%d]\n", url, node->name, (int)node->type);
964 val = xmlGetProp(node, "type");
966 av_log(s, AV_LOG_ERROR, "Unable to parse '%s' - missing type attrib\n", url);
967 ret = AVERROR_INVALIDDATA;
970 if (!av_strcasecmp(val, (const char *)"dynamic"))
974 attr = node->properties;
976 val = xmlGetProp(node, attr->name);
978 if (!av_strcasecmp(attr->name, (const char *)"availabilityStartTime")) {
979 c->availability_start_time = get_utc_date_time_insec(s, (const char *)val);
980 } else if (!av_strcasecmp(attr->name, (const char *)"publishTime")) {
981 c->publish_time = get_utc_date_time_insec(s, (const char *)val);
982 } else if (!av_strcasecmp(attr->name, (const char *)"minimumUpdatePeriod")) {
983 c->minimum_update_period = get_duration_insec(s, (const char *)val);
984 } else if (!av_strcasecmp(attr->name, (const char *)"timeShiftBufferDepth")) {
985 c->time_shift_buffer_depth = get_duration_insec(s, (const char *)val);
986 } else if (!av_strcasecmp(attr->name, (const char *)"minBufferTime")) {
987 c->min_buffer_time = get_duration_insec(s, (const char *)val);
988 } else if (!av_strcasecmp(attr->name, (const char *)"suggestedPresentationDelay")) {
989 c->suggested_presentation_delay = get_duration_insec(s, (const char *)val);
990 } else if (!av_strcasecmp(attr->name, (const char *)"mediaPresentationDuration")) {
991 c->media_presentation_duration = get_duration_insec(s, (const char *)val);
997 mpd_baseurl_node = find_child_node_by_name(node, "BaseURL");
999 // at now we can handle only one period, with the longest duration
1000 node = xmlFirstElementChild(node);
1002 if (!av_strcasecmp(node->name, (const char *)"Period")) {
1003 perdiod_duration_sec = 0;
1004 perdiod_start_sec = 0;
1005 attr = node->properties;
1007 val = xmlGetProp(node, attr->name);
1008 if (!av_strcasecmp(attr->name, (const char *)"duration")) {
1009 perdiod_duration_sec = get_duration_insec(s, (const char *)val);
1010 } else if (!av_strcasecmp(attr->name, (const char *)"start")) {
1011 perdiod_start_sec = get_duration_insec(s, (const char *)val);
1016 if ((perdiod_duration_sec) >= (c->period_duration)) {
1018 c->period_duration = perdiod_duration_sec;
1019 c->period_start = perdiod_start_sec;
1020 if (c->period_start > 0)
1021 c->media_presentation_duration = c->period_duration;
1024 node = xmlNextElementSibling(node);
1027 av_log(s, AV_LOG_ERROR, "Unable to parse '%s' - missing Period node\n", url);
1028 ret = AVERROR_INVALIDDATA;
1032 adaptionset_node = xmlFirstElementChild(period_node);
1033 while (adaptionset_node) {
1034 if (!av_strcasecmp(adaptionset_node->name, (const char *)"BaseURL")) {
1035 period_baseurl_node = adaptionset_node;
1036 } else if (!av_strcasecmp(adaptionset_node->name, (const char *)"AdaptationSet")) {
1037 parse_manifest_adaptationset(s, url, adaptionset_node, mpd_baseurl_node, period_baseurl_node);
1039 adaptionset_node = xmlNextElementSibling(adaptionset_node);
1042 /*free the document */
1055 static int64_t calc_cur_seg_no(AVFormatContext *s, struct representation *pls)
1057 DASHContext *c = s->priv_data;
1059 int64_t start_time_offset = 0;
1062 if (pls->n_fragments) {
1063 num = pls->first_seq_no;
1064 } else if (pls->n_timelines) {
1065 start_time_offset = get_segment_start_time_based_on_timeline(pls, 0xFFFFFFFF) - pls->timelines[pls->first_seq_no]->starttime; // total duration of playlist
1066 if (start_time_offset < 60 * pls->fragment_timescale)
1067 start_time_offset = 0;
1069 start_time_offset = start_time_offset - 60 * pls->fragment_timescale;
1071 num = calc_next_seg_no_from_timelines(pls, pls->timelines[pls->first_seq_no]->starttime + start_time_offset);
1073 num = pls->first_seq_no;
1074 } else if (pls->fragment_duration){
1075 if (pls->presentation_timeoffset) {
1076 num = pls->presentation_timeoffset * pls->fragment_timescale / pls->fragment_duration;
1077 } else if (c->publish_time > 0 && !c->availability_start_time) {
1078 num = pls->first_seq_no + (((c->publish_time - c->availability_start_time) - c->suggested_presentation_delay) * pls->fragment_timescale) / pls->fragment_duration;
1080 num = pls->first_seq_no + (((get_current_time_in_sec() - c->availability_start_time) - c->suggested_presentation_delay) * pls->fragment_timescale) / pls->fragment_duration;
1084 num = pls->first_seq_no;
1089 static int64_t calc_min_seg_no(AVFormatContext *s, struct representation *pls)
1091 DASHContext *c = s->priv_data;
1094 if (c->is_live && pls->fragment_duration) {
1095 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;
1097 num = pls->first_seq_no;
1102 static int64_t calc_max_seg_no(struct representation *pls, DASHContext *c)
1106 if (pls->n_fragments) {
1107 num = pls->first_seq_no + pls->n_fragments - 1;
1108 } else if (pls->n_timelines) {
1110 num = pls->first_seq_no + pls->n_timelines - 1;
1111 for (i = 0; i < pls->n_timelines; i++) {
1112 num += pls->timelines[i]->repeat;
1114 } else if (c->is_live && pls->fragment_duration) {
1115 num = pls->first_seq_no + (((get_current_time_in_sec() - c->availability_start_time)) * pls->fragment_timescale) / pls->fragment_duration;
1116 } else if (pls->fragment_duration) {
1117 num = pls->first_seq_no + (c->media_presentation_duration * pls->fragment_timescale) / pls->fragment_duration;
1123 static void move_timelines(struct representation *rep_src, struct representation *rep_dest, DASHContext *c)
1125 if (rep_dest && rep_src ) {
1126 free_timelines_list(rep_dest);
1127 rep_dest->timelines = rep_src->timelines;
1128 rep_dest->n_timelines = rep_src->n_timelines;
1129 rep_dest->first_seq_no = rep_src->first_seq_no;
1130 rep_dest->last_seq_no = calc_max_seg_no(rep_dest, c);
1131 rep_src->timelines = NULL;
1132 rep_src->n_timelines = 0;
1133 rep_dest->cur_seq_no = rep_src->cur_seq_no;
1137 static void move_segments(struct representation *rep_src, struct representation *rep_dest, DASHContext *c)
1139 if (rep_dest && rep_src ) {
1140 free_fragment_list(rep_dest);
1141 if (rep_src->start_number > (rep_dest->start_number + rep_dest->n_fragments))
1142 rep_dest->cur_seq_no = 0;
1144 rep_dest->cur_seq_no += rep_src->start_number - rep_dest->start_number;
1145 rep_dest->fragments = rep_src->fragments;
1146 rep_dest->n_fragments = rep_src->n_fragments;
1147 rep_dest->parent = rep_src->parent;
1148 rep_dest->last_seq_no = calc_max_seg_no(rep_dest, c);
1149 rep_src->fragments = NULL;
1150 rep_src->n_fragments = 0;
1155 static int refresh_manifest(AVFormatContext *s)
1159 DASHContext *c = s->priv_data;
1161 // save current context
1162 int n_videos = c->n_videos;
1163 struct representation **videos = c->videos;
1164 int n_audios = c->n_audios;
1165 struct representation **audios = c->audios;
1166 char *base_url = c->base_url;
1173 ret = parse_manifest(s, s->filename, NULL);
1177 if (c->n_videos != n_videos) {
1178 av_log(c, AV_LOG_ERROR,
1179 "new manifest has mismatched no. of video representations, %d -> %d\n",
1180 n_videos, c->n_videos);
1181 return AVERROR_INVALIDDATA;
1183 if (c->n_audios != n_audios) {
1184 av_log(c, AV_LOG_ERROR,
1185 "new manifest has mismatched no. of audio representations, %d -> %d\n",
1186 n_audios, c->n_audios);
1187 return AVERROR_INVALIDDATA;
1190 for (i = 0; i < n_videos; i++) {
1191 struct representation *cur_video = videos[i];
1192 struct representation *ccur_video = c->videos[i];
1193 if (cur_video->timelines) {
1194 // calc current time
1195 int64_t currentTime = get_segment_start_time_based_on_timeline(cur_video, cur_video->cur_seq_no) / cur_video->fragment_timescale;
1197 ccur_video->cur_seq_no = calc_next_seg_no_from_timelines(ccur_video, currentTime * cur_video->fragment_timescale - 1);
1198 if (ccur_video->cur_seq_no >= 0) {
1199 move_timelines(ccur_video, cur_video, c);
1202 if (cur_video->fragments) {
1203 move_segments(ccur_video, cur_video, c);
1206 for (i = 0; i < n_audios; i++) {
1207 struct representation *cur_audio = audios[i];
1208 struct representation *ccur_audio = c->audios[i];
1209 if (cur_audio->timelines) {
1210 // calc current time
1211 int64_t currentTime = get_segment_start_time_based_on_timeline(cur_audio, cur_audio->cur_seq_no) / cur_audio->fragment_timescale;
1213 ccur_audio->cur_seq_no = calc_next_seg_no_from_timelines(ccur_audio, currentTime * cur_audio->fragment_timescale - 1);
1214 if (ccur_audio->cur_seq_no >= 0) {
1215 move_timelines(ccur_audio, cur_audio, c);
1218 if (cur_audio->fragments) {
1219 move_segments(ccur_audio, cur_audio, c);
1228 c->base_url = base_url;
1233 c->n_audios = n_audios;
1235 c->n_videos = n_videos;
1240 static struct fragment *get_current_fragment(struct representation *pls)
1242 int64_t min_seq_no = 0;
1243 int64_t max_seq_no = 0;
1244 struct fragment *seg = NULL;
1245 struct fragment *seg_ptr = NULL;
1246 DASHContext *c = pls->parent->priv_data;
1248 while (( !ff_check_interrupt(c->interrupt_callback)&& pls->n_fragments > 0)) {
1249 if (pls->cur_seq_no < pls->n_fragments) {
1250 seg_ptr = pls->fragments[pls->cur_seq_no];
1251 seg = av_mallocz(sizeof(struct fragment));
1255 seg->url = av_strdup(seg_ptr->url);
1260 seg->size = seg_ptr->size;
1261 seg->url_offset = seg_ptr->url_offset;
1263 } else if (c->is_live) {
1264 refresh_manifest(pls->parent);
1270 min_seq_no = calc_min_seg_no(pls->parent, pls);
1271 max_seq_no = calc_max_seg_no(pls, c);
1273 if (pls->timelines || pls->fragments) {
1274 refresh_manifest(pls->parent);
1276 if (pls->cur_seq_no <= min_seq_no) {
1277 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);
1278 pls->cur_seq_no = calc_cur_seg_no(pls->parent, pls);
1279 } else if (pls->cur_seq_no > max_seq_no) {
1280 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);
1282 seg = av_mallocz(sizeof(struct fragment));
1286 } else if (pls->cur_seq_no <= pls->last_seq_no) {
1287 seg = av_mallocz(sizeof(struct fragment));
1293 char tmpfilename[MAX_URL_SIZE];
1295 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));
1296 seg->url = av_strireplace(pls->url_template, pls->url_template, tmpfilename);
1298 av_log(pls->parent, AV_LOG_WARNING, "Unable to resolve template url '%s', try to use origin template\n", pls->url_template);
1299 seg->url = av_strdup(pls->url_template);
1301 av_log(pls->parent, AV_LOG_ERROR, "Cannot resolve template url '%s'\n", pls->url_template);
1312 enum ReadFromURLMode {
1317 static int read_from_url(struct representation *pls, struct fragment *seg,
1318 uint8_t *buf, int buf_size,
1319 enum ReadFromURLMode mode)
1323 /* limit read if the fragment was only a part of a file */
1325 buf_size = FFMIN(buf_size, pls->cur_seg_size - pls->cur_seg_offset);
1327 if (mode == READ_COMPLETE) {
1328 ret = avio_read(pls->input, buf, buf_size);
1329 if (ret < buf_size) {
1330 av_log(pls->parent, AV_LOG_WARNING, "Could not read complete fragment.\n");
1333 ret = avio_read(pls->input, buf, buf_size);
1336 pls->cur_seg_offset += ret;
1341 static int open_input(DASHContext *c, struct representation *pls, struct fragment *seg)
1343 AVDictionary *opts = NULL;
1344 char url[MAX_URL_SIZE];
1347 set_httpheader_options(c, &opts);
1348 if (seg->size >= 0) {
1349 /* try to restrict the HTTP request to the part we want
1350 * (if this is in fact a HTTP request) */
1351 av_dict_set_int(&opts, "offset", seg->url_offset, 0);
1352 av_dict_set_int(&opts, "end_offset", seg->url_offset + seg->size, 0);
1355 ff_make_absolute_url(url, MAX_URL_SIZE, c->base_url, seg->url);
1356 av_log(pls->parent, AV_LOG_VERBOSE, "DASH request for url '%s', offset %"PRId64", playlist %d\n",
1357 url, seg->url_offset, pls->rep_idx);
1358 ret = open_url(pls->parent, &pls->input, url, c->avio_opts, opts, NULL);
1363 /* Seek to the requested position. If this was a HTTP request, the offset
1364 * should already be where want it to, but this allows e.g. local testing
1365 * without a HTTP server. */
1366 if (!ret && seg->url_offset) {
1367 int64_t seekret = avio_seek(pls->input, seg->url_offset, SEEK_SET);
1369 av_log(pls->parent, AV_LOG_ERROR, "Unable to seek to offset %"PRId64" of DASH fragment '%s'\n", seg->url_offset, seg->url);
1370 ret = (int) seekret;
1371 ff_format_io_close(pls->parent, &pls->input);
1376 av_dict_free(&opts);
1377 pls->cur_seg_offset = 0;
1378 pls->cur_seg_size = seg->size;
1382 static int update_init_section(struct representation *pls)
1384 static const int max_init_section_size = 1024 * 1024;
1385 DASHContext *c = pls->parent->priv_data;
1390 if (!pls->init_section || pls->init_sec_buf)
1393 ret = open_input(c, pls, pls->init_section);
1395 av_log(pls->parent, AV_LOG_WARNING,
1396 "Failed to open an initialization section in playlist %d\n",
1401 if (pls->init_section->size >= 0)
1402 sec_size = pls->init_section->size;
1403 else if ((urlsize = avio_size(pls->input)) >= 0)
1406 sec_size = max_init_section_size;
1408 av_log(pls->parent, AV_LOG_DEBUG,
1409 "Downloading an initialization section of size %"PRId64"\n",
1412 sec_size = FFMIN(sec_size, max_init_section_size);
1414 av_fast_malloc(&pls->init_sec_buf, &pls->init_sec_buf_size, sec_size);
1416 ret = read_from_url(pls, pls->init_section, pls->init_sec_buf,
1417 pls->init_sec_buf_size, READ_COMPLETE);
1418 ff_format_io_close(pls->parent, &pls->input);
1423 pls->init_sec_data_len = ret;
1424 pls->init_sec_buf_read_offset = 0;
1429 static int64_t seek_data(void *opaque, int64_t offset, int whence)
1431 struct representation *v = opaque;
1432 if (v->n_fragments && !v->init_sec_data_len) {
1433 return avio_seek(v->input, offset, whence);
1436 return AVERROR(ENOSYS);
1439 static int read_data(void *opaque, uint8_t *buf, int buf_size)
1442 struct representation *v = opaque;
1443 DASHContext *c = v->parent->priv_data;
1447 free_fragment(&v->cur_seg);
1448 v->cur_seg = get_current_fragment(v);
1454 /* load/update Media Initialization Section, if any */
1455 ret = update_init_section(v);
1459 ret = open_input(c, v, v->cur_seg);
1461 if (ff_check_interrupt(c->interrupt_callback)) {
1465 av_log(v->parent, AV_LOG_WARNING, "Failed to open fragment of playlist %d\n", v->rep_idx);
1471 if (v->init_sec_buf_read_offset < v->init_sec_data_len) {
1472 /* Push init section out first before first actual fragment */
1473 int copy_size = FFMIN(v->init_sec_data_len - v->init_sec_buf_read_offset, buf_size);
1474 memcpy(buf, v->init_sec_buf, copy_size);
1475 v->init_sec_buf_read_offset += copy_size;
1480 /* check the v->cur_seg, if it is null, get current and double check if the new v->cur_seg*/
1482 v->cur_seg = get_current_fragment(v);
1488 ret = read_from_url(v, v->cur_seg, buf, buf_size, READ_NORMAL);
1492 if (!v->is_restart_needed)
1494 v->is_restart_needed = 1;
1500 static int save_avio_options(AVFormatContext *s)
1502 DASHContext *c = s->priv_data;
1503 const char *opts[] = { "headers", "user_agent", "user-agent", "cookies", NULL }, **opt = opts;
1504 uint8_t *buf = NULL;
1508 if (av_opt_get(s->pb, *opt, AV_OPT_SEARCH_CHILDREN, &buf) >= 0) {
1509 if (buf[0] != '\0') {
1510 ret = av_dict_set(&c->avio_opts, *opt, buf, AV_DICT_DONT_STRDUP_VAL);
1525 static int nested_io_open(AVFormatContext *s, AVIOContext **pb, const char *url,
1526 int flags, AVDictionary **opts)
1528 av_log(s, AV_LOG_ERROR,
1529 "A DASH playlist item '%s' referred to an external file '%s'. "
1530 "Opening this file was forbidden for security reasons\n",
1532 return AVERROR(EPERM);
1535 static void close_demux_for_component(struct representation *pls)
1537 /* note: the internal buffer could have changed */
1538 av_freep(&pls->pb.buffer);
1539 memset(&pls->pb, 0x00, sizeof(AVIOContext));
1540 pls->ctx->pb = NULL;
1541 avformat_close_input(&pls->ctx);
1545 static int reopen_demux_for_component(AVFormatContext *s, struct representation *pls)
1547 DASHContext *c = s->priv_data;
1548 AVInputFormat *in_fmt = NULL;
1549 AVDictionary *in_fmt_opts = NULL;
1550 uint8_t *avio_ctx_buffer = NULL;
1554 close_demux_for_component(pls);
1556 if (!(pls->ctx = avformat_alloc_context())) {
1557 ret = AVERROR(ENOMEM);
1561 avio_ctx_buffer = av_malloc(INITIAL_BUFFER_SIZE);
1562 if (!avio_ctx_buffer ) {
1563 ret = AVERROR(ENOMEM);
1564 avformat_free_context(pls->ctx);
1569 ffio_init_context(&pls->pb, avio_ctx_buffer , INITIAL_BUFFER_SIZE, 0, pls, read_data, NULL, NULL);
1571 ffio_init_context(&pls->pb, avio_ctx_buffer , INITIAL_BUFFER_SIZE, 0, pls, read_data, NULL, seek_data);
1573 pls->pb.seekable = 0;
1575 if ((ret = ff_copy_whiteblacklists(pls->ctx, s)) < 0)
1578 pls->ctx->flags = AVFMT_FLAG_CUSTOM_IO;
1579 pls->ctx->probesize = 1024 * 4;
1580 pls->ctx->max_analyze_duration = 4 * AV_TIME_BASE;
1581 ret = av_probe_input_buffer(&pls->pb, &in_fmt, "", NULL, 0, 0);
1583 av_log(s, AV_LOG_ERROR, "Error when loading first fragment, playlist %d\n", (int)pls->rep_idx);
1584 avformat_free_context(pls->ctx);
1589 pls->ctx->pb = &pls->pb;
1590 pls->ctx->io_open = nested_io_open;
1592 // provide additional information from mpd if available
1593 ret = avformat_open_input(&pls->ctx, "", in_fmt, &in_fmt_opts); //pls->init_section->url
1594 av_dict_free(&in_fmt_opts);
1597 if (pls->n_fragments) {
1598 ret = avformat_find_stream_info(pls->ctx, NULL);
1607 static int open_demux_for_component(AVFormatContext *s, struct representation *pls)
1613 pls->cur_seq_no = calc_cur_seg_no(s, pls);
1614 pls->last_seq_no = calc_max_seg_no(pls, s->priv_data);
1616 ret = reopen_demux_for_component(s, pls);
1620 for (i = 0; i < pls->ctx->nb_streams; i++) {
1621 AVStream *st = avformat_new_stream(s, NULL);
1622 AVStream *ist = pls->ctx->streams[i];
1624 ret = AVERROR(ENOMEM);
1628 avcodec_parameters_copy(st->codecpar, pls->ctx->streams[i]->codecpar);
1629 avpriv_set_pts_info(st, ist->pts_wrap_bits, ist->time_base.num, ist->time_base.den);
1637 static int dash_read_header(AVFormatContext *s)
1639 void *u = (s->flags & AVFMT_FLAG_CUSTOM_IO) ? NULL : s->pb;
1640 DASHContext *c = s->priv_data;
1642 int stream_index = 0;
1645 c->interrupt_callback = &s->interrupt_callback;
1646 // if the URL context is good, read important options we must broker later
1648 update_options(&c->user_agent, "user-agent", u);
1649 update_options(&c->cookies, "cookies", u);
1650 update_options(&c->headers, "headers", u);
1653 if ((ret = parse_manifest(s, s->filename, s->pb)) < 0)
1656 if ((ret = save_avio_options(s)) < 0)
1659 /* If this isn't a live stream, fill the total duration of the
1662 s->duration = (int64_t) c->media_presentation_duration * AV_TIME_BASE;
1665 /* Open the demuxer for video and audio components if available */
1666 for (i = 0; i < c->n_videos; i++) {
1667 struct representation *cur_video = c->videos[i];
1668 ret = open_demux_for_component(s, cur_video);
1671 cur_video->stream_index = stream_index;
1675 for (i = 0; i < c->n_audios; i++) {
1676 struct representation *cur_audio = c->audios[i];
1677 ret = open_demux_for_component(s, cur_audio);
1680 cur_audio->stream_index = stream_index;
1684 if (!stream_index) {
1685 ret = AVERROR_INVALIDDATA;
1689 /* Create a program */
1692 program = av_new_program(s, 0);
1697 for (i = 0; i < c->n_videos; i++) {
1698 struct representation *pls = c->videos[i];
1700 av_program_add_stream_index(s, 0, pls->stream_index);
1701 pls->assoc_stream = s->streams[pls->stream_index];
1702 if (pls->bandwidth > 0)
1703 av_dict_set_int(&pls->assoc_stream->metadata, "variant_bitrate", pls->bandwidth, 0);
1705 av_dict_set(&pls->assoc_stream->metadata, "id", pls->id, 0);
1707 for (i = 0; i < c->n_audios; i++) {
1708 struct representation *pls = c->audios[i];
1710 av_program_add_stream_index(s, 0, pls->stream_index);
1711 pls->assoc_stream = s->streams[pls->stream_index];
1712 if (pls->bandwidth > 0)
1713 av_dict_set_int(&pls->assoc_stream->metadata, "variant_bitrate", pls->bandwidth, 0);
1715 av_dict_set(&pls->assoc_stream->metadata, "id", pls->id, 0);
1724 static void recheck_discard_flags(AVFormatContext *s, struct representation **p, int n)
1728 for (i = 0; i < n; i++) {
1729 struct representation *pls = p[i];
1731 int needed = !pls->assoc_stream || pls->assoc_stream->discard < AVDISCARD_ALL;
1732 if (needed && !pls->ctx) {
1733 pls->cur_seg_offset = 0;
1734 pls->init_sec_buf_read_offset = 0;
1736 for (j = 0; j < n; j++) {
1737 pls->cur_seq_no = FFMAX(pls->cur_seq_no, p[j]->cur_seq_no);
1739 reopen_demux_for_component(s, pls);
1740 av_log(s, AV_LOG_INFO, "Now receiving stream_index %d\n", pls->stream_index);
1741 } else if (!needed && pls->ctx) {
1742 close_demux_for_component(pls);
1744 ff_format_io_close(pls->parent, &pls->input);
1745 av_log(s, AV_LOG_INFO, "No longer receiving stream_index %d\n", pls->stream_index);
1750 static int dash_read_packet(AVFormatContext *s, AVPacket *pkt)
1752 DASHContext *c = s->priv_data;
1755 struct representation *cur = NULL;
1757 recheck_discard_flags(s, c->videos, c->n_videos);
1758 recheck_discard_flags(s, c->audios, c->n_audios);
1760 for (i = 0; i < c->n_videos; i++) {
1761 struct representation *pls = c->videos[i];
1764 if (!cur || pls->cur_timestamp < mints) {
1766 mints = pls->cur_timestamp;
1769 for (i = 0; i < c->n_audios; i++) {
1770 struct representation *pls = c->audios[i];
1773 if (!cur || pls->cur_timestamp < mints) {
1775 mints = pls->cur_timestamp;
1780 return AVERROR_INVALIDDATA;
1782 while (!ff_check_interrupt(c->interrupt_callback) && !ret) {
1783 ret = av_read_frame(cur->ctx, pkt);
1785 /* If we got a packet, return it */
1786 cur->cur_timestamp = av_rescale(pkt->pts, (int64_t)cur->ctx->streams[0]->time_base.num * 90000, cur->ctx->streams[0]->time_base.den);
1787 pkt->stream_index = cur->stream_index;
1790 if (cur->is_restart_needed) {
1791 cur->cur_seg_offset = 0;
1792 cur->init_sec_buf_read_offset = 0;
1794 ff_format_io_close(cur->parent, &cur->input);
1795 ret = reopen_demux_for_component(s, cur);
1796 cur->is_restart_needed = 0;
1802 static int dash_close(AVFormatContext *s)
1804 DASHContext *c = s->priv_data;
1808 av_freep(&c->cookies);
1809 av_freep(&c->user_agent);
1810 av_dict_free(&c->avio_opts);
1811 av_freep(&c->base_url);
1815 static int dash_seek(AVFormatContext *s, struct representation *pls, int64_t seek_pos_msec, int flags)
1820 int64_t duration = 0;
1822 av_log(pls->parent, AV_LOG_VERBOSE, "DASH seek pos[%"PRId64"ms], playlist %d\n", seek_pos_msec, pls->rep_idx);
1824 // single fragment mode
1825 if (pls->n_fragments == 1) {
1826 pls->cur_timestamp = 0;
1827 pls->cur_seg_offset = 0;
1828 ff_read_frame_flush(pls->ctx);
1829 return av_seek_frame(pls->ctx, -1, seek_pos_msec * 1000, flags);
1833 ff_format_io_close(pls->parent, &pls->input);
1835 // find the nearest fragment
1836 if (pls->n_timelines > 0 && pls->fragment_timescale > 0) {
1837 int64_t num = pls->first_seq_no;
1838 av_log(pls->parent, AV_LOG_VERBOSE, "dash_seek with SegmentTimeline start n_timelines[%d] "
1839 "last_seq_no[%"PRId64"], playlist %d.\n",
1840 (int)pls->n_timelines, (int64_t)pls->last_seq_no, (int)pls->rep_idx);
1841 for (i = 0; i < pls->n_timelines; i++) {
1842 if (pls->timelines[i]->starttime > 0) {
1843 duration = pls->timelines[i]->starttime;
1845 duration += pls->timelines[i]->duration;
1846 if (seek_pos_msec < ((duration * 1000) / pls->fragment_timescale)) {
1849 for (j = 0; j < pls->timelines[i]->repeat; j++) {
1850 duration += pls->timelines[i]->duration;
1852 if (seek_pos_msec < ((duration * 1000) / pls->fragment_timescale)) {
1860 pls->cur_seq_no = num > pls->last_seq_no ? pls->last_seq_no : num;
1861 av_log(pls->parent, AV_LOG_VERBOSE, "dash_seek with SegmentTimeline end cur_seq_no[%"PRId64"], playlist %d.\n",
1862 (int64_t)pls->cur_seq_no, (int)pls->rep_idx);
1863 } else if (pls->fragment_duration > 0) {
1864 pls->cur_seq_no = pls->first_seq_no + ((seek_pos_msec * pls->fragment_timescale) / pls->fragment_duration) / 1000;
1866 av_log(pls->parent, AV_LOG_ERROR, "dash_seek missing fragment_duration\n");
1867 pls->cur_seq_no = pls->first_seq_no;
1869 pls->cur_timestamp = 0;
1870 pls->cur_seg_offset = 0;
1871 pls->init_sec_buf_read_offset = 0;
1872 ret = reopen_demux_for_component(s, pls);
1877 static int dash_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
1880 DASHContext *c = s->priv_data;
1881 int64_t seek_pos_msec = av_rescale_rnd(timestamp, 1000,
1882 s->streams[stream_index]->time_base.den,
1883 flags & AVSEEK_FLAG_BACKWARD ?
1884 AV_ROUND_DOWN : AV_ROUND_UP);
1885 if ((flags & AVSEEK_FLAG_BYTE) || c->is_live)
1886 return AVERROR(ENOSYS);
1889 for (i = 0; i < c->n_videos; i++) {
1890 if (c->videos[i]->stream_index == stream_index) {
1891 ret = dash_seek(s, c->videos[i], seek_pos_msec, flags);
1894 for (i = 0; i < c->n_audios; i++) {
1895 if (c->audios[i]->stream_index == stream_index) {
1896 ret = dash_seek(s, c->audios[i], seek_pos_msec, flags);
1903 static int dash_probe(AVProbeData *p)
1905 if (!av_stristr(p->buf, "<MPD"))
1908 if (av_stristr(p->buf, "dash:profile:isoff-on-demand:2011") ||
1909 av_stristr(p->buf, "dash:profile:isoff-live:2011") ||
1910 av_stristr(p->buf, "dash:profile:isoff-live:2012") ||
1911 av_stristr(p->buf, "dash:profile:isoff-main:2011")) {
1912 return AVPROBE_SCORE_MAX;
1914 if (av_stristr(p->buf, "dash:profile")) {
1915 return AVPROBE_SCORE_MAX;
1921 #define OFFSET(x) offsetof(DASHContext, x)
1922 #define FLAGS AV_OPT_FLAG_DECODING_PARAM
1923 static const AVOption dash_options[] = {
1924 {"allowed_extensions", "List of file extensions that dash is allowed to access",
1925 OFFSET(allowed_extensions), AV_OPT_TYPE_STRING,
1926 {.str = "aac,m4a,m4s,m4v,mov,mp4"},
1927 INT_MIN, INT_MAX, FLAGS},
1931 static const AVClass dash_class = {
1932 .class_name = "dash",
1933 .item_name = av_default_item_name,
1934 .option = dash_options,
1935 .version = LIBAVUTIL_VERSION_INT,
1938 AVInputFormat ff_dash_demuxer = {
1940 .long_name = NULL_IF_CONFIG_SMALL("Dynamic Adaptive Streaming over HTTP"),
1941 .priv_class = &dash_class,
1942 .priv_data_size = sizeof(DASHContext),
1943 .read_probe = dash_probe,
1944 .read_header = dash_read_header,
1945 .read_packet = dash_read_packet,
1946 .read_close = dash_close,
1947 .read_seek = dash_read_seek,
1948 .flags = AVFMT_NO_BYTE_SEEK,