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;
154 static int ishttp(char *url)
156 const char *proto_name = avio_find_protocol_name(url);
157 return av_strstart(proto_name, "http", NULL);
160 static int aligned(int val)
162 return ((val + 0x3F) >> 6) << 6;
165 static uint64_t get_current_time_in_sec(void)
167 return av_gettime() / 1000000;
170 static uint64_t get_utc_date_time_insec(AVFormatContext *s, const char *datetime)
181 /* ISO-8601 date parser */
185 ret = sscanf(datetime, "%d-%d-%dT%d:%d:%fZ", &year, &month, &day, &hour, &minute, &second);
186 /* year, month, day, hour, minute, second 6 arguments */
188 av_log(s, AV_LOG_WARNING, "get_utc_date_time_insec get a wrong time format\n");
190 timeinfo.tm_year = year - 1900;
191 timeinfo.tm_mon = month - 1;
192 timeinfo.tm_mday = day;
193 timeinfo.tm_hour = hour;
194 timeinfo.tm_min = minute;
195 timeinfo.tm_sec = (int)second;
197 return av_timegm(&timeinfo);
200 static uint32_t get_duration_insec(AVFormatContext *s, const char *duration)
202 /* ISO-8601 duration parser */
210 const char *ptr = duration;
213 if (*ptr == 'P' || *ptr == 'T') {
218 if (sscanf(ptr, "%f%c%n", &value, &type, &size) != 2) {
219 av_log(s, AV_LOG_WARNING, "get_duration_insec get a wrong time format\n");
220 return 0; /* parser error */
224 days = (uint32_t)value;
227 hours = (uint32_t)value;
230 mins = (uint32_t)value;
233 secs = (uint32_t)value;
236 // handle invalid type
241 return ((days * 24 + hours) * 60 + mins) * 60 + secs;
244 static int64_t get_segment_start_time_based_on_timeline(struct representation *pls, int64_t cur_seq_no)
246 int64_t start_time = 0;
251 if (pls->n_timelines) {
252 for (i = 0; i < pls->n_timelines; i++) {
253 if (pls->timelines[i]->starttime > 0) {
254 start_time = pls->timelines[i]->starttime;
256 if (num == cur_seq_no)
259 start_time += pls->timelines[i]->duration;
260 for (j = 0; j < pls->timelines[i]->repeat; j++) {
262 if (num == cur_seq_no)
264 start_time += pls->timelines[i]->duration;
273 static int64_t calc_next_seg_no_from_timelines(struct representation *pls, int64_t cur_time)
278 int64_t start_time = 0;
280 for (i = 0; i < pls->n_timelines; i++) {
281 if (pls->timelines[i]->starttime > 0) {
282 start_time = pls->timelines[i]->starttime;
284 if (start_time > cur_time)
287 start_time += pls->timelines[i]->duration;
288 for (j = 0; j < pls->timelines[i]->repeat; j++) {
290 if (start_time > cur_time)
292 start_time += pls->timelines[i]->duration;
303 static void free_fragment(struct fragment **seg)
308 av_freep(&(*seg)->url);
312 static void free_fragment_list(struct representation *pls)
316 for (i = 0; i < pls->n_fragments; i++) {
317 free_fragment(&pls->fragments[i]);
319 av_freep(&pls->fragments);
320 pls->n_fragments = 0;
323 static void free_timelines_list(struct representation *pls)
327 for (i = 0; i < pls->n_timelines; i++) {
328 av_freep(&pls->timelines[i]);
330 av_freep(&pls->timelines);
331 pls->n_timelines = 0;
334 static void free_representation(struct representation *pls)
336 free_fragment_list(pls);
337 free_timelines_list(pls);
338 free_fragment(&pls->cur_seg);
339 free_fragment(&pls->init_section);
340 av_freep(&pls->init_sec_buf);
341 av_freep(&pls->pb.buffer);
343 ff_format_io_close(pls->parent, &pls->input);
346 avformat_close_input(&pls->ctx);
349 av_freep(&pls->url_template);
353 static void free_video_list(DASHContext *c)
356 for (i = 0; i < c->n_videos; i++) {
357 struct representation *pls = c->videos[i];
358 free_representation(pls);
360 av_freep(&c->videos);
364 static void free_audio_list(DASHContext *c)
367 for (i = 0; i < c->n_audios; i++) {
368 struct representation *pls = c->audios[i];
369 free_representation(pls);
371 av_freep(&c->audios);
375 static void set_httpheader_options(DASHContext *c, AVDictionary **opts)
377 // broker prior HTTP options that should be consistent across requests
378 av_dict_set(opts, "user-agent", c->user_agent, 0);
379 av_dict_set(opts, "cookies", c->cookies, 0);
380 av_dict_set(opts, "headers", c->headers, 0);
382 av_dict_set(opts, "seekable", "0", 0);
385 static void update_options(char **dest, const char *name, void *src)
388 av_opt_get(src, name, AV_OPT_SEARCH_CHILDREN, (uint8_t**)dest);
393 static int open_url(AVFormatContext *s, AVIOContext **pb, const char *url,
394 AVDictionary *opts, AVDictionary *opts2, int *is_http)
396 DASHContext *c = s->priv_data;
397 AVDictionary *tmp = NULL;
398 const char *proto_name = NULL;
401 av_dict_copy(&tmp, opts, 0);
402 av_dict_copy(&tmp, opts2, 0);
404 if (av_strstart(url, "crypto", NULL)) {
405 if (url[6] == '+' || url[6] == ':')
406 proto_name = avio_find_protocol_name(url + 7);
410 proto_name = avio_find_protocol_name(url);
413 return AVERROR_INVALIDDATA;
415 // only http(s) & file are allowed
416 if (av_strstart(proto_name, "file", NULL)) {
417 if (strcmp(c->allowed_extensions, "ALL") && !av_match_ext(url, c->allowed_extensions)) {
418 av_log(s, AV_LOG_ERROR,
419 "Filename extension of \'%s\' is not a common multimedia extension, blocked for security reasons.\n"
420 "If you wish to override this adjust allowed_extensions, you can set it to \'ALL\' to allow all\n",
422 return AVERROR_INVALIDDATA;
424 } else if (av_strstart(proto_name, "http", NULL)) {
427 return AVERROR_INVALIDDATA;
429 if (!strncmp(proto_name, url, strlen(proto_name)) && url[strlen(proto_name)] == ':')
431 else if (av_strstart(url, "crypto", NULL) && !strncmp(proto_name, url + 7, strlen(proto_name)) && url[7 + strlen(proto_name)] == ':')
433 else if (strcmp(proto_name, "file") || !strncmp(url, "file,", 5))
434 return AVERROR_INVALIDDATA;
437 ret = avio_open2(pb, url, AVIO_FLAG_READ, c->interrupt_callback, &tmp);
439 // update cookies on http response with setcookies.
440 char *new_cookies = NULL;
442 if (!(s->flags & AVFMT_FLAG_CUSTOM_IO))
443 av_opt_get(*pb, "cookies", AV_OPT_SEARCH_CHILDREN, (uint8_t**)&new_cookies);
447 c->cookies = new_cookies;
450 av_dict_set(&opts, "cookies", c->cookies, 0);
456 *is_http = av_strstart(proto_name, "http", NULL);
461 static char *get_content_url(xmlNodePtr *baseurl_nodes,
465 char *rep_bandwidth_val,
471 char *tmp_str = av_mallocz(max_url_size);
472 char *tmp_str_2 = av_mallocz(max_url_size);
474 if (!tmp_str || !tmp_str_2) {
478 for (i = 0; i < n_baseurl_nodes; ++i) {
479 if (baseurl_nodes[i] &&
480 baseurl_nodes[i]->children &&
481 baseurl_nodes[i]->children->type == XML_TEXT_NODE) {
482 text = xmlNodeGetContent(baseurl_nodes[i]->children);
484 memset(tmp_str, 0, max_url_size);
485 memset(tmp_str_2, 0, max_url_size);
486 ff_make_absolute_url(tmp_str_2, max_url_size, tmp_str, text);
487 av_strlcpy(tmp_str, tmp_str_2, max_url_size);
494 av_strlcat(tmp_str, (const char*)val, max_url_size);
497 url = av_strireplace(tmp_str, "$RepresentationID$", (const char*)rep_id_val);
501 av_strlcpy(tmp_str, url, max_url_size);
503 if (rep_bandwidth_val && tmp_str[0] != '\0') {
504 // free any previously assigned url before reassigning
506 url = av_strireplace(tmp_str, "$Bandwidth$", (const char*)rep_bandwidth_val);
517 static char *get_val_from_nodes_tab(xmlNodePtr *nodes, const int n_nodes, const char *attrname)
522 for (i = 0; i < n_nodes; ++i) {
524 val = xmlGetProp(nodes[i], attrname);
533 static xmlNodePtr find_child_node_by_name(xmlNodePtr rootnode, const char *nodename)
535 xmlNodePtr node = rootnode;
540 node = xmlFirstElementChild(node);
542 if (!av_strcasecmp(node->name, nodename)) {
545 node = xmlNextElementSibling(node);
550 static enum AVMediaType get_content_type(xmlNodePtr node)
552 enum AVMediaType type = AVMEDIA_TYPE_UNKNOWN;
558 for (i = 0; i < 2; i++) {
559 attr = i ? "mimeType" : "contentType";
560 val = xmlGetProp(node, attr);
562 if (av_stristr((const char *)val, "video")) {
563 type = AVMEDIA_TYPE_VIDEO;
564 } else if (av_stristr((const char *)val, "audio")) {
565 type = AVMEDIA_TYPE_AUDIO;
574 static struct fragment * get_Fragment(char *range)
576 struct fragment * seg = av_mallocz(sizeof(struct fragment));
583 char *str_end_offset;
584 char *str_offset = av_strtok(range, "-", &str_end_offset);
585 seg->url_offset = strtoll(str_offset, NULL, 10);
586 seg->size = strtoll(str_end_offset, NULL, 10) - seg->url_offset;
592 static int parse_manifest_segmenturlnode(AVFormatContext *s, struct representation *rep,
593 xmlNodePtr fragmenturl_node,
594 xmlNodePtr *baseurl_nodes,
596 char *rep_bandwidth_val)
598 DASHContext *c = s->priv_data;
599 char *initialization_val = NULL;
600 char *media_val = NULL;
601 char *range_val = NULL;
602 int max_url_size = c ? c->max_url_size: MAX_URL_SIZE;
604 if (!av_strcasecmp(fragmenturl_node->name, (const char *)"Initialization")) {
605 initialization_val = xmlGetProp(fragmenturl_node, "sourceURL");
606 range_val = xmlGetProp(fragmenturl_node, "range");
607 if (initialization_val || range_val) {
608 rep->init_section = get_Fragment(range_val);
609 if (!rep->init_section) {
610 xmlFree(initialization_val);
612 return AVERROR(ENOMEM);
614 rep->init_section->url = get_content_url(baseurl_nodes, 4,
620 if (!rep->init_section->url) {
621 av_free(rep->init_section);
622 xmlFree(initialization_val);
624 return AVERROR(ENOMEM);
626 xmlFree(initialization_val);
629 } else if (!av_strcasecmp(fragmenturl_node->name, (const char *)"SegmentURL")) {
630 media_val = xmlGetProp(fragmenturl_node, "media");
631 range_val = xmlGetProp(fragmenturl_node, "mediaRange");
632 if (media_val || range_val) {
633 struct fragment *seg = get_Fragment(range_val);
637 return AVERROR(ENOMEM);
639 seg->url = get_content_url(baseurl_nodes, 4,
648 return AVERROR(ENOMEM);
650 dynarray_add(&rep->fragments, &rep->n_fragments, seg);
659 static int parse_manifest_segmenttimeline(AVFormatContext *s, struct representation *rep,
660 xmlNodePtr fragment_timeline_node)
662 xmlAttrPtr attr = NULL;
665 if (!av_strcasecmp(fragment_timeline_node->name, (const char *)"S")) {
666 struct timeline *tml = av_mallocz(sizeof(struct timeline));
668 return AVERROR(ENOMEM);
670 attr = fragment_timeline_node->properties;
672 val = xmlGetProp(fragment_timeline_node, attr->name);
675 av_log(s, AV_LOG_WARNING, "parse_manifest_segmenttimeline attr->name = %s val is NULL\n", attr->name);
679 if (!av_strcasecmp(attr->name, (const char *)"t")) {
680 tml->starttime = (int64_t)strtoll(val, NULL, 10);
681 } else if (!av_strcasecmp(attr->name, (const char *)"r")) {
682 tml->repeat =(int64_t) strtoll(val, NULL, 10);
683 } else if (!av_strcasecmp(attr->name, (const char *)"d")) {
684 tml->duration = (int64_t)strtoll(val, NULL, 10);
689 dynarray_add(&rep->timelines, &rep->n_timelines, tml);
695 static int resolve_content_path(AVFormatContext *s, const char *url, int *max_url_size, xmlNodePtr *baseurl_nodes, int n_baseurl_nodes) {
697 char *tmp_str = NULL;
699 char *mpdName = NULL;
700 xmlNodePtr node = NULL;
701 char *baseurl = NULL;
702 char *root_url = NULL;
712 int tmp_max_url_size = strlen(url);
714 for (i = n_baseurl_nodes-1; i >= 0 ; i--) {
715 text = xmlNodeGetContent(baseurl_nodes[i]);
718 tmp_max_url_size += strlen(text);
726 tmp_max_url_size = aligned(tmp_max_url_size);
727 text = av_mallocz(tmp_max_url_size);
729 updated = AVERROR(ENOMEM);
732 av_strlcpy(text, url, strlen(url)+1);
733 while (mpdName = av_strtok(text, "/", &text)) {
734 size = strlen(mpdName);
737 path = av_mallocz(tmp_max_url_size);
738 tmp_str = av_mallocz(tmp_max_url_size);
739 if (!tmp_str || !path) {
740 updated = AVERROR(ENOMEM);
744 av_strlcpy (path, url, strlen(url) - size + 1);
745 for (rootId = n_baseurl_nodes - 1; rootId > 0; rootId --) {
746 if (!(node = baseurl_nodes[rootId])) {
749 if (ishttp(xmlNodeGetContent(node))) {
754 node = baseurl_nodes[rootId];
755 baseurl = xmlNodeGetContent(node);
756 root_url = (av_strcasecmp(baseurl, "")) ? baseurl : path;
758 xmlNodeSetContent(node, root_url);
762 size = strlen(root_url);
763 isRootHttp = ishttp(root_url);
765 if (root_url[size - 1] != token) {
766 av_strlcat(root_url, "/", size + 2);
770 for (i = 0; i < n_baseurl_nodes; ++i) {
774 text = xmlNodeGetContent(baseurl_nodes[i]);
776 memset(tmp_str, 0, strlen(tmp_str));
777 if (!ishttp(text) && isRootHttp) {
778 av_strlcpy(tmp_str, root_url, size + 1);
780 start = (text[0] == token);
781 av_strlcat(tmp_str, text + start, tmp_max_url_size);
782 xmlNodeSetContent(baseurl_nodes[i], tmp_str);
789 if (tmp_max_url_size > *max_url_size) {
790 *max_url_size = tmp_max_url_size;
798 static int parse_manifest_representation(AVFormatContext *s, const char *url,
800 xmlNodePtr adaptionset_node,
801 xmlNodePtr mpd_baseurl_node,
802 xmlNodePtr period_baseurl_node,
803 xmlNodePtr period_segmenttemplate_node,
804 xmlNodePtr period_segmentlist_node,
805 xmlNodePtr fragment_template_node,
806 xmlNodePtr content_component_node,
807 xmlNodePtr adaptionset_baseurl_node,
808 xmlNodePtr adaptionset_segmentlist_node,
809 xmlNodePtr adaptionset_supplementalproperty_node)
812 int32_t audio_rep_idx = 0;
813 int32_t video_rep_idx = 0;
814 DASHContext *c = s->priv_data;
815 struct representation *rep = NULL;
816 struct fragment *seg = NULL;
817 xmlNodePtr representation_segmenttemplate_node = NULL;
818 xmlNodePtr representation_baseurl_node = NULL;
819 xmlNodePtr representation_segmentlist_node = NULL;
820 xmlNodePtr segmentlists_tab[2];
821 xmlNodePtr fragment_timeline_node = NULL;
822 xmlNodePtr fragment_templates_tab[5];
823 char *duration_val = NULL;
824 char *presentation_timeoffset_val = NULL;
825 char *startnumber_val = NULL;
826 char *timescale_val = NULL;
827 char *initialization_val = NULL;
828 char *media_val = NULL;
830 xmlNodePtr baseurl_nodes[4];
831 xmlNodePtr representation_node = node;
832 char *rep_id_val = xmlGetProp(representation_node, "id");
833 char *rep_bandwidth_val = xmlGetProp(representation_node, "bandwidth");
834 char *rep_framerate_val = xmlGetProp(representation_node, "frameRate");
835 enum AVMediaType type = AVMEDIA_TYPE_UNKNOWN;
837 // try get information from representation
838 if (type == AVMEDIA_TYPE_UNKNOWN)
839 type = get_content_type(representation_node);
840 // try get information from contentComponen
841 if (type == AVMEDIA_TYPE_UNKNOWN)
842 type = get_content_type(content_component_node);
843 // try get information from adaption set
844 if (type == AVMEDIA_TYPE_UNKNOWN)
845 type = get_content_type(adaptionset_node);
846 if (type == AVMEDIA_TYPE_UNKNOWN) {
847 av_log(s, AV_LOG_VERBOSE, "Parsing '%s' - skipp not supported representation type\n", url);
848 } else if (type == AVMEDIA_TYPE_VIDEO || type == AVMEDIA_TYPE_AUDIO) {
849 // convert selected representation to our internal struct
850 rep = av_mallocz(sizeof(struct representation));
852 ret = AVERROR(ENOMEM);
855 representation_segmenttemplate_node = find_child_node_by_name(representation_node, "SegmentTemplate");
856 representation_baseurl_node = find_child_node_by_name(representation_node, "BaseURL");
857 representation_segmentlist_node = find_child_node_by_name(representation_node, "SegmentList");
859 baseurl_nodes[0] = mpd_baseurl_node;
860 baseurl_nodes[1] = period_baseurl_node;
861 baseurl_nodes[2] = adaptionset_baseurl_node;
862 baseurl_nodes[3] = representation_baseurl_node;
864 ret = resolve_content_path(s, url, &c->max_url_size, baseurl_nodes, 4);
865 c->max_url_size = aligned(c->max_url_size + strlen(rep_id_val) + strlen(rep_bandwidth_val));
866 if (ret == AVERROR(ENOMEM) || ret == 0) {
869 if (representation_segmenttemplate_node || fragment_template_node || period_segmenttemplate_node) {
870 fragment_timeline_node = NULL;
871 fragment_templates_tab[0] = representation_segmenttemplate_node;
872 fragment_templates_tab[1] = adaptionset_segmentlist_node;
873 fragment_templates_tab[2] = fragment_template_node;
874 fragment_templates_tab[3] = period_segmenttemplate_node;
875 fragment_templates_tab[4] = period_segmentlist_node;
877 presentation_timeoffset_val = get_val_from_nodes_tab(fragment_templates_tab, 4, "presentationTimeOffset");
878 duration_val = get_val_from_nodes_tab(fragment_templates_tab, 4, "duration");
879 startnumber_val = get_val_from_nodes_tab(fragment_templates_tab, 4, "startNumber");
880 timescale_val = get_val_from_nodes_tab(fragment_templates_tab, 4, "timescale");
881 initialization_val = get_val_from_nodes_tab(fragment_templates_tab, 4, "initialization");
882 media_val = get_val_from_nodes_tab(fragment_templates_tab, 4, "media");
884 if (initialization_val) {
885 rep->init_section = av_mallocz(sizeof(struct fragment));
886 if (!rep->init_section) {
888 ret = AVERROR(ENOMEM);
891 c->max_url_size = aligned(c->max_url_size + strlen(initialization_val));
892 rep->init_section->url = get_content_url(baseurl_nodes, 4, c->max_url_size, rep_id_val, rep_bandwidth_val, initialization_val);
893 if (!rep->init_section->url) {
894 av_free(rep->init_section);
896 ret = AVERROR(ENOMEM);
899 rep->init_section->size = -1;
900 xmlFree(initialization_val);
904 c->max_url_size = aligned(c->max_url_size + strlen(media_val));
905 rep->url_template = get_content_url(baseurl_nodes, 4, c->max_url_size, rep_id_val, rep_bandwidth_val, media_val);
909 if (presentation_timeoffset_val) {
910 rep->presentation_timeoffset = (int64_t) strtoll(presentation_timeoffset_val, NULL, 10);
911 xmlFree(presentation_timeoffset_val);
914 rep->fragment_duration = (int64_t) strtoll(duration_val, NULL, 10);
915 xmlFree(duration_val);
918 rep->fragment_timescale = (int64_t) strtoll(timescale_val, NULL, 10);
919 xmlFree(timescale_val);
921 if (startnumber_val) {
922 rep->first_seq_no = (int64_t) strtoll(startnumber_val, NULL, 10);
923 xmlFree(startnumber_val);
925 if (adaptionset_supplementalproperty_node) {
926 if (!av_strcasecmp(xmlGetProp(adaptionset_supplementalproperty_node,"schemeIdUri"), "http://dashif.org/guidelines/last-segment-number")) {
927 val = xmlGetProp(adaptionset_supplementalproperty_node,"value");
929 av_log(s, AV_LOG_ERROR, "Missing value attribute in adaptionset_supplementalproperty_node\n");
931 rep->last_seq_no =(int64_t) strtoll(val, NULL, 10) - 1;
937 fragment_timeline_node = find_child_node_by_name(representation_segmenttemplate_node, "SegmentTimeline");
939 if (!fragment_timeline_node)
940 fragment_timeline_node = find_child_node_by_name(fragment_template_node, "SegmentTimeline");
941 if (!fragment_timeline_node)
942 fragment_timeline_node = find_child_node_by_name(adaptionset_segmentlist_node, "SegmentTimeline");
943 if (!fragment_timeline_node)
944 fragment_timeline_node = find_child_node_by_name(period_segmentlist_node, "SegmentTimeline");
945 if (fragment_timeline_node) {
946 fragment_timeline_node = xmlFirstElementChild(fragment_timeline_node);
947 while (fragment_timeline_node) {
948 ret = parse_manifest_segmenttimeline(s, rep, fragment_timeline_node);
952 fragment_timeline_node = xmlNextElementSibling(fragment_timeline_node);
955 } else if (representation_baseurl_node && !representation_segmentlist_node) {
956 seg = av_mallocz(sizeof(struct fragment));
958 ret = AVERROR(ENOMEM);
961 seg->url = get_content_url(baseurl_nodes, 4, c->max_url_size, rep_id_val, rep_bandwidth_val, NULL);
964 ret = AVERROR(ENOMEM);
968 dynarray_add(&rep->fragments, &rep->n_fragments, seg);
969 } else if (representation_segmentlist_node) {
970 // TODO: https://www.brendanlong.com/the-structure-of-an-mpeg-dash-mpd.html
971 // http://www-itec.uni-klu.ac.at/dash/ddash/mpdGenerator.php?fragmentlength=15&type=full
972 xmlNodePtr fragmenturl_node = NULL;
973 segmentlists_tab[0] = representation_segmentlist_node;
974 segmentlists_tab[1] = adaptionset_segmentlist_node;
976 duration_val = get_val_from_nodes_tab(segmentlists_tab, 2, "duration");
977 timescale_val = get_val_from_nodes_tab(segmentlists_tab, 2, "timescale");
979 rep->fragment_duration = (int64_t) strtoll(duration_val, NULL, 10);
980 xmlFree(duration_val);
983 rep->fragment_timescale = (int64_t) strtoll(timescale_val, NULL, 10);
984 xmlFree(timescale_val);
986 fragmenturl_node = xmlFirstElementChild(representation_segmentlist_node);
987 while (fragmenturl_node) {
988 ret = parse_manifest_segmenturlnode(s, rep, fragmenturl_node,
995 fragmenturl_node = xmlNextElementSibling(fragmenturl_node);
998 fragment_timeline_node = find_child_node_by_name(representation_segmenttemplate_node, "SegmentTimeline");
1000 if (!fragment_timeline_node)
1001 fragment_timeline_node = find_child_node_by_name(fragment_template_node, "SegmentTimeline");
1002 if (!fragment_timeline_node)
1003 fragment_timeline_node = find_child_node_by_name(adaptionset_segmentlist_node, "SegmentTimeline");
1004 if (!fragment_timeline_node)
1005 fragment_timeline_node = find_child_node_by_name(period_segmentlist_node, "SegmentTimeline");
1006 if (fragment_timeline_node) {
1007 fragment_timeline_node = xmlFirstElementChild(fragment_timeline_node);
1008 while (fragment_timeline_node) {
1009 ret = parse_manifest_segmenttimeline(s, rep, fragment_timeline_node);
1013 fragment_timeline_node = xmlNextElementSibling(fragment_timeline_node);
1017 free_representation(rep);
1019 av_log(s, AV_LOG_ERROR, "Unknown format of Representation node id[%s] \n", (const char *)rep_id_val);
1023 if (rep->fragment_duration > 0 && !rep->fragment_timescale)
1024 rep->fragment_timescale = 1;
1025 rep->bandwidth = rep_bandwidth_val ? atoi(rep_bandwidth_val) : 0;
1026 strncpy(rep->id, rep_id_val ? rep_id_val : "", sizeof(rep->id));
1027 rep->framerate = av_make_q(0, 0);
1028 if (type == AVMEDIA_TYPE_VIDEO && rep_framerate_val) {
1029 ret = av_parse_video_rate(&rep->framerate, rep_framerate_val);
1031 av_log(s, AV_LOG_VERBOSE, "Ignoring invalid frame rate '%s'\n", rep_framerate_val);
1034 if (type == AVMEDIA_TYPE_VIDEO) {
1035 rep->rep_idx = video_rep_idx;
1036 dynarray_add(&c->videos, &c->n_videos, rep);
1038 rep->rep_idx = audio_rep_idx;
1039 dynarray_add(&c->audios, &c->n_audios, rep);
1044 video_rep_idx += type == AVMEDIA_TYPE_VIDEO;
1045 audio_rep_idx += type == AVMEDIA_TYPE_AUDIO;
1049 xmlFree(rep_id_val);
1050 if (rep_bandwidth_val)
1051 xmlFree(rep_bandwidth_val);
1052 if (rep_framerate_val)
1053 xmlFree(rep_framerate_val);
1058 static int parse_manifest_adaptationset(AVFormatContext *s, const char *url,
1059 xmlNodePtr adaptionset_node,
1060 xmlNodePtr mpd_baseurl_node,
1061 xmlNodePtr period_baseurl_node,
1062 xmlNodePtr period_segmenttemplate_node,
1063 xmlNodePtr period_segmentlist_node)
1066 xmlNodePtr fragment_template_node = NULL;
1067 xmlNodePtr content_component_node = NULL;
1068 xmlNodePtr adaptionset_baseurl_node = NULL;
1069 xmlNodePtr adaptionset_segmentlist_node = NULL;
1070 xmlNodePtr adaptionset_supplementalproperty_node = NULL;
1071 xmlNodePtr node = NULL;
1073 node = xmlFirstElementChild(adaptionset_node);
1075 if (!av_strcasecmp(node->name, (const char *)"SegmentTemplate")) {
1076 fragment_template_node = node;
1077 } else if (!av_strcasecmp(node->name, (const char *)"ContentComponent")) {
1078 content_component_node = node;
1079 } else if (!av_strcasecmp(node->name, (const char *)"BaseURL")) {
1080 adaptionset_baseurl_node = node;
1081 } else if (!av_strcasecmp(node->name, (const char *)"SegmentList")) {
1082 adaptionset_segmentlist_node = node;
1083 } else if (!av_strcasecmp(node->name, (const char *)"SupplementalProperty")) {
1084 adaptionset_supplementalproperty_node = node;
1085 } else if (!av_strcasecmp(node->name, (const char *)"Representation")) {
1086 ret = parse_manifest_representation(s, url, node,
1089 period_baseurl_node,
1090 period_segmenttemplate_node,
1091 period_segmentlist_node,
1092 fragment_template_node,
1093 content_component_node,
1094 adaptionset_baseurl_node,
1095 adaptionset_segmentlist_node,
1096 adaptionset_supplementalproperty_node);
1101 node = xmlNextElementSibling(node);
1106 static int parse_manifest(AVFormatContext *s, const char *url, AVIOContext *in)
1108 DASHContext *c = s->priv_data;
1111 uint8_t *new_url = NULL;
1112 int64_t filesize = 0;
1113 char *buffer = NULL;
1114 AVDictionary *opts = NULL;
1116 xmlNodePtr root_element = NULL;
1117 xmlNodePtr node = NULL;
1118 xmlNodePtr period_node = NULL;
1119 xmlNodePtr mpd_baseurl_node = NULL;
1120 xmlNodePtr period_baseurl_node = NULL;
1121 xmlNodePtr period_segmenttemplate_node = NULL;
1122 xmlNodePtr period_segmentlist_node = NULL;
1123 xmlNodePtr adaptionset_node = NULL;
1124 xmlAttrPtr attr = NULL;
1126 uint32_t period_duration_sec = 0;
1127 uint32_t period_start_sec = 0;
1132 set_httpheader_options(c, &opts);
1133 ret = avio_open2(&in, url, AVIO_FLAG_READ, c->interrupt_callback, &opts);
1134 av_dict_free(&opts);
1139 if (av_opt_get(in, "location", AV_OPT_SEARCH_CHILDREN, &new_url) >= 0) {
1140 c->base_url = av_strdup(new_url);
1142 c->base_url = av_strdup(url);
1145 filesize = avio_size(in);
1146 if (filesize <= 0) {
1147 filesize = 8 * 1024;
1150 buffer = av_mallocz(filesize);
1152 av_free(c->base_url);
1153 return AVERROR(ENOMEM);
1156 filesize = avio_read(in, buffer, filesize);
1157 if (filesize <= 0) {
1158 av_log(s, AV_LOG_ERROR, "Unable to read to offset '%s'\n", url);
1159 ret = AVERROR_INVALIDDATA;
1163 doc = xmlReadMemory(buffer, filesize, c->base_url, NULL, 0);
1164 root_element = xmlDocGetRootElement(doc);
1165 node = root_element;
1168 ret = AVERROR_INVALIDDATA;
1169 av_log(s, AV_LOG_ERROR, "Unable to parse '%s' - missing root node\n", url);
1173 if (node->type != XML_ELEMENT_NODE ||
1174 av_strcasecmp(node->name, (const char *)"MPD")) {
1175 ret = AVERROR_INVALIDDATA;
1176 av_log(s, AV_LOG_ERROR, "Unable to parse '%s' - wrong root node name[%s] type[%d]\n", url, node->name, (int)node->type);
1180 val = xmlGetProp(node, "type");
1182 av_log(s, AV_LOG_ERROR, "Unable to parse '%s' - missing type attrib\n", url);
1183 ret = AVERROR_INVALIDDATA;
1186 if (!av_strcasecmp(val, (const char *)"dynamic"))
1190 attr = node->properties;
1192 val = xmlGetProp(node, attr->name);
1194 if (!av_strcasecmp(attr->name, (const char *)"availabilityStartTime")) {
1195 c->availability_start_time = get_utc_date_time_insec(s, (const char *)val);
1196 } else if (!av_strcasecmp(attr->name, (const char *)"publishTime")) {
1197 c->publish_time = get_utc_date_time_insec(s, (const char *)val);
1198 } else if (!av_strcasecmp(attr->name, (const char *)"minimumUpdatePeriod")) {
1199 c->minimum_update_period = get_duration_insec(s, (const char *)val);
1200 } else if (!av_strcasecmp(attr->name, (const char *)"timeShiftBufferDepth")) {
1201 c->time_shift_buffer_depth = get_duration_insec(s, (const char *)val);
1202 } else if (!av_strcasecmp(attr->name, (const char *)"minBufferTime")) {
1203 c->min_buffer_time = get_duration_insec(s, (const char *)val);
1204 } else if (!av_strcasecmp(attr->name, (const char *)"suggestedPresentationDelay")) {
1205 c->suggested_presentation_delay = get_duration_insec(s, (const char *)val);
1206 } else if (!av_strcasecmp(attr->name, (const char *)"mediaPresentationDuration")) {
1207 c->media_presentation_duration = get_duration_insec(s, (const char *)val);
1213 mpd_baseurl_node = find_child_node_by_name(node, "BaseURL");
1214 if (!mpd_baseurl_node) {
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 */
1278 static int64_t calc_cur_seg_no(AVFormatContext *s, struct representation *pls)
1280 DASHContext *c = s->priv_data;
1282 int64_t start_time_offset = 0;
1285 if (pls->n_fragments) {
1286 num = pls->first_seq_no;
1287 } else if (pls->n_timelines) {
1288 start_time_offset = get_segment_start_time_based_on_timeline(pls, 0xFFFFFFFF) - 60 * pls->fragment_timescale; // 60 seconds before end
1289 num = calc_next_seg_no_from_timelines(pls, start_time_offset);
1291 num = pls->first_seq_no;
1293 num += pls->first_seq_no;
1294 } else if (pls->fragment_duration){
1295 if (pls->presentation_timeoffset) {
1296 num = pls->presentation_timeoffset * pls->fragment_timescale / pls->fragment_duration;
1297 } else if (c->publish_time > 0 && !c->availability_start_time) {
1298 num = pls->first_seq_no + (((c->publish_time - c->availability_start_time) - c->suggested_presentation_delay) * pls->fragment_timescale) / pls->fragment_duration;
1300 num = pls->first_seq_no + (((get_current_time_in_sec() - c->availability_start_time) - c->suggested_presentation_delay) * pls->fragment_timescale) / pls->fragment_duration;
1304 num = pls->first_seq_no;
1309 static int64_t calc_min_seg_no(AVFormatContext *s, struct representation *pls)
1311 DASHContext *c = s->priv_data;
1314 if (c->is_live && pls->fragment_duration) {
1315 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;
1317 num = pls->first_seq_no;
1322 static int64_t calc_max_seg_no(struct representation *pls, DASHContext *c)
1326 if (pls->n_fragments) {
1327 num = pls->first_seq_no + pls->n_fragments - 1;
1328 } else if (pls->n_timelines) {
1330 num = pls->first_seq_no + pls->n_timelines - 1;
1331 for (i = 0; i < pls->n_timelines; i++) {
1332 num += pls->timelines[i]->repeat;
1334 } else if (c->is_live && pls->fragment_duration) {
1335 num = pls->first_seq_no + (((get_current_time_in_sec() - c->availability_start_time)) * pls->fragment_timescale) / pls->fragment_duration;
1336 } else if (pls->fragment_duration) {
1337 num = pls->first_seq_no + (c->media_presentation_duration * pls->fragment_timescale) / pls->fragment_duration;
1343 static void move_timelines(struct representation *rep_src, struct representation *rep_dest, DASHContext *c)
1345 if (rep_dest && rep_src ) {
1346 free_timelines_list(rep_dest);
1347 rep_dest->timelines = rep_src->timelines;
1348 rep_dest->n_timelines = rep_src->n_timelines;
1349 rep_dest->first_seq_no = rep_src->first_seq_no;
1350 rep_dest->last_seq_no = calc_max_seg_no(rep_dest, c);
1351 rep_src->timelines = NULL;
1352 rep_src->n_timelines = 0;
1353 rep_dest->cur_seq_no = rep_src->cur_seq_no;
1357 static void move_segments(struct representation *rep_src, struct representation *rep_dest, DASHContext *c)
1359 if (rep_dest && rep_src ) {
1360 free_fragment_list(rep_dest);
1361 if (rep_src->start_number > (rep_dest->start_number + rep_dest->n_fragments))
1362 rep_dest->cur_seq_no = 0;
1364 rep_dest->cur_seq_no += rep_src->start_number - rep_dest->start_number;
1365 rep_dest->fragments = rep_src->fragments;
1366 rep_dest->n_fragments = rep_src->n_fragments;
1367 rep_dest->parent = rep_src->parent;
1368 rep_dest->last_seq_no = calc_max_seg_no(rep_dest, c);
1369 rep_src->fragments = NULL;
1370 rep_src->n_fragments = 0;
1375 static int refresh_manifest(AVFormatContext *s)
1379 DASHContext *c = s->priv_data;
1381 // save current context
1382 int n_videos = c->n_videos;
1383 struct representation **videos = c->videos;
1384 int n_audios = c->n_audios;
1385 struct representation **audios = c->audios;
1386 char *base_url = c->base_url;
1393 ret = parse_manifest(s, s->filename, NULL);
1397 if (c->n_videos != n_videos) {
1398 av_log(c, AV_LOG_ERROR,
1399 "new manifest has mismatched no. of video representations, %d -> %d\n",
1400 n_videos, c->n_videos);
1401 return AVERROR_INVALIDDATA;
1403 if (c->n_audios != n_audios) {
1404 av_log(c, AV_LOG_ERROR,
1405 "new manifest has mismatched no. of audio representations, %d -> %d\n",
1406 n_audios, c->n_audios);
1407 return AVERROR_INVALIDDATA;
1410 for (i = 0; i < n_videos; i++) {
1411 struct representation *cur_video = videos[i];
1412 struct representation *ccur_video = c->videos[i];
1413 if (cur_video->timelines) {
1414 // calc current time
1415 int64_t currentTime = get_segment_start_time_based_on_timeline(cur_video, cur_video->cur_seq_no) / cur_video->fragment_timescale;
1417 ccur_video->cur_seq_no = calc_next_seg_no_from_timelines(ccur_video, currentTime * cur_video->fragment_timescale - 1);
1418 if (ccur_video->cur_seq_no >= 0) {
1419 move_timelines(ccur_video, cur_video, c);
1422 if (cur_video->fragments) {
1423 move_segments(ccur_video, cur_video, c);
1426 for (i = 0; i < n_audios; i++) {
1427 struct representation *cur_audio = audios[i];
1428 struct representation *ccur_audio = c->audios[i];
1429 if (cur_audio->timelines) {
1430 // calc current time
1431 int64_t currentTime = get_segment_start_time_based_on_timeline(cur_audio, cur_audio->cur_seq_no) / cur_audio->fragment_timescale;
1433 ccur_audio->cur_seq_no = calc_next_seg_no_from_timelines(ccur_audio, currentTime * cur_audio->fragment_timescale - 1);
1434 if (ccur_audio->cur_seq_no >= 0) {
1435 move_timelines(ccur_audio, cur_audio, c);
1438 if (cur_audio->fragments) {
1439 move_segments(ccur_audio, cur_audio, c);
1448 c->base_url = base_url;
1453 c->n_audios = n_audios;
1455 c->n_videos = n_videos;
1460 static struct fragment *get_current_fragment(struct representation *pls)
1462 int64_t min_seq_no = 0;
1463 int64_t max_seq_no = 0;
1464 struct fragment *seg = NULL;
1465 struct fragment *seg_ptr = NULL;
1466 DASHContext *c = pls->parent->priv_data;
1468 while (( !ff_check_interrupt(c->interrupt_callback)&& pls->n_fragments > 0)) {
1469 if (pls->cur_seq_no < pls->n_fragments) {
1470 seg_ptr = pls->fragments[pls->cur_seq_no];
1471 seg = av_mallocz(sizeof(struct fragment));
1475 seg->url = av_strdup(seg_ptr->url);
1480 seg->size = seg_ptr->size;
1481 seg->url_offset = seg_ptr->url_offset;
1483 } else if (c->is_live) {
1484 refresh_manifest(pls->parent);
1490 min_seq_no = calc_min_seg_no(pls->parent, pls);
1491 max_seq_no = calc_max_seg_no(pls, c);
1493 if (pls->timelines || pls->fragments) {
1494 refresh_manifest(pls->parent);
1496 if (pls->cur_seq_no <= min_seq_no) {
1497 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);
1498 pls->cur_seq_no = calc_cur_seg_no(pls->parent, pls);
1499 } else if (pls->cur_seq_no > max_seq_no) {
1500 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);
1502 seg = av_mallocz(sizeof(struct fragment));
1506 } else if (pls->cur_seq_no <= pls->last_seq_no) {
1507 seg = av_mallocz(sizeof(struct fragment));
1513 char *tmpfilename= av_mallocz(c->max_url_size);
1517 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));
1518 seg->url = av_strireplace(pls->url_template, pls->url_template, tmpfilename);
1520 av_log(pls->parent, AV_LOG_WARNING, "Unable to resolve template url '%s', try to use origin template\n", pls->url_template);
1521 seg->url = av_strdup(pls->url_template);
1523 av_log(pls->parent, AV_LOG_ERROR, "Cannot resolve template url '%s'\n", pls->url_template);
1524 av_free(tmpfilename);
1528 av_free(tmpfilename);
1535 enum ReadFromURLMode {
1540 static int read_from_url(struct representation *pls, struct fragment *seg,
1541 uint8_t *buf, int buf_size,
1542 enum ReadFromURLMode mode)
1546 /* limit read if the fragment was only a part of a file */
1548 buf_size = FFMIN(buf_size, pls->cur_seg_size - pls->cur_seg_offset);
1550 if (mode == READ_COMPLETE) {
1551 ret = avio_read(pls->input, buf, buf_size);
1552 if (ret < buf_size) {
1553 av_log(pls->parent, AV_LOG_WARNING, "Could not read complete fragment.\n");
1556 ret = avio_read(pls->input, buf, buf_size);
1559 pls->cur_seg_offset += ret;
1564 static int open_input(DASHContext *c, struct representation *pls, struct fragment *seg)
1566 AVDictionary *opts = NULL;
1570 url = av_mallocz(c->max_url_size);
1574 set_httpheader_options(c, &opts);
1575 if (seg->size >= 0) {
1576 /* try to restrict the HTTP request to the part we want
1577 * (if this is in fact a HTTP request) */
1578 av_dict_set_int(&opts, "offset", seg->url_offset, 0);
1579 av_dict_set_int(&opts, "end_offset", seg->url_offset + seg->size, 0);
1582 ff_make_absolute_url(url, c->max_url_size, c->base_url, seg->url);
1583 av_log(pls->parent, AV_LOG_VERBOSE, "DASH request for url '%s', offset %"PRId64", playlist %d\n",
1584 url, seg->url_offset, pls->rep_idx);
1585 ret = open_url(pls->parent, &pls->input, url, c->avio_opts, opts, NULL);
1592 av_dict_free(&opts);
1593 pls->cur_seg_offset = 0;
1594 pls->cur_seg_size = seg->size;
1598 static int update_init_section(struct representation *pls)
1600 static const int max_init_section_size = 1024 * 1024;
1601 DASHContext *c = pls->parent->priv_data;
1606 if (!pls->init_section || pls->init_sec_buf)
1609 ret = open_input(c, pls, pls->init_section);
1611 av_log(pls->parent, AV_LOG_WARNING,
1612 "Failed to open an initialization section in playlist %d\n",
1617 if (pls->init_section->size >= 0)
1618 sec_size = pls->init_section->size;
1619 else if ((urlsize = avio_size(pls->input)) >= 0)
1622 sec_size = max_init_section_size;
1624 av_log(pls->parent, AV_LOG_DEBUG,
1625 "Downloading an initialization section of size %"PRId64"\n",
1628 sec_size = FFMIN(sec_size, max_init_section_size);
1630 av_fast_malloc(&pls->init_sec_buf, &pls->init_sec_buf_size, sec_size);
1632 ret = read_from_url(pls, pls->init_section, pls->init_sec_buf,
1633 pls->init_sec_buf_size, READ_COMPLETE);
1634 ff_format_io_close(pls->parent, &pls->input);
1639 pls->init_sec_data_len = ret;
1640 pls->init_sec_buf_read_offset = 0;
1645 static int64_t seek_data(void *opaque, int64_t offset, int whence)
1647 struct representation *v = opaque;
1648 if (v->n_fragments && !v->init_sec_data_len) {
1649 return avio_seek(v->input, offset, whence);
1652 return AVERROR(ENOSYS);
1655 static int read_data(void *opaque, uint8_t *buf, int buf_size)
1658 struct representation *v = opaque;
1659 DASHContext *c = v->parent->priv_data;
1663 free_fragment(&v->cur_seg);
1664 v->cur_seg = get_current_fragment(v);
1670 /* load/update Media Initialization Section, if any */
1671 ret = update_init_section(v);
1675 ret = open_input(c, v, v->cur_seg);
1677 if (ff_check_interrupt(c->interrupt_callback)) {
1681 av_log(v->parent, AV_LOG_WARNING, "Failed to open fragment of playlist %d\n", v->rep_idx);
1687 if (v->init_sec_buf_read_offset < v->init_sec_data_len) {
1688 /* Push init section out first before first actual fragment */
1689 int copy_size = FFMIN(v->init_sec_data_len - v->init_sec_buf_read_offset, buf_size);
1690 memcpy(buf, v->init_sec_buf, copy_size);
1691 v->init_sec_buf_read_offset += copy_size;
1696 /* check the v->cur_seg, if it is null, get current and double check if the new v->cur_seg*/
1698 v->cur_seg = get_current_fragment(v);
1704 ret = read_from_url(v, v->cur_seg, buf, buf_size, READ_NORMAL);
1708 if (c->is_live || v->cur_seq_no < v->last_seq_no) {
1709 if (!v->is_restart_needed)
1711 v->is_restart_needed = 1;
1718 static int save_avio_options(AVFormatContext *s)
1720 DASHContext *c = s->priv_data;
1721 const char *opts[] = { "headers", "user_agent", "user-agent", "cookies", NULL }, **opt = opts;
1722 uint8_t *buf = NULL;
1726 if (av_opt_get(s->pb, *opt, AV_OPT_SEARCH_CHILDREN, &buf) >= 0) {
1727 if (buf[0] != '\0') {
1728 ret = av_dict_set(&c->avio_opts, *opt, buf, AV_DICT_DONT_STRDUP_VAL);
1743 static int nested_io_open(AVFormatContext *s, AVIOContext **pb, const char *url,
1744 int flags, AVDictionary **opts)
1746 av_log(s, AV_LOG_ERROR,
1747 "A DASH playlist item '%s' referred to an external file '%s'. "
1748 "Opening this file was forbidden for security reasons\n",
1750 return AVERROR(EPERM);
1753 static void close_demux_for_component(struct representation *pls)
1755 /* note: the internal buffer could have changed */
1756 av_freep(&pls->pb.buffer);
1757 memset(&pls->pb, 0x00, sizeof(AVIOContext));
1758 pls->ctx->pb = NULL;
1759 avformat_close_input(&pls->ctx);
1763 static int reopen_demux_for_component(AVFormatContext *s, struct representation *pls)
1765 DASHContext *c = s->priv_data;
1766 AVInputFormat *in_fmt = NULL;
1767 AVDictionary *in_fmt_opts = NULL;
1768 uint8_t *avio_ctx_buffer = NULL;
1772 close_demux_for_component(pls);
1774 if (!(pls->ctx = avformat_alloc_context())) {
1775 ret = AVERROR(ENOMEM);
1779 avio_ctx_buffer = av_malloc(INITIAL_BUFFER_SIZE);
1780 if (!avio_ctx_buffer ) {
1781 ret = AVERROR(ENOMEM);
1782 avformat_free_context(pls->ctx);
1787 ffio_init_context(&pls->pb, avio_ctx_buffer , INITIAL_BUFFER_SIZE, 0, pls, read_data, NULL, NULL);
1789 ffio_init_context(&pls->pb, avio_ctx_buffer , INITIAL_BUFFER_SIZE, 0, pls, read_data, NULL, seek_data);
1791 pls->pb.seekable = 0;
1793 if ((ret = ff_copy_whiteblacklists(pls->ctx, s)) < 0)
1796 pls->ctx->flags = AVFMT_FLAG_CUSTOM_IO;
1797 pls->ctx->probesize = 1024 * 4;
1798 pls->ctx->max_analyze_duration = 4 * AV_TIME_BASE;
1799 ret = av_probe_input_buffer(&pls->pb, &in_fmt, "", NULL, 0, 0);
1801 av_log(s, AV_LOG_ERROR, "Error when loading first fragment, playlist %d\n", (int)pls->rep_idx);
1802 avformat_free_context(pls->ctx);
1807 pls->ctx->pb = &pls->pb;
1808 pls->ctx->io_open = nested_io_open;
1810 // provide additional information from mpd if available
1811 ret = avformat_open_input(&pls->ctx, "", in_fmt, &in_fmt_opts); //pls->init_section->url
1812 av_dict_free(&in_fmt_opts);
1815 if (pls->n_fragments) {
1816 #if FF_API_R_FRAME_RATE
1817 if (pls->framerate.den) {
1818 for (i = 0; i < pls->ctx->nb_streams; i++)
1819 pls->ctx->streams[i]->r_frame_rate = pls->framerate;
1823 ret = avformat_find_stream_info(pls->ctx, NULL);
1832 static int open_demux_for_component(AVFormatContext *s, struct representation *pls)
1838 pls->cur_seq_no = calc_cur_seg_no(s, pls);
1840 if (!pls->last_seq_no) {
1841 pls->last_seq_no = calc_max_seg_no(pls, s->priv_data);
1844 ret = reopen_demux_for_component(s, pls);
1848 for (i = 0; i < pls->ctx->nb_streams; i++) {
1849 AVStream *st = avformat_new_stream(s, NULL);
1850 AVStream *ist = pls->ctx->streams[i];
1852 ret = AVERROR(ENOMEM);
1856 avcodec_parameters_copy(st->codecpar, pls->ctx->streams[i]->codecpar);
1857 avpriv_set_pts_info(st, ist->pts_wrap_bits, ist->time_base.num, ist->time_base.den);
1865 static int dash_read_header(AVFormatContext *s)
1867 void *u = (s->flags & AVFMT_FLAG_CUSTOM_IO) ? NULL : s->pb;
1868 DASHContext *c = s->priv_data;
1870 int stream_index = 0;
1873 c->interrupt_callback = &s->interrupt_callback;
1874 // if the URL context is good, read important options we must broker later
1876 update_options(&c->user_agent, "user-agent", u);
1877 update_options(&c->cookies, "cookies", u);
1878 update_options(&c->headers, "headers", u);
1881 if ((ret = parse_manifest(s, s->filename, s->pb)) < 0)
1884 if ((ret = save_avio_options(s)) < 0)
1887 /* If this isn't a live stream, fill the total duration of the
1890 s->duration = (int64_t) c->media_presentation_duration * AV_TIME_BASE;
1893 /* Open the demuxer for video and audio components if available */
1894 for (i = 0; i < c->n_videos; i++) {
1895 struct representation *cur_video = c->videos[i];
1896 ret = open_demux_for_component(s, cur_video);
1899 cur_video->stream_index = stream_index;
1903 for (i = 0; i < c->n_audios; i++) {
1904 struct representation *cur_audio = c->audios[i];
1905 ret = open_demux_for_component(s, cur_audio);
1908 cur_audio->stream_index = stream_index;
1912 if (!stream_index) {
1913 ret = AVERROR_INVALIDDATA;
1917 /* Create a program */
1920 program = av_new_program(s, 0);
1925 for (i = 0; i < c->n_videos; i++) {
1926 struct representation *pls = c->videos[i];
1928 av_program_add_stream_index(s, 0, pls->stream_index);
1929 pls->assoc_stream = s->streams[pls->stream_index];
1930 if (pls->bandwidth > 0)
1931 av_dict_set_int(&pls->assoc_stream->metadata, "variant_bitrate", pls->bandwidth, 0);
1933 av_dict_set(&pls->assoc_stream->metadata, "id", pls->id, 0);
1935 for (i = 0; i < c->n_audios; i++) {
1936 struct representation *pls = c->audios[i];
1938 av_program_add_stream_index(s, 0, pls->stream_index);
1939 pls->assoc_stream = s->streams[pls->stream_index];
1940 if (pls->bandwidth > 0)
1941 av_dict_set_int(&pls->assoc_stream->metadata, "variant_bitrate", pls->bandwidth, 0);
1943 av_dict_set(&pls->assoc_stream->metadata, "id", pls->id, 0);
1952 static void recheck_discard_flags(AVFormatContext *s, struct representation **p, int n)
1956 for (i = 0; i < n; i++) {
1957 struct representation *pls = p[i];
1959 int needed = !pls->assoc_stream || pls->assoc_stream->discard < AVDISCARD_ALL;
1960 if (needed && !pls->ctx) {
1961 pls->cur_seg_offset = 0;
1962 pls->init_sec_buf_read_offset = 0;
1964 for (j = 0; j < n; j++) {
1965 pls->cur_seq_no = FFMAX(pls->cur_seq_no, p[j]->cur_seq_no);
1967 reopen_demux_for_component(s, pls);
1968 av_log(s, AV_LOG_INFO, "Now receiving stream_index %d\n", pls->stream_index);
1969 } else if (!needed && pls->ctx) {
1970 close_demux_for_component(pls);
1972 ff_format_io_close(pls->parent, &pls->input);
1973 av_log(s, AV_LOG_INFO, "No longer receiving stream_index %d\n", pls->stream_index);
1978 static int dash_read_packet(AVFormatContext *s, AVPacket *pkt)
1980 DASHContext *c = s->priv_data;
1983 struct representation *cur = NULL;
1985 recheck_discard_flags(s, c->videos, c->n_videos);
1986 recheck_discard_flags(s, c->audios, c->n_audios);
1988 for (i = 0; i < c->n_videos; i++) {
1989 struct representation *pls = c->videos[i];
1992 if (!cur || pls->cur_timestamp < mints) {
1994 mints = pls->cur_timestamp;
1997 for (i = 0; i < c->n_audios; i++) {
1998 struct representation *pls = c->audios[i];
2001 if (!cur || pls->cur_timestamp < mints) {
2003 mints = pls->cur_timestamp;
2008 return AVERROR_INVALIDDATA;
2010 while (!ff_check_interrupt(c->interrupt_callback) && !ret) {
2011 ret = av_read_frame(cur->ctx, pkt);
2013 /* If we got a packet, return it */
2014 cur->cur_timestamp = av_rescale(pkt->pts, (int64_t)cur->ctx->streams[0]->time_base.num * 90000, cur->ctx->streams[0]->time_base.den);
2015 pkt->stream_index = cur->stream_index;
2018 if (cur->is_restart_needed) {
2019 cur->cur_seg_offset = 0;
2020 cur->init_sec_buf_read_offset = 0;
2022 ff_format_io_close(cur->parent, &cur->input);
2023 ret = reopen_demux_for_component(s, cur);
2024 cur->is_restart_needed = 0;
2030 static int dash_close(AVFormatContext *s)
2032 DASHContext *c = s->priv_data;
2036 av_freep(&c->cookies);
2037 av_freep(&c->user_agent);
2038 av_dict_free(&c->avio_opts);
2039 av_freep(&c->base_url);
2043 static int dash_seek(AVFormatContext *s, struct representation *pls, int64_t seek_pos_msec, int flags, int dry_run)
2048 int64_t duration = 0;
2050 av_log(pls->parent, AV_LOG_VERBOSE, "DASH seek pos[%"PRId64"ms], playlist %d%s\n",
2051 seek_pos_msec, pls->rep_idx, dry_run ? " (dry)" : "");
2053 // single fragment mode
2054 if (pls->n_fragments == 1) {
2055 pls->cur_timestamp = 0;
2056 pls->cur_seg_offset = 0;
2059 ff_read_frame_flush(pls->ctx);
2060 return av_seek_frame(pls->ctx, -1, seek_pos_msec * 1000, flags);
2064 ff_format_io_close(pls->parent, &pls->input);
2066 // find the nearest fragment
2067 if (pls->n_timelines > 0 && pls->fragment_timescale > 0) {
2068 int64_t num = pls->first_seq_no;
2069 av_log(pls->parent, AV_LOG_VERBOSE, "dash_seek with SegmentTimeline start n_timelines[%d] "
2070 "last_seq_no[%"PRId64"], playlist %d.\n",
2071 (int)pls->n_timelines, (int64_t)pls->last_seq_no, (int)pls->rep_idx);
2072 for (i = 0; i < pls->n_timelines; i++) {
2073 if (pls->timelines[i]->starttime > 0) {
2074 duration = pls->timelines[i]->starttime;
2076 duration += pls->timelines[i]->duration;
2077 if (seek_pos_msec < ((duration * 1000) / pls->fragment_timescale)) {
2080 for (j = 0; j < pls->timelines[i]->repeat; j++) {
2081 duration += pls->timelines[i]->duration;
2083 if (seek_pos_msec < ((duration * 1000) / pls->fragment_timescale)) {
2091 pls->cur_seq_no = num > pls->last_seq_no ? pls->last_seq_no : num;
2092 av_log(pls->parent, AV_LOG_VERBOSE, "dash_seek with SegmentTimeline end cur_seq_no[%"PRId64"], playlist %d.\n",
2093 (int64_t)pls->cur_seq_no, (int)pls->rep_idx);
2094 } else if (pls->fragment_duration > 0) {
2095 pls->cur_seq_no = pls->first_seq_no + ((seek_pos_msec * pls->fragment_timescale) / pls->fragment_duration) / 1000;
2097 av_log(pls->parent, AV_LOG_ERROR, "dash_seek missing timeline or fragment_duration\n");
2098 pls->cur_seq_no = pls->first_seq_no;
2100 pls->cur_timestamp = 0;
2101 pls->cur_seg_offset = 0;
2102 pls->init_sec_buf_read_offset = 0;
2103 ret = dry_run ? 0 : reopen_demux_for_component(s, pls);
2108 static int dash_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
2111 DASHContext *c = s->priv_data;
2112 int64_t seek_pos_msec = av_rescale_rnd(timestamp, 1000,
2113 s->streams[stream_index]->time_base.den,
2114 flags & AVSEEK_FLAG_BACKWARD ?
2115 AV_ROUND_DOWN : AV_ROUND_UP);
2116 if ((flags & AVSEEK_FLAG_BYTE) || c->is_live)
2117 return AVERROR(ENOSYS);
2119 /* Seek in discarded streams with dry_run=1 to avoid reopening them */
2120 for (i = 0; i < c->n_videos; i++) {
2122 ret = dash_seek(s, c->videos[i], seek_pos_msec, flags, !c->videos[i]->ctx);
2124 for (i = 0; i < c->n_audios; i++) {
2126 ret = dash_seek(s, c->audios[i], seek_pos_msec, flags, !c->audios[i]->ctx);
2132 static int dash_probe(AVProbeData *p)
2134 if (!av_stristr(p->buf, "<MPD"))
2137 if (av_stristr(p->buf, "dash:profile:isoff-on-demand:2011") ||
2138 av_stristr(p->buf, "dash:profile:isoff-live:2011") ||
2139 av_stristr(p->buf, "dash:profile:isoff-live:2012") ||
2140 av_stristr(p->buf, "dash:profile:isoff-main:2011")) {
2141 return AVPROBE_SCORE_MAX;
2143 if (av_stristr(p->buf, "dash:profile")) {
2144 return AVPROBE_SCORE_MAX;
2150 #define OFFSET(x) offsetof(DASHContext, x)
2151 #define FLAGS AV_OPT_FLAG_DECODING_PARAM
2152 static const AVOption dash_options[] = {
2153 {"allowed_extensions", "List of file extensions that dash is allowed to access",
2154 OFFSET(allowed_extensions), AV_OPT_TYPE_STRING,
2155 {.str = "aac,m4a,m4s,m4v,mov,mp4"},
2156 INT_MIN, INT_MAX, FLAGS},
2160 static const AVClass dash_class = {
2161 .class_name = "dash",
2162 .item_name = av_default_item_name,
2163 .option = dash_options,
2164 .version = LIBAVUTIL_VERSION_INT,
2167 AVInputFormat ff_dash_demuxer = {
2169 .long_name = NULL_IF_CONFIG_SMALL("Dynamic Adaptive Streaming over HTTP"),
2170 .priv_class = &dash_class,
2171 .priv_data_size = sizeof(DASHContext),
2172 .read_probe = dash_probe,
2173 .read_header = dash_read_header,
2174 .read_packet = dash_read_packet,
2175 .read_close = dash_close,
2176 .read_seek = dash_read_seek,
2177 .flags = AVFMT_NO_BYTE_SEEK,