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 av_dict_copy(&tmp, opts, 0);
411 av_dict_copy(&tmp, opts2, 0);
413 if (av_strstart(url, "crypto", NULL)) {
414 if (url[6] == '+' || url[6] == ':')
415 proto_name = avio_find_protocol_name(url + 7);
419 proto_name = avio_find_protocol_name(url);
422 return AVERROR_INVALIDDATA;
424 // only http(s) & file are allowed
425 if (av_strstart(proto_name, "file", NULL)) {
426 if (strcmp(c->allowed_extensions, "ALL") && !av_match_ext(url, c->allowed_extensions)) {
427 av_log(s, AV_LOG_ERROR,
428 "Filename extension of \'%s\' is not a common multimedia extension, blocked for security reasons.\n"
429 "If you wish to override this adjust allowed_extensions, you can set it to \'ALL\' to allow all\n",
431 return AVERROR_INVALIDDATA;
433 } else if (av_strstart(proto_name, "http", NULL)) {
436 return AVERROR_INVALIDDATA;
438 if (!strncmp(proto_name, url, strlen(proto_name)) && url[strlen(proto_name)] == ':')
440 else if (av_strstart(url, "crypto", NULL) && !strncmp(proto_name, url + 7, strlen(proto_name)) && url[7 + strlen(proto_name)] == ':')
442 else if (strcmp(proto_name, "file") || !strncmp(url, "file,", 5))
443 return AVERROR_INVALIDDATA;
446 ret = avio_open2(pb, url, AVIO_FLAG_READ, c->interrupt_callback, &tmp);
448 // update cookies on http response with setcookies.
449 char *new_cookies = NULL;
451 if (!(s->flags & AVFMT_FLAG_CUSTOM_IO))
452 av_opt_get(*pb, "cookies", AV_OPT_SEARCH_CHILDREN, (uint8_t**)&new_cookies);
455 av_dict_set(&opts, "cookies", new_cookies, AV_DICT_DONT_STRDUP_VAL);
463 *is_http = av_strstart(proto_name, "http", NULL);
468 static char *get_content_url(xmlNodePtr *baseurl_nodes,
472 char *rep_bandwidth_val,
478 char *tmp_str = av_mallocz(max_url_size);
479 char *tmp_str_2 = av_mallocz(max_url_size);
481 if (!tmp_str || !tmp_str_2) {
485 for (i = 0; i < n_baseurl_nodes; ++i) {
486 if (baseurl_nodes[i] &&
487 baseurl_nodes[i]->children &&
488 baseurl_nodes[i]->children->type == XML_TEXT_NODE) {
489 text = xmlNodeGetContent(baseurl_nodes[i]->children);
491 memset(tmp_str, 0, max_url_size);
492 memset(tmp_str_2, 0, max_url_size);
493 ff_make_absolute_url(tmp_str_2, max_url_size, tmp_str, text);
494 av_strlcpy(tmp_str, tmp_str_2, max_url_size);
501 ff_make_absolute_url(tmp_str, max_url_size, tmp_str, val);
504 url = av_strireplace(tmp_str, "$RepresentationID$", (const char*)rep_id_val);
508 av_strlcpy(tmp_str, url, max_url_size);
510 if (rep_bandwidth_val && tmp_str[0] != '\0') {
511 // free any previously assigned url before reassigning
513 url = av_strireplace(tmp_str, "$Bandwidth$", (const char*)rep_bandwidth_val);
524 static char *get_val_from_nodes_tab(xmlNodePtr *nodes, const int n_nodes, const char *attrname)
529 for (i = 0; i < n_nodes; ++i) {
531 val = xmlGetProp(nodes[i], attrname);
540 static xmlNodePtr find_child_node_by_name(xmlNodePtr rootnode, const char *nodename)
542 xmlNodePtr node = rootnode;
547 node = xmlFirstElementChild(node);
549 if (!av_strcasecmp(node->name, nodename)) {
552 node = xmlNextElementSibling(node);
557 static enum AVMediaType get_content_type(xmlNodePtr node)
559 enum AVMediaType type = AVMEDIA_TYPE_UNKNOWN;
565 for (i = 0; i < 2; i++) {
566 attr = i ? "mimeType" : "contentType";
567 val = xmlGetProp(node, attr);
569 if (av_stristr((const char *)val, "video")) {
570 type = AVMEDIA_TYPE_VIDEO;
571 } else if (av_stristr((const char *)val, "audio")) {
572 type = AVMEDIA_TYPE_AUDIO;
573 } else if (av_stristr((const char *)val, "text")) {
574 type = AVMEDIA_TYPE_SUBTITLE;
583 static struct fragment * get_Fragment(char *range)
585 struct fragment * seg = av_mallocz(sizeof(struct fragment));
592 char *str_end_offset;
593 char *str_offset = av_strtok(range, "-", &str_end_offset);
594 seg->url_offset = strtoll(str_offset, NULL, 10);
595 seg->size = strtoll(str_end_offset, NULL, 10) - seg->url_offset + 1;
601 static int parse_manifest_segmenturlnode(AVFormatContext *s, struct representation *rep,
602 xmlNodePtr fragmenturl_node,
603 xmlNodePtr *baseurl_nodes,
605 char *rep_bandwidth_val)
607 DASHContext *c = s->priv_data;
608 char *initialization_val = NULL;
609 char *media_val = NULL;
610 char *range_val = NULL;
611 int max_url_size = c ? c->max_url_size: MAX_URL_SIZE;
613 if (!av_strcasecmp(fragmenturl_node->name, (const char *)"Initialization")) {
614 initialization_val = xmlGetProp(fragmenturl_node, "sourceURL");
615 range_val = xmlGetProp(fragmenturl_node, "range");
616 if (initialization_val || range_val) {
617 rep->init_section = get_Fragment(range_val);
618 if (!rep->init_section) {
619 xmlFree(initialization_val);
621 return AVERROR(ENOMEM);
623 rep->init_section->url = get_content_url(baseurl_nodes, 4,
629 if (!rep->init_section->url) {
630 av_free(rep->init_section);
631 xmlFree(initialization_val);
633 return AVERROR(ENOMEM);
635 xmlFree(initialization_val);
638 } else if (!av_strcasecmp(fragmenturl_node->name, (const char *)"SegmentURL")) {
639 media_val = xmlGetProp(fragmenturl_node, "media");
640 range_val = xmlGetProp(fragmenturl_node, "mediaRange");
641 if (media_val || range_val) {
642 struct fragment *seg = get_Fragment(range_val);
646 return AVERROR(ENOMEM);
648 seg->url = get_content_url(baseurl_nodes, 4,
657 return AVERROR(ENOMEM);
659 dynarray_add(&rep->fragments, &rep->n_fragments, seg);
668 static int parse_manifest_segmenttimeline(AVFormatContext *s, struct representation *rep,
669 xmlNodePtr fragment_timeline_node)
671 xmlAttrPtr attr = NULL;
674 if (!av_strcasecmp(fragment_timeline_node->name, (const char *)"S")) {
675 struct timeline *tml = av_mallocz(sizeof(struct timeline));
677 return AVERROR(ENOMEM);
679 attr = fragment_timeline_node->properties;
681 val = xmlGetProp(fragment_timeline_node, attr->name);
684 av_log(s, AV_LOG_WARNING, "parse_manifest_segmenttimeline attr->name = %s val is NULL\n", attr->name);
688 if (!av_strcasecmp(attr->name, (const char *)"t")) {
689 tml->starttime = (int64_t)strtoll(val, NULL, 10);
690 } else if (!av_strcasecmp(attr->name, (const char *)"r")) {
691 tml->repeat =(int64_t) strtoll(val, NULL, 10);
692 } else if (!av_strcasecmp(attr->name, (const char *)"d")) {
693 tml->duration = (int64_t)strtoll(val, NULL, 10);
698 dynarray_add(&rep->timelines, &rep->n_timelines, tml);
704 static int resolve_content_path(AVFormatContext *s, const char *url, int *max_url_size, xmlNodePtr *baseurl_nodes, int n_baseurl_nodes)
706 char *tmp_str = NULL;
708 char *mpdName = NULL;
709 xmlNodePtr node = NULL;
710 char *baseurl = NULL;
711 char *root_url = NULL;
721 int tmp_max_url_size = strlen(url);
723 for (i = n_baseurl_nodes-1; i >= 0 ; i--) {
724 text = xmlNodeGetContent(baseurl_nodes[i]);
727 tmp_max_url_size += strlen(text);
735 tmp_max_url_size = aligned(tmp_max_url_size);
736 text = av_mallocz(tmp_max_url_size);
738 updated = AVERROR(ENOMEM);
741 av_strlcpy(text, url, strlen(url)+1);
743 while (mpdName = av_strtok(tmp, "/", &tmp)) {
744 size = strlen(mpdName);
748 path = av_mallocz(tmp_max_url_size);
749 tmp_str = av_mallocz(tmp_max_url_size);
750 if (!tmp_str || !path) {
751 updated = AVERROR(ENOMEM);
755 av_strlcpy (path, url, strlen(url) - size + 1);
756 for (rootId = n_baseurl_nodes - 1; rootId > 0; rootId --) {
757 if (!(node = baseurl_nodes[rootId])) {
760 text = xmlNodeGetContent(node);
768 node = baseurl_nodes[rootId];
769 baseurl = xmlNodeGetContent(node);
770 root_url = (av_strcasecmp(baseurl, "")) ? baseurl : path;
772 xmlNodeSetContent(node, root_url);
776 size = strlen(root_url);
777 isRootHttp = ishttp(root_url);
779 if (root_url[size - 1] != token) {
780 av_strlcat(root_url, "/", size + 2);
784 for (i = 0; i < n_baseurl_nodes; ++i) {
788 text = xmlNodeGetContent(baseurl_nodes[i]);
789 if (text && !av_strstart(text, "/", NULL)) {
790 memset(tmp_str, 0, strlen(tmp_str));
791 if (!ishttp(text) && isRootHttp) {
792 av_strlcpy(tmp_str, root_url, size + 1);
794 start = (text[0] == token);
795 if (start && av_stristr(tmp_str, text)) {
797 if (!av_strncasecmp(tmp_str, "http://", 7)) {
799 } else if (!av_strncasecmp(tmp_str, "https://", 8)) {
803 memset(p + 1, 0, strlen(p));
805 av_strlcat(tmp_str, text + start, tmp_max_url_size);
806 xmlNodeSetContent(baseurl_nodes[i], tmp_str);
813 if (tmp_max_url_size > *max_url_size) {
814 *max_url_size = tmp_max_url_size;
823 static int parse_manifest_representation(AVFormatContext *s, const char *url,
825 xmlNodePtr adaptionset_node,
826 xmlNodePtr mpd_baseurl_node,
827 xmlNodePtr period_baseurl_node,
828 xmlNodePtr period_segmenttemplate_node,
829 xmlNodePtr period_segmentlist_node,
830 xmlNodePtr fragment_template_node,
831 xmlNodePtr content_component_node,
832 xmlNodePtr adaptionset_baseurl_node,
833 xmlNodePtr adaptionset_segmentlist_node,
834 xmlNodePtr adaptionset_supplementalproperty_node)
837 int32_t subtitle_rep_idx = 0;
838 int32_t audio_rep_idx = 0;
839 int32_t video_rep_idx = 0;
840 DASHContext *c = s->priv_data;
841 struct representation *rep = NULL;
842 struct fragment *seg = NULL;
843 xmlNodePtr representation_segmenttemplate_node = NULL;
844 xmlNodePtr representation_baseurl_node = NULL;
845 xmlNodePtr representation_segmentlist_node = NULL;
846 xmlNodePtr segmentlists_tab[3];
847 xmlNodePtr fragment_timeline_node = NULL;
848 xmlNodePtr fragment_templates_tab[5];
849 char *duration_val = NULL;
850 char *presentation_timeoffset_val = NULL;
851 char *startnumber_val = NULL;
852 char *timescale_val = NULL;
853 char *initialization_val = NULL;
854 char *media_val = NULL;
856 xmlNodePtr baseurl_nodes[4];
857 xmlNodePtr representation_node = node;
858 char *rep_id_val = xmlGetProp(representation_node, "id");
859 char *rep_bandwidth_val = xmlGetProp(representation_node, "bandwidth");
860 char *rep_framerate_val = xmlGetProp(representation_node, "frameRate");
861 enum AVMediaType type = AVMEDIA_TYPE_UNKNOWN;
863 // try get information from representation
864 if (type == AVMEDIA_TYPE_UNKNOWN)
865 type = get_content_type(representation_node);
866 // try get information from contentComponen
867 if (type == AVMEDIA_TYPE_UNKNOWN)
868 type = get_content_type(content_component_node);
869 // try get information from adaption set
870 if (type == AVMEDIA_TYPE_UNKNOWN)
871 type = get_content_type(adaptionset_node);
872 if (type == AVMEDIA_TYPE_UNKNOWN) {
873 av_log(s, AV_LOG_VERBOSE, "Parsing '%s' - skipp not supported representation type\n", url);
874 } else if (type == AVMEDIA_TYPE_VIDEO || type == AVMEDIA_TYPE_AUDIO || type == AVMEDIA_TYPE_SUBTITLE) {
875 // convert selected representation to our internal struct
876 rep = av_mallocz(sizeof(struct representation));
878 ret = AVERROR(ENOMEM);
881 if (c->adaptionset_lang) {
882 rep->lang = av_strdup(c->adaptionset_lang);
884 av_log(s, AV_LOG_ERROR, "alloc language memory failure\n");
886 ret = AVERROR(ENOMEM);
891 representation_segmenttemplate_node = find_child_node_by_name(representation_node, "SegmentTemplate");
892 representation_baseurl_node = find_child_node_by_name(representation_node, "BaseURL");
893 representation_segmentlist_node = find_child_node_by_name(representation_node, "SegmentList");
895 baseurl_nodes[0] = mpd_baseurl_node;
896 baseurl_nodes[1] = period_baseurl_node;
897 baseurl_nodes[2] = adaptionset_baseurl_node;
898 baseurl_nodes[3] = representation_baseurl_node;
900 ret = resolve_content_path(s, url, &c->max_url_size, baseurl_nodes, 4);
901 c->max_url_size = aligned(c->max_url_size
902 + (rep_id_val ? strlen(rep_id_val) : 0)
903 + (rep_bandwidth_val ? strlen(rep_bandwidth_val) : 0));
904 if (ret == AVERROR(ENOMEM) || ret == 0) {
907 if (representation_segmenttemplate_node || fragment_template_node || period_segmenttemplate_node) {
908 fragment_timeline_node = NULL;
909 fragment_templates_tab[0] = representation_segmenttemplate_node;
910 fragment_templates_tab[1] = adaptionset_segmentlist_node;
911 fragment_templates_tab[2] = fragment_template_node;
912 fragment_templates_tab[3] = period_segmenttemplate_node;
913 fragment_templates_tab[4] = period_segmentlist_node;
915 presentation_timeoffset_val = get_val_from_nodes_tab(fragment_templates_tab, 4, "presentationTimeOffset");
916 duration_val = get_val_from_nodes_tab(fragment_templates_tab, 4, "duration");
917 startnumber_val = get_val_from_nodes_tab(fragment_templates_tab, 4, "startNumber");
918 timescale_val = get_val_from_nodes_tab(fragment_templates_tab, 4, "timescale");
919 initialization_val = get_val_from_nodes_tab(fragment_templates_tab, 4, "initialization");
920 media_val = get_val_from_nodes_tab(fragment_templates_tab, 4, "media");
922 if (initialization_val) {
923 rep->init_section = av_mallocz(sizeof(struct fragment));
924 if (!rep->init_section) {
926 ret = AVERROR(ENOMEM);
929 c->max_url_size = aligned(c->max_url_size + strlen(initialization_val));
930 rep->init_section->url = get_content_url(baseurl_nodes, 4, c->max_url_size, rep_id_val, rep_bandwidth_val, initialization_val);
931 if (!rep->init_section->url) {
932 av_free(rep->init_section);
934 ret = AVERROR(ENOMEM);
937 rep->init_section->size = -1;
938 xmlFree(initialization_val);
942 c->max_url_size = aligned(c->max_url_size + strlen(media_val));
943 rep->url_template = get_content_url(baseurl_nodes, 4, c->max_url_size, rep_id_val, rep_bandwidth_val, media_val);
947 if (presentation_timeoffset_val) {
948 rep->presentation_timeoffset = (int64_t) strtoll(presentation_timeoffset_val, NULL, 10);
949 av_log(s, AV_LOG_TRACE, "rep->presentation_timeoffset = [%"PRId64"]\n", rep->presentation_timeoffset);
950 xmlFree(presentation_timeoffset_val);
953 rep->fragment_duration = (int64_t) strtoll(duration_val, NULL, 10);
954 av_log(s, AV_LOG_TRACE, "rep->fragment_duration = [%"PRId64"]\n", rep->fragment_duration);
955 xmlFree(duration_val);
958 rep->fragment_timescale = (int64_t) strtoll(timescale_val, NULL, 10);
959 av_log(s, AV_LOG_TRACE, "rep->fragment_timescale = [%"PRId64"]\n", rep->fragment_timescale);
960 xmlFree(timescale_val);
962 if (startnumber_val) {
963 rep->start_number = rep->first_seq_no = (int64_t) strtoll(startnumber_val, NULL, 10);
964 av_log(s, AV_LOG_TRACE, "rep->first_seq_no = [%"PRId64"]\n", rep->first_seq_no);
965 xmlFree(startnumber_val);
967 if (adaptionset_supplementalproperty_node) {
968 if (!av_strcasecmp(xmlGetProp(adaptionset_supplementalproperty_node,"schemeIdUri"), "http://dashif.org/guidelines/last-segment-number")) {
969 val = xmlGetProp(adaptionset_supplementalproperty_node,"value");
971 av_log(s, AV_LOG_ERROR, "Missing value attribute in adaptionset_supplementalproperty_node\n");
973 rep->last_seq_no =(int64_t) strtoll(val, NULL, 10) - 1;
979 fragment_timeline_node = find_child_node_by_name(representation_segmenttemplate_node, "SegmentTimeline");
981 if (!fragment_timeline_node)
982 fragment_timeline_node = find_child_node_by_name(fragment_template_node, "SegmentTimeline");
983 if (!fragment_timeline_node)
984 fragment_timeline_node = find_child_node_by_name(adaptionset_segmentlist_node, "SegmentTimeline");
985 if (!fragment_timeline_node)
986 fragment_timeline_node = find_child_node_by_name(period_segmentlist_node, "SegmentTimeline");
987 if (fragment_timeline_node) {
988 fragment_timeline_node = xmlFirstElementChild(fragment_timeline_node);
989 while (fragment_timeline_node) {
990 ret = parse_manifest_segmenttimeline(s, rep, fragment_timeline_node);
994 fragment_timeline_node = xmlNextElementSibling(fragment_timeline_node);
997 } else if (representation_baseurl_node && !representation_segmentlist_node) {
998 seg = av_mallocz(sizeof(struct fragment));
1000 ret = AVERROR(ENOMEM);
1003 seg->url = get_content_url(baseurl_nodes, 4, c->max_url_size, rep_id_val, rep_bandwidth_val, NULL);
1006 ret = AVERROR(ENOMEM);
1010 dynarray_add(&rep->fragments, &rep->n_fragments, seg);
1011 } else if (representation_segmentlist_node) {
1012 // TODO: https://www.brendanlong.com/the-structure-of-an-mpeg-dash-mpd.html
1013 // http://www-itec.uni-klu.ac.at/dash/ddash/mpdGenerator.php?fragmentlength=15&type=full
1014 xmlNodePtr fragmenturl_node = NULL;
1015 segmentlists_tab[0] = representation_segmentlist_node;
1016 segmentlists_tab[1] = adaptionset_segmentlist_node;
1017 segmentlists_tab[2] = period_segmentlist_node;
1019 duration_val = get_val_from_nodes_tab(segmentlists_tab, 3, "duration");
1020 timescale_val = get_val_from_nodes_tab(segmentlists_tab, 3, "timescale");
1021 startnumber_val = get_val_from_nodes_tab(segmentlists_tab, 3, "startNumber");
1023 rep->fragment_duration = (int64_t) strtoll(duration_val, NULL, 10);
1024 av_log(s, AV_LOG_TRACE, "rep->fragment_duration = [%"PRId64"]\n", rep->fragment_duration);
1025 xmlFree(duration_val);
1027 if (timescale_val) {
1028 rep->fragment_timescale = (int64_t) strtoll(timescale_val, NULL, 10);
1029 av_log(s, AV_LOG_TRACE, "rep->fragment_timescale = [%"PRId64"]\n", rep->fragment_timescale);
1030 xmlFree(timescale_val);
1032 if (startnumber_val) {
1033 rep->start_number = rep->first_seq_no = (int64_t) strtoll(startnumber_val, NULL, 10);
1034 av_log(s, AV_LOG_TRACE, "rep->first_seq_no = [%"PRId64"]\n", rep->first_seq_no);
1035 xmlFree(startnumber_val);
1038 fragmenturl_node = xmlFirstElementChild(representation_segmentlist_node);
1039 while (fragmenturl_node) {
1040 ret = parse_manifest_segmenturlnode(s, rep, fragmenturl_node,
1047 fragmenturl_node = xmlNextElementSibling(fragmenturl_node);
1050 fragment_timeline_node = find_child_node_by_name(representation_segmenttemplate_node, "SegmentTimeline");
1052 if (!fragment_timeline_node)
1053 fragment_timeline_node = find_child_node_by_name(fragment_template_node, "SegmentTimeline");
1054 if (!fragment_timeline_node)
1055 fragment_timeline_node = find_child_node_by_name(adaptionset_segmentlist_node, "SegmentTimeline");
1056 if (!fragment_timeline_node)
1057 fragment_timeline_node = find_child_node_by_name(period_segmentlist_node, "SegmentTimeline");
1058 if (fragment_timeline_node) {
1059 fragment_timeline_node = xmlFirstElementChild(fragment_timeline_node);
1060 while (fragment_timeline_node) {
1061 ret = parse_manifest_segmenttimeline(s, rep, fragment_timeline_node);
1065 fragment_timeline_node = xmlNextElementSibling(fragment_timeline_node);
1069 free_representation(rep);
1071 av_log(s, AV_LOG_ERROR, "Unknown format of Representation node id[%s] \n", (const char *)rep_id_val);
1075 if (rep->fragment_duration > 0 && !rep->fragment_timescale)
1076 rep->fragment_timescale = 1;
1077 rep->bandwidth = rep_bandwidth_val ? atoi(rep_bandwidth_val) : 0;
1078 strncpy(rep->id, rep_id_val ? rep_id_val : "", sizeof(rep->id));
1079 rep->framerate = av_make_q(0, 0);
1080 if (type == AVMEDIA_TYPE_VIDEO && rep_framerate_val) {
1081 ret = av_parse_video_rate(&rep->framerate, rep_framerate_val);
1083 av_log(s, AV_LOG_VERBOSE, "Ignoring invalid frame rate '%s'\n", rep_framerate_val);
1087 case AVMEDIA_TYPE_VIDEO:
1088 rep->rep_idx = video_rep_idx;
1089 dynarray_add(&c->videos, &c->n_videos, rep);
1091 case AVMEDIA_TYPE_AUDIO:
1092 rep->rep_idx = audio_rep_idx;
1093 dynarray_add(&c->audios, &c->n_audios, rep);
1095 case AVMEDIA_TYPE_SUBTITLE:
1096 rep->rep_idx = subtitle_rep_idx;
1097 dynarray_add(&c->subtitles, &c->n_subtitles, rep);
1100 av_log(s, AV_LOG_WARNING, "Unsupported the stream type %d\n", type);
1106 video_rep_idx += type == AVMEDIA_TYPE_VIDEO;
1107 audio_rep_idx += type == AVMEDIA_TYPE_AUDIO;
1108 subtitle_rep_idx += type == AVMEDIA_TYPE_SUBTITLE;
1112 xmlFree(rep_id_val);
1113 if (rep_bandwidth_val)
1114 xmlFree(rep_bandwidth_val);
1115 if (rep_framerate_val)
1116 xmlFree(rep_framerate_val);
1121 static int parse_manifest_adaptationset_attr(AVFormatContext *s, xmlNodePtr adaptionset_node)
1123 DASHContext *c = s->priv_data;
1125 if (!adaptionset_node) {
1126 av_log(s, AV_LOG_WARNING, "Cannot get AdaptionSet\n");
1127 return AVERROR(EINVAL);
1129 c->adaptionset_lang = xmlGetProp(adaptionset_node, "lang");
1134 static int parse_manifest_adaptationset(AVFormatContext *s, const char *url,
1135 xmlNodePtr adaptionset_node,
1136 xmlNodePtr mpd_baseurl_node,
1137 xmlNodePtr period_baseurl_node,
1138 xmlNodePtr period_segmenttemplate_node,
1139 xmlNodePtr period_segmentlist_node)
1142 DASHContext *c = s->priv_data;
1143 xmlNodePtr fragment_template_node = NULL;
1144 xmlNodePtr content_component_node = NULL;
1145 xmlNodePtr adaptionset_baseurl_node = NULL;
1146 xmlNodePtr adaptionset_segmentlist_node = NULL;
1147 xmlNodePtr adaptionset_supplementalproperty_node = NULL;
1148 xmlNodePtr node = NULL;
1150 ret = parse_manifest_adaptationset_attr(s, adaptionset_node);
1154 node = xmlFirstElementChild(adaptionset_node);
1156 if (!av_strcasecmp(node->name, (const char *)"SegmentTemplate")) {
1157 fragment_template_node = node;
1158 } else if (!av_strcasecmp(node->name, (const char *)"ContentComponent")) {
1159 content_component_node = node;
1160 } else if (!av_strcasecmp(node->name, (const char *)"BaseURL")) {
1161 adaptionset_baseurl_node = node;
1162 } else if (!av_strcasecmp(node->name, (const char *)"SegmentList")) {
1163 adaptionset_segmentlist_node = node;
1164 } else if (!av_strcasecmp(node->name, (const char *)"SupplementalProperty")) {
1165 adaptionset_supplementalproperty_node = node;
1166 } else if (!av_strcasecmp(node->name, (const char *)"Representation")) {
1167 ret = parse_manifest_representation(s, url, node,
1170 period_baseurl_node,
1171 period_segmenttemplate_node,
1172 period_segmentlist_node,
1173 fragment_template_node,
1174 content_component_node,
1175 adaptionset_baseurl_node,
1176 adaptionset_segmentlist_node,
1177 adaptionset_supplementalproperty_node);
1181 node = xmlNextElementSibling(node);
1185 av_freep(&c->adaptionset_lang);
1189 static int parse_programinformation(AVFormatContext *s, xmlNodePtr node)
1191 xmlChar *val = NULL;
1193 node = xmlFirstElementChild(node);
1195 if (!av_strcasecmp(node->name, "Title")) {
1196 val = xmlNodeGetContent(node);
1198 av_dict_set(&s->metadata, "Title", val, 0);
1200 } else if (!av_strcasecmp(node->name, "Source")) {
1201 val = xmlNodeGetContent(node);
1203 av_dict_set(&s->metadata, "Source", val, 0);
1205 } else if (!av_strcasecmp(node->name, "Copyright")) {
1206 val = xmlNodeGetContent(node);
1208 av_dict_set(&s->metadata, "Copyright", val, 0);
1211 node = xmlNextElementSibling(node);
1218 static int parse_manifest(AVFormatContext *s, const char *url, AVIOContext *in)
1220 DASHContext *c = s->priv_data;
1223 uint8_t *new_url = NULL;
1224 int64_t filesize = 0;
1226 AVDictionary *opts = NULL;
1228 xmlNodePtr root_element = NULL;
1229 xmlNodePtr node = NULL;
1230 xmlNodePtr period_node = NULL;
1231 xmlNodePtr tmp_node = NULL;
1232 xmlNodePtr mpd_baseurl_node = NULL;
1233 xmlNodePtr period_baseurl_node = NULL;
1234 xmlNodePtr period_segmenttemplate_node = NULL;
1235 xmlNodePtr period_segmentlist_node = NULL;
1236 xmlNodePtr adaptionset_node = NULL;
1237 xmlAttrPtr attr = NULL;
1239 uint32_t period_duration_sec = 0;
1240 uint32_t period_start_sec = 0;
1245 av_dict_copy(&opts, c->avio_opts, 0);
1246 ret = avio_open2(&in, url, AVIO_FLAG_READ, c->interrupt_callback, &opts);
1247 av_dict_free(&opts);
1252 if (av_opt_get(in, "location", AV_OPT_SEARCH_CHILDREN, &new_url) >= 0) {
1253 c->base_url = av_strdup(new_url);
1255 c->base_url = av_strdup(url);
1258 filesize = avio_size(in);
1259 filesize = filesize > 0 ? filesize : DEFAULT_MANIFEST_SIZE;
1261 if (filesize > MAX_BPRINT_READ_SIZE) {
1262 av_log(s, AV_LOG_ERROR, "Manifest too large: %"PRId64"\n", filesize);
1263 return AVERROR_INVALIDDATA;
1266 av_bprint_init(&buf, filesize + 1, AV_BPRINT_SIZE_UNLIMITED);
1268 if ((ret = avio_read_to_bprint(in, &buf, MAX_BPRINT_READ_SIZE)) < 0 ||
1270 (filesize = buf.len) == 0) {
1271 av_log(s, AV_LOG_ERROR, "Unable to read to manifest '%s'\n", url);
1273 ret = AVERROR_INVALIDDATA;
1277 doc = xmlReadMemory(buf.str, filesize, c->base_url, NULL, 0);
1278 root_element = xmlDocGetRootElement(doc);
1279 node = root_element;
1282 ret = AVERROR_INVALIDDATA;
1283 av_log(s, AV_LOG_ERROR, "Unable to parse '%s' - missing root node\n", url);
1287 if (node->type != XML_ELEMENT_NODE ||
1288 av_strcasecmp(node->name, (const char *)"MPD")) {
1289 ret = AVERROR_INVALIDDATA;
1290 av_log(s, AV_LOG_ERROR, "Unable to parse '%s' - wrong root node name[%s] type[%d]\n", url, node->name, (int)node->type);
1294 val = xmlGetProp(node, "type");
1296 av_log(s, AV_LOG_ERROR, "Unable to parse '%s' - missing type attrib\n", url);
1297 ret = AVERROR_INVALIDDATA;
1300 if (!av_strcasecmp(val, (const char *)"dynamic"))
1304 attr = node->properties;
1306 val = xmlGetProp(node, attr->name);
1308 if (!av_strcasecmp(attr->name, (const char *)"availabilityStartTime")) {
1309 c->availability_start_time = get_utc_date_time_insec(s, (const char *)val);
1310 av_log(s, AV_LOG_TRACE, "c->availability_start_time = [%"PRId64"]\n", c->availability_start_time);
1311 } else if (!av_strcasecmp(attr->name, (const char *)"availabilityEndTime")) {
1312 c->availability_end_time = get_utc_date_time_insec(s, (const char *)val);
1313 av_log(s, AV_LOG_TRACE, "c->availability_end_time = [%"PRId64"]\n", c->availability_end_time);
1314 } else if (!av_strcasecmp(attr->name, (const char *)"publishTime")) {
1315 c->publish_time = get_utc_date_time_insec(s, (const char *)val);
1316 av_log(s, AV_LOG_TRACE, "c->publish_time = [%"PRId64"]\n", c->publish_time);
1317 } else if (!av_strcasecmp(attr->name, (const char *)"minimumUpdatePeriod")) {
1318 c->minimum_update_period = get_duration_insec(s, (const char *)val);
1319 av_log(s, AV_LOG_TRACE, "c->minimum_update_period = [%"PRId64"]\n", c->minimum_update_period);
1320 } else if (!av_strcasecmp(attr->name, (const char *)"timeShiftBufferDepth")) {
1321 c->time_shift_buffer_depth = get_duration_insec(s, (const char *)val);
1322 av_log(s, AV_LOG_TRACE, "c->time_shift_buffer_depth = [%"PRId64"]\n", c->time_shift_buffer_depth);
1323 } else if (!av_strcasecmp(attr->name, (const char *)"minBufferTime")) {
1324 c->min_buffer_time = get_duration_insec(s, (const char *)val);
1325 av_log(s, AV_LOG_TRACE, "c->min_buffer_time = [%"PRId64"]\n", c->min_buffer_time);
1326 } else if (!av_strcasecmp(attr->name, (const char *)"suggestedPresentationDelay")) {
1327 c->suggested_presentation_delay = get_duration_insec(s, (const char *)val);
1328 av_log(s, AV_LOG_TRACE, "c->suggested_presentation_delay = [%"PRId64"]\n", c->suggested_presentation_delay);
1329 } else if (!av_strcasecmp(attr->name, (const char *)"mediaPresentationDuration")) {
1330 c->media_presentation_duration = get_duration_insec(s, (const char *)val);
1331 av_log(s, AV_LOG_TRACE, "c->media_presentation_duration = [%"PRId64"]\n", c->media_presentation_duration);
1337 tmp_node = find_child_node_by_name(node, "BaseURL");
1339 mpd_baseurl_node = xmlCopyNode(tmp_node,1);
1341 mpd_baseurl_node = xmlNewNode(NULL, "BaseURL");
1344 // at now we can handle only one period, with the longest duration
1345 node = xmlFirstElementChild(node);
1347 if (!av_strcasecmp(node->name, (const char *)"Period")) {
1348 period_duration_sec = 0;
1349 period_start_sec = 0;
1350 attr = node->properties;
1352 val = xmlGetProp(node, attr->name);
1353 if (!av_strcasecmp(attr->name, (const char *)"duration")) {
1354 period_duration_sec = get_duration_insec(s, (const char *)val);
1355 } else if (!av_strcasecmp(attr->name, (const char *)"start")) {
1356 period_start_sec = get_duration_insec(s, (const char *)val);
1361 if ((period_duration_sec) >= (c->period_duration)) {
1363 c->period_duration = period_duration_sec;
1364 c->period_start = period_start_sec;
1365 if (c->period_start > 0)
1366 c->media_presentation_duration = c->period_duration;
1368 } else if (!av_strcasecmp(node->name, "ProgramInformation")) {
1369 parse_programinformation(s, node);
1371 node = xmlNextElementSibling(node);
1374 av_log(s, AV_LOG_ERROR, "Unable to parse '%s' - missing Period node\n", url);
1375 ret = AVERROR_INVALIDDATA;
1379 adaptionset_node = xmlFirstElementChild(period_node);
1380 while (adaptionset_node) {
1381 if (!av_strcasecmp(adaptionset_node->name, (const char *)"BaseURL")) {
1382 period_baseurl_node = adaptionset_node;
1383 } else if (!av_strcasecmp(adaptionset_node->name, (const char *)"SegmentTemplate")) {
1384 period_segmenttemplate_node = adaptionset_node;
1385 } else if (!av_strcasecmp(adaptionset_node->name, (const char *)"SegmentList")) {
1386 period_segmentlist_node = adaptionset_node;
1387 } else if (!av_strcasecmp(adaptionset_node->name, (const char *)"AdaptationSet")) {
1388 parse_manifest_adaptationset(s, url, adaptionset_node, mpd_baseurl_node, period_baseurl_node, period_segmenttemplate_node, period_segmentlist_node);
1390 adaptionset_node = xmlNextElementSibling(adaptionset_node);
1393 /*free the document */
1396 xmlFreeNode(mpd_baseurl_node);
1400 av_bprint_finalize(&buf, NULL);
1407 static int64_t calc_cur_seg_no(AVFormatContext *s, struct representation *pls)
1409 DASHContext *c = s->priv_data;
1411 int64_t start_time_offset = 0;
1414 if (pls->n_fragments) {
1415 av_log(s, AV_LOG_TRACE, "in n_fragments mode\n");
1416 num = pls->first_seq_no;
1417 } else if (pls->n_timelines) {
1418 av_log(s, AV_LOG_TRACE, "in n_timelines mode\n");
1419 start_time_offset = get_segment_start_time_based_on_timeline(pls, 0xFFFFFFFF) - 60 * pls->fragment_timescale; // 60 seconds before end
1420 num = calc_next_seg_no_from_timelines(pls, start_time_offset);
1422 num = pls->first_seq_no;
1424 num += pls->first_seq_no;
1425 } else if (pls->fragment_duration){
1426 av_log(s, AV_LOG_TRACE, "in fragment_duration mode fragment_timescale = %"PRId64", presentation_timeoffset = %"PRId64"\n", pls->fragment_timescale, pls->presentation_timeoffset);
1427 if (pls->presentation_timeoffset) {
1428 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;
1429 } else if (c->publish_time > 0 && !c->availability_start_time) {
1430 if (c->min_buffer_time) {
1431 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;
1433 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;
1436 num = pls->first_seq_no + (((get_current_time_in_sec() - c->availability_start_time) - c->suggested_presentation_delay) * pls->fragment_timescale) / pls->fragment_duration;
1440 num = pls->first_seq_no;
1445 static int64_t calc_min_seg_no(AVFormatContext *s, struct representation *pls)
1447 DASHContext *c = s->priv_data;
1450 if (c->is_live && pls->fragment_duration) {
1451 av_log(s, AV_LOG_TRACE, "in live mode\n");
1452 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;
1454 num = pls->first_seq_no;
1459 static int64_t calc_max_seg_no(struct representation *pls, DASHContext *c)
1463 if (pls->n_fragments) {
1464 num = pls->first_seq_no + pls->n_fragments - 1;
1465 } else if (pls->n_timelines) {
1467 num = pls->first_seq_no + pls->n_timelines - 1;
1468 for (i = 0; i < pls->n_timelines; i++) {
1469 if (pls->timelines[i]->repeat == -1) {
1470 int length_of_each_segment = pls->timelines[i]->duration / pls->fragment_timescale;
1471 num = c->period_duration / length_of_each_segment;
1473 num += pls->timelines[i]->repeat;
1476 } else if (c->is_live && pls->fragment_duration) {
1477 num = pls->first_seq_no + (((get_current_time_in_sec() - c->availability_start_time)) * pls->fragment_timescale) / pls->fragment_duration;
1478 } else if (pls->fragment_duration) {
1479 num = pls->first_seq_no + (c->media_presentation_duration * pls->fragment_timescale) / pls->fragment_duration;
1485 static void move_timelines(struct representation *rep_src, struct representation *rep_dest, DASHContext *c)
1487 if (rep_dest && rep_src ) {
1488 free_timelines_list(rep_dest);
1489 rep_dest->timelines = rep_src->timelines;
1490 rep_dest->n_timelines = rep_src->n_timelines;
1491 rep_dest->first_seq_no = rep_src->first_seq_no;
1492 rep_dest->last_seq_no = calc_max_seg_no(rep_dest, c);
1493 rep_src->timelines = NULL;
1494 rep_src->n_timelines = 0;
1495 rep_dest->cur_seq_no = rep_src->cur_seq_no;
1499 static void move_segments(struct representation *rep_src, struct representation *rep_dest, DASHContext *c)
1501 if (rep_dest && rep_src ) {
1502 free_fragment_list(rep_dest);
1503 if (rep_src->start_number > (rep_dest->start_number + rep_dest->n_fragments))
1504 rep_dest->cur_seq_no = 0;
1506 rep_dest->cur_seq_no += rep_src->start_number - rep_dest->start_number;
1507 rep_dest->fragments = rep_src->fragments;
1508 rep_dest->n_fragments = rep_src->n_fragments;
1509 rep_dest->parent = rep_src->parent;
1510 rep_dest->last_seq_no = calc_max_seg_no(rep_dest, c);
1511 rep_src->fragments = NULL;
1512 rep_src->n_fragments = 0;
1517 static int refresh_manifest(AVFormatContext *s)
1520 DASHContext *c = s->priv_data;
1521 // save current context
1522 int n_videos = c->n_videos;
1523 struct representation **videos = c->videos;
1524 int n_audios = c->n_audios;
1525 struct representation **audios = c->audios;
1526 int n_subtitles = c->n_subtitles;
1527 struct representation **subtitles = c->subtitles;
1528 char *base_url = c->base_url;
1536 c->subtitles = NULL;
1537 ret = parse_manifest(s, s->url, NULL);
1541 if (c->n_videos != n_videos) {
1542 av_log(c, AV_LOG_ERROR,
1543 "new manifest has mismatched no. of video representations, %d -> %d\n",
1544 n_videos, c->n_videos);
1545 return AVERROR_INVALIDDATA;
1547 if (c->n_audios != n_audios) {
1548 av_log(c, AV_LOG_ERROR,
1549 "new manifest has mismatched no. of audio representations, %d -> %d\n",
1550 n_audios, c->n_audios);
1551 return AVERROR_INVALIDDATA;
1553 if (c->n_subtitles != n_subtitles) {
1554 av_log(c, AV_LOG_ERROR,
1555 "new manifest has mismatched no. of subtitles representations, %d -> %d\n",
1556 n_subtitles, c->n_subtitles);
1557 return AVERROR_INVALIDDATA;
1560 for (i = 0; i < n_videos; i++) {
1561 struct representation *cur_video = videos[i];
1562 struct representation *ccur_video = c->videos[i];
1563 if (cur_video->timelines) {
1564 // calc current time
1565 int64_t currentTime = get_segment_start_time_based_on_timeline(cur_video, cur_video->cur_seq_no) / cur_video->fragment_timescale;
1567 ccur_video->cur_seq_no = calc_next_seg_no_from_timelines(ccur_video, currentTime * cur_video->fragment_timescale - 1);
1568 if (ccur_video->cur_seq_no >= 0) {
1569 move_timelines(ccur_video, cur_video, c);
1572 if (cur_video->fragments) {
1573 move_segments(ccur_video, cur_video, c);
1576 for (i = 0; i < n_audios; i++) {
1577 struct representation *cur_audio = audios[i];
1578 struct representation *ccur_audio = c->audios[i];
1579 if (cur_audio->timelines) {
1580 // calc current time
1581 int64_t currentTime = get_segment_start_time_based_on_timeline(cur_audio, cur_audio->cur_seq_no) / cur_audio->fragment_timescale;
1583 ccur_audio->cur_seq_no = calc_next_seg_no_from_timelines(ccur_audio, currentTime * cur_audio->fragment_timescale - 1);
1584 if (ccur_audio->cur_seq_no >= 0) {
1585 move_timelines(ccur_audio, cur_audio, c);
1588 if (cur_audio->fragments) {
1589 move_segments(ccur_audio, cur_audio, c);
1598 c->base_url = base_url;
1601 free_subtitle_list(c);
1607 c->n_subtitles = n_subtitles;
1608 c->subtitles = subtitles;
1609 c->n_audios = n_audios;
1611 c->n_videos = n_videos;
1616 static struct fragment *get_current_fragment(struct representation *pls)
1618 int64_t min_seq_no = 0;
1619 int64_t max_seq_no = 0;
1620 struct fragment *seg = NULL;
1621 struct fragment *seg_ptr = NULL;
1622 DASHContext *c = pls->parent->priv_data;
1624 while (( !ff_check_interrupt(c->interrupt_callback)&& pls->n_fragments > 0)) {
1625 if (pls->cur_seq_no < pls->n_fragments) {
1626 seg_ptr = pls->fragments[pls->cur_seq_no];
1627 seg = av_mallocz(sizeof(struct fragment));
1631 seg->url = av_strdup(seg_ptr->url);
1636 seg->size = seg_ptr->size;
1637 seg->url_offset = seg_ptr->url_offset;
1639 } else if (c->is_live) {
1640 refresh_manifest(pls->parent);
1646 min_seq_no = calc_min_seg_no(pls->parent, pls);
1647 max_seq_no = calc_max_seg_no(pls, c);
1649 if (pls->timelines || pls->fragments) {
1650 refresh_manifest(pls->parent);
1652 if (pls->cur_seq_no <= min_seq_no) {
1653 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);
1654 pls->cur_seq_no = calc_cur_seg_no(pls->parent, pls);
1655 } else if (pls->cur_seq_no > max_seq_no) {
1656 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);
1658 seg = av_mallocz(sizeof(struct fragment));
1662 } else if (pls->cur_seq_no <= pls->last_seq_no) {
1663 seg = av_mallocz(sizeof(struct fragment));
1669 char *tmpfilename= av_mallocz(c->max_url_size);
1673 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));
1674 seg->url = av_strireplace(pls->url_template, pls->url_template, tmpfilename);
1676 av_log(pls->parent, AV_LOG_WARNING, "Unable to resolve template url '%s', try to use origin template\n", pls->url_template);
1677 seg->url = av_strdup(pls->url_template);
1679 av_log(pls->parent, AV_LOG_ERROR, "Cannot resolve template url '%s'\n", pls->url_template);
1680 av_free(tmpfilename);
1684 av_free(tmpfilename);
1691 static int read_from_url(struct representation *pls, struct fragment *seg,
1692 uint8_t *buf, int buf_size)
1696 /* limit read if the fragment was only a part of a file */
1698 buf_size = FFMIN(buf_size, pls->cur_seg_size - pls->cur_seg_offset);
1700 ret = avio_read(pls->input, buf, buf_size);
1702 pls->cur_seg_offset += ret;
1707 static int open_input(DASHContext *c, struct representation *pls, struct fragment *seg)
1709 AVDictionary *opts = NULL;
1713 url = av_mallocz(c->max_url_size);
1715 ret = AVERROR(ENOMEM);
1719 if (seg->size >= 0) {
1720 /* try to restrict the HTTP request to the part we want
1721 * (if this is in fact a HTTP request) */
1722 av_dict_set_int(&opts, "offset", seg->url_offset, 0);
1723 av_dict_set_int(&opts, "end_offset", seg->url_offset + seg->size, 0);
1726 ff_make_absolute_url(url, c->max_url_size, c->base_url, seg->url);
1727 av_log(pls->parent, AV_LOG_VERBOSE, "DASH request for url '%s', offset %"PRId64", playlist %d\n",
1728 url, seg->url_offset, pls->rep_idx);
1729 ret = open_url(pls->parent, &pls->input, url, c->avio_opts, opts, NULL);
1733 av_dict_free(&opts);
1734 pls->cur_seg_offset = 0;
1735 pls->cur_seg_size = seg->size;
1739 static int update_init_section(struct representation *pls)
1741 static const int max_init_section_size = 1024 * 1024;
1742 DASHContext *c = pls->parent->priv_data;
1747 if (!pls->init_section || pls->init_sec_buf)
1750 ret = open_input(c, pls, pls->init_section);
1752 av_log(pls->parent, AV_LOG_WARNING,
1753 "Failed to open an initialization section in playlist %d\n",
1758 if (pls->init_section->size >= 0)
1759 sec_size = pls->init_section->size;
1760 else if ((urlsize = avio_size(pls->input)) >= 0)
1763 sec_size = max_init_section_size;
1765 av_log(pls->parent, AV_LOG_DEBUG,
1766 "Downloading an initialization section of size %"PRId64"\n",
1769 sec_size = FFMIN(sec_size, max_init_section_size);
1771 av_fast_malloc(&pls->init_sec_buf, &pls->init_sec_buf_size, sec_size);
1773 ret = read_from_url(pls, pls->init_section, pls->init_sec_buf,
1774 pls->init_sec_buf_size);
1775 ff_format_io_close(pls->parent, &pls->input);
1780 pls->init_sec_data_len = ret;
1781 pls->init_sec_buf_read_offset = 0;
1786 static int64_t seek_data(void *opaque, int64_t offset, int whence)
1788 struct representation *v = opaque;
1789 if (v->n_fragments && !v->init_sec_data_len) {
1790 return avio_seek(v->input, offset, whence);
1793 return AVERROR(ENOSYS);
1796 static int read_data(void *opaque, uint8_t *buf, int buf_size)
1799 struct representation *v = opaque;
1800 DASHContext *c = v->parent->priv_data;
1804 free_fragment(&v->cur_seg);
1805 v->cur_seg = get_current_fragment(v);
1811 /* load/update Media Initialization Section, if any */
1812 ret = update_init_section(v);
1816 ret = open_input(c, v, v->cur_seg);
1818 if (ff_check_interrupt(c->interrupt_callback)) {
1822 av_log(v->parent, AV_LOG_WARNING, "Failed to open fragment of playlist %d\n", v->rep_idx);
1828 if (v->init_sec_buf_read_offset < v->init_sec_data_len) {
1829 /* Push init section out first before first actual fragment */
1830 int copy_size = FFMIN(v->init_sec_data_len - v->init_sec_buf_read_offset, buf_size);
1831 memcpy(buf, v->init_sec_buf, copy_size);
1832 v->init_sec_buf_read_offset += copy_size;
1837 /* check the v->cur_seg, if it is null, get current and double check if the new v->cur_seg*/
1839 v->cur_seg = get_current_fragment(v);
1845 ret = read_from_url(v, v->cur_seg, buf, buf_size);
1849 if (c->is_live || v->cur_seq_no < v->last_seq_no) {
1850 if (!v->is_restart_needed)
1852 v->is_restart_needed = 1;
1859 static int save_avio_options(AVFormatContext *s)
1861 DASHContext *c = s->priv_data;
1862 const char *opts[] = {
1863 "headers", "user_agent", "cookies", "http_proxy", "referer", "rw_timeout", "icy", NULL };
1864 const char **opt = opts;
1865 uint8_t *buf = NULL;
1869 if (av_opt_get(s->pb, *opt, AV_OPT_SEARCH_CHILDREN, &buf) >= 0) {
1870 if (buf[0] != '\0') {
1871 ret = av_dict_set(&c->avio_opts, *opt, buf, AV_DICT_DONT_STRDUP_VAL);
1886 static int nested_io_open(AVFormatContext *s, AVIOContext **pb, const char *url,
1887 int flags, AVDictionary **opts)
1889 av_log(s, AV_LOG_ERROR,
1890 "A DASH playlist item '%s' referred to an external file '%s'. "
1891 "Opening this file was forbidden for security reasons\n",
1893 return AVERROR(EPERM);
1896 static void close_demux_for_component(struct representation *pls)
1898 /* note: the internal buffer could have changed */
1899 av_freep(&pls->pb.buffer);
1900 memset(&pls->pb, 0x00, sizeof(AVIOContext));
1901 pls->ctx->pb = NULL;
1902 avformat_close_input(&pls->ctx);
1906 static int reopen_demux_for_component(AVFormatContext *s, struct representation *pls)
1908 DASHContext *c = s->priv_data;
1909 ff_const59 AVInputFormat *in_fmt = NULL;
1910 AVDictionary *in_fmt_opts = NULL;
1911 uint8_t *avio_ctx_buffer = NULL;
1915 close_demux_for_component(pls);
1918 if (ff_check_interrupt(&s->interrupt_callback)) {
1923 if (!(pls->ctx = avformat_alloc_context())) {
1924 ret = AVERROR(ENOMEM);
1928 avio_ctx_buffer = av_malloc(INITIAL_BUFFER_SIZE);
1929 if (!avio_ctx_buffer ) {
1930 ret = AVERROR(ENOMEM);
1931 avformat_free_context(pls->ctx);
1936 ffio_init_context(&pls->pb, avio_ctx_buffer , INITIAL_BUFFER_SIZE, 0, pls, read_data, NULL, NULL);
1938 ffio_init_context(&pls->pb, avio_ctx_buffer , INITIAL_BUFFER_SIZE, 0, pls, read_data, NULL, seek_data);
1940 pls->pb.seekable = 0;
1942 if ((ret = ff_copy_whiteblacklists(pls->ctx, s)) < 0)
1945 pls->ctx->flags = AVFMT_FLAG_CUSTOM_IO;
1946 pls->ctx->probesize = s->probesize > 0 ? s->probesize : 1024 * 4;
1947 pls->ctx->max_analyze_duration = s->max_analyze_duration > 0 ? s->max_analyze_duration : 4 * AV_TIME_BASE;
1948 pls->ctx->interrupt_callback = s->interrupt_callback;
1949 ret = av_probe_input_buffer(&pls->pb, &in_fmt, "", NULL, 0, 0);
1951 av_log(s, AV_LOG_ERROR, "Error when loading first fragment, playlist %d\n", (int)pls->rep_idx);
1952 avformat_free_context(pls->ctx);
1957 pls->ctx->pb = &pls->pb;
1958 pls->ctx->io_open = nested_io_open;
1960 // provide additional information from mpd if available
1961 ret = avformat_open_input(&pls->ctx, "", in_fmt, &in_fmt_opts); //pls->init_section->url
1962 av_dict_free(&in_fmt_opts);
1965 if (pls->n_fragments) {
1966 #if FF_API_R_FRAME_RATE
1967 if (pls->framerate.den) {
1968 for (i = 0; i < pls->ctx->nb_streams; i++)
1969 pls->ctx->streams[i]->r_frame_rate = pls->framerate;
1972 ret = avformat_find_stream_info(pls->ctx, NULL);
1981 static int open_demux_for_component(AVFormatContext *s, struct representation *pls)
1987 pls->cur_seq_no = calc_cur_seg_no(s, pls);
1989 if (!pls->last_seq_no) {
1990 pls->last_seq_no = calc_max_seg_no(pls, s->priv_data);
1993 ret = reopen_demux_for_component(s, pls);
1997 for (i = 0; i < pls->ctx->nb_streams; i++) {
1998 AVStream *st = avformat_new_stream(s, NULL);
1999 AVStream *ist = pls->ctx->streams[i];
2001 ret = AVERROR(ENOMEM);
2005 avcodec_parameters_copy(st->codecpar, ist->codecpar);
2006 avpriv_set_pts_info(st, ist->pts_wrap_bits, ist->time_base.num, ist->time_base.den);
2009 st->disposition = ist->disposition;
2012 for (int i = 0; i < ist->nb_side_data; i++) {
2013 const AVPacketSideData *sd_src = &ist->side_data[i];
2016 dst_data = av_stream_new_side_data(st, sd_src->type, sd_src->size);
2018 return AVERROR(ENOMEM);
2019 memcpy(dst_data, sd_src->data, sd_src->size);
2028 static int is_common_init_section_exist(struct representation **pls, int n_pls)
2030 struct fragment *first_init_section = pls[0]->init_section;
2032 int64_t url_offset = -1;
2036 if (first_init_section == NULL || n_pls == 0)
2039 url = first_init_section->url;
2040 url_offset = first_init_section->url_offset;
2041 size = pls[0]->init_section->size;
2042 for (i=0;i<n_pls;i++) {
2043 if (av_strcasecmp(pls[i]->init_section->url,url) || pls[i]->init_section->url_offset != url_offset || pls[i]->init_section->size != size) {
2050 static int copy_init_section(struct representation *rep_dest, struct representation *rep_src)
2052 rep_dest->init_sec_buf = av_mallocz(rep_src->init_sec_buf_size);
2053 if (!rep_dest->init_sec_buf) {
2054 av_log(rep_dest->ctx, AV_LOG_WARNING, "Cannot alloc memory for init_sec_buf\n");
2055 return AVERROR(ENOMEM);
2057 memcpy(rep_dest->init_sec_buf, rep_src->init_sec_buf, rep_src->init_sec_data_len);
2058 rep_dest->init_sec_buf_size = rep_src->init_sec_buf_size;
2059 rep_dest->init_sec_data_len = rep_src->init_sec_data_len;
2060 rep_dest->cur_timestamp = rep_src->cur_timestamp;
2066 static int dash_read_header(AVFormatContext *s)
2068 DASHContext *c = s->priv_data;
2069 struct representation *rep;
2071 int stream_index = 0;
2074 c->interrupt_callback = &s->interrupt_callback;
2076 if ((ret = save_avio_options(s)) < 0)
2079 if ((ret = parse_manifest(s, s->url, s->pb)) < 0)
2082 /* If this isn't a live stream, fill the total duration of the
2085 s->duration = (int64_t) c->media_presentation_duration * AV_TIME_BASE;
2087 av_dict_set(&c->avio_opts, "seekable", "0", 0);
2091 c->is_init_section_common_video = is_common_init_section_exist(c->videos, c->n_videos);
2093 /* Open the demuxer for video and audio components if available */
2094 for (i = 0; i < c->n_videos; i++) {
2096 if (i > 0 && c->is_init_section_common_video) {
2097 ret = copy_init_section(rep, c->videos[0]);
2101 ret = open_demux_for_component(s, rep);
2105 rep->stream_index = stream_index;
2110 c->is_init_section_common_audio = is_common_init_section_exist(c->audios, c->n_audios);
2112 for (i = 0; i < c->n_audios; i++) {
2114 if (i > 0 && c->is_init_section_common_audio) {
2115 ret = copy_init_section(rep, c->audios[0]);
2119 ret = open_demux_for_component(s, rep);
2123 rep->stream_index = stream_index;
2128 c->is_init_section_common_audio = is_common_init_section_exist(c->subtitles, c->n_subtitles);
2130 for (i = 0; i < c->n_subtitles; i++) {
2131 rep = c->subtitles[i];
2132 if (i > 0 && c->is_init_section_common_audio) {
2133 ret = copy_init_section(rep, c->subtitles[0]);
2137 ret = open_demux_for_component(s, rep);
2141 rep->stream_index = stream_index;
2145 if (!stream_index) {
2146 ret = AVERROR_INVALIDDATA;
2150 /* Create a program */
2153 program = av_new_program(s, 0);
2158 for (i = 0; i < c->n_videos; i++) {
2160 av_program_add_stream_index(s, 0, rep->stream_index);
2161 rep->assoc_stream = s->streams[rep->stream_index];
2162 if (rep->bandwidth > 0)
2163 av_dict_set_int(&rep->assoc_stream->metadata, "variant_bitrate", rep->bandwidth, 0);
2165 av_dict_set(&rep->assoc_stream->metadata, "id", rep->id, 0);
2167 for (i = 0; i < c->n_audios; i++) {
2169 av_program_add_stream_index(s, 0, rep->stream_index);
2170 rep->assoc_stream = s->streams[rep->stream_index];
2171 if (rep->bandwidth > 0)
2172 av_dict_set_int(&rep->assoc_stream->metadata, "variant_bitrate", rep->bandwidth, 0);
2174 av_dict_set(&rep->assoc_stream->metadata, "id", rep->id, 0);
2176 av_dict_set(&rep->assoc_stream->metadata, "language", rep->lang, 0);
2177 av_freep(&rep->lang);
2180 for (i = 0; i < c->n_subtitles; i++) {
2181 rep = c->subtitles[i];
2182 av_program_add_stream_index(s, 0, rep->stream_index);
2183 rep->assoc_stream = s->streams[rep->stream_index];
2185 av_dict_set(&rep->assoc_stream->metadata, "id", rep->id, 0);
2187 av_dict_set(&rep->assoc_stream->metadata, "language", rep->lang, 0);
2188 av_freep(&rep->lang);
2198 static void recheck_discard_flags(AVFormatContext *s, struct representation **p, int n)
2202 for (i = 0; i < n; i++) {
2203 struct representation *pls = p[i];
2204 int needed = !pls->assoc_stream || pls->assoc_stream->discard < AVDISCARD_ALL;
2206 if (needed && !pls->ctx) {
2207 pls->cur_seg_offset = 0;
2208 pls->init_sec_buf_read_offset = 0;
2210 for (j = 0; j < n; j++) {
2211 pls->cur_seq_no = FFMAX(pls->cur_seq_no, p[j]->cur_seq_no);
2213 reopen_demux_for_component(s, pls);
2214 av_log(s, AV_LOG_INFO, "Now receiving stream_index %d\n", pls->stream_index);
2215 } else if (!needed && pls->ctx) {
2216 close_demux_for_component(pls);
2217 ff_format_io_close(pls->parent, &pls->input);
2218 av_log(s, AV_LOG_INFO, "No longer receiving stream_index %d\n", pls->stream_index);
2223 static int dash_read_packet(AVFormatContext *s, AVPacket *pkt)
2225 DASHContext *c = s->priv_data;
2228 struct representation *cur = NULL;
2229 struct representation *rep = NULL;
2231 recheck_discard_flags(s, c->videos, c->n_videos);
2232 recheck_discard_flags(s, c->audios, c->n_audios);
2233 recheck_discard_flags(s, c->subtitles, c->n_subtitles);
2235 for (i = 0; i < c->n_videos; i++) {
2239 if (!cur || rep->cur_timestamp < mints) {
2241 mints = rep->cur_timestamp;
2244 for (i = 0; i < c->n_audios; i++) {
2248 if (!cur || rep->cur_timestamp < mints) {
2250 mints = rep->cur_timestamp;
2254 for (i = 0; i < c->n_subtitles; i++) {
2255 rep = c->subtitles[i];
2258 if (!cur || rep->cur_timestamp < mints) {
2260 mints = rep->cur_timestamp;
2265 return AVERROR_INVALIDDATA;
2267 while (!ff_check_interrupt(c->interrupt_callback) && !ret) {
2268 ret = av_read_frame(cur->ctx, pkt);
2270 /* If we got a packet, return it */
2271 cur->cur_timestamp = av_rescale(pkt->pts, (int64_t)cur->ctx->streams[0]->time_base.num * 90000, cur->ctx->streams[0]->time_base.den);
2272 pkt->stream_index = cur->stream_index;
2275 if (cur->is_restart_needed) {
2276 cur->cur_seg_offset = 0;
2277 cur->init_sec_buf_read_offset = 0;
2278 ff_format_io_close(cur->parent, &cur->input);
2279 ret = reopen_demux_for_component(s, cur);
2280 cur->is_restart_needed = 0;
2286 static int dash_close(AVFormatContext *s)
2288 DASHContext *c = s->priv_data;
2291 av_dict_free(&c->avio_opts);
2292 av_freep(&c->base_url);
2296 static int dash_seek(AVFormatContext *s, struct representation *pls, int64_t seek_pos_msec, int flags, int dry_run)
2301 int64_t duration = 0;
2303 av_log(pls->parent, AV_LOG_VERBOSE, "DASH seek pos[%"PRId64"ms], playlist %d%s\n",
2304 seek_pos_msec, pls->rep_idx, dry_run ? " (dry)" : "");
2306 // single fragment mode
2307 if (pls->n_fragments == 1) {
2308 pls->cur_timestamp = 0;
2309 pls->cur_seg_offset = 0;
2312 ff_read_frame_flush(pls->ctx);
2313 return av_seek_frame(pls->ctx, -1, seek_pos_msec * 1000, flags);
2316 ff_format_io_close(pls->parent, &pls->input);
2318 // find the nearest fragment
2319 if (pls->n_timelines > 0 && pls->fragment_timescale > 0) {
2320 int64_t num = pls->first_seq_no;
2321 av_log(pls->parent, AV_LOG_VERBOSE, "dash_seek with SegmentTimeline start n_timelines[%d] "
2322 "last_seq_no[%"PRId64"], playlist %d.\n",
2323 (int)pls->n_timelines, (int64_t)pls->last_seq_no, (int)pls->rep_idx);
2324 for (i = 0; i < pls->n_timelines; i++) {
2325 if (pls->timelines[i]->starttime > 0) {
2326 duration = pls->timelines[i]->starttime;
2328 duration += pls->timelines[i]->duration;
2329 if (seek_pos_msec < ((duration * 1000) / pls->fragment_timescale)) {
2332 for (j = 0; j < pls->timelines[i]->repeat; j++) {
2333 duration += pls->timelines[i]->duration;
2335 if (seek_pos_msec < ((duration * 1000) / pls->fragment_timescale)) {
2343 pls->cur_seq_no = num > pls->last_seq_no ? pls->last_seq_no : num;
2344 av_log(pls->parent, AV_LOG_VERBOSE, "dash_seek with SegmentTimeline end cur_seq_no[%"PRId64"], playlist %d.\n",
2345 (int64_t)pls->cur_seq_no, (int)pls->rep_idx);
2346 } else if (pls->fragment_duration > 0) {
2347 pls->cur_seq_no = pls->first_seq_no + ((seek_pos_msec * pls->fragment_timescale) / pls->fragment_duration) / 1000;
2349 av_log(pls->parent, AV_LOG_ERROR, "dash_seek missing timeline or fragment_duration\n");
2350 pls->cur_seq_no = pls->first_seq_no;
2352 pls->cur_timestamp = 0;
2353 pls->cur_seg_offset = 0;
2354 pls->init_sec_buf_read_offset = 0;
2355 ret = dry_run ? 0 : reopen_demux_for_component(s, pls);
2360 static int dash_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
2363 DASHContext *c = s->priv_data;
2364 int64_t seek_pos_msec = av_rescale_rnd(timestamp, 1000,
2365 s->streams[stream_index]->time_base.den,
2366 flags & AVSEEK_FLAG_BACKWARD ?
2367 AV_ROUND_DOWN : AV_ROUND_UP);
2368 if ((flags & AVSEEK_FLAG_BYTE) || c->is_live)
2369 return AVERROR(ENOSYS);
2371 /* Seek in discarded streams with dry_run=1 to avoid reopening them */
2372 for (i = 0; i < c->n_videos; i++) {
2374 ret = dash_seek(s, c->videos[i], seek_pos_msec, flags, !c->videos[i]->ctx);
2376 for (i = 0; i < c->n_audios; i++) {
2378 ret = dash_seek(s, c->audios[i], seek_pos_msec, flags, !c->audios[i]->ctx);
2380 for (i = 0; i < c->n_subtitles; i++) {
2382 ret = dash_seek(s, c->subtitles[i], seek_pos_msec, flags, !c->subtitles[i]->ctx);
2388 static int dash_probe(const AVProbeData *p)
2390 if (!av_stristr(p->buf, "<MPD"))
2393 if (av_stristr(p->buf, "dash:profile:isoff-on-demand:2011") ||
2394 av_stristr(p->buf, "dash:profile:isoff-live:2011") ||
2395 av_stristr(p->buf, "dash:profile:isoff-live:2012") ||
2396 av_stristr(p->buf, "dash:profile:isoff-main:2011") ||
2397 av_stristr(p->buf, "3GPP:PSS:profile:DASH1")) {
2398 return AVPROBE_SCORE_MAX;
2400 if (av_stristr(p->buf, "dash:profile")) {
2401 return AVPROBE_SCORE_MAX;
2407 #define OFFSET(x) offsetof(DASHContext, x)
2408 #define FLAGS AV_OPT_FLAG_DECODING_PARAM
2409 static const AVOption dash_options[] = {
2410 {"allowed_extensions", "List of file extensions that dash is allowed to access",
2411 OFFSET(allowed_extensions), AV_OPT_TYPE_STRING,
2412 {.str = "aac,m4a,m4s,m4v,mov,mp4,webm,ts"},
2413 INT_MIN, INT_MAX, FLAGS},
2417 static const AVClass dash_class = {
2418 .class_name = "dash",
2419 .item_name = av_default_item_name,
2420 .option = dash_options,
2421 .version = LIBAVUTIL_VERSION_INT,
2424 AVInputFormat ff_dash_demuxer = {
2426 .long_name = NULL_IF_CONFIG_SMALL("Dynamic Adaptive Streaming over HTTP"),
2427 .priv_class = &dash_class,
2428 .priv_data_size = sizeof(DASHContext),
2429 .read_probe = dash_probe,
2430 .read_header = dash_read_header,
2431 .read_packet = dash_read_packet,
2432 .read_close = dash_close,
2433 .read_seek = dash_read_seek,
2434 .flags = AVFMT_NO_BYTE_SEEK,