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;
90 AVStream *assoc_stream; /* demuxer stream associated with this representation */
93 struct fragment **fragments; /* VOD list of fragment for profile */
96 struct timeline **timelines;
100 int64_t start_number; /* used in case when we have dynamic list of segment to know which segments are new one*/
102 int64_t fragment_duration;
103 int64_t fragment_timescale;
105 int64_t presentation_timeoffset;
108 int64_t cur_seg_offset;
109 int64_t cur_seg_size;
110 struct fragment *cur_seg;
112 /* Currently active Media Initialization Section */
113 struct fragment *init_section;
114 uint8_t *init_sec_buf;
115 uint32_t init_sec_buf_size;
116 uint32_t init_sec_data_len;
117 uint32_t init_sec_buf_read_offset;
118 int64_t cur_timestamp;
119 int is_restart_needed;
122 typedef struct DASHContext {
123 const AVClass *class;
127 struct representation **videos;
129 struct representation **audios;
131 /* MediaPresentationDescription Attribute */
132 uint64_t media_presentation_duration;
133 uint64_t suggested_presentation_delay;
134 uint64_t availability_start_time;
135 uint64_t publish_time;
136 uint64_t minimum_update_period;
137 uint64_t time_shift_buffer_depth;
138 uint64_t min_buffer_time;
140 /* Period Attribute */
141 uint64_t period_duration;
142 uint64_t period_start;
145 AVIOInterruptCB *interrupt_callback;
146 char *user_agent; ///< holds HTTP user agent set as an AVOption to the HTTP protocol context
147 char *cookies; ///< holds HTTP cookie values set in either the initial response or as an AVOption to the HTTP protocol context
148 char *headers; ///< holds HTTP headers set as an AVOption to the HTTP protocol context
149 char *allowed_extensions;
150 AVDictionary *avio_opts;
153 /* Flags for init section*/
154 int is_init_section_common_video;
155 int is_init_section_common_audio;
159 static int ishttp(char *url)
161 const char *proto_name = avio_find_protocol_name(url);
162 return av_strstart(proto_name, "http", NULL);
165 static int aligned(int val)
167 return ((val + 0x3F) >> 6) << 6;
170 static uint64_t get_current_time_in_sec(void)
172 return av_gettime() / 1000000;
175 static uint64_t get_utc_date_time_insec(AVFormatContext *s, const char *datetime)
186 /* ISO-8601 date parser */
190 ret = sscanf(datetime, "%d-%d-%dT%d:%d:%fZ", &year, &month, &day, &hour, &minute, &second);
191 /* year, month, day, hour, minute, second 6 arguments */
193 av_log(s, AV_LOG_WARNING, "get_utc_date_time_insec get a wrong time format\n");
195 timeinfo.tm_year = year - 1900;
196 timeinfo.tm_mon = month - 1;
197 timeinfo.tm_mday = day;
198 timeinfo.tm_hour = hour;
199 timeinfo.tm_min = minute;
200 timeinfo.tm_sec = (int)second;
202 return av_timegm(&timeinfo);
205 static uint32_t get_duration_insec(AVFormatContext *s, const char *duration)
207 /* ISO-8601 duration parser */
215 const char *ptr = duration;
218 if (*ptr == 'P' || *ptr == 'T') {
223 if (sscanf(ptr, "%f%c%n", &value, &type, &size) != 2) {
224 av_log(s, AV_LOG_WARNING, "get_duration_insec get a wrong time format\n");
225 return 0; /* parser error */
229 days = (uint32_t)value;
232 hours = (uint32_t)value;
235 mins = (uint32_t)value;
238 secs = (uint32_t)value;
241 // handle invalid type
246 return ((days * 24 + hours) * 60 + mins) * 60 + secs;
249 static int64_t get_segment_start_time_based_on_timeline(struct representation *pls, int64_t cur_seq_no)
251 int64_t start_time = 0;
256 if (pls->n_timelines) {
257 for (i = 0; i < pls->n_timelines; i++) {
258 if (pls->timelines[i]->starttime > 0) {
259 start_time = pls->timelines[i]->starttime;
261 if (num == cur_seq_no)
264 start_time += pls->timelines[i]->duration;
265 for (j = 0; j < pls->timelines[i]->repeat; j++) {
267 if (num == cur_seq_no)
269 start_time += pls->timelines[i]->duration;
278 static int64_t calc_next_seg_no_from_timelines(struct representation *pls, int64_t cur_time)
283 int64_t start_time = 0;
285 for (i = 0; i < pls->n_timelines; i++) {
286 if (pls->timelines[i]->starttime > 0) {
287 start_time = pls->timelines[i]->starttime;
289 if (start_time > cur_time)
292 start_time += pls->timelines[i]->duration;
293 for (j = 0; j < pls->timelines[i]->repeat; j++) {
295 if (start_time > cur_time)
297 start_time += pls->timelines[i]->duration;
308 static void free_fragment(struct fragment **seg)
313 av_freep(&(*seg)->url);
317 static void free_fragment_list(struct representation *pls)
321 for (i = 0; i < pls->n_fragments; i++) {
322 free_fragment(&pls->fragments[i]);
324 av_freep(&pls->fragments);
325 pls->n_fragments = 0;
328 static void free_timelines_list(struct representation *pls)
332 for (i = 0; i < pls->n_timelines; i++) {
333 av_freep(&pls->timelines[i]);
335 av_freep(&pls->timelines);
336 pls->n_timelines = 0;
339 static void free_representation(struct representation *pls)
341 free_fragment_list(pls);
342 free_timelines_list(pls);
343 free_fragment(&pls->cur_seg);
344 free_fragment(&pls->init_section);
345 av_freep(&pls->init_sec_buf);
346 av_freep(&pls->pb.buffer);
348 ff_format_io_close(pls->parent, &pls->input);
351 avformat_close_input(&pls->ctx);
354 av_freep(&pls->url_template);
358 static void free_video_list(DASHContext *c)
361 for (i = 0; i < c->n_videos; i++) {
362 struct representation *pls = c->videos[i];
363 free_representation(pls);
365 av_freep(&c->videos);
369 static void free_audio_list(DASHContext *c)
372 for (i = 0; i < c->n_audios; i++) {
373 struct representation *pls = c->audios[i];
374 free_representation(pls);
376 av_freep(&c->audios);
380 static void set_httpheader_options(DASHContext *c, AVDictionary **opts)
382 // broker prior HTTP options that should be consistent across requests
383 av_dict_set(opts, "user_agent", c->user_agent, 0);
384 av_dict_set(opts, "cookies", c->cookies, 0);
385 av_dict_set(opts, "headers", c->headers, 0);
387 av_dict_set(opts, "seekable", "0", 0);
390 static void update_options(char **dest, const char *name, void *src)
393 av_opt_get(src, name, AV_OPT_SEARCH_CHILDREN, (uint8_t**)dest);
398 static int open_url(AVFormatContext *s, AVIOContext **pb, const char *url,
399 AVDictionary *opts, AVDictionary *opts2, int *is_http)
401 DASHContext *c = s->priv_data;
402 AVDictionary *tmp = NULL;
403 const char *proto_name = NULL;
406 av_dict_copy(&tmp, opts, 0);
407 av_dict_copy(&tmp, opts2, 0);
409 if (av_strstart(url, "crypto", NULL)) {
410 if (url[6] == '+' || url[6] == ':')
411 proto_name = avio_find_protocol_name(url + 7);
415 proto_name = avio_find_protocol_name(url);
418 return AVERROR_INVALIDDATA;
420 // only http(s) & file are allowed
421 if (av_strstart(proto_name, "file", NULL)) {
422 if (strcmp(c->allowed_extensions, "ALL") && !av_match_ext(url, c->allowed_extensions)) {
423 av_log(s, AV_LOG_ERROR,
424 "Filename extension of \'%s\' is not a common multimedia extension, blocked for security reasons.\n"
425 "If you wish to override this adjust allowed_extensions, you can set it to \'ALL\' to allow all\n",
427 return AVERROR_INVALIDDATA;
429 } else if (av_strstart(proto_name, "http", NULL)) {
432 return AVERROR_INVALIDDATA;
434 if (!strncmp(proto_name, url, strlen(proto_name)) && url[strlen(proto_name)] == ':')
436 else if (av_strstart(url, "crypto", NULL) && !strncmp(proto_name, url + 7, strlen(proto_name)) && url[7 + strlen(proto_name)] == ':')
438 else if (strcmp(proto_name, "file") || !strncmp(url, "file,", 5))
439 return AVERROR_INVALIDDATA;
442 ret = avio_open2(pb, url, AVIO_FLAG_READ, c->interrupt_callback, &tmp);
444 // update cookies on http response with setcookies.
445 char *new_cookies = NULL;
447 if (!(s->flags & AVFMT_FLAG_CUSTOM_IO))
448 av_opt_get(*pb, "cookies", AV_OPT_SEARCH_CHILDREN, (uint8_t**)&new_cookies);
452 c->cookies = new_cookies;
455 av_dict_set(&opts, "cookies", c->cookies, 0);
461 *is_http = av_strstart(proto_name, "http", NULL);
466 static char *get_content_url(xmlNodePtr *baseurl_nodes,
470 char *rep_bandwidth_val,
476 char *tmp_str = av_mallocz(max_url_size);
477 char *tmp_str_2 = av_mallocz(max_url_size);
479 if (!tmp_str || !tmp_str_2) {
483 for (i = 0; i < n_baseurl_nodes; ++i) {
484 if (baseurl_nodes[i] &&
485 baseurl_nodes[i]->children &&
486 baseurl_nodes[i]->children->type == XML_TEXT_NODE) {
487 text = xmlNodeGetContent(baseurl_nodes[i]->children);
489 memset(tmp_str, 0, max_url_size);
490 memset(tmp_str_2, 0, max_url_size);
491 ff_make_absolute_url(tmp_str_2, max_url_size, tmp_str, text);
492 av_strlcpy(tmp_str, tmp_str_2, max_url_size);
499 av_strlcat(tmp_str, (const char*)val, max_url_size);
502 url = av_strireplace(tmp_str, "$RepresentationID$", (const char*)rep_id_val);
506 av_strlcpy(tmp_str, url, max_url_size);
508 if (rep_bandwidth_val && tmp_str[0] != '\0') {
509 // free any previously assigned url before reassigning
511 url = av_strireplace(tmp_str, "$Bandwidth$", (const char*)rep_bandwidth_val);
522 static char *get_val_from_nodes_tab(xmlNodePtr *nodes, const int n_nodes, const char *attrname)
527 for (i = 0; i < n_nodes; ++i) {
529 val = xmlGetProp(nodes[i], attrname);
538 static xmlNodePtr find_child_node_by_name(xmlNodePtr rootnode, const char *nodename)
540 xmlNodePtr node = rootnode;
545 node = xmlFirstElementChild(node);
547 if (!av_strcasecmp(node->name, nodename)) {
550 node = xmlNextElementSibling(node);
555 static enum AVMediaType get_content_type(xmlNodePtr node)
557 enum AVMediaType type = AVMEDIA_TYPE_UNKNOWN;
563 for (i = 0; i < 2; i++) {
564 attr = i ? "mimeType" : "contentType";
565 val = xmlGetProp(node, attr);
567 if (av_stristr((const char *)val, "video")) {
568 type = AVMEDIA_TYPE_VIDEO;
569 } else if (av_stristr((const char *)val, "audio")) {
570 type = AVMEDIA_TYPE_AUDIO;
579 static struct fragment * get_Fragment(char *range)
581 struct fragment * seg = av_mallocz(sizeof(struct fragment));
588 char *str_end_offset;
589 char *str_offset = av_strtok(range, "-", &str_end_offset);
590 seg->url_offset = strtoll(str_offset, NULL, 10);
591 seg->size = strtoll(str_end_offset, NULL, 10) - seg->url_offset;
597 static int parse_manifest_segmenturlnode(AVFormatContext *s, struct representation *rep,
598 xmlNodePtr fragmenturl_node,
599 xmlNodePtr *baseurl_nodes,
601 char *rep_bandwidth_val)
603 DASHContext *c = s->priv_data;
604 char *initialization_val = NULL;
605 char *media_val = NULL;
606 char *range_val = NULL;
607 int max_url_size = c ? c->max_url_size: MAX_URL_SIZE;
609 if (!av_strcasecmp(fragmenturl_node->name, (const char *)"Initialization")) {
610 initialization_val = xmlGetProp(fragmenturl_node, "sourceURL");
611 range_val = xmlGetProp(fragmenturl_node, "range");
612 if (initialization_val || range_val) {
613 rep->init_section = get_Fragment(range_val);
614 if (!rep->init_section) {
615 xmlFree(initialization_val);
617 return AVERROR(ENOMEM);
619 rep->init_section->url = get_content_url(baseurl_nodes, 4,
625 if (!rep->init_section->url) {
626 av_free(rep->init_section);
627 xmlFree(initialization_val);
629 return AVERROR(ENOMEM);
631 xmlFree(initialization_val);
634 } else if (!av_strcasecmp(fragmenturl_node->name, (const char *)"SegmentURL")) {
635 media_val = xmlGetProp(fragmenturl_node, "media");
636 range_val = xmlGetProp(fragmenturl_node, "mediaRange");
637 if (media_val || range_val) {
638 struct fragment *seg = get_Fragment(range_val);
642 return AVERROR(ENOMEM);
644 seg->url = get_content_url(baseurl_nodes, 4,
653 return AVERROR(ENOMEM);
655 dynarray_add(&rep->fragments, &rep->n_fragments, seg);
664 static int parse_manifest_segmenttimeline(AVFormatContext *s, struct representation *rep,
665 xmlNodePtr fragment_timeline_node)
667 xmlAttrPtr attr = NULL;
670 if (!av_strcasecmp(fragment_timeline_node->name, (const char *)"S")) {
671 struct timeline *tml = av_mallocz(sizeof(struct timeline));
673 return AVERROR(ENOMEM);
675 attr = fragment_timeline_node->properties;
677 val = xmlGetProp(fragment_timeline_node, attr->name);
680 av_log(s, AV_LOG_WARNING, "parse_manifest_segmenttimeline attr->name = %s val is NULL\n", attr->name);
684 if (!av_strcasecmp(attr->name, (const char *)"t")) {
685 tml->starttime = (int64_t)strtoll(val, NULL, 10);
686 } else if (!av_strcasecmp(attr->name, (const char *)"r")) {
687 tml->repeat =(int64_t) strtoll(val, NULL, 10);
688 } else if (!av_strcasecmp(attr->name, (const char *)"d")) {
689 tml->duration = (int64_t)strtoll(val, NULL, 10);
694 dynarray_add(&rep->timelines, &rep->n_timelines, tml);
700 static int resolve_content_path(AVFormatContext *s, const char *url, int *max_url_size, xmlNodePtr *baseurl_nodes, int n_baseurl_nodes) {
702 char *tmp_str = NULL;
704 char *mpdName = NULL;
705 xmlNodePtr node = NULL;
706 char *baseurl = NULL;
707 char *root_url = NULL;
718 int tmp_max_url_size = strlen(url);
720 for (i = n_baseurl_nodes-1; i >= 0 ; i--) {
721 text = xmlNodeGetContent(baseurl_nodes[i]);
724 tmp_max_url_size += strlen(text);
732 tmp_max_url_size = aligned(tmp_max_url_size);
733 text = av_mallocz(tmp_max_url_size);
735 updated = AVERROR(ENOMEM);
738 av_strlcpy(text, url, strlen(url)+1);
740 while (mpdName = av_strtok(tmp, "/", &tmp)) {
741 size = strlen(mpdName);
745 path = av_mallocz(tmp_max_url_size);
746 tmp_str = av_mallocz(tmp_max_url_size);
747 if (!tmp_str || !path) {
748 updated = AVERROR(ENOMEM);
752 av_strlcpy (path, url, strlen(url) - size + 1);
753 for (rootId = n_baseurl_nodes - 1; rootId > 0; rootId --) {
754 if (!(node = baseurl_nodes[rootId])) {
757 if (ishttp(xmlNodeGetContent(node))) {
762 node = baseurl_nodes[rootId];
763 baseurl = xmlNodeGetContent(node);
764 root_url = (av_strcasecmp(baseurl, "")) ? baseurl : path;
766 xmlNodeSetContent(node, root_url);
770 size = strlen(root_url);
771 isRootHttp = ishttp(root_url);
773 if (root_url[size - 1] != token) {
774 av_strlcat(root_url, "/", size + 2);
778 for (i = 0; i < n_baseurl_nodes; ++i) {
782 text = xmlNodeGetContent(baseurl_nodes[i]);
784 memset(tmp_str, 0, strlen(tmp_str));
785 if (!ishttp(text) && isRootHttp) {
786 av_strlcpy(tmp_str, root_url, size + 1);
788 start = (text[0] == token);
789 av_strlcat(tmp_str, text + start, tmp_max_url_size);
790 xmlNodeSetContent(baseurl_nodes[i], tmp_str);
797 if (tmp_max_url_size > *max_url_size) {
798 *max_url_size = tmp_max_url_size;
807 static int parse_manifest_representation(AVFormatContext *s, const char *url,
809 xmlNodePtr adaptionset_node,
810 xmlNodePtr mpd_baseurl_node,
811 xmlNodePtr period_baseurl_node,
812 xmlNodePtr period_segmenttemplate_node,
813 xmlNodePtr period_segmentlist_node,
814 xmlNodePtr fragment_template_node,
815 xmlNodePtr content_component_node,
816 xmlNodePtr adaptionset_baseurl_node,
817 xmlNodePtr adaptionset_segmentlist_node,
818 xmlNodePtr adaptionset_supplementalproperty_node)
821 int32_t audio_rep_idx = 0;
822 int32_t video_rep_idx = 0;
823 DASHContext *c = s->priv_data;
824 struct representation *rep = NULL;
825 struct fragment *seg = NULL;
826 xmlNodePtr representation_segmenttemplate_node = NULL;
827 xmlNodePtr representation_baseurl_node = NULL;
828 xmlNodePtr representation_segmentlist_node = NULL;
829 xmlNodePtr segmentlists_tab[2];
830 xmlNodePtr fragment_timeline_node = NULL;
831 xmlNodePtr fragment_templates_tab[5];
832 char *duration_val = NULL;
833 char *presentation_timeoffset_val = NULL;
834 char *startnumber_val = NULL;
835 char *timescale_val = NULL;
836 char *initialization_val = NULL;
837 char *media_val = NULL;
839 xmlNodePtr baseurl_nodes[4];
840 xmlNodePtr representation_node = node;
841 char *rep_id_val = xmlGetProp(representation_node, "id");
842 char *rep_bandwidth_val = xmlGetProp(representation_node, "bandwidth");
843 char *rep_framerate_val = xmlGetProp(representation_node, "frameRate");
844 enum AVMediaType type = AVMEDIA_TYPE_UNKNOWN;
846 // try get information from representation
847 if (type == AVMEDIA_TYPE_UNKNOWN)
848 type = get_content_type(representation_node);
849 // try get information from contentComponen
850 if (type == AVMEDIA_TYPE_UNKNOWN)
851 type = get_content_type(content_component_node);
852 // try get information from adaption set
853 if (type == AVMEDIA_TYPE_UNKNOWN)
854 type = get_content_type(adaptionset_node);
855 if (type == AVMEDIA_TYPE_UNKNOWN) {
856 av_log(s, AV_LOG_VERBOSE, "Parsing '%s' - skipp not supported representation type\n", url);
857 } else if (type == AVMEDIA_TYPE_VIDEO || type == AVMEDIA_TYPE_AUDIO) {
858 // convert selected representation to our internal struct
859 rep = av_mallocz(sizeof(struct representation));
861 ret = AVERROR(ENOMEM);
864 representation_segmenttemplate_node = find_child_node_by_name(representation_node, "SegmentTemplate");
865 representation_baseurl_node = find_child_node_by_name(representation_node, "BaseURL");
866 representation_segmentlist_node = find_child_node_by_name(representation_node, "SegmentList");
868 baseurl_nodes[0] = mpd_baseurl_node;
869 baseurl_nodes[1] = period_baseurl_node;
870 baseurl_nodes[2] = adaptionset_baseurl_node;
871 baseurl_nodes[3] = representation_baseurl_node;
873 ret = resolve_content_path(s, url, &c->max_url_size, baseurl_nodes, 4);
874 c->max_url_size = aligned(c->max_url_size + strlen(rep_id_val) + strlen(rep_bandwidth_val));
875 if (ret == AVERROR(ENOMEM) || ret == 0) {
878 if (representation_segmenttemplate_node || fragment_template_node || period_segmenttemplate_node) {
879 fragment_timeline_node = NULL;
880 fragment_templates_tab[0] = representation_segmenttemplate_node;
881 fragment_templates_tab[1] = adaptionset_segmentlist_node;
882 fragment_templates_tab[2] = fragment_template_node;
883 fragment_templates_tab[3] = period_segmenttemplate_node;
884 fragment_templates_tab[4] = period_segmentlist_node;
886 presentation_timeoffset_val = get_val_from_nodes_tab(fragment_templates_tab, 4, "presentationTimeOffset");
887 duration_val = get_val_from_nodes_tab(fragment_templates_tab, 4, "duration");
888 startnumber_val = get_val_from_nodes_tab(fragment_templates_tab, 4, "startNumber");
889 timescale_val = get_val_from_nodes_tab(fragment_templates_tab, 4, "timescale");
890 initialization_val = get_val_from_nodes_tab(fragment_templates_tab, 4, "initialization");
891 media_val = get_val_from_nodes_tab(fragment_templates_tab, 4, "media");
893 if (initialization_val) {
894 rep->init_section = av_mallocz(sizeof(struct fragment));
895 if (!rep->init_section) {
897 ret = AVERROR(ENOMEM);
900 c->max_url_size = aligned(c->max_url_size + strlen(initialization_val));
901 rep->init_section->url = get_content_url(baseurl_nodes, 4, c->max_url_size, rep_id_val, rep_bandwidth_val, initialization_val);
902 if (!rep->init_section->url) {
903 av_free(rep->init_section);
905 ret = AVERROR(ENOMEM);
908 rep->init_section->size = -1;
909 xmlFree(initialization_val);
913 c->max_url_size = aligned(c->max_url_size + strlen(media_val));
914 rep->url_template = get_content_url(baseurl_nodes, 4, c->max_url_size, rep_id_val, rep_bandwidth_val, media_val);
918 if (presentation_timeoffset_val) {
919 rep->presentation_timeoffset = (int64_t) strtoll(presentation_timeoffset_val, NULL, 10);
920 xmlFree(presentation_timeoffset_val);
923 rep->fragment_duration = (int64_t) strtoll(duration_val, NULL, 10);
924 xmlFree(duration_val);
927 rep->fragment_timescale = (int64_t) strtoll(timescale_val, NULL, 10);
928 xmlFree(timescale_val);
930 if (startnumber_val) {
931 rep->first_seq_no = (int64_t) strtoll(startnumber_val, NULL, 10);
932 xmlFree(startnumber_val);
934 if (adaptionset_supplementalproperty_node) {
935 if (!av_strcasecmp(xmlGetProp(adaptionset_supplementalproperty_node,"schemeIdUri"), "http://dashif.org/guidelines/last-segment-number")) {
936 val = xmlGetProp(adaptionset_supplementalproperty_node,"value");
938 av_log(s, AV_LOG_ERROR, "Missing value attribute in adaptionset_supplementalproperty_node\n");
940 rep->last_seq_no =(int64_t) strtoll(val, NULL, 10) - 1;
946 fragment_timeline_node = find_child_node_by_name(representation_segmenttemplate_node, "SegmentTimeline");
948 if (!fragment_timeline_node)
949 fragment_timeline_node = find_child_node_by_name(fragment_template_node, "SegmentTimeline");
950 if (!fragment_timeline_node)
951 fragment_timeline_node = find_child_node_by_name(adaptionset_segmentlist_node, "SegmentTimeline");
952 if (!fragment_timeline_node)
953 fragment_timeline_node = find_child_node_by_name(period_segmentlist_node, "SegmentTimeline");
954 if (fragment_timeline_node) {
955 fragment_timeline_node = xmlFirstElementChild(fragment_timeline_node);
956 while (fragment_timeline_node) {
957 ret = parse_manifest_segmenttimeline(s, rep, fragment_timeline_node);
961 fragment_timeline_node = xmlNextElementSibling(fragment_timeline_node);
964 } else if (representation_baseurl_node && !representation_segmentlist_node) {
965 seg = av_mallocz(sizeof(struct fragment));
967 ret = AVERROR(ENOMEM);
970 seg->url = get_content_url(baseurl_nodes, 4, c->max_url_size, rep_id_val, rep_bandwidth_val, NULL);
973 ret = AVERROR(ENOMEM);
977 dynarray_add(&rep->fragments, &rep->n_fragments, seg);
978 } else if (representation_segmentlist_node) {
979 // TODO: https://www.brendanlong.com/the-structure-of-an-mpeg-dash-mpd.html
980 // http://www-itec.uni-klu.ac.at/dash/ddash/mpdGenerator.php?fragmentlength=15&type=full
981 xmlNodePtr fragmenturl_node = NULL;
982 segmentlists_tab[0] = representation_segmentlist_node;
983 segmentlists_tab[1] = adaptionset_segmentlist_node;
985 duration_val = get_val_from_nodes_tab(segmentlists_tab, 2, "duration");
986 timescale_val = get_val_from_nodes_tab(segmentlists_tab, 2, "timescale");
988 rep->fragment_duration = (int64_t) strtoll(duration_val, NULL, 10);
989 xmlFree(duration_val);
992 rep->fragment_timescale = (int64_t) strtoll(timescale_val, NULL, 10);
993 xmlFree(timescale_val);
995 fragmenturl_node = xmlFirstElementChild(representation_segmentlist_node);
996 while (fragmenturl_node) {
997 ret = parse_manifest_segmenturlnode(s, rep, fragmenturl_node,
1004 fragmenturl_node = xmlNextElementSibling(fragmenturl_node);
1007 fragment_timeline_node = find_child_node_by_name(representation_segmenttemplate_node, "SegmentTimeline");
1009 if (!fragment_timeline_node)
1010 fragment_timeline_node = find_child_node_by_name(fragment_template_node, "SegmentTimeline");
1011 if (!fragment_timeline_node)
1012 fragment_timeline_node = find_child_node_by_name(adaptionset_segmentlist_node, "SegmentTimeline");
1013 if (!fragment_timeline_node)
1014 fragment_timeline_node = find_child_node_by_name(period_segmentlist_node, "SegmentTimeline");
1015 if (fragment_timeline_node) {
1016 fragment_timeline_node = xmlFirstElementChild(fragment_timeline_node);
1017 while (fragment_timeline_node) {
1018 ret = parse_manifest_segmenttimeline(s, rep, fragment_timeline_node);
1022 fragment_timeline_node = xmlNextElementSibling(fragment_timeline_node);
1026 free_representation(rep);
1028 av_log(s, AV_LOG_ERROR, "Unknown format of Representation node id[%s] \n", (const char *)rep_id_val);
1032 if (rep->fragment_duration > 0 && !rep->fragment_timescale)
1033 rep->fragment_timescale = 1;
1034 rep->bandwidth = rep_bandwidth_val ? atoi(rep_bandwidth_val) : 0;
1035 strncpy(rep->id, rep_id_val ? rep_id_val : "", sizeof(rep->id));
1036 rep->framerate = av_make_q(0, 0);
1037 if (type == AVMEDIA_TYPE_VIDEO && rep_framerate_val) {
1038 ret = av_parse_video_rate(&rep->framerate, rep_framerate_val);
1040 av_log(s, AV_LOG_VERBOSE, "Ignoring invalid frame rate '%s'\n", rep_framerate_val);
1043 if (type == AVMEDIA_TYPE_VIDEO) {
1044 rep->rep_idx = video_rep_idx;
1045 dynarray_add(&c->videos, &c->n_videos, rep);
1047 rep->rep_idx = audio_rep_idx;
1048 dynarray_add(&c->audios, &c->n_audios, rep);
1053 video_rep_idx += type == AVMEDIA_TYPE_VIDEO;
1054 audio_rep_idx += type == AVMEDIA_TYPE_AUDIO;
1058 xmlFree(rep_id_val);
1059 if (rep_bandwidth_val)
1060 xmlFree(rep_bandwidth_val);
1061 if (rep_framerate_val)
1062 xmlFree(rep_framerate_val);
1067 static int parse_manifest_adaptationset(AVFormatContext *s, const char *url,
1068 xmlNodePtr adaptionset_node,
1069 xmlNodePtr mpd_baseurl_node,
1070 xmlNodePtr period_baseurl_node,
1071 xmlNodePtr period_segmenttemplate_node,
1072 xmlNodePtr period_segmentlist_node)
1075 xmlNodePtr fragment_template_node = NULL;
1076 xmlNodePtr content_component_node = NULL;
1077 xmlNodePtr adaptionset_baseurl_node = NULL;
1078 xmlNodePtr adaptionset_segmentlist_node = NULL;
1079 xmlNodePtr adaptionset_supplementalproperty_node = NULL;
1080 xmlNodePtr node = NULL;
1082 node = xmlFirstElementChild(adaptionset_node);
1084 if (!av_strcasecmp(node->name, (const char *)"SegmentTemplate")) {
1085 fragment_template_node = node;
1086 } else if (!av_strcasecmp(node->name, (const char *)"ContentComponent")) {
1087 content_component_node = node;
1088 } else if (!av_strcasecmp(node->name, (const char *)"BaseURL")) {
1089 adaptionset_baseurl_node = node;
1090 } else if (!av_strcasecmp(node->name, (const char *)"SegmentList")) {
1091 adaptionset_segmentlist_node = node;
1092 } else if (!av_strcasecmp(node->name, (const char *)"SupplementalProperty")) {
1093 adaptionset_supplementalproperty_node = node;
1094 } else if (!av_strcasecmp(node->name, (const char *)"Representation")) {
1095 ret = parse_manifest_representation(s, url, node,
1098 period_baseurl_node,
1099 period_segmenttemplate_node,
1100 period_segmentlist_node,
1101 fragment_template_node,
1102 content_component_node,
1103 adaptionset_baseurl_node,
1104 adaptionset_segmentlist_node,
1105 adaptionset_supplementalproperty_node);
1110 node = xmlNextElementSibling(node);
1115 static int parse_manifest(AVFormatContext *s, const char *url, AVIOContext *in)
1117 DASHContext *c = s->priv_data;
1120 uint8_t *new_url = NULL;
1121 int64_t filesize = 0;
1122 char *buffer = NULL;
1123 AVDictionary *opts = NULL;
1125 xmlNodePtr root_element = NULL;
1126 xmlNodePtr node = NULL;
1127 xmlNodePtr period_node = NULL;
1128 xmlNodePtr tmp_node = NULL;
1129 xmlNodePtr mpd_baseurl_node = NULL;
1130 xmlNodePtr period_baseurl_node = NULL;
1131 xmlNodePtr period_segmenttemplate_node = NULL;
1132 xmlNodePtr period_segmentlist_node = NULL;
1133 xmlNodePtr adaptionset_node = NULL;
1134 xmlAttrPtr attr = NULL;
1136 uint32_t period_duration_sec = 0;
1137 uint32_t period_start_sec = 0;
1142 set_httpheader_options(c, &opts);
1143 ret = avio_open2(&in, url, AVIO_FLAG_READ, c->interrupt_callback, &opts);
1144 av_dict_free(&opts);
1149 if (av_opt_get(in, "location", AV_OPT_SEARCH_CHILDREN, &new_url) >= 0) {
1150 c->base_url = av_strdup(new_url);
1152 c->base_url = av_strdup(url);
1155 filesize = avio_size(in);
1156 if (filesize <= 0) {
1157 filesize = 8 * 1024;
1160 buffer = av_mallocz(filesize);
1162 av_free(c->base_url);
1163 return AVERROR(ENOMEM);
1166 filesize = avio_read(in, buffer, filesize);
1167 if (filesize <= 0) {
1168 av_log(s, AV_LOG_ERROR, "Unable to read to offset '%s'\n", url);
1169 ret = AVERROR_INVALIDDATA;
1173 doc = xmlReadMemory(buffer, filesize, c->base_url, NULL, 0);
1174 root_element = xmlDocGetRootElement(doc);
1175 node = root_element;
1178 ret = AVERROR_INVALIDDATA;
1179 av_log(s, AV_LOG_ERROR, "Unable to parse '%s' - missing root node\n", url);
1183 if (node->type != XML_ELEMENT_NODE ||
1184 av_strcasecmp(node->name, (const char *)"MPD")) {
1185 ret = AVERROR_INVALIDDATA;
1186 av_log(s, AV_LOG_ERROR, "Unable to parse '%s' - wrong root node name[%s] type[%d]\n", url, node->name, (int)node->type);
1190 val = xmlGetProp(node, "type");
1192 av_log(s, AV_LOG_ERROR, "Unable to parse '%s' - missing type attrib\n", url);
1193 ret = AVERROR_INVALIDDATA;
1196 if (!av_strcasecmp(val, (const char *)"dynamic"))
1200 attr = node->properties;
1202 val = xmlGetProp(node, attr->name);
1204 if (!av_strcasecmp(attr->name, (const char *)"availabilityStartTime")) {
1205 c->availability_start_time = get_utc_date_time_insec(s, (const char *)val);
1206 } else if (!av_strcasecmp(attr->name, (const char *)"publishTime")) {
1207 c->publish_time = get_utc_date_time_insec(s, (const char *)val);
1208 } else if (!av_strcasecmp(attr->name, (const char *)"minimumUpdatePeriod")) {
1209 c->minimum_update_period = get_duration_insec(s, (const char *)val);
1210 } else if (!av_strcasecmp(attr->name, (const char *)"timeShiftBufferDepth")) {
1211 c->time_shift_buffer_depth = get_duration_insec(s, (const char *)val);
1212 } else if (!av_strcasecmp(attr->name, (const char *)"minBufferTime")) {
1213 c->min_buffer_time = get_duration_insec(s, (const char *)val);
1214 } else if (!av_strcasecmp(attr->name, (const char *)"suggestedPresentationDelay")) {
1215 c->suggested_presentation_delay = get_duration_insec(s, (const char *)val);
1216 } else if (!av_strcasecmp(attr->name, (const char *)"mediaPresentationDuration")) {
1217 c->media_presentation_duration = get_duration_insec(s, (const char *)val);
1223 tmp_node = find_child_node_by_name(node, "BaseURL");
1225 mpd_baseurl_node = xmlCopyNode(tmp_node,1);
1227 mpd_baseurl_node = xmlNewNode(NULL, "BaseURL");
1230 // at now we can handle only one period, with the longest duration
1231 node = xmlFirstElementChild(node);
1233 if (!av_strcasecmp(node->name, (const char *)"Period")) {
1234 period_duration_sec = 0;
1235 period_start_sec = 0;
1236 attr = node->properties;
1238 val = xmlGetProp(node, attr->name);
1239 if (!av_strcasecmp(attr->name, (const char *)"duration")) {
1240 period_duration_sec = get_duration_insec(s, (const char *)val);
1241 } else if (!av_strcasecmp(attr->name, (const char *)"start")) {
1242 period_start_sec = get_duration_insec(s, (const char *)val);
1247 if ((period_duration_sec) >= (c->period_duration)) {
1249 c->period_duration = period_duration_sec;
1250 c->period_start = period_start_sec;
1251 if (c->period_start > 0)
1252 c->media_presentation_duration = c->period_duration;
1255 node = xmlNextElementSibling(node);
1258 av_log(s, AV_LOG_ERROR, "Unable to parse '%s' - missing Period node\n", url);
1259 ret = AVERROR_INVALIDDATA;
1263 adaptionset_node = xmlFirstElementChild(period_node);
1264 while (adaptionset_node) {
1265 if (!av_strcasecmp(adaptionset_node->name, (const char *)"BaseURL")) {
1266 period_baseurl_node = adaptionset_node;
1267 } else if (!av_strcasecmp(adaptionset_node->name, (const char *)"SegmentTemplate")) {
1268 period_segmenttemplate_node = adaptionset_node;
1269 } else if (!av_strcasecmp(adaptionset_node->name, (const char *)"SegmentList")) {
1270 period_segmentlist_node = adaptionset_node;
1271 } else if (!av_strcasecmp(adaptionset_node->name, (const char *)"AdaptationSet")) {
1272 parse_manifest_adaptationset(s, url, adaptionset_node, mpd_baseurl_node, period_baseurl_node, period_segmenttemplate_node, period_segmentlist_node);
1274 adaptionset_node = xmlNextElementSibling(adaptionset_node);
1277 /*free the document */
1280 xmlFreeNode(mpd_baseurl_node);
1291 static int64_t calc_cur_seg_no(AVFormatContext *s, struct representation *pls)
1293 DASHContext *c = s->priv_data;
1295 int64_t start_time_offset = 0;
1298 if (pls->n_fragments) {
1299 num = pls->first_seq_no;
1300 } else if (pls->n_timelines) {
1301 start_time_offset = get_segment_start_time_based_on_timeline(pls, 0xFFFFFFFF) - 60 * pls->fragment_timescale; // 60 seconds before end
1302 num = calc_next_seg_no_from_timelines(pls, start_time_offset);
1304 num = pls->first_seq_no;
1306 num += pls->first_seq_no;
1307 } else if (pls->fragment_duration){
1308 if (pls->presentation_timeoffset) {
1309 num = pls->presentation_timeoffset * pls->fragment_timescale / pls->fragment_duration;
1310 } else if (c->publish_time > 0 && !c->availability_start_time) {
1311 num = pls->first_seq_no + (((c->publish_time - c->availability_start_time) - c->suggested_presentation_delay) * pls->fragment_timescale) / pls->fragment_duration;
1313 num = pls->first_seq_no + (((get_current_time_in_sec() - c->availability_start_time) - c->suggested_presentation_delay) * pls->fragment_timescale) / pls->fragment_duration;
1317 num = pls->first_seq_no;
1322 static int64_t calc_min_seg_no(AVFormatContext *s, struct representation *pls)
1324 DASHContext *c = s->priv_data;
1327 if (c->is_live && pls->fragment_duration) {
1328 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;
1330 num = pls->first_seq_no;
1335 static int64_t calc_max_seg_no(struct representation *pls, DASHContext *c)
1339 if (pls->n_fragments) {
1340 num = pls->first_seq_no + pls->n_fragments - 1;
1341 } else if (pls->n_timelines) {
1343 num = pls->first_seq_no + pls->n_timelines - 1;
1344 for (i = 0; i < pls->n_timelines; i++) {
1345 num += pls->timelines[i]->repeat;
1347 } else if (c->is_live && pls->fragment_duration) {
1348 num = pls->first_seq_no + (((get_current_time_in_sec() - c->availability_start_time)) * pls->fragment_timescale) / pls->fragment_duration;
1349 } else if (pls->fragment_duration) {
1350 num = pls->first_seq_no + (c->media_presentation_duration * pls->fragment_timescale) / pls->fragment_duration;
1356 static void move_timelines(struct representation *rep_src, struct representation *rep_dest, DASHContext *c)
1358 if (rep_dest && rep_src ) {
1359 free_timelines_list(rep_dest);
1360 rep_dest->timelines = rep_src->timelines;
1361 rep_dest->n_timelines = rep_src->n_timelines;
1362 rep_dest->first_seq_no = rep_src->first_seq_no;
1363 rep_dest->last_seq_no = calc_max_seg_no(rep_dest, c);
1364 rep_src->timelines = NULL;
1365 rep_src->n_timelines = 0;
1366 rep_dest->cur_seq_no = rep_src->cur_seq_no;
1370 static void move_segments(struct representation *rep_src, struct representation *rep_dest, DASHContext *c)
1372 if (rep_dest && rep_src ) {
1373 free_fragment_list(rep_dest);
1374 if (rep_src->start_number > (rep_dest->start_number + rep_dest->n_fragments))
1375 rep_dest->cur_seq_no = 0;
1377 rep_dest->cur_seq_no += rep_src->start_number - rep_dest->start_number;
1378 rep_dest->fragments = rep_src->fragments;
1379 rep_dest->n_fragments = rep_src->n_fragments;
1380 rep_dest->parent = rep_src->parent;
1381 rep_dest->last_seq_no = calc_max_seg_no(rep_dest, c);
1382 rep_src->fragments = NULL;
1383 rep_src->n_fragments = 0;
1388 static int refresh_manifest(AVFormatContext *s)
1392 DASHContext *c = s->priv_data;
1394 // save current context
1395 int n_videos = c->n_videos;
1396 struct representation **videos = c->videos;
1397 int n_audios = c->n_audios;
1398 struct representation **audios = c->audios;
1399 char *base_url = c->base_url;
1406 ret = parse_manifest(s, s->url, NULL);
1410 if (c->n_videos != n_videos) {
1411 av_log(c, AV_LOG_ERROR,
1412 "new manifest has mismatched no. of video representations, %d -> %d\n",
1413 n_videos, c->n_videos);
1414 return AVERROR_INVALIDDATA;
1416 if (c->n_audios != n_audios) {
1417 av_log(c, AV_LOG_ERROR,
1418 "new manifest has mismatched no. of audio representations, %d -> %d\n",
1419 n_audios, c->n_audios);
1420 return AVERROR_INVALIDDATA;
1423 for (i = 0; i < n_videos; i++) {
1424 struct representation *cur_video = videos[i];
1425 struct representation *ccur_video = c->videos[i];
1426 if (cur_video->timelines) {
1427 // calc current time
1428 int64_t currentTime = get_segment_start_time_based_on_timeline(cur_video, cur_video->cur_seq_no) / cur_video->fragment_timescale;
1430 ccur_video->cur_seq_no = calc_next_seg_no_from_timelines(ccur_video, currentTime * cur_video->fragment_timescale - 1);
1431 if (ccur_video->cur_seq_no >= 0) {
1432 move_timelines(ccur_video, cur_video, c);
1435 if (cur_video->fragments) {
1436 move_segments(ccur_video, cur_video, c);
1439 for (i = 0; i < n_audios; i++) {
1440 struct representation *cur_audio = audios[i];
1441 struct representation *ccur_audio = c->audios[i];
1442 if (cur_audio->timelines) {
1443 // calc current time
1444 int64_t currentTime = get_segment_start_time_based_on_timeline(cur_audio, cur_audio->cur_seq_no) / cur_audio->fragment_timescale;
1446 ccur_audio->cur_seq_no = calc_next_seg_no_from_timelines(ccur_audio, currentTime * cur_audio->fragment_timescale - 1);
1447 if (ccur_audio->cur_seq_no >= 0) {
1448 move_timelines(ccur_audio, cur_audio, c);
1451 if (cur_audio->fragments) {
1452 move_segments(ccur_audio, cur_audio, c);
1461 c->base_url = base_url;
1466 c->n_audios = n_audios;
1468 c->n_videos = n_videos;
1473 static struct fragment *get_current_fragment(struct representation *pls)
1475 int64_t min_seq_no = 0;
1476 int64_t max_seq_no = 0;
1477 struct fragment *seg = NULL;
1478 struct fragment *seg_ptr = NULL;
1479 DASHContext *c = pls->parent->priv_data;
1481 while (( !ff_check_interrupt(c->interrupt_callback)&& pls->n_fragments > 0)) {
1482 if (pls->cur_seq_no < pls->n_fragments) {
1483 seg_ptr = pls->fragments[pls->cur_seq_no];
1484 seg = av_mallocz(sizeof(struct fragment));
1488 seg->url = av_strdup(seg_ptr->url);
1493 seg->size = seg_ptr->size;
1494 seg->url_offset = seg_ptr->url_offset;
1496 } else if (c->is_live) {
1497 refresh_manifest(pls->parent);
1503 min_seq_no = calc_min_seg_no(pls->parent, pls);
1504 max_seq_no = calc_max_seg_no(pls, c);
1506 if (pls->timelines || pls->fragments) {
1507 refresh_manifest(pls->parent);
1509 if (pls->cur_seq_no <= min_seq_no) {
1510 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);
1511 pls->cur_seq_no = calc_cur_seg_no(pls->parent, pls);
1512 } else if (pls->cur_seq_no > max_seq_no) {
1513 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);
1515 seg = av_mallocz(sizeof(struct fragment));
1519 } else if (pls->cur_seq_no <= pls->last_seq_no) {
1520 seg = av_mallocz(sizeof(struct fragment));
1526 char *tmpfilename= av_mallocz(c->max_url_size);
1530 ff_dash_fill_tmpl_params(tmpfilename, c->max_url_size, pls->url_template, 0, pls->cur_seq_no, 0, get_segment_start_time_based_on_timeline(pls, pls->cur_seq_no));
1531 seg->url = av_strireplace(pls->url_template, pls->url_template, tmpfilename);
1533 av_log(pls->parent, AV_LOG_WARNING, "Unable to resolve template url '%s', try to use origin template\n", pls->url_template);
1534 seg->url = av_strdup(pls->url_template);
1536 av_log(pls->parent, AV_LOG_ERROR, "Cannot resolve template url '%s'\n", pls->url_template);
1537 av_free(tmpfilename);
1541 av_free(tmpfilename);
1548 enum ReadFromURLMode {
1553 static int read_from_url(struct representation *pls, struct fragment *seg,
1554 uint8_t *buf, int buf_size,
1555 enum ReadFromURLMode mode)
1559 /* limit read if the fragment was only a part of a file */
1561 buf_size = FFMIN(buf_size, pls->cur_seg_size - pls->cur_seg_offset);
1563 if (mode == READ_COMPLETE) {
1564 ret = avio_read(pls->input, buf, buf_size);
1565 if (ret < buf_size) {
1566 av_log(pls->parent, AV_LOG_WARNING, "Could not read complete fragment.\n");
1569 ret = avio_read(pls->input, buf, buf_size);
1572 pls->cur_seg_offset += ret;
1577 static int open_input(DASHContext *c, struct representation *pls, struct fragment *seg)
1579 AVDictionary *opts = NULL;
1583 url = av_mallocz(c->max_url_size);
1587 set_httpheader_options(c, &opts);
1588 if (seg->size >= 0) {
1589 /* try to restrict the HTTP request to the part we want
1590 * (if this is in fact a HTTP request) */
1591 av_dict_set_int(&opts, "offset", seg->url_offset, 0);
1592 av_dict_set_int(&opts, "end_offset", seg->url_offset + seg->size, 0);
1595 ff_make_absolute_url(url, c->max_url_size, c->base_url, seg->url);
1596 av_log(pls->parent, AV_LOG_VERBOSE, "DASH request for url '%s', offset %"PRId64", playlist %d\n",
1597 url, seg->url_offset, pls->rep_idx);
1598 ret = open_url(pls->parent, &pls->input, url, c->avio_opts, opts, NULL);
1605 av_dict_free(&opts);
1606 pls->cur_seg_offset = 0;
1607 pls->cur_seg_size = seg->size;
1611 static int update_init_section(struct representation *pls)
1613 static const int max_init_section_size = 1024 * 1024;
1614 DASHContext *c = pls->parent->priv_data;
1619 if (!pls->init_section || pls->init_sec_buf)
1622 ret = open_input(c, pls, pls->init_section);
1624 av_log(pls->parent, AV_LOG_WARNING,
1625 "Failed to open an initialization section in playlist %d\n",
1630 if (pls->init_section->size >= 0)
1631 sec_size = pls->init_section->size;
1632 else if ((urlsize = avio_size(pls->input)) >= 0)
1635 sec_size = max_init_section_size;
1637 av_log(pls->parent, AV_LOG_DEBUG,
1638 "Downloading an initialization section of size %"PRId64"\n",
1641 sec_size = FFMIN(sec_size, max_init_section_size);
1643 av_fast_malloc(&pls->init_sec_buf, &pls->init_sec_buf_size, sec_size);
1645 ret = read_from_url(pls, pls->init_section, pls->init_sec_buf,
1646 pls->init_sec_buf_size, READ_COMPLETE);
1647 ff_format_io_close(pls->parent, &pls->input);
1652 pls->init_sec_data_len = ret;
1653 pls->init_sec_buf_read_offset = 0;
1658 static int64_t seek_data(void *opaque, int64_t offset, int whence)
1660 struct representation *v = opaque;
1661 if (v->n_fragments && !v->init_sec_data_len) {
1662 return avio_seek(v->input, offset, whence);
1665 return AVERROR(ENOSYS);
1668 static int read_data(void *opaque, uint8_t *buf, int buf_size)
1671 struct representation *v = opaque;
1672 DASHContext *c = v->parent->priv_data;
1676 free_fragment(&v->cur_seg);
1677 v->cur_seg = get_current_fragment(v);
1683 /* load/update Media Initialization Section, if any */
1684 ret = update_init_section(v);
1688 ret = open_input(c, v, v->cur_seg);
1690 if (ff_check_interrupt(c->interrupt_callback)) {
1694 av_log(v->parent, AV_LOG_WARNING, "Failed to open fragment of playlist %d\n", v->rep_idx);
1700 if (v->init_sec_buf_read_offset < v->init_sec_data_len) {
1701 /* Push init section out first before first actual fragment */
1702 int copy_size = FFMIN(v->init_sec_data_len - v->init_sec_buf_read_offset, buf_size);
1703 memcpy(buf, v->init_sec_buf, copy_size);
1704 v->init_sec_buf_read_offset += copy_size;
1709 /* check the v->cur_seg, if it is null, get current and double check if the new v->cur_seg*/
1711 v->cur_seg = get_current_fragment(v);
1717 ret = read_from_url(v, v->cur_seg, buf, buf_size, READ_NORMAL);
1721 if (c->is_live || v->cur_seq_no < v->last_seq_no) {
1722 if (!v->is_restart_needed)
1724 v->is_restart_needed = 1;
1731 static int save_avio_options(AVFormatContext *s)
1733 DASHContext *c = s->priv_data;
1734 const char *opts[] = { "headers", "user_agent", "user_agent", "cookies", NULL }, **opt = opts;
1735 uint8_t *buf = NULL;
1739 if (av_opt_get(s->pb, *opt, AV_OPT_SEARCH_CHILDREN, &buf) >= 0) {
1740 if (buf[0] != '\0') {
1741 ret = av_dict_set(&c->avio_opts, *opt, buf, AV_DICT_DONT_STRDUP_VAL);
1756 static int nested_io_open(AVFormatContext *s, AVIOContext **pb, const char *url,
1757 int flags, AVDictionary **opts)
1759 av_log(s, AV_LOG_ERROR,
1760 "A DASH playlist item '%s' referred to an external file '%s'. "
1761 "Opening this file was forbidden for security reasons\n",
1763 return AVERROR(EPERM);
1766 static void close_demux_for_component(struct representation *pls)
1768 /* note: the internal buffer could have changed */
1769 av_freep(&pls->pb.buffer);
1770 memset(&pls->pb, 0x00, sizeof(AVIOContext));
1771 pls->ctx->pb = NULL;
1772 avformat_close_input(&pls->ctx);
1776 static int reopen_demux_for_component(AVFormatContext *s, struct representation *pls)
1778 DASHContext *c = s->priv_data;
1779 AVInputFormat *in_fmt = NULL;
1780 AVDictionary *in_fmt_opts = NULL;
1781 uint8_t *avio_ctx_buffer = NULL;
1785 close_demux_for_component(pls);
1787 if (!(pls->ctx = avformat_alloc_context())) {
1788 ret = AVERROR(ENOMEM);
1792 avio_ctx_buffer = av_malloc(INITIAL_BUFFER_SIZE);
1793 if (!avio_ctx_buffer ) {
1794 ret = AVERROR(ENOMEM);
1795 avformat_free_context(pls->ctx);
1800 ffio_init_context(&pls->pb, avio_ctx_buffer , INITIAL_BUFFER_SIZE, 0, pls, read_data, NULL, NULL);
1802 ffio_init_context(&pls->pb, avio_ctx_buffer , INITIAL_BUFFER_SIZE, 0, pls, read_data, NULL, seek_data);
1804 pls->pb.seekable = 0;
1806 if ((ret = ff_copy_whiteblacklists(pls->ctx, s)) < 0)
1809 pls->ctx->flags = AVFMT_FLAG_CUSTOM_IO;
1810 pls->ctx->probesize = 1024 * 4;
1811 pls->ctx->max_analyze_duration = 4 * AV_TIME_BASE;
1812 ret = av_probe_input_buffer(&pls->pb, &in_fmt, "", NULL, 0, 0);
1814 av_log(s, AV_LOG_ERROR, "Error when loading first fragment, playlist %d\n", (int)pls->rep_idx);
1815 avformat_free_context(pls->ctx);
1820 pls->ctx->pb = &pls->pb;
1821 pls->ctx->io_open = nested_io_open;
1823 // provide additional information from mpd if available
1824 ret = avformat_open_input(&pls->ctx, "", in_fmt, &in_fmt_opts); //pls->init_section->url
1825 av_dict_free(&in_fmt_opts);
1828 if (pls->n_fragments) {
1829 #if FF_API_R_FRAME_RATE
1830 if (pls->framerate.den) {
1831 for (i = 0; i < pls->ctx->nb_streams; i++)
1832 pls->ctx->streams[i]->r_frame_rate = pls->framerate;
1836 ret = avformat_find_stream_info(pls->ctx, NULL);
1845 static int open_demux_for_component(AVFormatContext *s, struct representation *pls)
1851 pls->cur_seq_no = calc_cur_seg_no(s, pls);
1853 if (!pls->last_seq_no) {
1854 pls->last_seq_no = calc_max_seg_no(pls, s->priv_data);
1857 ret = reopen_demux_for_component(s, pls);
1861 for (i = 0; i < pls->ctx->nb_streams; i++) {
1862 AVStream *st = avformat_new_stream(s, NULL);
1863 AVStream *ist = pls->ctx->streams[i];
1865 ret = AVERROR(ENOMEM);
1869 avcodec_parameters_copy(st->codecpar, pls->ctx->streams[i]->codecpar);
1870 avpriv_set_pts_info(st, ist->pts_wrap_bits, ist->time_base.num, ist->time_base.den);
1878 static int is_common_init_section_exist(struct representation **pls, int n_pls)
1880 struct fragment *first_init_section = pls[0]->init_section;
1882 int64_t url_offset = -1;
1886 if (first_init_section == NULL || n_pls == 0)
1889 url = first_init_section->url;
1890 url_offset = first_init_section->url_offset;
1891 size = pls[0]->init_section->size;
1892 for (i=0;i<n_pls;i++) {
1893 if (av_strcasecmp(pls[i]->init_section->url,url) || pls[i]->init_section->url_offset != url_offset || pls[i]->init_section->size != size) {
1900 static void copy_init_section(struct representation *rep_dest, struct representation *rep_src)
1902 *rep_dest->init_section = *rep_src->init_section;
1903 rep_dest->init_sec_buf = av_mallocz(rep_src->init_sec_buf_size);
1904 memcpy(rep_dest->init_sec_buf, rep_src->init_sec_buf, rep_src->init_sec_data_len);
1905 rep_dest->init_sec_buf_size = rep_src->init_sec_buf_size;
1906 rep_dest->init_sec_data_len = rep_src->init_sec_data_len;
1907 rep_dest->cur_timestamp = rep_src->cur_timestamp;
1911 static int dash_read_header(AVFormatContext *s)
1913 void *u = (s->flags & AVFMT_FLAG_CUSTOM_IO) ? NULL : s->pb;
1914 DASHContext *c = s->priv_data;
1916 int stream_index = 0;
1919 c->interrupt_callback = &s->interrupt_callback;
1920 // if the URL context is good, read important options we must broker later
1922 update_options(&c->user_agent, "user_agent", u);
1923 update_options(&c->cookies, "cookies", u);
1924 update_options(&c->headers, "headers", u);
1927 if ((ret = parse_manifest(s, s->url, s->pb)) < 0)
1930 if ((ret = save_avio_options(s)) < 0)
1933 /* If this isn't a live stream, fill the total duration of the
1936 s->duration = (int64_t) c->media_presentation_duration * AV_TIME_BASE;
1939 c->is_init_section_common_video = is_common_init_section_exist(c->videos, c->n_videos);
1941 /* Open the demuxer for video and audio components if available */
1942 for (i = 0; i < c->n_videos; i++) {
1943 struct representation *cur_video = c->videos[i];
1944 if (i > 0 && c->is_init_section_common_video) {
1945 copy_init_section(cur_video,c->videos[0]);
1947 ret = open_demux_for_component(s, cur_video);
1951 cur_video->stream_index = stream_index;
1955 c->is_init_section_common_audio = is_common_init_section_exist(c->audios, c->n_audios);
1957 for (i = 0; i < c->n_audios; i++) {
1958 struct representation *cur_audio = c->audios[i];
1959 if (i > 0 && c->is_init_section_common_audio) {
1960 copy_init_section(cur_audio,c->audios[0]);
1962 ret = open_demux_for_component(s, cur_audio);
1966 cur_audio->stream_index = stream_index;
1970 if (!stream_index) {
1971 ret = AVERROR_INVALIDDATA;
1975 /* Create a program */
1978 program = av_new_program(s, 0);
1983 for (i = 0; i < c->n_videos; i++) {
1984 struct representation *pls = c->videos[i];
1986 av_program_add_stream_index(s, 0, pls->stream_index);
1987 pls->assoc_stream = s->streams[pls->stream_index];
1988 if (pls->bandwidth > 0)
1989 av_dict_set_int(&pls->assoc_stream->metadata, "variant_bitrate", pls->bandwidth, 0);
1991 av_dict_set(&pls->assoc_stream->metadata, "id", pls->id, 0);
1993 for (i = 0; i < c->n_audios; i++) {
1994 struct representation *pls = c->audios[i];
1996 av_program_add_stream_index(s, 0, pls->stream_index);
1997 pls->assoc_stream = s->streams[pls->stream_index];
1998 if (pls->bandwidth > 0)
1999 av_dict_set_int(&pls->assoc_stream->metadata, "variant_bitrate", pls->bandwidth, 0);
2001 av_dict_set(&pls->assoc_stream->metadata, "id", pls->id, 0);
2010 static void recheck_discard_flags(AVFormatContext *s, struct representation **p, int n)
2014 for (i = 0; i < n; i++) {
2015 struct representation *pls = p[i];
2017 int needed = !pls->assoc_stream || pls->assoc_stream->discard < AVDISCARD_ALL;
2018 if (needed && !pls->ctx) {
2019 pls->cur_seg_offset = 0;
2020 pls->init_sec_buf_read_offset = 0;
2022 for (j = 0; j < n; j++) {
2023 pls->cur_seq_no = FFMAX(pls->cur_seq_no, p[j]->cur_seq_no);
2025 reopen_demux_for_component(s, pls);
2026 av_log(s, AV_LOG_INFO, "Now receiving stream_index %d\n", pls->stream_index);
2027 } else if (!needed && pls->ctx) {
2028 close_demux_for_component(pls);
2030 ff_format_io_close(pls->parent, &pls->input);
2031 av_log(s, AV_LOG_INFO, "No longer receiving stream_index %d\n", pls->stream_index);
2036 static int dash_read_packet(AVFormatContext *s, AVPacket *pkt)
2038 DASHContext *c = s->priv_data;
2041 struct representation *cur = NULL;
2043 recheck_discard_flags(s, c->videos, c->n_videos);
2044 recheck_discard_flags(s, c->audios, c->n_audios);
2046 for (i = 0; i < c->n_videos; i++) {
2047 struct representation *pls = c->videos[i];
2050 if (!cur || pls->cur_timestamp < mints) {
2052 mints = pls->cur_timestamp;
2055 for (i = 0; i < c->n_audios; i++) {
2056 struct representation *pls = c->audios[i];
2059 if (!cur || pls->cur_timestamp < mints) {
2061 mints = pls->cur_timestamp;
2066 return AVERROR_INVALIDDATA;
2068 while (!ff_check_interrupt(c->interrupt_callback) && !ret) {
2069 ret = av_read_frame(cur->ctx, pkt);
2071 /* If we got a packet, return it */
2072 cur->cur_timestamp = av_rescale(pkt->pts, (int64_t)cur->ctx->streams[0]->time_base.num * 90000, cur->ctx->streams[0]->time_base.den);
2073 pkt->stream_index = cur->stream_index;
2076 if (cur->is_restart_needed) {
2077 cur->cur_seg_offset = 0;
2078 cur->init_sec_buf_read_offset = 0;
2080 ff_format_io_close(cur->parent, &cur->input);
2081 ret = reopen_demux_for_component(s, cur);
2082 cur->is_restart_needed = 0;
2088 static int dash_close(AVFormatContext *s)
2090 DASHContext *c = s->priv_data;
2094 av_freep(&c->cookies);
2095 av_freep(&c->user_agent);
2096 av_dict_free(&c->avio_opts);
2097 av_freep(&c->base_url);
2101 static int dash_seek(AVFormatContext *s, struct representation *pls, int64_t seek_pos_msec, int flags, int dry_run)
2106 int64_t duration = 0;
2108 av_log(pls->parent, AV_LOG_VERBOSE, "DASH seek pos[%"PRId64"ms], playlist %d%s\n",
2109 seek_pos_msec, pls->rep_idx, dry_run ? " (dry)" : "");
2111 // single fragment mode
2112 if (pls->n_fragments == 1) {
2113 pls->cur_timestamp = 0;
2114 pls->cur_seg_offset = 0;
2117 ff_read_frame_flush(pls->ctx);
2118 return av_seek_frame(pls->ctx, -1, seek_pos_msec * 1000, flags);
2122 ff_format_io_close(pls->parent, &pls->input);
2124 // find the nearest fragment
2125 if (pls->n_timelines > 0 && pls->fragment_timescale > 0) {
2126 int64_t num = pls->first_seq_no;
2127 av_log(pls->parent, AV_LOG_VERBOSE, "dash_seek with SegmentTimeline start n_timelines[%d] "
2128 "last_seq_no[%"PRId64"], playlist %d.\n",
2129 (int)pls->n_timelines, (int64_t)pls->last_seq_no, (int)pls->rep_idx);
2130 for (i = 0; i < pls->n_timelines; i++) {
2131 if (pls->timelines[i]->starttime > 0) {
2132 duration = pls->timelines[i]->starttime;
2134 duration += pls->timelines[i]->duration;
2135 if (seek_pos_msec < ((duration * 1000) / pls->fragment_timescale)) {
2138 for (j = 0; j < pls->timelines[i]->repeat; j++) {
2139 duration += pls->timelines[i]->duration;
2141 if (seek_pos_msec < ((duration * 1000) / pls->fragment_timescale)) {
2149 pls->cur_seq_no = num > pls->last_seq_no ? pls->last_seq_no : num;
2150 av_log(pls->parent, AV_LOG_VERBOSE, "dash_seek with SegmentTimeline end cur_seq_no[%"PRId64"], playlist %d.\n",
2151 (int64_t)pls->cur_seq_no, (int)pls->rep_idx);
2152 } else if (pls->fragment_duration > 0) {
2153 pls->cur_seq_no = pls->first_seq_no + ((seek_pos_msec * pls->fragment_timescale) / pls->fragment_duration) / 1000;
2155 av_log(pls->parent, AV_LOG_ERROR, "dash_seek missing timeline or fragment_duration\n");
2156 pls->cur_seq_no = pls->first_seq_no;
2158 pls->cur_timestamp = 0;
2159 pls->cur_seg_offset = 0;
2160 pls->init_sec_buf_read_offset = 0;
2161 ret = dry_run ? 0 : reopen_demux_for_component(s, pls);
2166 static int dash_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
2169 DASHContext *c = s->priv_data;
2170 int64_t seek_pos_msec = av_rescale_rnd(timestamp, 1000,
2171 s->streams[stream_index]->time_base.den,
2172 flags & AVSEEK_FLAG_BACKWARD ?
2173 AV_ROUND_DOWN : AV_ROUND_UP);
2174 if ((flags & AVSEEK_FLAG_BYTE) || c->is_live)
2175 return AVERROR(ENOSYS);
2177 /* Seek in discarded streams with dry_run=1 to avoid reopening them */
2178 for (i = 0; i < c->n_videos; i++) {
2180 ret = dash_seek(s, c->videos[i], seek_pos_msec, flags, !c->videos[i]->ctx);
2182 for (i = 0; i < c->n_audios; i++) {
2184 ret = dash_seek(s, c->audios[i], seek_pos_msec, flags, !c->audios[i]->ctx);
2190 static int dash_probe(AVProbeData *p)
2192 if (!av_stristr(p->buf, "<MPD"))
2195 if (av_stristr(p->buf, "dash:profile:isoff-on-demand:2011") ||
2196 av_stristr(p->buf, "dash:profile:isoff-live:2011") ||
2197 av_stristr(p->buf, "dash:profile:isoff-live:2012") ||
2198 av_stristr(p->buf, "dash:profile:isoff-main:2011")) {
2199 return AVPROBE_SCORE_MAX;
2201 if (av_stristr(p->buf, "dash:profile")) {
2202 return AVPROBE_SCORE_MAX;
2208 #define OFFSET(x) offsetof(DASHContext, x)
2209 #define FLAGS AV_OPT_FLAG_DECODING_PARAM
2210 static const AVOption dash_options[] = {
2211 {"allowed_extensions", "List of file extensions that dash is allowed to access",
2212 OFFSET(allowed_extensions), AV_OPT_TYPE_STRING,
2213 {.str = "aac,m4a,m4s,m4v,mov,mp4"},
2214 INT_MIN, INT_MAX, FLAGS},
2218 static const AVClass dash_class = {
2219 .class_name = "dash",
2220 .item_name = av_default_item_name,
2221 .option = dash_options,
2222 .version = LIBAVUTIL_VERSION_INT,
2225 AVInputFormat ff_dash_demuxer = {
2227 .long_name = NULL_IF_CONFIG_SMALL("Dynamic Adaptive Streaming over HTTP"),
2228 .priv_class = &dash_class,
2229 .priv_data_size = sizeof(DASHContext),
2230 .read_probe = dash_probe,
2231 .read_header = dash_read_header,
2232 .read_packet = dash_read_packet,
2233 .read_close = dash_close,
2234 .read_seek = dash_read_seek,
2235 .flags = AVFMT_NO_BYTE_SEEK,