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
32 #define MAX_BPRINT_READ_SIZE (UINT_MAX - 1)
33 #define DEFAULT_MANIFEST_SIZE 8 * 1024
42 * reference to : ISO_IEC_23009-1-DASH-2012
44 * Table: Table 17 — Semantics of SegmentTimeline element
47 /* starttime: Element or Attribute Name
48 * specifies the MPD start time, in @timescale units,
49 * the first Segment in the series starts relative to the beginning of the Period.
50 * The value of this attribute must be equal to or greater than the sum of the previous S
51 * element earliest presentation time and the sum of the contiguous Segment durations.
52 * If the value of the attribute is greater than what is expressed by the previous S element,
53 * it expresses discontinuities in the timeline.
54 * If not present then the value shall be assumed to be zero for the first S element
55 * and for the subsequent S elements, the value shall be assumed to be the sum of
56 * the previous S element's earliest presentation time and contiguous duration
57 * (i.e. previous S@starttime + @duration * (@repeat + 1)).
60 /* repeat: Element or Attribute Name
61 * specifies the repeat count of the number of following contiguous Segments with
62 * the same duration expressed by the value of @duration. This value is zero-based
63 * (e.g. a value of three means four Segments in the contiguous series).
66 /* duration: Element or Attribute Name
67 * specifies the Segment duration, in units of the value of the @timescale.
73 * Each playlist has its own demuxer. If it is currently active,
74 * it has an opened AVIOContext too, and potentially an AVPacket
75 * containing the next packet from this stream.
77 struct representation {
81 AVFormatContext *parent;
88 enum AVMediaType type;
93 AVStream *assoc_stream; /* demuxer stream associated with this representation */
96 struct fragment **fragments; /* VOD list of fragment for profile */
99 struct timeline **timelines;
101 int64_t first_seq_no;
103 int64_t start_number; /* used in case when we have dynamic list of segment to know which segments are new one*/
105 int64_t fragment_duration;
106 int64_t fragment_timescale;
108 int64_t presentation_timeoffset;
111 int64_t cur_seg_offset;
112 int64_t cur_seg_size;
113 struct fragment *cur_seg;
115 /* Currently active Media Initialization Section */
116 struct fragment *init_section;
117 uint8_t *init_sec_buf;
118 uint32_t init_sec_buf_size;
119 uint32_t init_sec_data_len;
120 uint32_t init_sec_buf_read_offset;
121 int64_t cur_timestamp;
122 int is_restart_needed;
125 typedef struct DASHContext {
126 const AVClass *class;
130 struct representation **videos;
132 struct representation **audios;
134 struct representation **subtitles;
136 /* MediaPresentationDescription Attribute */
137 uint64_t media_presentation_duration;
138 uint64_t suggested_presentation_delay;
139 uint64_t availability_start_time;
140 uint64_t availability_end_time;
141 uint64_t publish_time;
142 uint64_t minimum_update_period;
143 uint64_t time_shift_buffer_depth;
144 uint64_t min_buffer_time;
146 /* Period Attribute */
147 uint64_t period_duration;
148 uint64_t period_start;
150 /* AdaptationSet Attribute */
151 char *adaptionset_lang;
154 AVIOInterruptCB *interrupt_callback;
155 char *allowed_extensions;
156 AVDictionary *avio_opts;
159 /* Flags for init section*/
160 int is_init_section_common_video;
161 int is_init_section_common_audio;
165 static int ishttp(char *url)
167 const char *proto_name = avio_find_protocol_name(url);
168 return av_strstart(proto_name, "http", NULL);
171 static int aligned(int val)
173 return ((val + 0x3F) >> 6) << 6;
176 static uint64_t get_current_time_in_sec(void)
178 return av_gettime() / 1000000;
181 static uint64_t get_utc_date_time_insec(AVFormatContext *s, const char *datetime)
192 /* ISO-8601 date parser */
196 ret = sscanf(datetime, "%d-%d-%dT%d:%d:%fZ", &year, &month, &day, &hour, &minute, &second);
197 /* year, month, day, hour, minute, second 6 arguments */
199 av_log(s, AV_LOG_WARNING, "get_utc_date_time_insec get a wrong time format\n");
201 timeinfo.tm_year = year - 1900;
202 timeinfo.tm_mon = month - 1;
203 timeinfo.tm_mday = day;
204 timeinfo.tm_hour = hour;
205 timeinfo.tm_min = minute;
206 timeinfo.tm_sec = (int)second;
208 return av_timegm(&timeinfo);
211 static uint32_t get_duration_insec(AVFormatContext *s, const char *duration)
213 /* ISO-8601 duration parser */
221 const char *ptr = duration;
224 if (*ptr == 'P' || *ptr == 'T') {
229 if (sscanf(ptr, "%f%c%n", &value, &type, &size) != 2) {
230 av_log(s, AV_LOG_WARNING, "get_duration_insec get a wrong time format\n");
231 return 0; /* parser error */
235 days = (uint32_t)value;
238 hours = (uint32_t)value;
241 mins = (uint32_t)value;
244 secs = (uint32_t)value;
247 // handle invalid type
252 return ((days * 24 + hours) * 60 + mins) * 60 + secs;
255 static int64_t get_segment_start_time_based_on_timeline(struct representation *pls, int64_t cur_seq_no)
257 int64_t start_time = 0;
262 if (pls->n_timelines) {
263 for (i = 0; i < pls->n_timelines; i++) {
264 if (pls->timelines[i]->starttime > 0) {
265 start_time = pls->timelines[i]->starttime;
267 if (num == cur_seq_no)
270 start_time += pls->timelines[i]->duration;
272 if (pls->timelines[i]->repeat == -1) {
273 start_time = pls->timelines[i]->duration * cur_seq_no;
277 for (j = 0; j < pls->timelines[i]->repeat; j++) {
279 if (num == cur_seq_no)
281 start_time += pls->timelines[i]->duration;
290 static int64_t calc_next_seg_no_from_timelines(struct representation *pls, int64_t cur_time)
295 int64_t start_time = 0;
297 for (i = 0; i < pls->n_timelines; i++) {
298 if (pls->timelines[i]->starttime > 0) {
299 start_time = pls->timelines[i]->starttime;
301 if (start_time > cur_time)
304 start_time += pls->timelines[i]->duration;
305 for (j = 0; j < pls->timelines[i]->repeat; j++) {
307 if (start_time > cur_time)
309 start_time += pls->timelines[i]->duration;
320 static void free_fragment(struct fragment **seg)
325 av_freep(&(*seg)->url);
329 static void free_fragment_list(struct representation *pls)
333 for (i = 0; i < pls->n_fragments; i++) {
334 free_fragment(&pls->fragments[i]);
336 av_freep(&pls->fragments);
337 pls->n_fragments = 0;
340 static void free_timelines_list(struct representation *pls)
344 for (i = 0; i < pls->n_timelines; i++) {
345 av_freep(&pls->timelines[i]);
347 av_freep(&pls->timelines);
348 pls->n_timelines = 0;
351 static void free_representation(struct representation *pls)
353 free_fragment_list(pls);
354 free_timelines_list(pls);
355 free_fragment(&pls->cur_seg);
356 free_fragment(&pls->init_section);
357 av_freep(&pls->init_sec_buf);
358 av_freep(&pls->pb.buffer);
359 ff_format_io_close(pls->parent, &pls->input);
362 avformat_close_input(&pls->ctx);
365 av_freep(&pls->url_template);
369 static void free_video_list(DASHContext *c)
372 for (i = 0; i < c->n_videos; i++) {
373 struct representation *pls = c->videos[i];
374 free_representation(pls);
376 av_freep(&c->videos);
380 static void free_audio_list(DASHContext *c)
383 for (i = 0; i < c->n_audios; i++) {
384 struct representation *pls = c->audios[i];
385 free_representation(pls);
387 av_freep(&c->audios);
391 static void free_subtitle_list(DASHContext *c)
394 for (i = 0; i < c->n_subtitles; i++) {
395 struct representation *pls = c->subtitles[i];
396 free_representation(pls);
398 av_freep(&c->subtitles);
402 static int open_url(AVFormatContext *s, AVIOContext **pb, const char *url,
403 AVDictionary *opts, AVDictionary *opts2, int *is_http)
405 DASHContext *c = s->priv_data;
406 AVDictionary *tmp = NULL;
407 const char *proto_name = NULL;
410 if (av_strstart(url, "crypto", NULL)) {
411 if (url[6] == '+' || url[6] == ':')
412 proto_name = avio_find_protocol_name(url + 7);
416 proto_name = avio_find_protocol_name(url);
419 return AVERROR_INVALIDDATA;
421 // only http(s) & file are allowed
422 if (av_strstart(proto_name, "file", NULL)) {
423 if (strcmp(c->allowed_extensions, "ALL") && !av_match_ext(url, c->allowed_extensions)) {
424 av_log(s, AV_LOG_ERROR,
425 "Filename extension of \'%s\' is not a common multimedia extension, blocked for security reasons.\n"
426 "If you wish to override this adjust allowed_extensions, you can set it to \'ALL\' to allow all\n",
428 return AVERROR_INVALIDDATA;
430 } else if (av_strstart(proto_name, "http", NULL)) {
433 return AVERROR_INVALIDDATA;
435 if (!strncmp(proto_name, url, strlen(proto_name)) && url[strlen(proto_name)] == ':')
437 else if (av_strstart(url, "crypto", NULL) && !strncmp(proto_name, url + 7, strlen(proto_name)) && url[7 + strlen(proto_name)] == ':')
439 else if (strcmp(proto_name, "file") || !strncmp(url, "file,", 5))
440 return AVERROR_INVALIDDATA;
443 av_dict_copy(&tmp, opts, 0);
444 av_dict_copy(&tmp, opts2, 0);
445 ret = avio_open2(pb, url, AVIO_FLAG_READ, c->interrupt_callback, &tmp);
447 // update cookies on http response with setcookies.
448 char *new_cookies = NULL;
450 if (!(s->flags & AVFMT_FLAG_CUSTOM_IO))
451 av_opt_get(*pb, "cookies", AV_OPT_SEARCH_CHILDREN, (uint8_t**)&new_cookies);
454 av_dict_set(&opts, "cookies", new_cookies, AV_DICT_DONT_STRDUP_VAL);
462 *is_http = av_strstart(proto_name, "http", NULL);
467 static char *get_content_url(xmlNodePtr *baseurl_nodes,
471 char *rep_bandwidth_val,
477 char *tmp_str = av_mallocz(max_url_size);
478 char *tmp_str_2 = av_mallocz(max_url_size);
480 if (!tmp_str || !tmp_str_2) {
484 for (i = 0; i < n_baseurl_nodes; ++i) {
485 if (baseurl_nodes[i] &&
486 baseurl_nodes[i]->children &&
487 baseurl_nodes[i]->children->type == XML_TEXT_NODE) {
488 text = xmlNodeGetContent(baseurl_nodes[i]->children);
490 memset(tmp_str, 0, max_url_size);
491 memset(tmp_str_2, 0, max_url_size);
492 ff_make_absolute_url(tmp_str_2, max_url_size, tmp_str, text);
493 av_strlcpy(tmp_str, tmp_str_2, max_url_size);
500 ff_make_absolute_url(tmp_str, max_url_size, tmp_str, val);
503 url = av_strireplace(tmp_str, "$RepresentationID$", (const char*)rep_id_val);
507 av_strlcpy(tmp_str, url, max_url_size);
509 if (rep_bandwidth_val && tmp_str[0] != '\0') {
510 // free any previously assigned url before reassigning
512 url = av_strireplace(tmp_str, "$Bandwidth$", (const char*)rep_bandwidth_val);
523 static char *get_val_from_nodes_tab(xmlNodePtr *nodes, const int n_nodes, const char *attrname)
528 for (i = 0; i < n_nodes; ++i) {
530 val = xmlGetProp(nodes[i], attrname);
539 static xmlNodePtr find_child_node_by_name(xmlNodePtr rootnode, const char *nodename)
541 xmlNodePtr node = rootnode;
546 node = xmlFirstElementChild(node);
548 if (!av_strcasecmp(node->name, nodename)) {
551 node = xmlNextElementSibling(node);
556 static enum AVMediaType get_content_type(xmlNodePtr node)
558 enum AVMediaType type = AVMEDIA_TYPE_UNKNOWN;
564 for (i = 0; i < 2; i++) {
565 attr = i ? "mimeType" : "contentType";
566 val = xmlGetProp(node, attr);
568 if (av_stristr((const char *)val, "video")) {
569 type = AVMEDIA_TYPE_VIDEO;
570 } else if (av_stristr((const char *)val, "audio")) {
571 type = AVMEDIA_TYPE_AUDIO;
572 } else if (av_stristr((const char *)val, "text")) {
573 type = AVMEDIA_TYPE_SUBTITLE;
582 static struct fragment * get_Fragment(char *range)
584 struct fragment * seg = av_mallocz(sizeof(struct fragment));
591 char *str_end_offset;
592 char *str_offset = av_strtok(range, "-", &str_end_offset);
593 seg->url_offset = strtoll(str_offset, NULL, 10);
594 seg->size = strtoll(str_end_offset, NULL, 10) - seg->url_offset + 1;
600 static int parse_manifest_segmenturlnode(AVFormatContext *s, struct representation *rep,
601 xmlNodePtr fragmenturl_node,
602 xmlNodePtr *baseurl_nodes,
604 char *rep_bandwidth_val)
606 DASHContext *c = s->priv_data;
607 char *initialization_val = NULL;
608 char *media_val = NULL;
609 char *range_val = NULL;
610 int max_url_size = c ? c->max_url_size: MAX_URL_SIZE;
612 if (!av_strcasecmp(fragmenturl_node->name, (const char *)"Initialization")) {
613 initialization_val = xmlGetProp(fragmenturl_node, "sourceURL");
614 range_val = xmlGetProp(fragmenturl_node, "range");
615 if (initialization_val || range_val) {
616 free_fragment(&rep->init_section);
617 rep->init_section = get_Fragment(range_val);
619 if (!rep->init_section) {
620 xmlFree(initialization_val);
621 return AVERROR(ENOMEM);
623 rep->init_section->url = get_content_url(baseurl_nodes, 4,
628 xmlFree(initialization_val);
629 if (!rep->init_section->url) {
630 av_freep(&rep->init_section);
631 return AVERROR(ENOMEM);
634 } else if (!av_strcasecmp(fragmenturl_node->name, (const char *)"SegmentURL")) {
635 media_val = xmlGetProp(fragmenturl_node, "media");
636 range_val = xmlGetProp(fragmenturl_node, "mediaRange");
637 if (media_val || range_val) {
638 struct fragment *seg = get_Fragment(range_val);
642 return AVERROR(ENOMEM);
644 seg->url = get_content_url(baseurl_nodes, 4,
652 return AVERROR(ENOMEM);
654 dynarray_add(&rep->fragments, &rep->n_fragments, seg);
661 static int parse_manifest_segmenttimeline(AVFormatContext *s, struct representation *rep,
662 xmlNodePtr fragment_timeline_node)
664 xmlAttrPtr attr = NULL;
667 if (!av_strcasecmp(fragment_timeline_node->name, (const char *)"S")) {
668 struct timeline *tml = av_mallocz(sizeof(struct timeline));
670 return AVERROR(ENOMEM);
672 attr = fragment_timeline_node->properties;
674 val = xmlGetProp(fragment_timeline_node, attr->name);
677 av_log(s, AV_LOG_WARNING, "parse_manifest_segmenttimeline attr->name = %s val is NULL\n", attr->name);
681 if (!av_strcasecmp(attr->name, (const char *)"t")) {
682 tml->starttime = (int64_t)strtoll(val, NULL, 10);
683 } else if (!av_strcasecmp(attr->name, (const char *)"r")) {
684 tml->repeat =(int64_t) strtoll(val, NULL, 10);
685 } else if (!av_strcasecmp(attr->name, (const char *)"d")) {
686 tml->duration = (int64_t)strtoll(val, NULL, 10);
691 dynarray_add(&rep->timelines, &rep->n_timelines, tml);
697 static int resolve_content_path(AVFormatContext *s, const char *url, int *max_url_size, xmlNodePtr *baseurl_nodes, int n_baseurl_nodes)
699 char *tmp_str = NULL;
701 char *mpdName = NULL;
702 xmlNodePtr node = NULL;
703 char *baseurl = NULL;
704 char *root_url = NULL;
714 int tmp_max_url_size = strlen(url);
716 for (i = n_baseurl_nodes-1; i >= 0 ; i--) {
717 text = xmlNodeGetContent(baseurl_nodes[i]);
720 tmp_max_url_size += strlen(text);
728 tmp_max_url_size = aligned(tmp_max_url_size);
729 text = av_mallocz(tmp_max_url_size);
731 updated = AVERROR(ENOMEM);
734 av_strlcpy(text, url, strlen(url)+1);
736 while (mpdName = av_strtok(tmp, "/", &tmp)) {
737 size = strlen(mpdName);
741 path = av_mallocz(tmp_max_url_size);
742 tmp_str = av_mallocz(tmp_max_url_size);
743 if (!tmp_str || !path) {
744 updated = AVERROR(ENOMEM);
748 av_strlcpy (path, url, strlen(url) - size + 1);
749 for (rootId = n_baseurl_nodes - 1; rootId > 0; rootId --) {
750 if (!(node = baseurl_nodes[rootId])) {
753 text = xmlNodeGetContent(node);
761 node = baseurl_nodes[rootId];
762 baseurl = xmlNodeGetContent(node);
763 root_url = (av_strcasecmp(baseurl, "")) ? baseurl : path;
765 xmlNodeSetContent(node, root_url);
769 size = strlen(root_url);
770 isRootHttp = ishttp(root_url);
772 if (root_url[size - 1] != token) {
773 av_strlcat(root_url, "/", size + 2);
777 for (i = 0; i < n_baseurl_nodes; ++i) {
781 text = xmlNodeGetContent(baseurl_nodes[i]);
782 if (text && !av_strstart(text, "/", NULL)) {
783 memset(tmp_str, 0, strlen(tmp_str));
784 if (!ishttp(text) && isRootHttp) {
785 av_strlcpy(tmp_str, root_url, size + 1);
787 start = (text[0] == token);
788 if (start && av_stristr(tmp_str, text)) {
790 if (!av_strncasecmp(tmp_str, "http://", 7)) {
792 } else if (!av_strncasecmp(tmp_str, "https://", 8)) {
796 memset(p + 1, 0, strlen(p));
798 av_strlcat(tmp_str, text + start, tmp_max_url_size);
799 xmlNodeSetContent(baseurl_nodes[i], tmp_str);
806 if (tmp_max_url_size > *max_url_size) {
807 *max_url_size = tmp_max_url_size;
816 static int parse_manifest_representation(AVFormatContext *s, const char *url,
818 xmlNodePtr adaptionset_node,
819 xmlNodePtr mpd_baseurl_node,
820 xmlNodePtr period_baseurl_node,
821 xmlNodePtr period_segmenttemplate_node,
822 xmlNodePtr period_segmentlist_node,
823 xmlNodePtr fragment_template_node,
824 xmlNodePtr content_component_node,
825 xmlNodePtr adaptionset_baseurl_node,
826 xmlNodePtr adaptionset_segmentlist_node,
827 xmlNodePtr adaptionset_supplementalproperty_node)
830 int32_t subtitle_rep_idx = 0;
831 int32_t audio_rep_idx = 0;
832 int32_t video_rep_idx = 0;
833 DASHContext *c = s->priv_data;
834 struct representation *rep = NULL;
835 struct fragment *seg = NULL;
836 xmlNodePtr representation_segmenttemplate_node = NULL;
837 xmlNodePtr representation_baseurl_node = NULL;
838 xmlNodePtr representation_segmentlist_node = NULL;
839 xmlNodePtr segmentlists_tab[3];
840 xmlNodePtr fragment_timeline_node = NULL;
841 xmlNodePtr fragment_templates_tab[5];
842 char *duration_val = NULL;
843 char *presentation_timeoffset_val = NULL;
844 char *startnumber_val = NULL;
845 char *timescale_val = NULL;
846 char *initialization_val = NULL;
847 char *media_val = NULL;
849 xmlNodePtr baseurl_nodes[4];
850 xmlNodePtr representation_node = node;
851 char *rep_id_val = xmlGetProp(representation_node, "id");
852 char *rep_bandwidth_val = xmlGetProp(representation_node, "bandwidth");
853 char *rep_framerate_val = xmlGetProp(representation_node, "frameRate");
854 enum AVMediaType type = AVMEDIA_TYPE_UNKNOWN;
856 // try get information from representation
857 if (type == AVMEDIA_TYPE_UNKNOWN)
858 type = get_content_type(representation_node);
859 // try get information from contentComponen
860 if (type == AVMEDIA_TYPE_UNKNOWN)
861 type = get_content_type(content_component_node);
862 // try get information from adaption set
863 if (type == AVMEDIA_TYPE_UNKNOWN)
864 type = get_content_type(adaptionset_node);
865 if (type == AVMEDIA_TYPE_UNKNOWN) {
866 av_log(s, AV_LOG_VERBOSE, "Parsing '%s' - skipp not supported representation type\n", url);
867 } else if (type == AVMEDIA_TYPE_VIDEO || type == AVMEDIA_TYPE_AUDIO || type == AVMEDIA_TYPE_SUBTITLE) {
868 // convert selected representation to our internal struct
869 rep = av_mallocz(sizeof(struct representation));
871 ret = AVERROR(ENOMEM);
874 if (c->adaptionset_lang) {
875 rep->lang = av_strdup(c->adaptionset_lang);
877 av_log(s, AV_LOG_ERROR, "alloc language memory failure\n");
879 ret = AVERROR(ENOMEM);
884 representation_segmenttemplate_node = find_child_node_by_name(representation_node, "SegmentTemplate");
885 representation_baseurl_node = find_child_node_by_name(representation_node, "BaseURL");
886 representation_segmentlist_node = find_child_node_by_name(representation_node, "SegmentList");
888 baseurl_nodes[0] = mpd_baseurl_node;
889 baseurl_nodes[1] = period_baseurl_node;
890 baseurl_nodes[2] = adaptionset_baseurl_node;
891 baseurl_nodes[3] = representation_baseurl_node;
893 ret = resolve_content_path(s, url, &c->max_url_size, baseurl_nodes, 4);
894 c->max_url_size = aligned(c->max_url_size
895 + (rep_id_val ? strlen(rep_id_val) : 0)
896 + (rep_bandwidth_val ? strlen(rep_bandwidth_val) : 0));
897 if (ret == AVERROR(ENOMEM) || ret == 0) {
900 if (representation_segmenttemplate_node || fragment_template_node || period_segmenttemplate_node) {
901 fragment_timeline_node = NULL;
902 fragment_templates_tab[0] = representation_segmenttemplate_node;
903 fragment_templates_tab[1] = adaptionset_segmentlist_node;
904 fragment_templates_tab[2] = fragment_template_node;
905 fragment_templates_tab[3] = period_segmenttemplate_node;
906 fragment_templates_tab[4] = period_segmentlist_node;
908 presentation_timeoffset_val = get_val_from_nodes_tab(fragment_templates_tab, 4, "presentationTimeOffset");
909 duration_val = get_val_from_nodes_tab(fragment_templates_tab, 4, "duration");
910 startnumber_val = get_val_from_nodes_tab(fragment_templates_tab, 4, "startNumber");
911 timescale_val = get_val_from_nodes_tab(fragment_templates_tab, 4, "timescale");
912 initialization_val = get_val_from_nodes_tab(fragment_templates_tab, 4, "initialization");
913 media_val = get_val_from_nodes_tab(fragment_templates_tab, 4, "media");
915 if (initialization_val) {
916 rep->init_section = av_mallocz(sizeof(struct fragment));
917 if (!rep->init_section) {
919 ret = AVERROR(ENOMEM);
922 c->max_url_size = aligned(c->max_url_size + strlen(initialization_val));
923 rep->init_section->url = get_content_url(baseurl_nodes, 4, c->max_url_size, rep_id_val, rep_bandwidth_val, initialization_val);
924 if (!rep->init_section->url) {
925 av_free(rep->init_section);
927 ret = AVERROR(ENOMEM);
930 rep->init_section->size = -1;
931 xmlFree(initialization_val);
935 c->max_url_size = aligned(c->max_url_size + strlen(media_val));
936 rep->url_template = get_content_url(baseurl_nodes, 4, c->max_url_size, rep_id_val, rep_bandwidth_val, media_val);
940 if (presentation_timeoffset_val) {
941 rep->presentation_timeoffset = (int64_t) strtoll(presentation_timeoffset_val, NULL, 10);
942 av_log(s, AV_LOG_TRACE, "rep->presentation_timeoffset = [%"PRId64"]\n", rep->presentation_timeoffset);
943 xmlFree(presentation_timeoffset_val);
946 rep->fragment_duration = (int64_t) strtoll(duration_val, NULL, 10);
947 av_log(s, AV_LOG_TRACE, "rep->fragment_duration = [%"PRId64"]\n", rep->fragment_duration);
948 xmlFree(duration_val);
951 rep->fragment_timescale = (int64_t) strtoll(timescale_val, NULL, 10);
952 av_log(s, AV_LOG_TRACE, "rep->fragment_timescale = [%"PRId64"]\n", rep->fragment_timescale);
953 xmlFree(timescale_val);
955 if (startnumber_val) {
956 rep->start_number = rep->first_seq_no = (int64_t) strtoll(startnumber_val, NULL, 10);
957 av_log(s, AV_LOG_TRACE, "rep->first_seq_no = [%"PRId64"]\n", rep->first_seq_no);
958 xmlFree(startnumber_val);
960 if (adaptionset_supplementalproperty_node) {
961 if (!av_strcasecmp(xmlGetProp(adaptionset_supplementalproperty_node,"schemeIdUri"), "http://dashif.org/guidelines/last-segment-number")) {
962 val = xmlGetProp(adaptionset_supplementalproperty_node,"value");
964 av_log(s, AV_LOG_ERROR, "Missing value attribute in adaptionset_supplementalproperty_node\n");
966 rep->last_seq_no =(int64_t) strtoll(val, NULL, 10) - 1;
972 fragment_timeline_node = find_child_node_by_name(representation_segmenttemplate_node, "SegmentTimeline");
974 if (!fragment_timeline_node)
975 fragment_timeline_node = find_child_node_by_name(fragment_template_node, "SegmentTimeline");
976 if (!fragment_timeline_node)
977 fragment_timeline_node = find_child_node_by_name(adaptionset_segmentlist_node, "SegmentTimeline");
978 if (!fragment_timeline_node)
979 fragment_timeline_node = find_child_node_by_name(period_segmentlist_node, "SegmentTimeline");
980 if (fragment_timeline_node) {
981 fragment_timeline_node = xmlFirstElementChild(fragment_timeline_node);
982 while (fragment_timeline_node) {
983 ret = parse_manifest_segmenttimeline(s, rep, fragment_timeline_node);
987 fragment_timeline_node = xmlNextElementSibling(fragment_timeline_node);
990 } else if (representation_baseurl_node && !representation_segmentlist_node) {
991 seg = av_mallocz(sizeof(struct fragment));
993 ret = AVERROR(ENOMEM);
996 seg->url = get_content_url(baseurl_nodes, 4, c->max_url_size, rep_id_val, rep_bandwidth_val, NULL);
999 ret = AVERROR(ENOMEM);
1003 dynarray_add(&rep->fragments, &rep->n_fragments, seg);
1004 } else if (representation_segmentlist_node) {
1005 // TODO: https://www.brendanlong.com/the-structure-of-an-mpeg-dash-mpd.html
1006 // http://www-itec.uni-klu.ac.at/dash/ddash/mpdGenerator.php?fragmentlength=15&type=full
1007 xmlNodePtr fragmenturl_node = NULL;
1008 segmentlists_tab[0] = representation_segmentlist_node;
1009 segmentlists_tab[1] = adaptionset_segmentlist_node;
1010 segmentlists_tab[2] = period_segmentlist_node;
1012 duration_val = get_val_from_nodes_tab(segmentlists_tab, 3, "duration");
1013 timescale_val = get_val_from_nodes_tab(segmentlists_tab, 3, "timescale");
1014 startnumber_val = get_val_from_nodes_tab(segmentlists_tab, 3, "startNumber");
1016 rep->fragment_duration = (int64_t) strtoll(duration_val, NULL, 10);
1017 av_log(s, AV_LOG_TRACE, "rep->fragment_duration = [%"PRId64"]\n", rep->fragment_duration);
1018 xmlFree(duration_val);
1020 if (timescale_val) {
1021 rep->fragment_timescale = (int64_t) strtoll(timescale_val, NULL, 10);
1022 av_log(s, AV_LOG_TRACE, "rep->fragment_timescale = [%"PRId64"]\n", rep->fragment_timescale);
1023 xmlFree(timescale_val);
1025 if (startnumber_val) {
1026 rep->start_number = rep->first_seq_no = (int64_t) strtoll(startnumber_val, NULL, 10);
1027 av_log(s, AV_LOG_TRACE, "rep->first_seq_no = [%"PRId64"]\n", rep->first_seq_no);
1028 xmlFree(startnumber_val);
1031 fragmenturl_node = xmlFirstElementChild(representation_segmentlist_node);
1032 while (fragmenturl_node) {
1033 ret = parse_manifest_segmenturlnode(s, rep, fragmenturl_node,
1040 fragmenturl_node = xmlNextElementSibling(fragmenturl_node);
1043 fragment_timeline_node = find_child_node_by_name(adaptionset_segmentlist_node, "SegmentTimeline");
1044 if (!fragment_timeline_node)
1045 fragment_timeline_node = find_child_node_by_name(period_segmentlist_node, "SegmentTimeline");
1046 if (fragment_timeline_node) {
1047 fragment_timeline_node = xmlFirstElementChild(fragment_timeline_node);
1048 while (fragment_timeline_node) {
1049 ret = parse_manifest_segmenttimeline(s, rep, fragment_timeline_node);
1053 fragment_timeline_node = xmlNextElementSibling(fragment_timeline_node);
1057 free_representation(rep);
1059 av_log(s, AV_LOG_ERROR, "Unknown format of Representation node id[%s] \n", (const char *)rep_id_val);
1063 if (rep->fragment_duration > 0 && !rep->fragment_timescale)
1064 rep->fragment_timescale = 1;
1065 rep->bandwidth = rep_bandwidth_val ? atoi(rep_bandwidth_val) : 0;
1066 strncpy(rep->id, rep_id_val ? rep_id_val : "", sizeof(rep->id));
1067 rep->framerate = av_make_q(0, 0);
1068 if (type == AVMEDIA_TYPE_VIDEO && rep_framerate_val) {
1069 ret = av_parse_video_rate(&rep->framerate, rep_framerate_val);
1071 av_log(s, AV_LOG_VERBOSE, "Ignoring invalid frame rate '%s'\n", rep_framerate_val);
1075 case AVMEDIA_TYPE_VIDEO:
1076 rep->rep_idx = video_rep_idx;
1077 dynarray_add(&c->videos, &c->n_videos, rep);
1079 case AVMEDIA_TYPE_AUDIO:
1080 rep->rep_idx = audio_rep_idx;
1081 dynarray_add(&c->audios, &c->n_audios, rep);
1083 case AVMEDIA_TYPE_SUBTITLE:
1084 rep->rep_idx = subtitle_rep_idx;
1085 dynarray_add(&c->subtitles, &c->n_subtitles, rep);
1088 av_log(s, AV_LOG_WARNING, "Unsupported the stream type %d\n", type);
1094 video_rep_idx += type == AVMEDIA_TYPE_VIDEO;
1095 audio_rep_idx += type == AVMEDIA_TYPE_AUDIO;
1096 subtitle_rep_idx += type == AVMEDIA_TYPE_SUBTITLE;
1100 xmlFree(rep_id_val);
1101 if (rep_bandwidth_val)
1102 xmlFree(rep_bandwidth_val);
1103 if (rep_framerate_val)
1104 xmlFree(rep_framerate_val);
1109 static int parse_manifest_adaptationset_attr(AVFormatContext *s, xmlNodePtr adaptionset_node)
1111 DASHContext *c = s->priv_data;
1113 if (!adaptionset_node) {
1114 av_log(s, AV_LOG_WARNING, "Cannot get AdaptionSet\n");
1115 return AVERROR(EINVAL);
1117 c->adaptionset_lang = xmlGetProp(adaptionset_node, "lang");
1122 static int parse_manifest_adaptationset(AVFormatContext *s, const char *url,
1123 xmlNodePtr adaptionset_node,
1124 xmlNodePtr mpd_baseurl_node,
1125 xmlNodePtr period_baseurl_node,
1126 xmlNodePtr period_segmenttemplate_node,
1127 xmlNodePtr period_segmentlist_node)
1130 DASHContext *c = s->priv_data;
1131 xmlNodePtr fragment_template_node = NULL;
1132 xmlNodePtr content_component_node = NULL;
1133 xmlNodePtr adaptionset_baseurl_node = NULL;
1134 xmlNodePtr adaptionset_segmentlist_node = NULL;
1135 xmlNodePtr adaptionset_supplementalproperty_node = NULL;
1136 xmlNodePtr node = NULL;
1138 ret = parse_manifest_adaptationset_attr(s, adaptionset_node);
1142 node = xmlFirstElementChild(adaptionset_node);
1144 if (!av_strcasecmp(node->name, (const char *)"SegmentTemplate")) {
1145 fragment_template_node = node;
1146 } else if (!av_strcasecmp(node->name, (const char *)"ContentComponent")) {
1147 content_component_node = node;
1148 } else if (!av_strcasecmp(node->name, (const char *)"BaseURL")) {
1149 adaptionset_baseurl_node = node;
1150 } else if (!av_strcasecmp(node->name, (const char *)"SegmentList")) {
1151 adaptionset_segmentlist_node = node;
1152 } else if (!av_strcasecmp(node->name, (const char *)"SupplementalProperty")) {
1153 adaptionset_supplementalproperty_node = node;
1154 } else if (!av_strcasecmp(node->name, (const char *)"Representation")) {
1155 ret = parse_manifest_representation(s, url, node,
1158 period_baseurl_node,
1159 period_segmenttemplate_node,
1160 period_segmentlist_node,
1161 fragment_template_node,
1162 content_component_node,
1163 adaptionset_baseurl_node,
1164 adaptionset_segmentlist_node,
1165 adaptionset_supplementalproperty_node);
1169 node = xmlNextElementSibling(node);
1173 av_freep(&c->adaptionset_lang);
1177 static int parse_programinformation(AVFormatContext *s, xmlNodePtr node)
1179 xmlChar *val = NULL;
1181 node = xmlFirstElementChild(node);
1183 if (!av_strcasecmp(node->name, "Title")) {
1184 val = xmlNodeGetContent(node);
1186 av_dict_set(&s->metadata, "Title", val, 0);
1188 } else if (!av_strcasecmp(node->name, "Source")) {
1189 val = xmlNodeGetContent(node);
1191 av_dict_set(&s->metadata, "Source", val, 0);
1193 } else if (!av_strcasecmp(node->name, "Copyright")) {
1194 val = xmlNodeGetContent(node);
1196 av_dict_set(&s->metadata, "Copyright", val, 0);
1199 node = xmlNextElementSibling(node);
1206 static int parse_manifest(AVFormatContext *s, const char *url, AVIOContext *in)
1208 DASHContext *c = s->priv_data;
1211 uint8_t *new_url = NULL;
1212 int64_t filesize = 0;
1214 AVDictionary *opts = NULL;
1216 xmlNodePtr root_element = NULL;
1217 xmlNodePtr node = NULL;
1218 xmlNodePtr period_node = NULL;
1219 xmlNodePtr tmp_node = NULL;
1220 xmlNodePtr mpd_baseurl_node = NULL;
1221 xmlNodePtr period_baseurl_node = NULL;
1222 xmlNodePtr period_segmenttemplate_node = NULL;
1223 xmlNodePtr period_segmentlist_node = NULL;
1224 xmlNodePtr adaptionset_node = NULL;
1225 xmlAttrPtr attr = NULL;
1227 uint32_t period_duration_sec = 0;
1228 uint32_t period_start_sec = 0;
1233 av_dict_copy(&opts, c->avio_opts, 0);
1234 ret = avio_open2(&in, url, AVIO_FLAG_READ, c->interrupt_callback, &opts);
1235 av_dict_free(&opts);
1240 if (av_opt_get(in, "location", AV_OPT_SEARCH_CHILDREN, &new_url) >= 0) {
1241 c->base_url = av_strdup(new_url);
1243 c->base_url = av_strdup(url);
1246 filesize = avio_size(in);
1247 filesize = filesize > 0 ? filesize : DEFAULT_MANIFEST_SIZE;
1249 if (filesize > MAX_BPRINT_READ_SIZE) {
1250 av_log(s, AV_LOG_ERROR, "Manifest too large: %"PRId64"\n", filesize);
1251 return AVERROR_INVALIDDATA;
1254 av_bprint_init(&buf, filesize + 1, AV_BPRINT_SIZE_UNLIMITED);
1256 if ((ret = avio_read_to_bprint(in, &buf, MAX_BPRINT_READ_SIZE)) < 0 ||
1258 (filesize = buf.len) == 0) {
1259 av_log(s, AV_LOG_ERROR, "Unable to read to manifest '%s'\n", url);
1261 ret = AVERROR_INVALIDDATA;
1265 doc = xmlReadMemory(buf.str, filesize, c->base_url, NULL, 0);
1266 root_element = xmlDocGetRootElement(doc);
1267 node = root_element;
1270 ret = AVERROR_INVALIDDATA;
1271 av_log(s, AV_LOG_ERROR, "Unable to parse '%s' - missing root node\n", url);
1275 if (node->type != XML_ELEMENT_NODE ||
1276 av_strcasecmp(node->name, (const char *)"MPD")) {
1277 ret = AVERROR_INVALIDDATA;
1278 av_log(s, AV_LOG_ERROR, "Unable to parse '%s' - wrong root node name[%s] type[%d]\n", url, node->name, (int)node->type);
1282 val = xmlGetProp(node, "type");
1284 av_log(s, AV_LOG_ERROR, "Unable to parse '%s' - missing type attrib\n", url);
1285 ret = AVERROR_INVALIDDATA;
1288 if (!av_strcasecmp(val, (const char *)"dynamic"))
1292 attr = node->properties;
1294 val = xmlGetProp(node, attr->name);
1296 if (!av_strcasecmp(attr->name, (const char *)"availabilityStartTime")) {
1297 c->availability_start_time = get_utc_date_time_insec(s, (const char *)val);
1298 av_log(s, AV_LOG_TRACE, "c->availability_start_time = [%"PRId64"]\n", c->availability_start_time);
1299 } else if (!av_strcasecmp(attr->name, (const char *)"availabilityEndTime")) {
1300 c->availability_end_time = get_utc_date_time_insec(s, (const char *)val);
1301 av_log(s, AV_LOG_TRACE, "c->availability_end_time = [%"PRId64"]\n", c->availability_end_time);
1302 } else if (!av_strcasecmp(attr->name, (const char *)"publishTime")) {
1303 c->publish_time = get_utc_date_time_insec(s, (const char *)val);
1304 av_log(s, AV_LOG_TRACE, "c->publish_time = [%"PRId64"]\n", c->publish_time);
1305 } else if (!av_strcasecmp(attr->name, (const char *)"minimumUpdatePeriod")) {
1306 c->minimum_update_period = get_duration_insec(s, (const char *)val);
1307 av_log(s, AV_LOG_TRACE, "c->minimum_update_period = [%"PRId64"]\n", c->minimum_update_period);
1308 } else if (!av_strcasecmp(attr->name, (const char *)"timeShiftBufferDepth")) {
1309 c->time_shift_buffer_depth = get_duration_insec(s, (const char *)val);
1310 av_log(s, AV_LOG_TRACE, "c->time_shift_buffer_depth = [%"PRId64"]\n", c->time_shift_buffer_depth);
1311 } else if (!av_strcasecmp(attr->name, (const char *)"minBufferTime")) {
1312 c->min_buffer_time = get_duration_insec(s, (const char *)val);
1313 av_log(s, AV_LOG_TRACE, "c->min_buffer_time = [%"PRId64"]\n", c->min_buffer_time);
1314 } else if (!av_strcasecmp(attr->name, (const char *)"suggestedPresentationDelay")) {
1315 c->suggested_presentation_delay = get_duration_insec(s, (const char *)val);
1316 av_log(s, AV_LOG_TRACE, "c->suggested_presentation_delay = [%"PRId64"]\n", c->suggested_presentation_delay);
1317 } else if (!av_strcasecmp(attr->name, (const char *)"mediaPresentationDuration")) {
1318 c->media_presentation_duration = get_duration_insec(s, (const char *)val);
1319 av_log(s, AV_LOG_TRACE, "c->media_presentation_duration = [%"PRId64"]\n", c->media_presentation_duration);
1325 tmp_node = find_child_node_by_name(node, "BaseURL");
1327 mpd_baseurl_node = xmlCopyNode(tmp_node,1);
1329 mpd_baseurl_node = xmlNewNode(NULL, "BaseURL");
1332 // at now we can handle only one period, with the longest duration
1333 node = xmlFirstElementChild(node);
1335 if (!av_strcasecmp(node->name, (const char *)"Period")) {
1336 period_duration_sec = 0;
1337 period_start_sec = 0;
1338 attr = node->properties;
1340 val = xmlGetProp(node, attr->name);
1341 if (!av_strcasecmp(attr->name, (const char *)"duration")) {
1342 period_duration_sec = get_duration_insec(s, (const char *)val);
1343 } else if (!av_strcasecmp(attr->name, (const char *)"start")) {
1344 period_start_sec = get_duration_insec(s, (const char *)val);
1349 if ((period_duration_sec) >= (c->period_duration)) {
1351 c->period_duration = period_duration_sec;
1352 c->period_start = period_start_sec;
1353 if (c->period_start > 0)
1354 c->media_presentation_duration = c->period_duration;
1356 } else if (!av_strcasecmp(node->name, "ProgramInformation")) {
1357 parse_programinformation(s, node);
1359 node = xmlNextElementSibling(node);
1362 av_log(s, AV_LOG_ERROR, "Unable to parse '%s' - missing Period node\n", url);
1363 ret = AVERROR_INVALIDDATA;
1367 adaptionset_node = xmlFirstElementChild(period_node);
1368 while (adaptionset_node) {
1369 if (!av_strcasecmp(adaptionset_node->name, (const char *)"BaseURL")) {
1370 period_baseurl_node = adaptionset_node;
1371 } else if (!av_strcasecmp(adaptionset_node->name, (const char *)"SegmentTemplate")) {
1372 period_segmenttemplate_node = adaptionset_node;
1373 } else if (!av_strcasecmp(adaptionset_node->name, (const char *)"SegmentList")) {
1374 period_segmentlist_node = adaptionset_node;
1375 } else if (!av_strcasecmp(adaptionset_node->name, (const char *)"AdaptationSet")) {
1376 parse_manifest_adaptationset(s, url, adaptionset_node, mpd_baseurl_node, period_baseurl_node, period_segmenttemplate_node, period_segmentlist_node);
1378 adaptionset_node = xmlNextElementSibling(adaptionset_node);
1381 /*free the document */
1384 xmlFreeNode(mpd_baseurl_node);
1388 av_bprint_finalize(&buf, NULL);
1395 static int64_t calc_cur_seg_no(AVFormatContext *s, struct representation *pls)
1397 DASHContext *c = s->priv_data;
1399 int64_t start_time_offset = 0;
1402 if (pls->n_fragments) {
1403 av_log(s, AV_LOG_TRACE, "in n_fragments mode\n");
1404 num = pls->first_seq_no;
1405 } else if (pls->n_timelines) {
1406 av_log(s, AV_LOG_TRACE, "in n_timelines mode\n");
1407 start_time_offset = get_segment_start_time_based_on_timeline(pls, 0xFFFFFFFF) - 60 * pls->fragment_timescale; // 60 seconds before end
1408 num = calc_next_seg_no_from_timelines(pls, start_time_offset);
1410 num = pls->first_seq_no;
1412 num += pls->first_seq_no;
1413 } else if (pls->fragment_duration){
1414 av_log(s, AV_LOG_TRACE, "in fragment_duration mode fragment_timescale = %"PRId64", presentation_timeoffset = %"PRId64"\n", pls->fragment_timescale, pls->presentation_timeoffset);
1415 if (pls->presentation_timeoffset) {
1416 num = pls->first_seq_no + (((get_current_time_in_sec() - c->availability_start_time) * pls->fragment_timescale)-pls->presentation_timeoffset) / pls->fragment_duration - c->min_buffer_time;
1417 } else if (c->publish_time > 0 && !c->availability_start_time) {
1418 if (c->min_buffer_time) {
1419 num = pls->first_seq_no + (((c->publish_time + pls->fragment_duration) - c->suggested_presentation_delay) * pls->fragment_timescale) / pls->fragment_duration - c->min_buffer_time;
1421 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;
1424 num = pls->first_seq_no + (((get_current_time_in_sec() - c->availability_start_time) - c->suggested_presentation_delay) * pls->fragment_timescale) / pls->fragment_duration;
1428 num = pls->first_seq_no;
1433 static int64_t calc_min_seg_no(AVFormatContext *s, struct representation *pls)
1435 DASHContext *c = s->priv_data;
1438 if (c->is_live && pls->fragment_duration) {
1439 av_log(s, AV_LOG_TRACE, "in live mode\n");
1440 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;
1442 num = pls->first_seq_no;
1447 static int64_t calc_max_seg_no(struct representation *pls, DASHContext *c)
1451 if (pls->n_fragments) {
1452 num = pls->first_seq_no + pls->n_fragments - 1;
1453 } else if (pls->n_timelines) {
1455 num = pls->first_seq_no + pls->n_timelines - 1;
1456 for (i = 0; i < pls->n_timelines; i++) {
1457 if (pls->timelines[i]->repeat == -1) {
1458 int length_of_each_segment = pls->timelines[i]->duration / pls->fragment_timescale;
1459 num = c->period_duration / length_of_each_segment;
1461 num += pls->timelines[i]->repeat;
1464 } else if (c->is_live && pls->fragment_duration) {
1465 num = pls->first_seq_no + (((get_current_time_in_sec() - c->availability_start_time)) * pls->fragment_timescale) / pls->fragment_duration;
1466 } else if (pls->fragment_duration) {
1467 num = pls->first_seq_no + (c->media_presentation_duration * pls->fragment_timescale) / pls->fragment_duration;
1473 static void move_timelines(struct representation *rep_src, struct representation *rep_dest, DASHContext *c)
1475 if (rep_dest && rep_src ) {
1476 free_timelines_list(rep_dest);
1477 rep_dest->timelines = rep_src->timelines;
1478 rep_dest->n_timelines = rep_src->n_timelines;
1479 rep_dest->first_seq_no = rep_src->first_seq_no;
1480 rep_dest->last_seq_no = calc_max_seg_no(rep_dest, c);
1481 rep_src->timelines = NULL;
1482 rep_src->n_timelines = 0;
1483 rep_dest->cur_seq_no = rep_src->cur_seq_no;
1487 static void move_segments(struct representation *rep_src, struct representation *rep_dest, DASHContext *c)
1489 if (rep_dest && rep_src ) {
1490 free_fragment_list(rep_dest);
1491 if (rep_src->start_number > (rep_dest->start_number + rep_dest->n_fragments))
1492 rep_dest->cur_seq_no = 0;
1494 rep_dest->cur_seq_no += rep_src->start_number - rep_dest->start_number;
1495 rep_dest->fragments = rep_src->fragments;
1496 rep_dest->n_fragments = rep_src->n_fragments;
1497 rep_dest->parent = rep_src->parent;
1498 rep_dest->last_seq_no = calc_max_seg_no(rep_dest, c);
1499 rep_src->fragments = NULL;
1500 rep_src->n_fragments = 0;
1505 static int refresh_manifest(AVFormatContext *s)
1508 DASHContext *c = s->priv_data;
1509 // save current context
1510 int n_videos = c->n_videos;
1511 struct representation **videos = c->videos;
1512 int n_audios = c->n_audios;
1513 struct representation **audios = c->audios;
1514 int n_subtitles = c->n_subtitles;
1515 struct representation **subtitles = c->subtitles;
1516 char *base_url = c->base_url;
1524 c->subtitles = NULL;
1525 ret = parse_manifest(s, s->url, NULL);
1529 if (c->n_videos != n_videos) {
1530 av_log(c, AV_LOG_ERROR,
1531 "new manifest has mismatched no. of video representations, %d -> %d\n",
1532 n_videos, c->n_videos);
1533 return AVERROR_INVALIDDATA;
1535 if (c->n_audios != n_audios) {
1536 av_log(c, AV_LOG_ERROR,
1537 "new manifest has mismatched no. of audio representations, %d -> %d\n",
1538 n_audios, c->n_audios);
1539 return AVERROR_INVALIDDATA;
1541 if (c->n_subtitles != n_subtitles) {
1542 av_log(c, AV_LOG_ERROR,
1543 "new manifest has mismatched no. of subtitles representations, %d -> %d\n",
1544 n_subtitles, c->n_subtitles);
1545 return AVERROR_INVALIDDATA;
1548 for (i = 0; i < n_videos; i++) {
1549 struct representation *cur_video = videos[i];
1550 struct representation *ccur_video = c->videos[i];
1551 if (cur_video->timelines) {
1552 // calc current time
1553 int64_t currentTime = get_segment_start_time_based_on_timeline(cur_video, cur_video->cur_seq_no) / cur_video->fragment_timescale;
1555 ccur_video->cur_seq_no = calc_next_seg_no_from_timelines(ccur_video, currentTime * cur_video->fragment_timescale - 1);
1556 if (ccur_video->cur_seq_no >= 0) {
1557 move_timelines(ccur_video, cur_video, c);
1560 if (cur_video->fragments) {
1561 move_segments(ccur_video, cur_video, c);
1564 for (i = 0; i < n_audios; i++) {
1565 struct representation *cur_audio = audios[i];
1566 struct representation *ccur_audio = c->audios[i];
1567 if (cur_audio->timelines) {
1568 // calc current time
1569 int64_t currentTime = get_segment_start_time_based_on_timeline(cur_audio, cur_audio->cur_seq_no) / cur_audio->fragment_timescale;
1571 ccur_audio->cur_seq_no = calc_next_seg_no_from_timelines(ccur_audio, currentTime * cur_audio->fragment_timescale - 1);
1572 if (ccur_audio->cur_seq_no >= 0) {
1573 move_timelines(ccur_audio, cur_audio, c);
1576 if (cur_audio->fragments) {
1577 move_segments(ccur_audio, cur_audio, c);
1586 c->base_url = base_url;
1589 free_subtitle_list(c);
1595 c->n_subtitles = n_subtitles;
1596 c->subtitles = subtitles;
1597 c->n_audios = n_audios;
1599 c->n_videos = n_videos;
1604 static struct fragment *get_current_fragment(struct representation *pls)
1606 int64_t min_seq_no = 0;
1607 int64_t max_seq_no = 0;
1608 struct fragment *seg = NULL;
1609 struct fragment *seg_ptr = NULL;
1610 DASHContext *c = pls->parent->priv_data;
1612 while (( !ff_check_interrupt(c->interrupt_callback)&& pls->n_fragments > 0)) {
1613 if (pls->cur_seq_no < pls->n_fragments) {
1614 seg_ptr = pls->fragments[pls->cur_seq_no];
1615 seg = av_mallocz(sizeof(struct fragment));
1619 seg->url = av_strdup(seg_ptr->url);
1624 seg->size = seg_ptr->size;
1625 seg->url_offset = seg_ptr->url_offset;
1627 } else if (c->is_live) {
1628 refresh_manifest(pls->parent);
1634 min_seq_no = calc_min_seg_no(pls->parent, pls);
1635 max_seq_no = calc_max_seg_no(pls, c);
1637 if (pls->timelines || pls->fragments) {
1638 refresh_manifest(pls->parent);
1640 if (pls->cur_seq_no <= min_seq_no) {
1641 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);
1642 pls->cur_seq_no = calc_cur_seg_no(pls->parent, pls);
1643 } else if (pls->cur_seq_no > max_seq_no) {
1644 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);
1646 seg = av_mallocz(sizeof(struct fragment));
1650 } else if (pls->cur_seq_no <= pls->last_seq_no) {
1651 seg = av_mallocz(sizeof(struct fragment));
1657 char *tmpfilename= av_mallocz(c->max_url_size);
1661 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));
1662 seg->url = av_strireplace(pls->url_template, pls->url_template, tmpfilename);
1664 av_log(pls->parent, AV_LOG_WARNING, "Unable to resolve template url '%s', try to use origin template\n", pls->url_template);
1665 seg->url = av_strdup(pls->url_template);
1667 av_log(pls->parent, AV_LOG_ERROR, "Cannot resolve template url '%s'\n", pls->url_template);
1668 av_free(tmpfilename);
1672 av_free(tmpfilename);
1679 static int read_from_url(struct representation *pls, struct fragment *seg,
1680 uint8_t *buf, int buf_size)
1684 /* limit read if the fragment was only a part of a file */
1686 buf_size = FFMIN(buf_size, pls->cur_seg_size - pls->cur_seg_offset);
1688 ret = avio_read(pls->input, buf, buf_size);
1690 pls->cur_seg_offset += ret;
1695 static int open_input(DASHContext *c, struct representation *pls, struct fragment *seg)
1697 AVDictionary *opts = NULL;
1701 url = av_mallocz(c->max_url_size);
1703 ret = AVERROR(ENOMEM);
1707 if (seg->size >= 0) {
1708 /* try to restrict the HTTP request to the part we want
1709 * (if this is in fact a HTTP request) */
1710 av_dict_set_int(&opts, "offset", seg->url_offset, 0);
1711 av_dict_set_int(&opts, "end_offset", seg->url_offset + seg->size, 0);
1714 ff_make_absolute_url(url, c->max_url_size, c->base_url, seg->url);
1715 av_log(pls->parent, AV_LOG_VERBOSE, "DASH request for url '%s', offset %"PRId64", playlist %d\n",
1716 url, seg->url_offset, pls->rep_idx);
1717 ret = open_url(pls->parent, &pls->input, url, c->avio_opts, opts, NULL);
1721 av_dict_free(&opts);
1722 pls->cur_seg_offset = 0;
1723 pls->cur_seg_size = seg->size;
1727 static int update_init_section(struct representation *pls)
1729 static const int max_init_section_size = 1024 * 1024;
1730 DASHContext *c = pls->parent->priv_data;
1735 if (!pls->init_section || pls->init_sec_buf)
1738 ret = open_input(c, pls, pls->init_section);
1740 av_log(pls->parent, AV_LOG_WARNING,
1741 "Failed to open an initialization section in playlist %d\n",
1746 if (pls->init_section->size >= 0)
1747 sec_size = pls->init_section->size;
1748 else if ((urlsize = avio_size(pls->input)) >= 0)
1751 sec_size = max_init_section_size;
1753 av_log(pls->parent, AV_LOG_DEBUG,
1754 "Downloading an initialization section of size %"PRId64"\n",
1757 sec_size = FFMIN(sec_size, max_init_section_size);
1759 av_fast_malloc(&pls->init_sec_buf, &pls->init_sec_buf_size, sec_size);
1761 ret = read_from_url(pls, pls->init_section, pls->init_sec_buf,
1762 pls->init_sec_buf_size);
1763 ff_format_io_close(pls->parent, &pls->input);
1768 pls->init_sec_data_len = ret;
1769 pls->init_sec_buf_read_offset = 0;
1774 static int64_t seek_data(void *opaque, int64_t offset, int whence)
1776 struct representation *v = opaque;
1777 if (v->n_fragments && !v->init_sec_data_len) {
1778 return avio_seek(v->input, offset, whence);
1781 return AVERROR(ENOSYS);
1784 static int read_data(void *opaque, uint8_t *buf, int buf_size)
1787 struct representation *v = opaque;
1788 DASHContext *c = v->parent->priv_data;
1792 free_fragment(&v->cur_seg);
1793 v->cur_seg = get_current_fragment(v);
1799 /* load/update Media Initialization Section, if any */
1800 ret = update_init_section(v);
1804 ret = open_input(c, v, v->cur_seg);
1806 if (ff_check_interrupt(c->interrupt_callback)) {
1810 av_log(v->parent, AV_LOG_WARNING, "Failed to open fragment of playlist %d\n", v->rep_idx);
1816 if (v->init_sec_buf_read_offset < v->init_sec_data_len) {
1817 /* Push init section out first before first actual fragment */
1818 int copy_size = FFMIN(v->init_sec_data_len - v->init_sec_buf_read_offset, buf_size);
1819 memcpy(buf, v->init_sec_buf, copy_size);
1820 v->init_sec_buf_read_offset += copy_size;
1825 /* check the v->cur_seg, if it is null, get current and double check if the new v->cur_seg*/
1827 v->cur_seg = get_current_fragment(v);
1833 ret = read_from_url(v, v->cur_seg, buf, buf_size);
1837 if (c->is_live || v->cur_seq_no < v->last_seq_no) {
1838 if (!v->is_restart_needed)
1840 v->is_restart_needed = 1;
1847 static int save_avio_options(AVFormatContext *s)
1849 DASHContext *c = s->priv_data;
1850 const char *opts[] = {
1851 "headers", "user_agent", "cookies", "http_proxy", "referer", "rw_timeout", "icy", NULL };
1852 const char **opt = opts;
1853 uint8_t *buf = NULL;
1857 if (av_opt_get(s->pb, *opt, AV_OPT_SEARCH_CHILDREN, &buf) >= 0) {
1858 if (buf[0] != '\0') {
1859 ret = av_dict_set(&c->avio_opts, *opt, buf, AV_DICT_DONT_STRDUP_VAL);
1872 static int nested_io_open(AVFormatContext *s, AVIOContext **pb, const char *url,
1873 int flags, AVDictionary **opts)
1875 av_log(s, AV_LOG_ERROR,
1876 "A DASH playlist item '%s' referred to an external file '%s'. "
1877 "Opening this file was forbidden for security reasons\n",
1879 return AVERROR(EPERM);
1882 static void close_demux_for_component(struct representation *pls)
1884 /* note: the internal buffer could have changed */
1885 av_freep(&pls->pb.buffer);
1886 memset(&pls->pb, 0x00, sizeof(AVIOContext));
1887 pls->ctx->pb = NULL;
1888 avformat_close_input(&pls->ctx);
1891 static int reopen_demux_for_component(AVFormatContext *s, struct representation *pls)
1893 DASHContext *c = s->priv_data;
1894 ff_const59 AVInputFormat *in_fmt = NULL;
1895 AVDictionary *in_fmt_opts = NULL;
1896 uint8_t *avio_ctx_buffer = NULL;
1900 close_demux_for_component(pls);
1903 if (ff_check_interrupt(&s->interrupt_callback)) {
1908 if (!(pls->ctx = avformat_alloc_context())) {
1909 ret = AVERROR(ENOMEM);
1913 avio_ctx_buffer = av_malloc(INITIAL_BUFFER_SIZE);
1914 if (!avio_ctx_buffer ) {
1915 ret = AVERROR(ENOMEM);
1916 avformat_free_context(pls->ctx);
1921 ffio_init_context(&pls->pb, avio_ctx_buffer , INITIAL_BUFFER_SIZE, 0, pls, read_data, NULL, NULL);
1923 ffio_init_context(&pls->pb, avio_ctx_buffer , INITIAL_BUFFER_SIZE, 0, pls, read_data, NULL, seek_data);
1925 pls->pb.seekable = 0;
1927 if ((ret = ff_copy_whiteblacklists(pls->ctx, s)) < 0)
1930 pls->ctx->flags = AVFMT_FLAG_CUSTOM_IO;
1931 pls->ctx->probesize = s->probesize > 0 ? s->probesize : 1024 * 4;
1932 pls->ctx->max_analyze_duration = s->max_analyze_duration > 0 ? s->max_analyze_duration : 4 * AV_TIME_BASE;
1933 pls->ctx->interrupt_callback = s->interrupt_callback;
1934 ret = av_probe_input_buffer(&pls->pb, &in_fmt, "", NULL, 0, 0);
1936 av_log(s, AV_LOG_ERROR, "Error when loading first fragment, playlist %d\n", (int)pls->rep_idx);
1937 avformat_free_context(pls->ctx);
1942 pls->ctx->pb = &pls->pb;
1943 pls->ctx->io_open = nested_io_open;
1945 // provide additional information from mpd if available
1946 ret = avformat_open_input(&pls->ctx, "", in_fmt, &in_fmt_opts); //pls->init_section->url
1947 av_dict_free(&in_fmt_opts);
1950 if (pls->n_fragments) {
1951 #if FF_API_R_FRAME_RATE
1952 if (pls->framerate.den) {
1953 for (i = 0; i < pls->ctx->nb_streams; i++)
1954 pls->ctx->streams[i]->r_frame_rate = pls->framerate;
1957 ret = avformat_find_stream_info(pls->ctx, NULL);
1966 static int open_demux_for_component(AVFormatContext *s, struct representation *pls)
1972 pls->cur_seq_no = calc_cur_seg_no(s, pls);
1974 if (!pls->last_seq_no) {
1975 pls->last_seq_no = calc_max_seg_no(pls, s->priv_data);
1978 ret = reopen_demux_for_component(s, pls);
1982 for (i = 0; i < pls->ctx->nb_streams; i++) {
1983 AVStream *st = avformat_new_stream(s, NULL);
1984 AVStream *ist = pls->ctx->streams[i];
1986 ret = AVERROR(ENOMEM);
1990 avcodec_parameters_copy(st->codecpar, ist->codecpar);
1991 avpriv_set_pts_info(st, ist->pts_wrap_bits, ist->time_base.num, ist->time_base.den);
1994 st->disposition = ist->disposition;
1997 for (int i = 0; i < ist->nb_side_data; i++) {
1998 const AVPacketSideData *sd_src = &ist->side_data[i];
2001 dst_data = av_stream_new_side_data(st, sd_src->type, sd_src->size);
2003 return AVERROR(ENOMEM);
2004 memcpy(dst_data, sd_src->data, sd_src->size);
2013 static int is_common_init_section_exist(struct representation **pls, int n_pls)
2015 struct fragment *first_init_section = pls[0]->init_section;
2017 int64_t url_offset = -1;
2021 if (first_init_section == NULL || n_pls == 0)
2024 url = first_init_section->url;
2025 url_offset = first_init_section->url_offset;
2026 size = pls[0]->init_section->size;
2027 for (i=0;i<n_pls;i++) {
2028 if (av_strcasecmp(pls[i]->init_section->url,url) || pls[i]->init_section->url_offset != url_offset || pls[i]->init_section->size != size) {
2035 static int copy_init_section(struct representation *rep_dest, struct representation *rep_src)
2037 rep_dest->init_sec_buf = av_mallocz(rep_src->init_sec_buf_size);
2038 if (!rep_dest->init_sec_buf) {
2039 av_log(rep_dest->ctx, AV_LOG_WARNING, "Cannot alloc memory for init_sec_buf\n");
2040 return AVERROR(ENOMEM);
2042 memcpy(rep_dest->init_sec_buf, rep_src->init_sec_buf, rep_src->init_sec_data_len);
2043 rep_dest->init_sec_buf_size = rep_src->init_sec_buf_size;
2044 rep_dest->init_sec_data_len = rep_src->init_sec_data_len;
2045 rep_dest->cur_timestamp = rep_src->cur_timestamp;
2051 static int dash_read_header(AVFormatContext *s)
2053 DASHContext *c = s->priv_data;
2054 struct representation *rep;
2056 int stream_index = 0;
2059 c->interrupt_callback = &s->interrupt_callback;
2061 if ((ret = save_avio_options(s)) < 0)
2064 if ((ret = parse_manifest(s, s->url, s->pb)) < 0)
2067 /* If this isn't a live stream, fill the total duration of the
2070 s->duration = (int64_t) c->media_presentation_duration * AV_TIME_BASE;
2072 av_dict_set(&c->avio_opts, "seekable", "0", 0);
2076 c->is_init_section_common_video = is_common_init_section_exist(c->videos, c->n_videos);
2078 /* Open the demuxer for video and audio components if available */
2079 for (i = 0; i < c->n_videos; i++) {
2081 if (i > 0 && c->is_init_section_common_video) {
2082 ret = copy_init_section(rep, c->videos[0]);
2086 ret = open_demux_for_component(s, rep);
2090 rep->stream_index = stream_index;
2095 c->is_init_section_common_audio = is_common_init_section_exist(c->audios, c->n_audios);
2097 for (i = 0; i < c->n_audios; i++) {
2099 if (i > 0 && c->is_init_section_common_audio) {
2100 ret = copy_init_section(rep, c->audios[0]);
2104 ret = open_demux_for_component(s, rep);
2108 rep->stream_index = stream_index;
2113 c->is_init_section_common_audio = is_common_init_section_exist(c->subtitles, c->n_subtitles);
2115 for (i = 0; i < c->n_subtitles; i++) {
2116 rep = c->subtitles[i];
2117 if (i > 0 && c->is_init_section_common_audio) {
2118 ret = copy_init_section(rep, c->subtitles[0]);
2122 ret = open_demux_for_component(s, rep);
2126 rep->stream_index = stream_index;
2130 if (!stream_index) {
2131 ret = AVERROR_INVALIDDATA;
2135 /* Create a program */
2138 program = av_new_program(s, 0);
2143 for (i = 0; i < c->n_videos; i++) {
2145 av_program_add_stream_index(s, 0, rep->stream_index);
2146 rep->assoc_stream = s->streams[rep->stream_index];
2147 if (rep->bandwidth > 0)
2148 av_dict_set_int(&rep->assoc_stream->metadata, "variant_bitrate", rep->bandwidth, 0);
2150 av_dict_set(&rep->assoc_stream->metadata, "id", rep->id, 0);
2152 for (i = 0; i < c->n_audios; i++) {
2154 av_program_add_stream_index(s, 0, rep->stream_index);
2155 rep->assoc_stream = s->streams[rep->stream_index];
2156 if (rep->bandwidth > 0)
2157 av_dict_set_int(&rep->assoc_stream->metadata, "variant_bitrate", rep->bandwidth, 0);
2159 av_dict_set(&rep->assoc_stream->metadata, "id", rep->id, 0);
2161 av_dict_set(&rep->assoc_stream->metadata, "language", rep->lang, 0);
2162 av_freep(&rep->lang);
2165 for (i = 0; i < c->n_subtitles; i++) {
2166 rep = c->subtitles[i];
2167 av_program_add_stream_index(s, 0, rep->stream_index);
2168 rep->assoc_stream = s->streams[rep->stream_index];
2170 av_dict_set(&rep->assoc_stream->metadata, "id", rep->id, 0);
2172 av_dict_set(&rep->assoc_stream->metadata, "language", rep->lang, 0);
2173 av_freep(&rep->lang);
2183 static void recheck_discard_flags(AVFormatContext *s, struct representation **p, int n)
2187 for (i = 0; i < n; i++) {
2188 struct representation *pls = p[i];
2189 int needed = !pls->assoc_stream || pls->assoc_stream->discard < AVDISCARD_ALL;
2191 if (needed && !pls->ctx) {
2192 pls->cur_seg_offset = 0;
2193 pls->init_sec_buf_read_offset = 0;
2195 for (j = 0; j < n; j++) {
2196 pls->cur_seq_no = FFMAX(pls->cur_seq_no, p[j]->cur_seq_no);
2198 reopen_demux_for_component(s, pls);
2199 av_log(s, AV_LOG_INFO, "Now receiving stream_index %d\n", pls->stream_index);
2200 } else if (!needed && pls->ctx) {
2201 close_demux_for_component(pls);
2202 ff_format_io_close(pls->parent, &pls->input);
2203 av_log(s, AV_LOG_INFO, "No longer receiving stream_index %d\n", pls->stream_index);
2208 static int dash_read_packet(AVFormatContext *s, AVPacket *pkt)
2210 DASHContext *c = s->priv_data;
2213 struct representation *cur = NULL;
2214 struct representation *rep = NULL;
2216 recheck_discard_flags(s, c->videos, c->n_videos);
2217 recheck_discard_flags(s, c->audios, c->n_audios);
2218 recheck_discard_flags(s, c->subtitles, c->n_subtitles);
2220 for (i = 0; i < c->n_videos; i++) {
2224 if (!cur || rep->cur_timestamp < mints) {
2226 mints = rep->cur_timestamp;
2229 for (i = 0; i < c->n_audios; i++) {
2233 if (!cur || rep->cur_timestamp < mints) {
2235 mints = rep->cur_timestamp;
2239 for (i = 0; i < c->n_subtitles; i++) {
2240 rep = c->subtitles[i];
2243 if (!cur || rep->cur_timestamp < mints) {
2245 mints = rep->cur_timestamp;
2250 return AVERROR_INVALIDDATA;
2252 while (!ff_check_interrupt(c->interrupt_callback) && !ret) {
2253 ret = av_read_frame(cur->ctx, pkt);
2255 /* If we got a packet, return it */
2256 cur->cur_timestamp = av_rescale(pkt->pts, (int64_t)cur->ctx->streams[0]->time_base.num * 90000, cur->ctx->streams[0]->time_base.den);
2257 pkt->stream_index = cur->stream_index;
2260 if (cur->is_restart_needed) {
2261 cur->cur_seg_offset = 0;
2262 cur->init_sec_buf_read_offset = 0;
2263 ff_format_io_close(cur->parent, &cur->input);
2264 ret = reopen_demux_for_component(s, cur);
2265 cur->is_restart_needed = 0;
2271 static int dash_close(AVFormatContext *s)
2273 DASHContext *c = s->priv_data;
2276 free_subtitle_list(c);
2277 av_dict_free(&c->avio_opts);
2278 av_freep(&c->base_url);
2282 static int dash_seek(AVFormatContext *s, struct representation *pls, int64_t seek_pos_msec, int flags, int dry_run)
2287 int64_t duration = 0;
2289 av_log(pls->parent, AV_LOG_VERBOSE, "DASH seek pos[%"PRId64"ms], playlist %d%s\n",
2290 seek_pos_msec, pls->rep_idx, dry_run ? " (dry)" : "");
2292 // single fragment mode
2293 if (pls->n_fragments == 1) {
2294 pls->cur_timestamp = 0;
2295 pls->cur_seg_offset = 0;
2298 ff_read_frame_flush(pls->ctx);
2299 return av_seek_frame(pls->ctx, -1, seek_pos_msec * 1000, flags);
2302 ff_format_io_close(pls->parent, &pls->input);
2304 // find the nearest fragment
2305 if (pls->n_timelines > 0 && pls->fragment_timescale > 0) {
2306 int64_t num = pls->first_seq_no;
2307 av_log(pls->parent, AV_LOG_VERBOSE, "dash_seek with SegmentTimeline start n_timelines[%d] "
2308 "last_seq_no[%"PRId64"], playlist %d.\n",
2309 (int)pls->n_timelines, (int64_t)pls->last_seq_no, (int)pls->rep_idx);
2310 for (i = 0; i < pls->n_timelines; i++) {
2311 if (pls->timelines[i]->starttime > 0) {
2312 duration = pls->timelines[i]->starttime;
2314 duration += pls->timelines[i]->duration;
2315 if (seek_pos_msec < ((duration * 1000) / pls->fragment_timescale)) {
2318 for (j = 0; j < pls->timelines[i]->repeat; j++) {
2319 duration += pls->timelines[i]->duration;
2321 if (seek_pos_msec < ((duration * 1000) / pls->fragment_timescale)) {
2329 pls->cur_seq_no = num > pls->last_seq_no ? pls->last_seq_no : num;
2330 av_log(pls->parent, AV_LOG_VERBOSE, "dash_seek with SegmentTimeline end cur_seq_no[%"PRId64"], playlist %d.\n",
2331 (int64_t)pls->cur_seq_no, (int)pls->rep_idx);
2332 } else if (pls->fragment_duration > 0) {
2333 pls->cur_seq_no = pls->first_seq_no + ((seek_pos_msec * pls->fragment_timescale) / pls->fragment_duration) / 1000;
2335 av_log(pls->parent, AV_LOG_ERROR, "dash_seek missing timeline or fragment_duration\n");
2336 pls->cur_seq_no = pls->first_seq_no;
2338 pls->cur_timestamp = 0;
2339 pls->cur_seg_offset = 0;
2340 pls->init_sec_buf_read_offset = 0;
2341 ret = dry_run ? 0 : reopen_demux_for_component(s, pls);
2346 static int dash_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
2349 DASHContext *c = s->priv_data;
2350 int64_t seek_pos_msec = av_rescale_rnd(timestamp, 1000,
2351 s->streams[stream_index]->time_base.den,
2352 flags & AVSEEK_FLAG_BACKWARD ?
2353 AV_ROUND_DOWN : AV_ROUND_UP);
2354 if ((flags & AVSEEK_FLAG_BYTE) || c->is_live)
2355 return AVERROR(ENOSYS);
2357 /* Seek in discarded streams with dry_run=1 to avoid reopening them */
2358 for (i = 0; i < c->n_videos; i++) {
2360 ret = dash_seek(s, c->videos[i], seek_pos_msec, flags, !c->videos[i]->ctx);
2362 for (i = 0; i < c->n_audios; i++) {
2364 ret = dash_seek(s, c->audios[i], seek_pos_msec, flags, !c->audios[i]->ctx);
2366 for (i = 0; i < c->n_subtitles; i++) {
2368 ret = dash_seek(s, c->subtitles[i], seek_pos_msec, flags, !c->subtitles[i]->ctx);
2374 static int dash_probe(const AVProbeData *p)
2376 if (!av_stristr(p->buf, "<MPD"))
2379 if (av_stristr(p->buf, "dash:profile:isoff-on-demand:2011") ||
2380 av_stristr(p->buf, "dash:profile:isoff-live:2011") ||
2381 av_stristr(p->buf, "dash:profile:isoff-live:2012") ||
2382 av_stristr(p->buf, "dash:profile:isoff-main:2011") ||
2383 av_stristr(p->buf, "3GPP:PSS:profile:DASH1")) {
2384 return AVPROBE_SCORE_MAX;
2386 if (av_stristr(p->buf, "dash:profile")) {
2387 return AVPROBE_SCORE_MAX;
2393 #define OFFSET(x) offsetof(DASHContext, x)
2394 #define FLAGS AV_OPT_FLAG_DECODING_PARAM
2395 static const AVOption dash_options[] = {
2396 {"allowed_extensions", "List of file extensions that dash is allowed to access",
2397 OFFSET(allowed_extensions), AV_OPT_TYPE_STRING,
2398 {.str = "aac,m4a,m4s,m4v,mov,mp4,webm,ts"},
2399 INT_MIN, INT_MAX, FLAGS},
2403 static const AVClass dash_class = {
2404 .class_name = "dash",
2405 .item_name = av_default_item_name,
2406 .option = dash_options,
2407 .version = LIBAVUTIL_VERSION_INT,
2410 AVInputFormat ff_dash_demuxer = {
2412 .long_name = NULL_IF_CONFIG_SMALL("Dynamic Adaptive Streaming over HTTP"),
2413 .priv_class = &dash_class,
2414 .priv_data_size = sizeof(DASHContext),
2415 .read_probe = dash_probe,
2416 .read_header = dash_read_header,
2417 .read_packet = dash_read_packet,
2418 .read_close = dash_close,
2419 .read_seek = dash_read_seek,
2420 .flags = AVFMT_NO_BYTE_SEEK,