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 *allowed_extensions;
147 AVDictionary *avio_opts;
150 /* Flags for init section*/
151 int is_init_section_common_video;
152 int is_init_section_common_audio;
156 static int ishttp(char *url)
158 const char *proto_name = avio_find_protocol_name(url);
159 return av_strstart(proto_name, "http", NULL);
162 static int aligned(int val)
164 return ((val + 0x3F) >> 6) << 6;
167 static uint64_t get_current_time_in_sec(void)
169 return av_gettime() / 1000000;
172 static uint64_t get_utc_date_time_insec(AVFormatContext *s, const char *datetime)
183 /* ISO-8601 date parser */
187 ret = sscanf(datetime, "%d-%d-%dT%d:%d:%fZ", &year, &month, &day, &hour, &minute, &second);
188 /* year, month, day, hour, minute, second 6 arguments */
190 av_log(s, AV_LOG_WARNING, "get_utc_date_time_insec get a wrong time format\n");
192 timeinfo.tm_year = year - 1900;
193 timeinfo.tm_mon = month - 1;
194 timeinfo.tm_mday = day;
195 timeinfo.tm_hour = hour;
196 timeinfo.tm_min = minute;
197 timeinfo.tm_sec = (int)second;
199 return av_timegm(&timeinfo);
202 static uint32_t get_duration_insec(AVFormatContext *s, const char *duration)
204 /* ISO-8601 duration parser */
212 const char *ptr = duration;
215 if (*ptr == 'P' || *ptr == 'T') {
220 if (sscanf(ptr, "%f%c%n", &value, &type, &size) != 2) {
221 av_log(s, AV_LOG_WARNING, "get_duration_insec get a wrong time format\n");
222 return 0; /* parser error */
226 days = (uint32_t)value;
229 hours = (uint32_t)value;
232 mins = (uint32_t)value;
235 secs = (uint32_t)value;
238 // handle invalid type
243 return ((days * 24 + hours) * 60 + mins) * 60 + secs;
246 static int64_t get_segment_start_time_based_on_timeline(struct representation *pls, int64_t cur_seq_no)
248 int64_t start_time = 0;
253 if (pls->n_timelines) {
254 for (i = 0; i < pls->n_timelines; i++) {
255 if (pls->timelines[i]->starttime > 0) {
256 start_time = pls->timelines[i]->starttime;
258 if (num == cur_seq_no)
261 start_time += pls->timelines[i]->duration;
263 if (pls->timelines[i]->repeat == -1) {
264 start_time = pls->timelines[i]->duration * cur_seq_no;
268 for (j = 0; j < pls->timelines[i]->repeat; j++) {
270 if (num == cur_seq_no)
272 start_time += pls->timelines[i]->duration;
281 static int64_t calc_next_seg_no_from_timelines(struct representation *pls, int64_t cur_time)
286 int64_t start_time = 0;
288 for (i = 0; i < pls->n_timelines; i++) {
289 if (pls->timelines[i]->starttime > 0) {
290 start_time = pls->timelines[i]->starttime;
292 if (start_time > cur_time)
295 start_time += pls->timelines[i]->duration;
296 for (j = 0; j < pls->timelines[i]->repeat; j++) {
298 if (start_time > cur_time)
300 start_time += pls->timelines[i]->duration;
311 static void free_fragment(struct fragment **seg)
316 av_freep(&(*seg)->url);
320 static void free_fragment_list(struct representation *pls)
324 for (i = 0; i < pls->n_fragments; i++) {
325 free_fragment(&pls->fragments[i]);
327 av_freep(&pls->fragments);
328 pls->n_fragments = 0;
331 static void free_timelines_list(struct representation *pls)
335 for (i = 0; i < pls->n_timelines; i++) {
336 av_freep(&pls->timelines[i]);
338 av_freep(&pls->timelines);
339 pls->n_timelines = 0;
342 static void free_representation(struct representation *pls)
344 free_fragment_list(pls);
345 free_timelines_list(pls);
346 free_fragment(&pls->cur_seg);
347 free_fragment(&pls->init_section);
348 av_freep(&pls->init_sec_buf);
349 av_freep(&pls->pb.buffer);
351 ff_format_io_close(pls->parent, &pls->input);
354 avformat_close_input(&pls->ctx);
357 av_freep(&pls->url_template);
361 static void free_video_list(DASHContext *c)
364 for (i = 0; i < c->n_videos; i++) {
365 struct representation *pls = c->videos[i];
366 free_representation(pls);
368 av_freep(&c->videos);
372 static void free_audio_list(DASHContext *c)
375 for (i = 0; i < c->n_audios; i++) {
376 struct representation *pls = c->audios[i];
377 free_representation(pls);
379 av_freep(&c->audios);
383 static int open_url(AVFormatContext *s, AVIOContext **pb, const char *url,
384 AVDictionary *opts, AVDictionary *opts2, int *is_http)
386 DASHContext *c = s->priv_data;
387 AVDictionary *tmp = NULL;
388 const char *proto_name = NULL;
391 av_dict_copy(&tmp, opts, 0);
392 av_dict_copy(&tmp, opts2, 0);
394 if (av_strstart(url, "crypto", NULL)) {
395 if (url[6] == '+' || url[6] == ':')
396 proto_name = avio_find_protocol_name(url + 7);
400 proto_name = avio_find_protocol_name(url);
403 return AVERROR_INVALIDDATA;
405 // only http(s) & file are allowed
406 if (av_strstart(proto_name, "file", NULL)) {
407 if (strcmp(c->allowed_extensions, "ALL") && !av_match_ext(url, c->allowed_extensions)) {
408 av_log(s, AV_LOG_ERROR,
409 "Filename extension of \'%s\' is not a common multimedia extension, blocked for security reasons.\n"
410 "If you wish to override this adjust allowed_extensions, you can set it to \'ALL\' to allow all\n",
412 return AVERROR_INVALIDDATA;
414 } else if (av_strstart(proto_name, "http", NULL)) {
417 return AVERROR_INVALIDDATA;
419 if (!strncmp(proto_name, url, strlen(proto_name)) && url[strlen(proto_name)] == ':')
421 else if (av_strstart(url, "crypto", NULL) && !strncmp(proto_name, url + 7, strlen(proto_name)) && url[7 + strlen(proto_name)] == ':')
423 else if (strcmp(proto_name, "file") || !strncmp(url, "file,", 5))
424 return AVERROR_INVALIDDATA;
427 ret = avio_open2(pb, url, AVIO_FLAG_READ, c->interrupt_callback, &tmp);
429 // update cookies on http response with setcookies.
430 char *new_cookies = NULL;
432 if (!(s->flags & AVFMT_FLAG_CUSTOM_IO))
433 av_opt_get(*pb, "cookies", AV_OPT_SEARCH_CHILDREN, (uint8_t**)&new_cookies);
436 av_dict_set(&opts, "cookies", new_cookies, AV_DICT_DONT_STRDUP_VAL);
444 *is_http = av_strstart(proto_name, "http", NULL);
449 static char *get_content_url(xmlNodePtr *baseurl_nodes,
453 char *rep_bandwidth_val,
459 char *tmp_str = av_mallocz(max_url_size);
460 char *tmp_str_2 = av_mallocz(max_url_size);
462 if (!tmp_str || !tmp_str_2) {
466 for (i = 0; i < n_baseurl_nodes; ++i) {
467 if (baseurl_nodes[i] &&
468 baseurl_nodes[i]->children &&
469 baseurl_nodes[i]->children->type == XML_TEXT_NODE) {
470 text = xmlNodeGetContent(baseurl_nodes[i]->children);
472 memset(tmp_str, 0, max_url_size);
473 memset(tmp_str_2, 0, max_url_size);
474 ff_make_absolute_url(tmp_str_2, max_url_size, tmp_str, text);
475 av_strlcpy(tmp_str, tmp_str_2, max_url_size);
482 av_strlcat(tmp_str, (const char*)val, max_url_size);
485 url = av_strireplace(tmp_str, "$RepresentationID$", (const char*)rep_id_val);
489 av_strlcpy(tmp_str, url, max_url_size);
491 if (rep_bandwidth_val && tmp_str[0] != '\0') {
492 // free any previously assigned url before reassigning
494 url = av_strireplace(tmp_str, "$Bandwidth$", (const char*)rep_bandwidth_val);
505 static char *get_val_from_nodes_tab(xmlNodePtr *nodes, const int n_nodes, const char *attrname)
510 for (i = 0; i < n_nodes; ++i) {
512 val = xmlGetProp(nodes[i], attrname);
521 static xmlNodePtr find_child_node_by_name(xmlNodePtr rootnode, const char *nodename)
523 xmlNodePtr node = rootnode;
528 node = xmlFirstElementChild(node);
530 if (!av_strcasecmp(node->name, nodename)) {
533 node = xmlNextElementSibling(node);
538 static enum AVMediaType get_content_type(xmlNodePtr node)
540 enum AVMediaType type = AVMEDIA_TYPE_UNKNOWN;
546 for (i = 0; i < 2; i++) {
547 attr = i ? "mimeType" : "contentType";
548 val = xmlGetProp(node, attr);
550 if (av_stristr((const char *)val, "video")) {
551 type = AVMEDIA_TYPE_VIDEO;
552 } else if (av_stristr((const char *)val, "audio")) {
553 type = AVMEDIA_TYPE_AUDIO;
562 static struct fragment * get_Fragment(char *range)
564 struct fragment * seg = av_mallocz(sizeof(struct fragment));
571 char *str_end_offset;
572 char *str_offset = av_strtok(range, "-", &str_end_offset);
573 seg->url_offset = strtoll(str_offset, NULL, 10);
574 seg->size = strtoll(str_end_offset, NULL, 10) - seg->url_offset;
580 static int parse_manifest_segmenturlnode(AVFormatContext *s, struct representation *rep,
581 xmlNodePtr fragmenturl_node,
582 xmlNodePtr *baseurl_nodes,
584 char *rep_bandwidth_val)
586 DASHContext *c = s->priv_data;
587 char *initialization_val = NULL;
588 char *media_val = NULL;
589 char *range_val = NULL;
590 int max_url_size = c ? c->max_url_size: MAX_URL_SIZE;
592 if (!av_strcasecmp(fragmenturl_node->name, (const char *)"Initialization")) {
593 initialization_val = xmlGetProp(fragmenturl_node, "sourceURL");
594 range_val = xmlGetProp(fragmenturl_node, "range");
595 if (initialization_val || range_val) {
596 rep->init_section = get_Fragment(range_val);
597 if (!rep->init_section) {
598 xmlFree(initialization_val);
600 return AVERROR(ENOMEM);
602 rep->init_section->url = get_content_url(baseurl_nodes, 4,
608 if (!rep->init_section->url) {
609 av_free(rep->init_section);
610 xmlFree(initialization_val);
612 return AVERROR(ENOMEM);
614 xmlFree(initialization_val);
617 } else if (!av_strcasecmp(fragmenturl_node->name, (const char *)"SegmentURL")) {
618 media_val = xmlGetProp(fragmenturl_node, "media");
619 range_val = xmlGetProp(fragmenturl_node, "mediaRange");
620 if (media_val || range_val) {
621 struct fragment *seg = get_Fragment(range_val);
625 return AVERROR(ENOMEM);
627 seg->url = get_content_url(baseurl_nodes, 4,
636 return AVERROR(ENOMEM);
638 dynarray_add(&rep->fragments, &rep->n_fragments, seg);
647 static int parse_manifest_segmenttimeline(AVFormatContext *s, struct representation *rep,
648 xmlNodePtr fragment_timeline_node)
650 xmlAttrPtr attr = NULL;
653 if (!av_strcasecmp(fragment_timeline_node->name, (const char *)"S")) {
654 struct timeline *tml = av_mallocz(sizeof(struct timeline));
656 return AVERROR(ENOMEM);
658 attr = fragment_timeline_node->properties;
660 val = xmlGetProp(fragment_timeline_node, attr->name);
663 av_log(s, AV_LOG_WARNING, "parse_manifest_segmenttimeline attr->name = %s val is NULL\n", attr->name);
667 if (!av_strcasecmp(attr->name, (const char *)"t")) {
668 tml->starttime = (int64_t)strtoll(val, NULL, 10);
669 } else if (!av_strcasecmp(attr->name, (const char *)"r")) {
670 tml->repeat =(int64_t) strtoll(val, NULL, 10);
671 } else if (!av_strcasecmp(attr->name, (const char *)"d")) {
672 tml->duration = (int64_t)strtoll(val, NULL, 10);
677 dynarray_add(&rep->timelines, &rep->n_timelines, tml);
683 static int resolve_content_path(AVFormatContext *s, const char *url, int *max_url_size, xmlNodePtr *baseurl_nodes, int n_baseurl_nodes) {
685 char *tmp_str = NULL;
687 char *mpdName = NULL;
688 xmlNodePtr node = NULL;
689 char *baseurl = NULL;
690 char *root_url = NULL;
701 int tmp_max_url_size = strlen(url);
703 for (i = n_baseurl_nodes-1; i >= 0 ; i--) {
704 text = xmlNodeGetContent(baseurl_nodes[i]);
707 tmp_max_url_size += strlen(text);
715 tmp_max_url_size = aligned(tmp_max_url_size);
716 text = av_mallocz(tmp_max_url_size);
718 updated = AVERROR(ENOMEM);
721 av_strlcpy(text, url, strlen(url)+1);
723 while (mpdName = av_strtok(tmp, "/", &tmp)) {
724 size = strlen(mpdName);
728 path = av_mallocz(tmp_max_url_size);
729 tmp_str = av_mallocz(tmp_max_url_size);
730 if (!tmp_str || !path) {
731 updated = AVERROR(ENOMEM);
735 av_strlcpy (path, url, strlen(url) - size + 1);
736 for (rootId = n_baseurl_nodes - 1; rootId > 0; rootId --) {
737 if (!(node = baseurl_nodes[rootId])) {
740 text = xmlNodeGetContent(node);
748 node = baseurl_nodes[rootId];
749 baseurl = xmlNodeGetContent(node);
750 root_url = (av_strcasecmp(baseurl, "")) ? baseurl : path;
752 xmlNodeSetContent(node, root_url);
756 size = strlen(root_url);
757 isRootHttp = ishttp(root_url);
759 if (root_url[size - 1] != token) {
760 av_strlcat(root_url, "/", size + 2);
764 for (i = 0; i < n_baseurl_nodes; ++i) {
768 text = xmlNodeGetContent(baseurl_nodes[i]);
770 memset(tmp_str, 0, strlen(tmp_str));
771 if (!ishttp(text) && isRootHttp) {
772 av_strlcpy(tmp_str, root_url, size + 1);
774 start = (text[0] == token);
775 av_strlcat(tmp_str, text + start, tmp_max_url_size);
776 xmlNodeSetContent(baseurl_nodes[i], tmp_str);
783 if (tmp_max_url_size > *max_url_size) {
784 *max_url_size = tmp_max_url_size;
793 static int parse_manifest_representation(AVFormatContext *s, const char *url,
795 xmlNodePtr adaptionset_node,
796 xmlNodePtr mpd_baseurl_node,
797 xmlNodePtr period_baseurl_node,
798 xmlNodePtr period_segmenttemplate_node,
799 xmlNodePtr period_segmentlist_node,
800 xmlNodePtr fragment_template_node,
801 xmlNodePtr content_component_node,
802 xmlNodePtr adaptionset_baseurl_node,
803 xmlNodePtr adaptionset_segmentlist_node,
804 xmlNodePtr adaptionset_supplementalproperty_node)
807 int32_t audio_rep_idx = 0;
808 int32_t video_rep_idx = 0;
809 DASHContext *c = s->priv_data;
810 struct representation *rep = NULL;
811 struct fragment *seg = NULL;
812 xmlNodePtr representation_segmenttemplate_node = NULL;
813 xmlNodePtr representation_baseurl_node = NULL;
814 xmlNodePtr representation_segmentlist_node = NULL;
815 xmlNodePtr segmentlists_tab[2];
816 xmlNodePtr fragment_timeline_node = NULL;
817 xmlNodePtr fragment_templates_tab[5];
818 char *duration_val = NULL;
819 char *presentation_timeoffset_val = NULL;
820 char *startnumber_val = NULL;
821 char *timescale_val = NULL;
822 char *initialization_val = NULL;
823 char *media_val = NULL;
825 xmlNodePtr baseurl_nodes[4];
826 xmlNodePtr representation_node = node;
827 char *rep_id_val = xmlGetProp(representation_node, "id");
828 char *rep_bandwidth_val = xmlGetProp(representation_node, "bandwidth");
829 char *rep_framerate_val = xmlGetProp(representation_node, "frameRate");
830 enum AVMediaType type = AVMEDIA_TYPE_UNKNOWN;
832 // try get information from representation
833 if (type == AVMEDIA_TYPE_UNKNOWN)
834 type = get_content_type(representation_node);
835 // try get information from contentComponen
836 if (type == AVMEDIA_TYPE_UNKNOWN)
837 type = get_content_type(content_component_node);
838 // try get information from adaption set
839 if (type == AVMEDIA_TYPE_UNKNOWN)
840 type = get_content_type(adaptionset_node);
841 if (type == AVMEDIA_TYPE_UNKNOWN) {
842 av_log(s, AV_LOG_VERBOSE, "Parsing '%s' - skipp not supported representation type\n", url);
843 } else if (type == AVMEDIA_TYPE_VIDEO || type == AVMEDIA_TYPE_AUDIO) {
844 // convert selected representation to our internal struct
845 rep = av_mallocz(sizeof(struct representation));
847 ret = AVERROR(ENOMEM);
850 representation_segmenttemplate_node = find_child_node_by_name(representation_node, "SegmentTemplate");
851 representation_baseurl_node = find_child_node_by_name(representation_node, "BaseURL");
852 representation_segmentlist_node = find_child_node_by_name(representation_node, "SegmentList");
854 baseurl_nodes[0] = mpd_baseurl_node;
855 baseurl_nodes[1] = period_baseurl_node;
856 baseurl_nodes[2] = adaptionset_baseurl_node;
857 baseurl_nodes[3] = representation_baseurl_node;
859 ret = resolve_content_path(s, url, &c->max_url_size, baseurl_nodes, 4);
860 c->max_url_size = aligned(c->max_url_size
861 + (rep_id_val ? strlen(rep_id_val) : 0)
862 + (rep_bandwidth_val ? strlen(rep_bandwidth_val) : 0));
863 if (ret == AVERROR(ENOMEM) || ret == 0) {
866 if (representation_segmenttemplate_node || fragment_template_node || period_segmenttemplate_node) {
867 fragment_timeline_node = NULL;
868 fragment_templates_tab[0] = representation_segmenttemplate_node;
869 fragment_templates_tab[1] = adaptionset_segmentlist_node;
870 fragment_templates_tab[2] = fragment_template_node;
871 fragment_templates_tab[3] = period_segmenttemplate_node;
872 fragment_templates_tab[4] = period_segmentlist_node;
874 presentation_timeoffset_val = get_val_from_nodes_tab(fragment_templates_tab, 4, "presentationTimeOffset");
875 duration_val = get_val_from_nodes_tab(fragment_templates_tab, 4, "duration");
876 startnumber_val = get_val_from_nodes_tab(fragment_templates_tab, 4, "startNumber");
877 timescale_val = get_val_from_nodes_tab(fragment_templates_tab, 4, "timescale");
878 initialization_val = get_val_from_nodes_tab(fragment_templates_tab, 4, "initialization");
879 media_val = get_val_from_nodes_tab(fragment_templates_tab, 4, "media");
881 if (initialization_val) {
882 rep->init_section = av_mallocz(sizeof(struct fragment));
883 if (!rep->init_section) {
885 ret = AVERROR(ENOMEM);
888 c->max_url_size = aligned(c->max_url_size + strlen(initialization_val));
889 rep->init_section->url = get_content_url(baseurl_nodes, 4, c->max_url_size, rep_id_val, rep_bandwidth_val, initialization_val);
890 if (!rep->init_section->url) {
891 av_free(rep->init_section);
893 ret = AVERROR(ENOMEM);
896 rep->init_section->size = -1;
897 xmlFree(initialization_val);
901 c->max_url_size = aligned(c->max_url_size + strlen(media_val));
902 rep->url_template = get_content_url(baseurl_nodes, 4, c->max_url_size, rep_id_val, rep_bandwidth_val, media_val);
906 if (presentation_timeoffset_val) {
907 rep->presentation_timeoffset = (int64_t) strtoll(presentation_timeoffset_val, NULL, 10);
908 xmlFree(presentation_timeoffset_val);
911 rep->fragment_duration = (int64_t) strtoll(duration_val, NULL, 10);
912 xmlFree(duration_val);
915 rep->fragment_timescale = (int64_t) strtoll(timescale_val, NULL, 10);
916 xmlFree(timescale_val);
918 if (startnumber_val) {
919 rep->first_seq_no = (int64_t) strtoll(startnumber_val, NULL, 10);
920 xmlFree(startnumber_val);
922 if (adaptionset_supplementalproperty_node) {
923 if (!av_strcasecmp(xmlGetProp(adaptionset_supplementalproperty_node,"schemeIdUri"), "http://dashif.org/guidelines/last-segment-number")) {
924 val = xmlGetProp(adaptionset_supplementalproperty_node,"value");
926 av_log(s, AV_LOG_ERROR, "Missing value attribute in adaptionset_supplementalproperty_node\n");
928 rep->last_seq_no =(int64_t) strtoll(val, NULL, 10) - 1;
934 fragment_timeline_node = find_child_node_by_name(representation_segmenttemplate_node, "SegmentTimeline");
936 if (!fragment_timeline_node)
937 fragment_timeline_node = find_child_node_by_name(fragment_template_node, "SegmentTimeline");
938 if (!fragment_timeline_node)
939 fragment_timeline_node = find_child_node_by_name(adaptionset_segmentlist_node, "SegmentTimeline");
940 if (!fragment_timeline_node)
941 fragment_timeline_node = find_child_node_by_name(period_segmentlist_node, "SegmentTimeline");
942 if (fragment_timeline_node) {
943 fragment_timeline_node = xmlFirstElementChild(fragment_timeline_node);
944 while (fragment_timeline_node) {
945 ret = parse_manifest_segmenttimeline(s, rep, fragment_timeline_node);
949 fragment_timeline_node = xmlNextElementSibling(fragment_timeline_node);
952 } else if (representation_baseurl_node && !representation_segmentlist_node) {
953 seg = av_mallocz(sizeof(struct fragment));
955 ret = AVERROR(ENOMEM);
958 seg->url = get_content_url(baseurl_nodes, 4, c->max_url_size, rep_id_val, rep_bandwidth_val, NULL);
961 ret = AVERROR(ENOMEM);
965 dynarray_add(&rep->fragments, &rep->n_fragments, seg);
966 } else if (representation_segmentlist_node) {
967 // TODO: https://www.brendanlong.com/the-structure-of-an-mpeg-dash-mpd.html
968 // http://www-itec.uni-klu.ac.at/dash/ddash/mpdGenerator.php?fragmentlength=15&type=full
969 xmlNodePtr fragmenturl_node = NULL;
970 segmentlists_tab[0] = representation_segmentlist_node;
971 segmentlists_tab[1] = adaptionset_segmentlist_node;
973 duration_val = get_val_from_nodes_tab(segmentlists_tab, 2, "duration");
974 timescale_val = get_val_from_nodes_tab(segmentlists_tab, 2, "timescale");
976 rep->fragment_duration = (int64_t) strtoll(duration_val, NULL, 10);
977 xmlFree(duration_val);
980 rep->fragment_timescale = (int64_t) strtoll(timescale_val, NULL, 10);
981 xmlFree(timescale_val);
983 fragmenturl_node = xmlFirstElementChild(representation_segmentlist_node);
984 while (fragmenturl_node) {
985 ret = parse_manifest_segmenturlnode(s, rep, fragmenturl_node,
992 fragmenturl_node = xmlNextElementSibling(fragmenturl_node);
995 fragment_timeline_node = find_child_node_by_name(representation_segmenttemplate_node, "SegmentTimeline");
997 if (!fragment_timeline_node)
998 fragment_timeline_node = find_child_node_by_name(fragment_template_node, "SegmentTimeline");
999 if (!fragment_timeline_node)
1000 fragment_timeline_node = find_child_node_by_name(adaptionset_segmentlist_node, "SegmentTimeline");
1001 if (!fragment_timeline_node)
1002 fragment_timeline_node = find_child_node_by_name(period_segmentlist_node, "SegmentTimeline");
1003 if (fragment_timeline_node) {
1004 fragment_timeline_node = xmlFirstElementChild(fragment_timeline_node);
1005 while (fragment_timeline_node) {
1006 ret = parse_manifest_segmenttimeline(s, rep, fragment_timeline_node);
1010 fragment_timeline_node = xmlNextElementSibling(fragment_timeline_node);
1014 free_representation(rep);
1016 av_log(s, AV_LOG_ERROR, "Unknown format of Representation node id[%s] \n", (const char *)rep_id_val);
1020 if (rep->fragment_duration > 0 && !rep->fragment_timescale)
1021 rep->fragment_timescale = 1;
1022 rep->bandwidth = rep_bandwidth_val ? atoi(rep_bandwidth_val) : 0;
1023 strncpy(rep->id, rep_id_val ? rep_id_val : "", sizeof(rep->id));
1024 rep->framerate = av_make_q(0, 0);
1025 if (type == AVMEDIA_TYPE_VIDEO && rep_framerate_val) {
1026 ret = av_parse_video_rate(&rep->framerate, rep_framerate_val);
1028 av_log(s, AV_LOG_VERBOSE, "Ignoring invalid frame rate '%s'\n", rep_framerate_val);
1031 if (type == AVMEDIA_TYPE_VIDEO) {
1032 rep->rep_idx = video_rep_idx;
1033 dynarray_add(&c->videos, &c->n_videos, rep);
1035 rep->rep_idx = audio_rep_idx;
1036 dynarray_add(&c->audios, &c->n_audios, rep);
1041 video_rep_idx += type == AVMEDIA_TYPE_VIDEO;
1042 audio_rep_idx += type == AVMEDIA_TYPE_AUDIO;
1046 xmlFree(rep_id_val);
1047 if (rep_bandwidth_val)
1048 xmlFree(rep_bandwidth_val);
1049 if (rep_framerate_val)
1050 xmlFree(rep_framerate_val);
1055 static int parse_manifest_adaptationset(AVFormatContext *s, const char *url,
1056 xmlNodePtr adaptionset_node,
1057 xmlNodePtr mpd_baseurl_node,
1058 xmlNodePtr period_baseurl_node,
1059 xmlNodePtr period_segmenttemplate_node,
1060 xmlNodePtr period_segmentlist_node)
1063 xmlNodePtr fragment_template_node = NULL;
1064 xmlNodePtr content_component_node = NULL;
1065 xmlNodePtr adaptionset_baseurl_node = NULL;
1066 xmlNodePtr adaptionset_segmentlist_node = NULL;
1067 xmlNodePtr adaptionset_supplementalproperty_node = NULL;
1068 xmlNodePtr node = NULL;
1070 node = xmlFirstElementChild(adaptionset_node);
1072 if (!av_strcasecmp(node->name, (const char *)"SegmentTemplate")) {
1073 fragment_template_node = node;
1074 } else if (!av_strcasecmp(node->name, (const char *)"ContentComponent")) {
1075 content_component_node = node;
1076 } else if (!av_strcasecmp(node->name, (const char *)"BaseURL")) {
1077 adaptionset_baseurl_node = node;
1078 } else if (!av_strcasecmp(node->name, (const char *)"SegmentList")) {
1079 adaptionset_segmentlist_node = node;
1080 } else if (!av_strcasecmp(node->name, (const char *)"SupplementalProperty")) {
1081 adaptionset_supplementalproperty_node = node;
1082 } else if (!av_strcasecmp(node->name, (const char *)"Representation")) {
1083 ret = parse_manifest_representation(s, url, node,
1086 period_baseurl_node,
1087 period_segmenttemplate_node,
1088 period_segmentlist_node,
1089 fragment_template_node,
1090 content_component_node,
1091 adaptionset_baseurl_node,
1092 adaptionset_segmentlist_node,
1093 adaptionset_supplementalproperty_node);
1098 node = xmlNextElementSibling(node);
1103 static int parse_manifest(AVFormatContext *s, const char *url, AVIOContext *in)
1105 DASHContext *c = s->priv_data;
1108 uint8_t *new_url = NULL;
1109 int64_t filesize = 0;
1110 char *buffer = NULL;
1111 AVDictionary *opts = NULL;
1113 xmlNodePtr root_element = NULL;
1114 xmlNodePtr node = NULL;
1115 xmlNodePtr period_node = NULL;
1116 xmlNodePtr tmp_node = NULL;
1117 xmlNodePtr mpd_baseurl_node = NULL;
1118 xmlNodePtr period_baseurl_node = NULL;
1119 xmlNodePtr period_segmenttemplate_node = NULL;
1120 xmlNodePtr period_segmentlist_node = NULL;
1121 xmlNodePtr adaptionset_node = NULL;
1122 xmlAttrPtr attr = NULL;
1124 uint32_t period_duration_sec = 0;
1125 uint32_t period_start_sec = 0;
1130 av_dict_copy(&opts, c->avio_opts, 0);
1131 ret = avio_open2(&in, url, AVIO_FLAG_READ, c->interrupt_callback, &opts);
1132 av_dict_free(&opts);
1137 if (av_opt_get(in, "location", AV_OPT_SEARCH_CHILDREN, &new_url) >= 0) {
1138 c->base_url = av_strdup(new_url);
1140 c->base_url = av_strdup(url);
1143 filesize = avio_size(in);
1144 if (filesize <= 0) {
1145 filesize = 8 * 1024;
1148 buffer = av_mallocz(filesize);
1150 av_free(c->base_url);
1151 return AVERROR(ENOMEM);
1154 filesize = avio_read(in, buffer, filesize);
1155 if (filesize <= 0) {
1156 av_log(s, AV_LOG_ERROR, "Unable to read to offset '%s'\n", url);
1157 ret = AVERROR_INVALIDDATA;
1161 doc = xmlReadMemory(buffer, filesize, c->base_url, NULL, 0);
1162 root_element = xmlDocGetRootElement(doc);
1163 node = root_element;
1166 ret = AVERROR_INVALIDDATA;
1167 av_log(s, AV_LOG_ERROR, "Unable to parse '%s' - missing root node\n", url);
1171 if (node->type != XML_ELEMENT_NODE ||
1172 av_strcasecmp(node->name, (const char *)"MPD")) {
1173 ret = AVERROR_INVALIDDATA;
1174 av_log(s, AV_LOG_ERROR, "Unable to parse '%s' - wrong root node name[%s] type[%d]\n", url, node->name, (int)node->type);
1178 val = xmlGetProp(node, "type");
1180 av_log(s, AV_LOG_ERROR, "Unable to parse '%s' - missing type attrib\n", url);
1181 ret = AVERROR_INVALIDDATA;
1184 if (!av_strcasecmp(val, (const char *)"dynamic"))
1188 attr = node->properties;
1190 val = xmlGetProp(node, attr->name);
1192 if (!av_strcasecmp(attr->name, (const char *)"availabilityStartTime")) {
1193 c->availability_start_time = get_utc_date_time_insec(s, (const char *)val);
1194 } else if (!av_strcasecmp(attr->name, (const char *)"publishTime")) {
1195 c->publish_time = get_utc_date_time_insec(s, (const char *)val);
1196 } else if (!av_strcasecmp(attr->name, (const char *)"minimumUpdatePeriod")) {
1197 c->minimum_update_period = get_duration_insec(s, (const char *)val);
1198 } else if (!av_strcasecmp(attr->name, (const char *)"timeShiftBufferDepth")) {
1199 c->time_shift_buffer_depth = get_duration_insec(s, (const char *)val);
1200 } else if (!av_strcasecmp(attr->name, (const char *)"minBufferTime")) {
1201 c->min_buffer_time = get_duration_insec(s, (const char *)val);
1202 } else if (!av_strcasecmp(attr->name, (const char *)"suggestedPresentationDelay")) {
1203 c->suggested_presentation_delay = get_duration_insec(s, (const char *)val);
1204 } else if (!av_strcasecmp(attr->name, (const char *)"mediaPresentationDuration")) {
1205 c->media_presentation_duration = get_duration_insec(s, (const char *)val);
1211 tmp_node = find_child_node_by_name(node, "BaseURL");
1213 mpd_baseurl_node = xmlCopyNode(tmp_node,1);
1215 mpd_baseurl_node = xmlNewNode(NULL, "BaseURL");
1218 // at now we can handle only one period, with the longest duration
1219 node = xmlFirstElementChild(node);
1221 if (!av_strcasecmp(node->name, (const char *)"Period")) {
1222 period_duration_sec = 0;
1223 period_start_sec = 0;
1224 attr = node->properties;
1226 val = xmlGetProp(node, attr->name);
1227 if (!av_strcasecmp(attr->name, (const char *)"duration")) {
1228 period_duration_sec = get_duration_insec(s, (const char *)val);
1229 } else if (!av_strcasecmp(attr->name, (const char *)"start")) {
1230 period_start_sec = get_duration_insec(s, (const char *)val);
1235 if ((period_duration_sec) >= (c->period_duration)) {
1237 c->period_duration = period_duration_sec;
1238 c->period_start = period_start_sec;
1239 if (c->period_start > 0)
1240 c->media_presentation_duration = c->period_duration;
1243 node = xmlNextElementSibling(node);
1246 av_log(s, AV_LOG_ERROR, "Unable to parse '%s' - missing Period node\n", url);
1247 ret = AVERROR_INVALIDDATA;
1251 adaptionset_node = xmlFirstElementChild(period_node);
1252 while (adaptionset_node) {
1253 if (!av_strcasecmp(adaptionset_node->name, (const char *)"BaseURL")) {
1254 period_baseurl_node = adaptionset_node;
1255 } else if (!av_strcasecmp(adaptionset_node->name, (const char *)"SegmentTemplate")) {
1256 period_segmenttemplate_node = adaptionset_node;
1257 } else if (!av_strcasecmp(adaptionset_node->name, (const char *)"SegmentList")) {
1258 period_segmentlist_node = adaptionset_node;
1259 } else if (!av_strcasecmp(adaptionset_node->name, (const char *)"AdaptationSet")) {
1260 parse_manifest_adaptationset(s, url, adaptionset_node, mpd_baseurl_node, period_baseurl_node, period_segmenttemplate_node, period_segmentlist_node);
1262 adaptionset_node = xmlNextElementSibling(adaptionset_node);
1265 /*free the document */
1268 xmlFreeNode(mpd_baseurl_node);
1279 static int64_t calc_cur_seg_no(AVFormatContext *s, struct representation *pls)
1281 DASHContext *c = s->priv_data;
1283 int64_t start_time_offset = 0;
1286 if (pls->n_fragments) {
1287 num = pls->first_seq_no;
1288 } else if (pls->n_timelines) {
1289 start_time_offset = get_segment_start_time_based_on_timeline(pls, 0xFFFFFFFF) - 60 * pls->fragment_timescale; // 60 seconds before end
1290 num = calc_next_seg_no_from_timelines(pls, start_time_offset);
1292 num = pls->first_seq_no;
1294 num += pls->first_seq_no;
1295 } else if (pls->fragment_duration){
1296 if (pls->presentation_timeoffset) {
1297 num = pls->presentation_timeoffset * pls->fragment_timescale / pls->fragment_duration;
1298 } else if (c->publish_time > 0 && !c->availability_start_time) {
1299 num = pls->first_seq_no + (((c->publish_time - c->time_shift_buffer_depth + pls->fragment_duration) - c->suggested_presentation_delay) * pls->fragment_timescale) / pls->fragment_duration;
1301 num = pls->first_seq_no + (((get_current_time_in_sec() - c->availability_start_time) - c->suggested_presentation_delay) * pls->fragment_timescale) / pls->fragment_duration;
1305 num = pls->first_seq_no;
1310 static int64_t calc_min_seg_no(AVFormatContext *s, struct representation *pls)
1312 DASHContext *c = s->priv_data;
1315 if (c->is_live && pls->fragment_duration) {
1316 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;
1318 num = pls->first_seq_no;
1323 static int64_t calc_max_seg_no(struct representation *pls, DASHContext *c)
1327 if (pls->n_fragments) {
1328 num = pls->first_seq_no + pls->n_fragments - 1;
1329 } else if (pls->n_timelines) {
1331 num = pls->first_seq_no + pls->n_timelines - 1;
1332 for (i = 0; i < pls->n_timelines; i++) {
1333 if (pls->timelines[i]->repeat == -1) {
1334 int length_of_each_segment = pls->timelines[i]->duration / pls->fragment_timescale;
1335 num = c->period_duration / length_of_each_segment;
1337 num += pls->timelines[i]->repeat;
1340 } else if (c->is_live && pls->fragment_duration) {
1341 num = pls->first_seq_no + (((get_current_time_in_sec() - c->availability_start_time)) * pls->fragment_timescale) / pls->fragment_duration;
1342 } else if (pls->fragment_duration) {
1343 num = pls->first_seq_no + (c->media_presentation_duration * pls->fragment_timescale) / pls->fragment_duration;
1349 static void move_timelines(struct representation *rep_src, struct representation *rep_dest, DASHContext *c)
1351 if (rep_dest && rep_src ) {
1352 free_timelines_list(rep_dest);
1353 rep_dest->timelines = rep_src->timelines;
1354 rep_dest->n_timelines = rep_src->n_timelines;
1355 rep_dest->first_seq_no = rep_src->first_seq_no;
1356 rep_dest->last_seq_no = calc_max_seg_no(rep_dest, c);
1357 rep_src->timelines = NULL;
1358 rep_src->n_timelines = 0;
1359 rep_dest->cur_seq_no = rep_src->cur_seq_no;
1363 static void move_segments(struct representation *rep_src, struct representation *rep_dest, DASHContext *c)
1365 if (rep_dest && rep_src ) {
1366 free_fragment_list(rep_dest);
1367 if (rep_src->start_number > (rep_dest->start_number + rep_dest->n_fragments))
1368 rep_dest->cur_seq_no = 0;
1370 rep_dest->cur_seq_no += rep_src->start_number - rep_dest->start_number;
1371 rep_dest->fragments = rep_src->fragments;
1372 rep_dest->n_fragments = rep_src->n_fragments;
1373 rep_dest->parent = rep_src->parent;
1374 rep_dest->last_seq_no = calc_max_seg_no(rep_dest, c);
1375 rep_src->fragments = NULL;
1376 rep_src->n_fragments = 0;
1381 static int refresh_manifest(AVFormatContext *s)
1385 DASHContext *c = s->priv_data;
1387 // save current context
1388 int n_videos = c->n_videos;
1389 struct representation **videos = c->videos;
1390 int n_audios = c->n_audios;
1391 struct representation **audios = c->audios;
1392 char *base_url = c->base_url;
1399 ret = parse_manifest(s, s->url, NULL);
1403 if (c->n_videos != n_videos) {
1404 av_log(c, AV_LOG_ERROR,
1405 "new manifest has mismatched no. of video representations, %d -> %d\n",
1406 n_videos, c->n_videos);
1407 return AVERROR_INVALIDDATA;
1409 if (c->n_audios != n_audios) {
1410 av_log(c, AV_LOG_ERROR,
1411 "new manifest has mismatched no. of audio representations, %d -> %d\n",
1412 n_audios, c->n_audios);
1413 return AVERROR_INVALIDDATA;
1416 for (i = 0; i < n_videos; i++) {
1417 struct representation *cur_video = videos[i];
1418 struct representation *ccur_video = c->videos[i];
1419 if (cur_video->timelines) {
1420 // calc current time
1421 int64_t currentTime = get_segment_start_time_based_on_timeline(cur_video, cur_video->cur_seq_no) / cur_video->fragment_timescale;
1423 ccur_video->cur_seq_no = calc_next_seg_no_from_timelines(ccur_video, currentTime * cur_video->fragment_timescale - 1);
1424 if (ccur_video->cur_seq_no >= 0) {
1425 move_timelines(ccur_video, cur_video, c);
1428 if (cur_video->fragments) {
1429 move_segments(ccur_video, cur_video, c);
1432 for (i = 0; i < n_audios; i++) {
1433 struct representation *cur_audio = audios[i];
1434 struct representation *ccur_audio = c->audios[i];
1435 if (cur_audio->timelines) {
1436 // calc current time
1437 int64_t currentTime = get_segment_start_time_based_on_timeline(cur_audio, cur_audio->cur_seq_no) / cur_audio->fragment_timescale;
1439 ccur_audio->cur_seq_no = calc_next_seg_no_from_timelines(ccur_audio, currentTime * cur_audio->fragment_timescale - 1);
1440 if (ccur_audio->cur_seq_no >= 0) {
1441 move_timelines(ccur_audio, cur_audio, c);
1444 if (cur_audio->fragments) {
1445 move_segments(ccur_audio, cur_audio, c);
1454 c->base_url = base_url;
1459 c->n_audios = n_audios;
1461 c->n_videos = n_videos;
1466 static struct fragment *get_current_fragment(struct representation *pls)
1468 int64_t min_seq_no = 0;
1469 int64_t max_seq_no = 0;
1470 struct fragment *seg = NULL;
1471 struct fragment *seg_ptr = NULL;
1472 DASHContext *c = pls->parent->priv_data;
1474 while (( !ff_check_interrupt(c->interrupt_callback)&& pls->n_fragments > 0)) {
1475 if (pls->cur_seq_no < pls->n_fragments) {
1476 seg_ptr = pls->fragments[pls->cur_seq_no];
1477 seg = av_mallocz(sizeof(struct fragment));
1481 seg->url = av_strdup(seg_ptr->url);
1486 seg->size = seg_ptr->size;
1487 seg->url_offset = seg_ptr->url_offset;
1489 } else if (c->is_live) {
1490 refresh_manifest(pls->parent);
1496 min_seq_no = calc_min_seg_no(pls->parent, pls);
1497 max_seq_no = calc_max_seg_no(pls, c);
1499 if (pls->timelines || pls->fragments) {
1500 refresh_manifest(pls->parent);
1502 if (pls->cur_seq_no <= min_seq_no) {
1503 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);
1504 pls->cur_seq_no = calc_cur_seg_no(pls->parent, pls);
1505 } else if (pls->cur_seq_no > max_seq_no) {
1506 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);
1508 seg = av_mallocz(sizeof(struct fragment));
1512 } else if (pls->cur_seq_no <= pls->last_seq_no) {
1513 seg = av_mallocz(sizeof(struct fragment));
1519 char *tmpfilename= av_mallocz(c->max_url_size);
1523 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));
1524 seg->url = av_strireplace(pls->url_template, pls->url_template, tmpfilename);
1526 av_log(pls->parent, AV_LOG_WARNING, "Unable to resolve template url '%s', try to use origin template\n", pls->url_template);
1527 seg->url = av_strdup(pls->url_template);
1529 av_log(pls->parent, AV_LOG_ERROR, "Cannot resolve template url '%s'\n", pls->url_template);
1530 av_free(tmpfilename);
1534 av_free(tmpfilename);
1541 enum ReadFromURLMode {
1546 static int read_from_url(struct representation *pls, struct fragment *seg,
1547 uint8_t *buf, int buf_size,
1548 enum ReadFromURLMode mode)
1552 /* limit read if the fragment was only a part of a file */
1554 buf_size = FFMIN(buf_size, pls->cur_seg_size - pls->cur_seg_offset);
1556 if (mode == READ_COMPLETE) {
1557 ret = avio_read(pls->input, buf, buf_size);
1558 if (ret < buf_size) {
1559 av_log(pls->parent, AV_LOG_WARNING, "Could not read complete fragment.\n");
1562 ret = avio_read(pls->input, buf, buf_size);
1565 pls->cur_seg_offset += ret;
1570 static int open_input(DASHContext *c, struct representation *pls, struct fragment *seg)
1572 AVDictionary *opts = NULL;
1576 url = av_mallocz(c->max_url_size);
1581 if (seg->size >= 0) {
1582 /* try to restrict the HTTP request to the part we want
1583 * (if this is in fact a HTTP request) */
1584 av_dict_set_int(&opts, "offset", seg->url_offset, 0);
1585 av_dict_set_int(&opts, "end_offset", seg->url_offset + seg->size, 0);
1588 ff_make_absolute_url(url, c->max_url_size, c->base_url, seg->url);
1589 av_log(pls->parent, AV_LOG_VERBOSE, "DASH request for url '%s', offset %"PRId64", playlist %d\n",
1590 url, seg->url_offset, pls->rep_idx);
1591 ret = open_url(pls->parent, &pls->input, url, c->avio_opts, opts, NULL);
1598 av_dict_free(&opts);
1599 pls->cur_seg_offset = 0;
1600 pls->cur_seg_size = seg->size;
1604 static int update_init_section(struct representation *pls)
1606 static const int max_init_section_size = 1024 * 1024;
1607 DASHContext *c = pls->parent->priv_data;
1612 if (!pls->init_section || pls->init_sec_buf)
1615 ret = open_input(c, pls, pls->init_section);
1617 av_log(pls->parent, AV_LOG_WARNING,
1618 "Failed to open an initialization section in playlist %d\n",
1623 if (pls->init_section->size >= 0)
1624 sec_size = pls->init_section->size;
1625 else if ((urlsize = avio_size(pls->input)) >= 0)
1628 sec_size = max_init_section_size;
1630 av_log(pls->parent, AV_LOG_DEBUG,
1631 "Downloading an initialization section of size %"PRId64"\n",
1634 sec_size = FFMIN(sec_size, max_init_section_size);
1636 av_fast_malloc(&pls->init_sec_buf, &pls->init_sec_buf_size, sec_size);
1638 ret = read_from_url(pls, pls->init_section, pls->init_sec_buf,
1639 pls->init_sec_buf_size, READ_COMPLETE);
1640 ff_format_io_close(pls->parent, &pls->input);
1645 pls->init_sec_data_len = ret;
1646 pls->init_sec_buf_read_offset = 0;
1651 static int64_t seek_data(void *opaque, int64_t offset, int whence)
1653 struct representation *v = opaque;
1654 if (v->n_fragments && !v->init_sec_data_len) {
1655 return avio_seek(v->input, offset, whence);
1658 return AVERROR(ENOSYS);
1661 static int read_data(void *opaque, uint8_t *buf, int buf_size)
1664 struct representation *v = opaque;
1665 DASHContext *c = v->parent->priv_data;
1669 free_fragment(&v->cur_seg);
1670 v->cur_seg = get_current_fragment(v);
1676 /* load/update Media Initialization Section, if any */
1677 ret = update_init_section(v);
1681 ret = open_input(c, v, v->cur_seg);
1683 if (ff_check_interrupt(c->interrupt_callback)) {
1687 av_log(v->parent, AV_LOG_WARNING, "Failed to open fragment of playlist %d\n", v->rep_idx);
1693 if (v->init_sec_buf_read_offset < v->init_sec_data_len) {
1694 /* Push init section out first before first actual fragment */
1695 int copy_size = FFMIN(v->init_sec_data_len - v->init_sec_buf_read_offset, buf_size);
1696 memcpy(buf, v->init_sec_buf, copy_size);
1697 v->init_sec_buf_read_offset += copy_size;
1702 /* check the v->cur_seg, if it is null, get current and double check if the new v->cur_seg*/
1704 v->cur_seg = get_current_fragment(v);
1710 ret = read_from_url(v, v->cur_seg, buf, buf_size, READ_NORMAL);
1714 if (c->is_live || v->cur_seq_no < v->last_seq_no) {
1715 if (!v->is_restart_needed)
1717 v->is_restart_needed = 1;
1724 static int save_avio_options(AVFormatContext *s)
1726 DASHContext *c = s->priv_data;
1727 const char *opts[] = { "headers", "user_agent", "cookies", NULL }, **opt = opts;
1728 uint8_t *buf = NULL;
1732 if (av_opt_get(s->pb, *opt, AV_OPT_SEARCH_CHILDREN, &buf) >= 0) {
1733 if (buf[0] != '\0') {
1734 ret = av_dict_set(&c->avio_opts, *opt, buf, AV_DICT_DONT_STRDUP_VAL);
1749 static int nested_io_open(AVFormatContext *s, AVIOContext **pb, const char *url,
1750 int flags, AVDictionary **opts)
1752 av_log(s, AV_LOG_ERROR,
1753 "A DASH playlist item '%s' referred to an external file '%s'. "
1754 "Opening this file was forbidden for security reasons\n",
1756 return AVERROR(EPERM);
1759 static void close_demux_for_component(struct representation *pls)
1761 /* note: the internal buffer could have changed */
1762 av_freep(&pls->pb.buffer);
1763 memset(&pls->pb, 0x00, sizeof(AVIOContext));
1764 pls->ctx->pb = NULL;
1765 avformat_close_input(&pls->ctx);
1769 static int reopen_demux_for_component(AVFormatContext *s, struct representation *pls)
1771 DASHContext *c = s->priv_data;
1772 AVInputFormat *in_fmt = NULL;
1773 AVDictionary *in_fmt_opts = NULL;
1774 uint8_t *avio_ctx_buffer = NULL;
1778 close_demux_for_component(pls);
1781 if (ff_check_interrupt(&s->interrupt_callback)) {
1786 if (!(pls->ctx = avformat_alloc_context())) {
1787 ret = AVERROR(ENOMEM);
1791 avio_ctx_buffer = av_malloc(INITIAL_BUFFER_SIZE);
1792 if (!avio_ctx_buffer ) {
1793 ret = AVERROR(ENOMEM);
1794 avformat_free_context(pls->ctx);
1799 ffio_init_context(&pls->pb, avio_ctx_buffer , INITIAL_BUFFER_SIZE, 0, pls, read_data, NULL, NULL);
1801 ffio_init_context(&pls->pb, avio_ctx_buffer , INITIAL_BUFFER_SIZE, 0, pls, read_data, NULL, seek_data);
1803 pls->pb.seekable = 0;
1805 if ((ret = ff_copy_whiteblacklists(pls->ctx, s)) < 0)
1808 pls->ctx->flags = AVFMT_FLAG_CUSTOM_IO;
1809 pls->ctx->probesize = 1024 * 4;
1810 pls->ctx->max_analyze_duration = 4 * AV_TIME_BASE;
1811 ret = av_probe_input_buffer(&pls->pb, &in_fmt, "", NULL, 0, 0);
1813 av_log(s, AV_LOG_ERROR, "Error when loading first fragment, playlist %d\n", (int)pls->rep_idx);
1814 avformat_free_context(pls->ctx);
1819 pls->ctx->pb = &pls->pb;
1820 pls->ctx->io_open = nested_io_open;
1822 // provide additional information from mpd if available
1823 ret = avformat_open_input(&pls->ctx, "", in_fmt, &in_fmt_opts); //pls->init_section->url
1824 av_dict_free(&in_fmt_opts);
1827 if (pls->n_fragments) {
1828 #if FF_API_R_FRAME_RATE
1829 if (pls->framerate.den) {
1830 for (i = 0; i < pls->ctx->nb_streams; i++)
1831 pls->ctx->streams[i]->r_frame_rate = pls->framerate;
1835 ret = avformat_find_stream_info(pls->ctx, NULL);
1844 static int open_demux_for_component(AVFormatContext *s, struct representation *pls)
1850 pls->cur_seq_no = calc_cur_seg_no(s, pls);
1852 if (!pls->last_seq_no) {
1853 pls->last_seq_no = calc_max_seg_no(pls, s->priv_data);
1856 ret = reopen_demux_for_component(s, pls);
1860 for (i = 0; i < pls->ctx->nb_streams; i++) {
1861 AVStream *st = avformat_new_stream(s, NULL);
1862 AVStream *ist = pls->ctx->streams[i];
1864 ret = AVERROR(ENOMEM);
1868 avcodec_parameters_copy(st->codecpar, pls->ctx->streams[i]->codecpar);
1869 avpriv_set_pts_info(st, ist->pts_wrap_bits, ist->time_base.num, ist->time_base.den);
1877 static int is_common_init_section_exist(struct representation **pls, int n_pls)
1879 struct fragment *first_init_section = pls[0]->init_section;
1881 int64_t url_offset = -1;
1885 if (first_init_section == NULL || n_pls == 0)
1888 url = first_init_section->url;
1889 url_offset = first_init_section->url_offset;
1890 size = pls[0]->init_section->size;
1891 for (i=0;i<n_pls;i++) {
1892 if (av_strcasecmp(pls[i]->init_section->url,url) || pls[i]->init_section->url_offset != url_offset || pls[i]->init_section->size != size) {
1899 static void copy_init_section(struct representation *rep_dest, struct representation *rep_src)
1901 rep_dest->init_sec_buf = av_mallocz(rep_src->init_sec_buf_size);
1902 memcpy(rep_dest->init_sec_buf, rep_src->init_sec_buf, rep_src->init_sec_data_len);
1903 rep_dest->init_sec_buf_size = rep_src->init_sec_buf_size;
1904 rep_dest->init_sec_data_len = rep_src->init_sec_data_len;
1905 rep_dest->cur_timestamp = rep_src->cur_timestamp;
1909 static int dash_read_header(AVFormatContext *s)
1911 DASHContext *c = s->priv_data;
1913 int stream_index = 0;
1916 c->interrupt_callback = &s->interrupt_callback;
1918 if ((ret = save_avio_options(s)) < 0)
1921 av_dict_set(&c->avio_opts, "seekable", "0", 0);
1923 if ((ret = parse_manifest(s, s->url, s->pb)) < 0)
1926 /* If this isn't a live stream, fill the total duration of the
1929 s->duration = (int64_t) c->media_presentation_duration * AV_TIME_BASE;
1933 c->is_init_section_common_video = is_common_init_section_exist(c->videos, c->n_videos);
1935 /* Open the demuxer for video and audio components if available */
1936 for (i = 0; i < c->n_videos; i++) {
1937 struct representation *cur_video = c->videos[i];
1938 if (i > 0 && c->is_init_section_common_video) {
1939 copy_init_section(cur_video,c->videos[0]);
1941 ret = open_demux_for_component(s, cur_video);
1945 cur_video->stream_index = stream_index;
1950 c->is_init_section_common_audio = is_common_init_section_exist(c->audios, c->n_audios);
1952 for (i = 0; i < c->n_audios; i++) {
1953 struct representation *cur_audio = c->audios[i];
1954 if (i > 0 && c->is_init_section_common_audio) {
1955 copy_init_section(cur_audio,c->audios[0]);
1957 ret = open_demux_for_component(s, cur_audio);
1961 cur_audio->stream_index = stream_index;
1965 if (!stream_index) {
1966 ret = AVERROR_INVALIDDATA;
1970 /* Create a program */
1973 program = av_new_program(s, 0);
1978 for (i = 0; i < c->n_videos; i++) {
1979 struct representation *pls = c->videos[i];
1981 av_program_add_stream_index(s, 0, pls->stream_index);
1982 pls->assoc_stream = s->streams[pls->stream_index];
1983 if (pls->bandwidth > 0)
1984 av_dict_set_int(&pls->assoc_stream->metadata, "variant_bitrate", pls->bandwidth, 0);
1986 av_dict_set(&pls->assoc_stream->metadata, "id", pls->id, 0);
1988 for (i = 0; i < c->n_audios; i++) {
1989 struct representation *pls = c->audios[i];
1991 av_program_add_stream_index(s, 0, pls->stream_index);
1992 pls->assoc_stream = s->streams[pls->stream_index];
1993 if (pls->bandwidth > 0)
1994 av_dict_set_int(&pls->assoc_stream->metadata, "variant_bitrate", pls->bandwidth, 0);
1996 av_dict_set(&pls->assoc_stream->metadata, "id", pls->id, 0);
2005 static void recheck_discard_flags(AVFormatContext *s, struct representation **p, int n)
2009 for (i = 0; i < n; i++) {
2010 struct representation *pls = p[i];
2012 int needed = !pls->assoc_stream || pls->assoc_stream->discard < AVDISCARD_ALL;
2013 if (needed && !pls->ctx) {
2014 pls->cur_seg_offset = 0;
2015 pls->init_sec_buf_read_offset = 0;
2017 for (j = 0; j < n; j++) {
2018 pls->cur_seq_no = FFMAX(pls->cur_seq_no, p[j]->cur_seq_no);
2020 reopen_demux_for_component(s, pls);
2021 av_log(s, AV_LOG_INFO, "Now receiving stream_index %d\n", pls->stream_index);
2022 } else if (!needed && pls->ctx) {
2023 close_demux_for_component(pls);
2025 ff_format_io_close(pls->parent, &pls->input);
2026 av_log(s, AV_LOG_INFO, "No longer receiving stream_index %d\n", pls->stream_index);
2031 static int dash_read_packet(AVFormatContext *s, AVPacket *pkt)
2033 DASHContext *c = s->priv_data;
2036 struct representation *cur = NULL;
2038 recheck_discard_flags(s, c->videos, c->n_videos);
2039 recheck_discard_flags(s, c->audios, c->n_audios);
2041 for (i = 0; i < c->n_videos; i++) {
2042 struct representation *pls = c->videos[i];
2045 if (!cur || pls->cur_timestamp < mints) {
2047 mints = pls->cur_timestamp;
2050 for (i = 0; i < c->n_audios; i++) {
2051 struct representation *pls = c->audios[i];
2054 if (!cur || pls->cur_timestamp < mints) {
2056 mints = pls->cur_timestamp;
2061 return AVERROR_INVALIDDATA;
2063 while (!ff_check_interrupt(c->interrupt_callback) && !ret) {
2064 ret = av_read_frame(cur->ctx, pkt);
2066 /* If we got a packet, return it */
2067 cur->cur_timestamp = av_rescale(pkt->pts, (int64_t)cur->ctx->streams[0]->time_base.num * 90000, cur->ctx->streams[0]->time_base.den);
2068 pkt->stream_index = cur->stream_index;
2071 if (cur->is_restart_needed) {
2072 cur->cur_seg_offset = 0;
2073 cur->init_sec_buf_read_offset = 0;
2075 ff_format_io_close(cur->parent, &cur->input);
2076 ret = reopen_demux_for_component(s, cur);
2077 cur->is_restart_needed = 0;
2083 static int dash_close(AVFormatContext *s)
2085 DASHContext *c = s->priv_data;
2089 av_dict_free(&c->avio_opts);
2090 av_freep(&c->base_url);
2094 static int dash_seek(AVFormatContext *s, struct representation *pls, int64_t seek_pos_msec, int flags, int dry_run)
2099 int64_t duration = 0;
2101 av_log(pls->parent, AV_LOG_VERBOSE, "DASH seek pos[%"PRId64"ms], playlist %d%s\n",
2102 seek_pos_msec, pls->rep_idx, dry_run ? " (dry)" : "");
2104 // single fragment mode
2105 if (pls->n_fragments == 1) {
2106 pls->cur_timestamp = 0;
2107 pls->cur_seg_offset = 0;
2110 ff_read_frame_flush(pls->ctx);
2111 return av_seek_frame(pls->ctx, -1, seek_pos_msec * 1000, flags);
2115 ff_format_io_close(pls->parent, &pls->input);
2117 // find the nearest fragment
2118 if (pls->n_timelines > 0 && pls->fragment_timescale > 0) {
2119 int64_t num = pls->first_seq_no;
2120 av_log(pls->parent, AV_LOG_VERBOSE, "dash_seek with SegmentTimeline start n_timelines[%d] "
2121 "last_seq_no[%"PRId64"], playlist %d.\n",
2122 (int)pls->n_timelines, (int64_t)pls->last_seq_no, (int)pls->rep_idx);
2123 for (i = 0; i < pls->n_timelines; i++) {
2124 if (pls->timelines[i]->starttime > 0) {
2125 duration = pls->timelines[i]->starttime;
2127 duration += pls->timelines[i]->duration;
2128 if (seek_pos_msec < ((duration * 1000) / pls->fragment_timescale)) {
2131 for (j = 0; j < pls->timelines[i]->repeat; j++) {
2132 duration += pls->timelines[i]->duration;
2134 if (seek_pos_msec < ((duration * 1000) / pls->fragment_timescale)) {
2142 pls->cur_seq_no = num > pls->last_seq_no ? pls->last_seq_no : num;
2143 av_log(pls->parent, AV_LOG_VERBOSE, "dash_seek with SegmentTimeline end cur_seq_no[%"PRId64"], playlist %d.\n",
2144 (int64_t)pls->cur_seq_no, (int)pls->rep_idx);
2145 } else if (pls->fragment_duration > 0) {
2146 pls->cur_seq_no = pls->first_seq_no + ((seek_pos_msec * pls->fragment_timescale) / pls->fragment_duration) / 1000;
2148 av_log(pls->parent, AV_LOG_ERROR, "dash_seek missing timeline or fragment_duration\n");
2149 pls->cur_seq_no = pls->first_seq_no;
2151 pls->cur_timestamp = 0;
2152 pls->cur_seg_offset = 0;
2153 pls->init_sec_buf_read_offset = 0;
2154 ret = dry_run ? 0 : reopen_demux_for_component(s, pls);
2159 static int dash_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
2162 DASHContext *c = s->priv_data;
2163 int64_t seek_pos_msec = av_rescale_rnd(timestamp, 1000,
2164 s->streams[stream_index]->time_base.den,
2165 flags & AVSEEK_FLAG_BACKWARD ?
2166 AV_ROUND_DOWN : AV_ROUND_UP);
2167 if ((flags & AVSEEK_FLAG_BYTE) || c->is_live)
2168 return AVERROR(ENOSYS);
2170 /* Seek in discarded streams with dry_run=1 to avoid reopening them */
2171 for (i = 0; i < c->n_videos; i++) {
2173 ret = dash_seek(s, c->videos[i], seek_pos_msec, flags, !c->videos[i]->ctx);
2175 for (i = 0; i < c->n_audios; i++) {
2177 ret = dash_seek(s, c->audios[i], seek_pos_msec, flags, !c->audios[i]->ctx);
2183 static int dash_probe(AVProbeData *p)
2185 if (!av_stristr(p->buf, "<MPD"))
2188 if (av_stristr(p->buf, "dash:profile:isoff-on-demand:2011") ||
2189 av_stristr(p->buf, "dash:profile:isoff-live:2011") ||
2190 av_stristr(p->buf, "dash:profile:isoff-live:2012") ||
2191 av_stristr(p->buf, "dash:profile:isoff-main:2011")) {
2192 return AVPROBE_SCORE_MAX;
2194 if (av_stristr(p->buf, "dash:profile")) {
2195 return AVPROBE_SCORE_MAX;
2201 #define OFFSET(x) offsetof(DASHContext, x)
2202 #define FLAGS AV_OPT_FLAG_DECODING_PARAM
2203 static const AVOption dash_options[] = {
2204 {"allowed_extensions", "List of file extensions that dash is allowed to access",
2205 OFFSET(allowed_extensions), AV_OPT_TYPE_STRING,
2206 {.str = "aac,m4a,m4s,m4v,mov,mp4"},
2207 INT_MIN, INT_MAX, FLAGS},
2211 static const AVClass dash_class = {
2212 .class_name = "dash",
2213 .item_name = av_default_item_name,
2214 .option = dash_options,
2215 .version = LIBAVUTIL_VERSION_INT,
2218 AVInputFormat ff_dash_demuxer = {
2220 .long_name = NULL_IF_CONFIG_SMALL("Dynamic Adaptive Streaming over HTTP"),
2221 .priv_class = &dash_class,
2222 .priv_data_size = sizeof(DASHContext),
2223 .read_probe = dash_probe,
2224 .read_header = dash_read_header,
2225 .read_packet = dash_read_packet,
2226 .read_close = dash_close,
2227 .read_seek = dash_read_seek,
2228 .flags = AVFMT_NO_BYTE_SEEK,