2 * Dynamic Adaptive Streaming over HTTP demux
3 * Copyright (c) 2017 samsamsam@o2.pl based on HLS demux
4 * Copyright (c) 2017 Steven Liu
6 * This file is part of FFmpeg.
8 * FFmpeg is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * FFmpeg is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with FFmpeg; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22 #include <libxml/parser.h>
23 #include "libavutil/intreadwrite.h"
24 #include "libavutil/opt.h"
25 #include "libavutil/time.h"
26 #include "libavutil/parseutils.h"
28 #include "avio_internal.h"
31 #define INITIAL_BUFFER_SIZE 32768
40 * reference to : ISO_IEC_23009-1-DASH-2012
42 * Table: Table 17 — Semantics of SegmentTimeline element
45 /* starttime: Element or Attribute Name
46 * specifies the MPD start time, in @timescale units,
47 * the first Segment in the series starts relative to the beginning of the Period.
48 * The value of this attribute must be equal to or greater than the sum of the previous S
49 * element earliest presentation time and the sum of the contiguous Segment durations.
50 * If the value of the attribute is greater than what is expressed by the previous S element,
51 * it expresses discontinuities in the timeline.
52 * If not present then the value shall be assumed to be zero for the first S element
53 * and for the subsequent S elements, the value shall be assumed to be the sum of
54 * the previous S element's earliest presentation time and contiguous duration
55 * (i.e. previous S@starttime + @duration * (@repeat + 1)).
58 /* repeat: Element or Attribute Name
59 * specifies the repeat count of the number of following contiguous Segments with
60 * the same duration expressed by the value of @duration. This value is zero-based
61 * (e.g. a value of three means four Segments in the contiguous series).
64 /* duration: Element or Attribute Name
65 * specifies the Segment duration, in units of the value of the @timescale.
71 * Each playlist has its own demuxer. If it is currently active,
72 * it has an opened AVIOContext too, and potentially an AVPacket
73 * containing the next packet from this stream.
75 struct representation {
79 AVFormatContext *parent;
86 enum AVMediaType type;
89 struct fragment **fragments; /* VOD list of fragment for profile */
92 struct timeline **timelines;
96 int64_t start_number; /* used in case when we have dynamic list of segment to know which segments are new one*/
98 int64_t fragment_duration;
99 int64_t fragment_timescale;
101 int64_t presentation_timeoffset;
104 int64_t cur_seg_offset;
105 int64_t cur_seg_size;
106 struct fragment *cur_seg;
108 /* Currently active Media Initialization Section */
109 struct fragment *init_section;
110 uint8_t *init_sec_buf;
111 uint32_t init_sec_buf_size;
112 uint32_t init_sec_data_len;
113 uint32_t init_sec_buf_read_offset;
114 int64_t cur_timestamp;
115 int is_restart_needed;
118 typedef struct DASHContext {
119 const AVClass *class;
121 struct representation *cur_video;
122 struct representation *cur_audio;
124 /* MediaPresentationDescription Attribute */
125 uint64_t media_presentation_duration;
126 uint64_t suggested_presentation_delay;
127 uint64_t availability_start_time;
128 uint64_t publish_time;
129 uint64_t minimum_update_period;
130 uint64_t time_shift_buffer_depth;
131 uint64_t min_buffer_time;
133 /* Period Attribute */
134 uint64_t period_duration;
135 uint64_t period_start;
138 AVIOInterruptCB *interrupt_callback;
139 char *user_agent; ///< holds HTTP user agent set as an AVOption to the HTTP protocol context
140 char *cookies; ///< holds HTTP cookie values set in either the initial response or as an AVOption to the HTTP protocol context
141 char *headers; ///< holds HTTP headers set as an AVOption to the HTTP protocol context
142 char *allowed_extensions;
143 AVDictionary *avio_opts;
146 static uint64_t get_current_time_in_sec(void)
148 return av_gettime() / 1000000;
151 static uint64_t get_utc_date_time_insec(AVFormatContext *s, const char *datetime)
162 /* ISO-8601 date parser */
166 ret = sscanf(datetime, "%d-%d-%dT%d:%d:%fZ", &year, &month, &day, &hour, &minute, &second);
167 /* year, month, day, hour, minute, second 6 arguments */
169 av_log(s, AV_LOG_WARNING, "get_utc_date_time_insec get a wrong time format\n");
171 timeinfo.tm_year = year - 1900;
172 timeinfo.tm_mon = month - 1;
173 timeinfo.tm_mday = day;
174 timeinfo.tm_hour = hour;
175 timeinfo.tm_min = minute;
176 timeinfo.tm_sec = (int)second;
178 return av_timegm(&timeinfo);
181 static uint32_t get_duration_insec(AVFormatContext *s, const char *duration)
183 /* ISO-8601 duration parser */
191 const char *ptr = duration;
194 if (*ptr == 'P' || *ptr == 'T') {
199 if (sscanf(ptr, "%f%c%n", &value, &type, &size) != 2) {
200 av_log(s, AV_LOG_WARNING, "get_duration_insec get a wrong time format\n");
201 return 0; /* parser error */
205 days = (uint32_t)value;
208 hours = (uint32_t)value;
211 mins = (uint32_t)value;
214 secs = (uint32_t)value;
217 // handle invalid type
222 return ((days * 24 + hours) * 60 + mins) * 60 + secs;
225 static int64_t get_segment_start_time_based_on_timeline(struct representation *pls, int64_t cur_seq_no)
227 int64_t start_time = 0;
232 if (pls->n_timelines) {
233 for (i = 0; i < pls->n_timelines; i++) {
234 if (pls->timelines[i]->starttime > 0) {
235 start_time = pls->timelines[i]->starttime;
237 if (num == cur_seq_no)
240 start_time += pls->timelines[i]->duration;
241 for (j = 0; j < pls->timelines[i]->repeat; j++) {
243 if (num == cur_seq_no)
245 start_time += pls->timelines[i]->duration;
254 static int64_t calc_next_seg_no_from_timelines(struct representation *pls, int64_t cur_time)
259 int64_t start_time = 0;
261 for (i = 0; i < pls->n_timelines; i++) {
262 if (pls->timelines[i]->starttime > 0) {
263 start_time = pls->timelines[i]->starttime;
265 if (start_time > cur_time)
268 start_time += pls->timelines[i]->duration;
269 for (j = 0; j < pls->timelines[i]->repeat; j++) {
271 if (start_time > cur_time)
273 start_time += pls->timelines[i]->duration;
284 static void free_fragment(struct fragment **seg)
289 av_freep(&(*seg)->url);
293 static void free_fragment_list(struct representation *pls)
297 for (i = 0; i < pls->n_fragments; i++) {
298 free_fragment(&pls->fragments[i]);
300 av_freep(&pls->fragments);
301 pls->n_fragments = 0;
304 static void free_timelines_list(struct representation *pls)
308 for (i = 0; i < pls->n_timelines; i++) {
309 av_freep(&pls->timelines[i]);
311 av_freep(&pls->timelines);
312 pls->n_timelines = 0;
315 static void free_representation(struct representation *pls)
317 free_fragment_list(pls);
318 free_timelines_list(pls);
319 free_fragment(&pls->cur_seg);
320 free_fragment(&pls->init_section);
321 av_freep(&pls->init_sec_buf);
322 av_freep(&pls->pb.buffer);
324 ff_format_io_close(pls->parent, &pls->input);
327 avformat_close_input(&pls->ctx);
330 av_freep(&pls->url_template);
334 static void set_httpheader_options(DASHContext *c, AVDictionary **opts)
336 // broker prior HTTP options that should be consistent across requests
337 av_dict_set(opts, "user-agent", c->user_agent, 0);
338 av_dict_set(opts, "cookies", c->cookies, 0);
339 av_dict_set(opts, "headers", c->headers, 0);
341 av_dict_set(opts, "seekable", "0", 0);
344 static void update_options(char **dest, const char *name, void *src)
347 av_opt_get(src, name, AV_OPT_SEARCH_CHILDREN, (uint8_t**)dest);
352 static int open_url(AVFormatContext *s, AVIOContext **pb, const char *url,
353 AVDictionary *opts, AVDictionary *opts2, int *is_http)
355 DASHContext *c = s->priv_data;
356 AVDictionary *tmp = NULL;
357 const char *proto_name = NULL;
360 av_dict_copy(&tmp, opts, 0);
361 av_dict_copy(&tmp, opts2, 0);
363 if (av_strstart(url, "crypto", NULL)) {
364 if (url[6] == '+' || url[6] == ':')
365 proto_name = avio_find_protocol_name(url + 7);
369 proto_name = avio_find_protocol_name(url);
372 return AVERROR_INVALIDDATA;
374 // only http(s) & file are allowed
375 if (av_strstart(proto_name, "file", NULL)) {
376 if (strcmp(c->allowed_extensions, "ALL") && !av_match_ext(url, c->allowed_extensions)) {
377 av_log(s, AV_LOG_ERROR,
378 "Filename extension of \'%s\' is not a common multimedia extension, blocked for security reasons.\n"
379 "If you wish to override this adjust allowed_extensions, you can set it to \'ALL\' to allow all\n",
381 return AVERROR_INVALIDDATA;
383 } else if (av_strstart(proto_name, "http", NULL)) {
386 return AVERROR_INVALIDDATA;
388 if (!strncmp(proto_name, url, strlen(proto_name)) && url[strlen(proto_name)] == ':')
390 else if (av_strstart(url, "crypto", NULL) && !strncmp(proto_name, url + 7, strlen(proto_name)) && url[7 + strlen(proto_name)] == ':')
392 else if (strcmp(proto_name, "file") || !strncmp(url, "file,", 5))
393 return AVERROR_INVALIDDATA;
395 ret = s->io_open(s, pb, url, AVIO_FLAG_READ, &tmp);
397 // update cookies on http response with setcookies.
398 char *new_cookies = NULL;
400 if (!(s->flags & AVFMT_FLAG_CUSTOM_IO))
401 av_opt_get(*pb, "cookies", AV_OPT_SEARCH_CHILDREN, (uint8_t**)&new_cookies);
405 c->cookies = new_cookies;
408 av_dict_set(&opts, "cookies", c->cookies, 0);
414 *is_http = av_strstart(proto_name, "http", NULL);
419 static char *get_content_url(xmlNodePtr *baseurl_nodes,
422 char *rep_bandwidth_val,
428 char tmp_str[MAX_URL_SIZE];
429 char tmp_str_2[MAX_URL_SIZE];
431 memset(tmp_str, 0, sizeof(tmp_str));
433 for (i = 0; i < n_baseurl_nodes; ++i) {
434 if (baseurl_nodes[i] &&
435 baseurl_nodes[i]->children &&
436 baseurl_nodes[i]->children->type == XML_TEXT_NODE) {
437 text = xmlNodeGetContent(baseurl_nodes[i]->children);
439 memset(tmp_str, 0, sizeof(tmp_str));
440 memset(tmp_str_2, 0, sizeof(tmp_str_2));
441 ff_make_absolute_url(tmp_str_2, MAX_URL_SIZE, tmp_str, text);
442 av_strlcpy(tmp_str, tmp_str_2, sizeof(tmp_str));
449 av_strlcat(tmp_str, (const char*)val, sizeof(tmp_str));
452 url = av_strireplace(tmp_str, "$RepresentationID$", (const char*)rep_id_val);
456 av_strlcpy(tmp_str, url, sizeof(tmp_str));
459 if (rep_bandwidth_val && tmp_str[0] != '\0') {
460 url = av_strireplace(tmp_str, "$Bandwidth$", (const char*)rep_bandwidth_val);
468 static char *get_val_from_nodes_tab(xmlNodePtr *nodes, const int n_nodes, const char *attrname)
473 for (i = 0; i < n_nodes; ++i) {
475 val = xmlGetProp(nodes[i], attrname);
484 static xmlNodePtr find_child_node_by_name(xmlNodePtr rootnode, const char *nodename)
486 xmlNodePtr node = rootnode;
491 node = xmlFirstElementChild(node);
493 if (!av_strcasecmp(node->name, nodename)) {
496 node = xmlNextElementSibling(node);
501 static enum AVMediaType get_content_type(xmlNodePtr node)
503 enum AVMediaType type = AVMEDIA_TYPE_UNKNOWN;
509 for (i = 0; i < 2; i++) {
510 attr = i ? "mimeType" : "contentType";
511 val = xmlGetProp(node, attr);
513 if (av_stristr((const char *)val, "video")) {
514 type = AVMEDIA_TYPE_VIDEO;
515 } else if (av_stristr((const char *)val, "audio")) {
516 type = AVMEDIA_TYPE_AUDIO;
525 static int parse_manifest_segmenturlnode(AVFormatContext *s, struct representation *rep,
526 xmlNodePtr fragmenturl_node,
527 xmlNodePtr *baseurl_nodes,
529 char *rep_bandwidth_val)
531 char *initialization_val = NULL;
532 char *media_val = NULL;
534 if (!av_strcasecmp(fragmenturl_node->name, (const char *)"Initialization")) {
535 initialization_val = xmlGetProp(fragmenturl_node, "sourceURL");
536 if (initialization_val) {
537 rep->init_section = av_mallocz(sizeof(struct fragment));
538 if (!rep->init_section) {
539 xmlFree(initialization_val);
540 return AVERROR(ENOMEM);
542 rep->init_section->url = get_content_url(baseurl_nodes, 4,
546 if (!rep->init_section->url) {
547 av_free(rep->init_section);
548 xmlFree(initialization_val);
549 return AVERROR(ENOMEM);
551 rep->init_section->size = -1;
552 xmlFree(initialization_val);
554 } else if (!av_strcasecmp(fragmenturl_node->name, (const char *)"SegmentURL")) {
555 media_val = xmlGetProp(fragmenturl_node, "media");
557 struct fragment *seg = av_mallocz(sizeof(struct fragment));
560 return AVERROR(ENOMEM);
562 seg->url = get_content_url(baseurl_nodes, 4,
569 return AVERROR(ENOMEM);
572 dynarray_add(&rep->fragments, &rep->n_fragments, seg);
580 static int parse_manifest_segmenttimeline(AVFormatContext *s, struct representation *rep,
581 xmlNodePtr fragment_timeline_node)
583 xmlAttrPtr attr = NULL;
586 if (!av_strcasecmp(fragment_timeline_node->name, (const char *)"S")) {
587 struct timeline *tml = av_mallocz(sizeof(struct timeline));
589 return AVERROR(ENOMEM);
591 attr = fragment_timeline_node->properties;
593 val = xmlGetProp(fragment_timeline_node, attr->name);
596 av_log(s, AV_LOG_WARNING, "parse_manifest_segmenttimeline attr->name = %s val is NULL\n", attr->name);
600 if (!av_strcasecmp(attr->name, (const char *)"t")) {
601 tml->starttime = (int64_t)strtoll(val, NULL, 10);
602 } else if (!av_strcasecmp(attr->name, (const char *)"r")) {
603 tml->repeat =(int64_t) strtoll(val, NULL, 10);
604 } else if (!av_strcasecmp(attr->name, (const char *)"d")) {
605 tml->duration = (int64_t)strtoll(val, NULL, 10);
610 dynarray_add(&rep->timelines, &rep->n_timelines, tml);
616 static int parse_manifest_representation(AVFormatContext *s, const char *url,
618 xmlNodePtr adaptionset_node,
619 xmlNodePtr mpd_baseurl_node,
620 xmlNodePtr period_baseurl_node,
621 xmlNodePtr fragment_template_node,
622 xmlNodePtr content_component_node,
623 xmlNodePtr adaptionset_baseurl_node)
626 int32_t audio_rep_idx = 0;
627 int32_t video_rep_idx = 0;
628 DASHContext *c = s->priv_data;
629 struct representation *rep = NULL;
630 struct fragment *seg = NULL;
631 xmlNodePtr representation_segmenttemplate_node = NULL;
632 xmlNodePtr representation_baseurl_node = NULL;
633 xmlNodePtr representation_segmentlist_node = NULL;
634 xmlNodePtr fragment_timeline_node = NULL;
635 xmlNodePtr fragment_templates_tab[2];
636 char *duration_val = NULL;
637 char *presentation_timeoffset_val = NULL;
638 char *startnumber_val = NULL;
639 char *timescale_val = NULL;
640 char *initialization_val = NULL;
641 char *media_val = NULL;
642 xmlNodePtr baseurl_nodes[4];
643 xmlNodePtr representation_node = node;
644 char *rep_id_val = xmlGetProp(representation_node, "id");
645 char *rep_bandwidth_val = xmlGetProp(representation_node, "bandwidth");
646 enum AVMediaType type = AVMEDIA_TYPE_UNKNOWN;
648 // try get information from representation
649 if (type == AVMEDIA_TYPE_UNKNOWN)
650 type = get_content_type(representation_node);
651 // try get information from contentComponen
652 if (type == AVMEDIA_TYPE_UNKNOWN)
653 type = get_content_type(content_component_node);
654 // try get information from adaption set
655 if (type == AVMEDIA_TYPE_UNKNOWN)
656 type = get_content_type(adaptionset_node);
657 if (type == AVMEDIA_TYPE_UNKNOWN) {
658 av_log(s, AV_LOG_VERBOSE, "Parsing '%s' - skipp not supported representation type\n", url);
659 } else if ((type == AVMEDIA_TYPE_VIDEO && !c->cur_video) || (type == AVMEDIA_TYPE_AUDIO && !c->cur_audio)) {
660 // convert selected representation to our internal struct
661 rep = av_mallocz(sizeof(struct representation));
663 ret = AVERROR(ENOMEM);
666 representation_segmenttemplate_node = find_child_node_by_name(representation_node, "SegmentTemplate");
667 representation_baseurl_node = find_child_node_by_name(representation_node, "BaseURL");
668 representation_segmentlist_node = find_child_node_by_name(representation_node, "SegmentList");
670 baseurl_nodes[0] = mpd_baseurl_node;
671 baseurl_nodes[1] = period_baseurl_node;
672 baseurl_nodes[2] = adaptionset_baseurl_node;
673 baseurl_nodes[3] = representation_baseurl_node;
675 if (representation_segmenttemplate_node || fragment_template_node) {
676 fragment_timeline_node = NULL;
677 fragment_templates_tab[0] = representation_segmenttemplate_node;
678 fragment_templates_tab[1] = fragment_template_node;
680 presentation_timeoffset_val = get_val_from_nodes_tab(fragment_templates_tab, 2, "presentationTimeOffset");
681 duration_val = get_val_from_nodes_tab(fragment_templates_tab, 2, "duration");
682 startnumber_val = get_val_from_nodes_tab(fragment_templates_tab, 2, "startNumber");
683 timescale_val = get_val_from_nodes_tab(fragment_templates_tab, 2, "timescale");
684 initialization_val = get_val_from_nodes_tab(fragment_templates_tab, 2, "initialization");
685 media_val = get_val_from_nodes_tab(fragment_templates_tab, 2, "media");
687 if (initialization_val) {
688 rep->init_section = av_mallocz(sizeof(struct fragment));
689 if (!rep->init_section) {
691 ret = AVERROR(ENOMEM);
694 rep->init_section->url = get_content_url(baseurl_nodes, 4, rep_id_val, rep_bandwidth_val, initialization_val);
695 if (!rep->init_section->url) {
696 av_free(rep->init_section);
698 ret = AVERROR(ENOMEM);
701 rep->init_section->size = -1;
702 xmlFree(initialization_val);
706 rep->url_template = get_content_url(baseurl_nodes, 4, rep_id_val, rep_bandwidth_val, media_val);
710 if (presentation_timeoffset_val) {
711 rep->presentation_timeoffset = (int64_t) strtoll(presentation_timeoffset_val, NULL, 10);
712 xmlFree(presentation_timeoffset_val);
715 rep->fragment_duration = (int64_t) strtoll(duration_val, NULL, 10);
716 xmlFree(duration_val);
719 rep->fragment_timescale = (int64_t) strtoll(timescale_val, NULL, 10);
720 xmlFree(timescale_val);
722 if (startnumber_val) {
723 rep->first_seq_no = (int64_t) strtoll(startnumber_val, NULL, 10);
724 xmlFree(startnumber_val);
727 fragment_timeline_node = find_child_node_by_name(representation_segmenttemplate_node, "SegmentTimeline");
729 if (!fragment_timeline_node)
730 fragment_timeline_node = find_child_node_by_name(fragment_template_node, "SegmentTimeline");
731 if (fragment_timeline_node) {
732 fragment_timeline_node = xmlFirstElementChild(fragment_timeline_node);
733 while (fragment_timeline_node) {
734 ret = parse_manifest_segmenttimeline(s, rep, fragment_timeline_node);
738 fragment_timeline_node = xmlNextElementSibling(fragment_timeline_node);
741 } else if (representation_baseurl_node && !representation_segmentlist_node) {
742 seg = av_mallocz(sizeof(struct fragment));
744 ret = AVERROR(ENOMEM);
747 seg->url = get_content_url(baseurl_nodes, 4, rep_id_val, rep_bandwidth_val, NULL);
750 ret = AVERROR(ENOMEM);
754 dynarray_add(&rep->fragments, &rep->n_fragments, seg);
755 } else if (representation_segmentlist_node) {
756 // TODO: https://www.brendanlong.com/the-structure-of-an-mpeg-dash-mpd.html
757 // http://www-itec.uni-klu.ac.at/dash/ddash/mpdGenerator.php?fragmentlength=15&type=full
758 xmlNodePtr fragmenturl_node = NULL;
759 duration_val = xmlGetProp(representation_segmentlist_node, "duration");
760 timescale_val = xmlGetProp(representation_segmentlist_node, "timescale");
762 rep->fragment_duration = (int64_t) strtoll(duration_val, NULL, 10);
763 xmlFree(duration_val);
766 rep->fragment_timescale = (int64_t) strtoll(timescale_val, NULL, 10);
767 xmlFree(timescale_val);
769 fragmenturl_node = xmlFirstElementChild(representation_segmentlist_node);
770 while (fragmenturl_node) {
771 ret = parse_manifest_segmenturlnode(s, rep, fragmenturl_node,
778 fragmenturl_node = xmlNextElementSibling(fragmenturl_node);
781 fragment_timeline_node = find_child_node_by_name(representation_segmenttemplate_node, "SegmentTimeline");
783 if (!fragment_timeline_node)
784 fragment_timeline_node = find_child_node_by_name(fragment_template_node, "SegmentTimeline");
785 if (fragment_timeline_node) {
786 fragment_timeline_node = xmlFirstElementChild(fragment_timeline_node);
787 while (fragment_timeline_node) {
788 ret = parse_manifest_segmenttimeline(s, rep, fragment_timeline_node);
792 fragment_timeline_node = xmlNextElementSibling(fragment_timeline_node);
796 free_representation(rep);
798 av_log(s, AV_LOG_ERROR, "Unknown format of Representation node id[%s] \n", (const char *)rep_id_val);
802 if (rep->fragment_duration > 0 && !rep->fragment_timescale)
803 rep->fragment_timescale = 1;
804 if (type == AVMEDIA_TYPE_VIDEO) {
805 rep->rep_idx = video_rep_idx;
808 rep->rep_idx = audio_rep_idx;
814 video_rep_idx += type == AVMEDIA_TYPE_VIDEO;
815 audio_rep_idx += type == AVMEDIA_TYPE_AUDIO;
820 if (rep_bandwidth_val)
821 xmlFree(rep_bandwidth_val);
826 static int parse_manifest_adaptationset(AVFormatContext *s, const char *url,
827 xmlNodePtr adaptionset_node,
828 xmlNodePtr mpd_baseurl_node,
829 xmlNodePtr period_baseurl_node)
832 xmlNodePtr fragment_template_node = NULL;
833 xmlNodePtr content_component_node = NULL;
834 xmlNodePtr adaptionset_baseurl_node = NULL;
835 xmlNodePtr node = NULL;
837 node = xmlFirstElementChild(adaptionset_node);
839 if (!av_strcasecmp(node->name, (const char *)"SegmentTemplate")) {
840 fragment_template_node = node;
841 } else if (!av_strcasecmp(node->name, (const char *)"ContentComponent")) {
842 content_component_node = node;
843 } else if (!av_strcasecmp(node->name, (const char *)"BaseURL")) {
844 adaptionset_baseurl_node = node;
845 } else if (!av_strcasecmp(node->name, (const char *)"Representation")) {
846 ret = parse_manifest_representation(s, url, node,
850 fragment_template_node,
851 content_component_node,
852 adaptionset_baseurl_node);
857 node = xmlNextElementSibling(node);
862 static int parse_manifest(AVFormatContext *s, const char *url, AVIOContext *in)
864 DASHContext *c = s->priv_data;
867 uint8_t *new_url = NULL;
868 int64_t filesize = 0;
870 AVDictionary *opts = NULL;
872 xmlNodePtr root_element = NULL;
873 xmlNodePtr node = NULL;
874 xmlNodePtr period_node = NULL;
875 xmlNodePtr mpd_baseurl_node = NULL;
876 xmlNodePtr period_baseurl_node = NULL;
877 xmlNodePtr adaptionset_node = NULL;
878 xmlAttrPtr attr = NULL;
880 uint32_t perdiod_duration_sec = 0;
881 uint32_t perdiod_start_sec = 0;
882 int32_t audio_rep_idx = 0;
883 int32_t video_rep_idx = 0;
888 set_httpheader_options(c, &opts);
889 ret = avio_open2(&in, url, AVIO_FLAG_READ, c->interrupt_callback, &opts);
895 if (av_opt_get(in, "location", AV_OPT_SEARCH_CHILDREN, &new_url) >= 0) {
896 c->base_url = av_strdup(new_url);
898 c->base_url = av_strdup(url);
901 filesize = avio_size(in);
906 buffer = av_mallocz(filesize);
908 av_free(c->base_url);
909 return AVERROR(ENOMEM);
912 filesize = avio_read(in, buffer, filesize);
914 av_log(s, AV_LOG_ERROR, "Unable to read to offset '%s'\n", url);
915 ret = AVERROR_INVALIDDATA;
919 doc = xmlReadMemory(buffer, filesize, c->base_url, NULL, 0);
920 root_element = xmlDocGetRootElement(doc);
924 ret = AVERROR_INVALIDDATA;
925 av_log(s, AV_LOG_ERROR, "Unable to parse '%s' - missing root node\n", url);
929 if (node->type != XML_ELEMENT_NODE ||
930 av_strcasecmp(node->name, (const char *)"MPD")) {
931 ret = AVERROR_INVALIDDATA;
932 av_log(s, AV_LOG_ERROR, "Unable to parse '%s' - wrong root node name[%s] type[%d]\n", url, node->name, (int)node->type);
936 val = xmlGetProp(node, "type");
938 av_log(s, AV_LOG_ERROR, "Unable to parse '%s' - missing type attrib\n", url);
939 ret = AVERROR_INVALIDDATA;
942 if (!av_strcasecmp(val, (const char *)"dynamic"))
946 attr = node->properties;
948 val = xmlGetProp(node, attr->name);
950 if (!av_strcasecmp(attr->name, (const char *)"availabilityStartTime")) {
951 c->availability_start_time = get_utc_date_time_insec(s, (const char *)val);
952 } else if (!av_strcasecmp(attr->name, (const char *)"publishTime")) {
953 c->publish_time = get_utc_date_time_insec(s, (const char *)val);
954 } else if (!av_strcasecmp(attr->name, (const char *)"minimumUpdatePeriod")) {
955 c->minimum_update_period = get_duration_insec(s, (const char *)val);
956 } else if (!av_strcasecmp(attr->name, (const char *)"timeShiftBufferDepth")) {
957 c->time_shift_buffer_depth = get_duration_insec(s, (const char *)val);
958 } else if (!av_strcasecmp(attr->name, (const char *)"minBufferTime")) {
959 c->min_buffer_time = get_duration_insec(s, (const char *)val);
960 } else if (!av_strcasecmp(attr->name, (const char *)"suggestedPresentationDelay")) {
961 c->suggested_presentation_delay = get_duration_insec(s, (const char *)val);
962 } else if (!av_strcasecmp(attr->name, (const char *)"mediaPresentationDuration")) {
963 c->media_presentation_duration = get_duration_insec(s, (const char *)val);
969 mpd_baseurl_node = find_child_node_by_name(node, "BaseURL");
971 // at now we can handle only one period, with the longest duration
972 node = xmlFirstElementChild(node);
974 if (!av_strcasecmp(node->name, (const char *)"Period")) {
975 perdiod_duration_sec = 0;
976 perdiod_start_sec = 0;
977 attr = node->properties;
979 val = xmlGetProp(node, attr->name);
980 if (!av_strcasecmp(attr->name, (const char *)"duration")) {
981 perdiod_duration_sec = get_duration_insec(s, (const char *)val);
982 } else if (!av_strcasecmp(attr->name, (const char *)"start")) {
983 perdiod_start_sec = get_duration_insec(s, (const char *)val);
988 if ((perdiod_duration_sec) >= (c->period_duration)) {
990 c->period_duration = perdiod_duration_sec;
991 c->period_start = perdiod_start_sec;
992 if (c->period_start > 0)
993 c->media_presentation_duration = c->period_duration;
996 node = xmlNextElementSibling(node);
999 av_log(s, AV_LOG_ERROR, "Unable to parse '%s' - missing Period node\n", url);
1000 ret = AVERROR_INVALIDDATA;
1004 adaptionset_node = xmlFirstElementChild(period_node);
1005 while (adaptionset_node) {
1006 if (!av_strcasecmp(adaptionset_node->name, (const char *)"BaseURL")) {
1007 period_baseurl_node = adaptionset_node;
1008 } else if (!av_strcasecmp(adaptionset_node->name, (const char *)"AdaptationSet")) {
1009 parse_manifest_adaptationset(s, url, adaptionset_node, mpd_baseurl_node, period_baseurl_node);
1011 adaptionset_node = xmlNextElementSibling(adaptionset_node);
1014 c->cur_video->rep_count = video_rep_idx;
1015 av_log(s, AV_LOG_VERBOSE, "rep_idx[%d]\n", (int)c->cur_video->rep_idx);
1016 av_log(s, AV_LOG_VERBOSE, "rep_count[%d]\n", (int)video_rep_idx);
1019 c->cur_audio->rep_count = audio_rep_idx;
1022 /*free the document */
1035 static int64_t calc_cur_seg_no(AVFormatContext *s, struct representation *pls)
1037 DASHContext *c = s->priv_data;
1039 int64_t start_time_offset = 0;
1042 if (pls->n_fragments) {
1043 num = pls->first_seq_no;
1044 } else if (pls->n_timelines) {
1045 start_time_offset = get_segment_start_time_based_on_timeline(pls, 0xFFFFFFFF) - pls->timelines[pls->first_seq_no]->starttime; // total duration of playlist
1046 if (start_time_offset < 60 * pls->fragment_timescale)
1047 start_time_offset = 0;
1049 start_time_offset = start_time_offset - 60 * pls->fragment_timescale;
1051 num = calc_next_seg_no_from_timelines(pls, pls->timelines[pls->first_seq_no]->starttime + start_time_offset);
1053 num = pls->first_seq_no;
1054 } else if (pls->fragment_duration){
1055 if (pls->presentation_timeoffset) {
1056 num = pls->presentation_timeoffset * pls->fragment_timescale / pls->fragment_duration;
1057 } else if (c->publish_time > 0 && !c->availability_start_time) {
1058 num = pls->first_seq_no + (((c->publish_time - c->availability_start_time) - c->suggested_presentation_delay) * pls->fragment_timescale) / pls->fragment_duration;
1060 num = pls->first_seq_no + (((get_current_time_in_sec() - c->availability_start_time) - c->suggested_presentation_delay) * pls->fragment_timescale) / pls->fragment_duration;
1064 num = pls->first_seq_no;
1069 static int64_t calc_min_seg_no(AVFormatContext *s, struct representation *pls)
1071 DASHContext *c = s->priv_data;
1074 if (c->is_live && pls->fragment_duration) {
1075 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;
1077 num = pls->first_seq_no;
1082 static int64_t calc_max_seg_no(struct representation *pls, DASHContext *c)
1086 if (pls->n_fragments) {
1087 num = pls->first_seq_no + pls->n_fragments - 1;
1088 } else if (pls->n_timelines) {
1090 num = pls->first_seq_no + pls->n_timelines - 1;
1091 for (i = 0; i < pls->n_timelines; i++) {
1092 num += pls->timelines[i]->repeat;
1094 } else if (c->is_live && pls->fragment_duration) {
1095 num = pls->first_seq_no + (((get_current_time_in_sec() - c->availability_start_time)) * pls->fragment_timescale) / pls->fragment_duration;
1096 } else if (pls->fragment_duration) {
1097 num = pls->first_seq_no + (c->media_presentation_duration * pls->fragment_timescale) / pls->fragment_duration;
1103 static void move_timelines(struct representation *rep_src, struct representation *rep_dest, DASHContext *c)
1105 if (rep_dest && rep_src ) {
1106 free_timelines_list(rep_dest);
1107 rep_dest->timelines = rep_src->timelines;
1108 rep_dest->n_timelines = rep_src->n_timelines;
1109 rep_dest->first_seq_no = rep_src->first_seq_no;
1110 rep_dest->last_seq_no = calc_max_seg_no(rep_dest, c);
1111 rep_src->timelines = NULL;
1112 rep_src->n_timelines = 0;
1113 rep_dest->cur_seq_no = rep_src->cur_seq_no;
1117 static void move_segments(struct representation *rep_src, struct representation *rep_dest, DASHContext *c)
1119 if (rep_dest && rep_src ) {
1120 free_fragment_list(rep_dest);
1121 if (rep_src->start_number > (rep_dest->start_number + rep_dest->n_fragments))
1122 rep_dest->cur_seq_no = 0;
1124 rep_dest->cur_seq_no += rep_src->start_number - rep_dest->start_number;
1125 rep_dest->fragments = rep_src->fragments;
1126 rep_dest->n_fragments = rep_src->n_fragments;
1127 rep_dest->parent = rep_src->parent;
1128 rep_dest->last_seq_no = calc_max_seg_no(rep_dest, c);
1129 rep_src->fragments = NULL;
1130 rep_src->n_fragments = 0;
1135 static int refresh_manifest(AVFormatContext *s)
1139 DASHContext *c = s->priv_data;
1141 // save current context
1142 struct representation *cur_video = c->cur_video;
1143 struct representation *cur_audio = c->cur_audio;
1144 char *base_url = c->base_url;
1147 c->cur_video = NULL;
1148 c->cur_audio = NULL;
1149 ret = parse_manifest(s, s->filename, NULL);
1153 if (cur_video && cur_video->timelines || cur_audio && cur_audio->timelines) {
1154 // calc current time
1155 int64_t currentVideoTime = 0;
1156 int64_t currentAudioTime = 0;
1157 if (cur_video && cur_video->timelines)
1158 currentVideoTime = get_segment_start_time_based_on_timeline(cur_video, cur_video->cur_seq_no) / cur_video->fragment_timescale;
1159 if (cur_audio && cur_audio->timelines)
1160 currentAudioTime = get_segment_start_time_based_on_timeline(cur_audio, cur_audio->cur_seq_no) / cur_audio->fragment_timescale;
1162 if (cur_video && cur_video->timelines) {
1163 c->cur_video->cur_seq_no = calc_next_seg_no_from_timelines(c->cur_video, currentVideoTime * cur_video->fragment_timescale - 1);
1164 if (c->cur_video->cur_seq_no >= 0) {
1165 move_timelines(c->cur_video, cur_video, c);
1168 if (cur_audio && cur_audio->timelines) {
1169 c->cur_audio->cur_seq_no = calc_next_seg_no_from_timelines(c->cur_audio, currentAudioTime * cur_audio->fragment_timescale - 1);
1170 if (c->cur_audio->cur_seq_no >= 0) {
1171 move_timelines(c->cur_audio, cur_audio, c);
1175 if (cur_video && cur_video->fragments) {
1176 move_segments(c->cur_video, cur_video, c);
1178 if (cur_audio && cur_audio->fragments) {
1179 move_segments(c->cur_audio, cur_audio, c);
1187 c->base_url = base_url;
1189 free_representation(c->cur_audio);
1191 free_representation(c->cur_video);
1192 c->cur_audio = cur_audio;
1193 c->cur_video = cur_video;
1197 static struct fragment *get_current_fragment(struct representation *pls)
1199 int64_t min_seq_no = 0;
1200 int64_t max_seq_no = 0;
1201 struct fragment *seg = NULL;
1202 struct fragment *seg_ptr = NULL;
1203 DASHContext *c = pls->parent->priv_data;
1205 while (( !ff_check_interrupt(c->interrupt_callback)&& pls->n_fragments > 0)) {
1206 if (pls->cur_seq_no < pls->n_fragments) {
1207 seg_ptr = pls->fragments[pls->cur_seq_no];
1208 seg = av_mallocz(sizeof(struct fragment));
1212 seg->url = av_strdup(seg_ptr->url);
1217 seg->size = seg_ptr->size;
1218 seg->url_offset = seg_ptr->url_offset;
1220 } else if (c->is_live) {
1221 refresh_manifest(pls->parent);
1227 min_seq_no = calc_min_seg_no(pls->parent, pls);
1228 max_seq_no = calc_max_seg_no(pls, c);
1230 if (pls->timelines || pls->fragments) {
1231 refresh_manifest(pls->parent);
1233 if (pls->cur_seq_no <= min_seq_no) {
1234 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);
1235 pls->cur_seq_no = calc_cur_seg_no(pls->parent, pls);
1236 } else if (pls->cur_seq_no > max_seq_no) {
1237 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);
1239 seg = av_mallocz(sizeof(struct fragment));
1243 } else if (pls->cur_seq_no <= pls->last_seq_no) {
1244 seg = av_mallocz(sizeof(struct fragment));
1250 char tmpfilename[MAX_URL_SIZE];
1252 ff_dash_fill_tmpl_params(tmpfilename, sizeof(tmpfilename), pls->url_template, 0, pls->cur_seq_no, 0, get_segment_start_time_based_on_timeline(pls, pls->cur_seq_no));
1253 seg->url = av_strireplace(pls->url_template, pls->url_template, tmpfilename);
1255 av_log(pls->parent, AV_LOG_WARNING, "Unable to resolve template url '%s', try to use origin template\n", pls->url_template);
1256 seg->url = av_strdup(pls->url_template);
1258 av_log(pls->parent, AV_LOG_ERROR, "Cannot resolve template url '%s'\n", pls->url_template);
1269 enum ReadFromURLMode {
1274 static int read_from_url(struct representation *pls, struct fragment *seg,
1275 uint8_t *buf, int buf_size,
1276 enum ReadFromURLMode mode)
1280 /* limit read if the fragment was only a part of a file */
1282 buf_size = FFMIN(buf_size, pls->cur_seg_size - pls->cur_seg_offset);
1284 if (mode == READ_COMPLETE) {
1285 ret = avio_read(pls->input, buf, buf_size);
1286 if (ret < buf_size) {
1287 av_log(pls->parent, AV_LOG_WARNING, "Could not read complete fragment.\n");
1290 ret = avio_read(pls->input, buf, buf_size);
1293 pls->cur_seg_offset += ret;
1298 static int open_input(DASHContext *c, struct representation *pls, struct fragment *seg)
1300 AVDictionary *opts = NULL;
1301 char url[MAX_URL_SIZE];
1304 set_httpheader_options(c, &opts);
1305 if (seg->size >= 0) {
1306 /* try to restrict the HTTP request to the part we want
1307 * (if this is in fact a HTTP request) */
1308 av_dict_set_int(&opts, "offset", seg->url_offset, 0);
1309 av_dict_set_int(&opts, "end_offset", seg->url_offset + seg->size, 0);
1312 ff_make_absolute_url(url, MAX_URL_SIZE, c->base_url, seg->url);
1313 av_log(pls->parent, AV_LOG_VERBOSE, "DASH request for url '%s', offset %"PRId64", playlist %d\n",
1314 url, seg->url_offset, pls->rep_idx);
1315 ret = open_url(pls->parent, &pls->input, url, c->avio_opts, opts, NULL);
1320 /* Seek to the requested position. If this was a HTTP request, the offset
1321 * should already be where want it to, but this allows e.g. local testing
1322 * without a HTTP server. */
1323 if (!ret && seg->url_offset) {
1324 int64_t seekret = avio_seek(pls->input, seg->url_offset, SEEK_SET);
1326 av_log(pls->parent, AV_LOG_ERROR, "Unable to seek to offset %"PRId64" of DASH fragment '%s'\n", seg->url_offset, seg->url);
1327 ret = (int) seekret;
1328 ff_format_io_close(pls->parent, &pls->input);
1333 av_dict_free(&opts);
1334 pls->cur_seg_offset = 0;
1335 pls->cur_seg_size = seg->size;
1339 static int update_init_section(struct representation *pls)
1341 static const int max_init_section_size = 1024 * 1024;
1342 DASHContext *c = pls->parent->priv_data;
1347 if (!pls->init_section || pls->init_sec_buf)
1350 ret = open_input(c, pls, pls->init_section);
1352 av_log(pls->parent, AV_LOG_WARNING,
1353 "Failed to open an initialization section in playlist %d\n",
1358 if (pls->init_section->size >= 0)
1359 sec_size = pls->init_section->size;
1360 else if ((urlsize = avio_size(pls->input)) >= 0)
1363 sec_size = max_init_section_size;
1365 av_log(pls->parent, AV_LOG_DEBUG,
1366 "Downloading an initialization section of size %"PRId64"\n",
1369 sec_size = FFMIN(sec_size, max_init_section_size);
1371 av_fast_malloc(&pls->init_sec_buf, &pls->init_sec_buf_size, sec_size);
1373 ret = read_from_url(pls, pls->init_section, pls->init_sec_buf,
1374 pls->init_sec_buf_size, READ_COMPLETE);
1375 ff_format_io_close(pls->parent, &pls->input);
1380 pls->init_sec_data_len = ret;
1381 pls->init_sec_buf_read_offset = 0;
1386 static int64_t seek_data(void *opaque, int64_t offset, int whence)
1388 struct representation *v = opaque;
1389 if (v->n_fragments && !v->init_sec_data_len) {
1390 return avio_seek(v->input, offset, whence);
1393 return AVERROR(ENOSYS);
1396 static int read_data(void *opaque, uint8_t *buf, int buf_size)
1399 struct representation *v = opaque;
1400 DASHContext *c = v->parent->priv_data;
1404 free_fragment(&v->cur_seg);
1405 v->cur_seg = get_current_fragment(v);
1411 /* load/update Media Initialization Section, if any */
1412 ret = update_init_section(v);
1416 ret = open_input(c, v, v->cur_seg);
1418 if (ff_check_interrupt(c->interrupt_callback)) {
1422 av_log(v->parent, AV_LOG_WARNING, "Failed to open fragment of playlist %d\n", v->rep_idx);
1428 if (v->init_sec_buf_read_offset < v->init_sec_data_len) {
1429 /* Push init section out first before first actual fragment */
1430 int copy_size = FFMIN(v->init_sec_data_len - v->init_sec_buf_read_offset, buf_size);
1431 memcpy(buf, v->init_sec_buf, copy_size);
1432 v->init_sec_buf_read_offset += copy_size;
1437 /* check the v->cur_seg, if it is null, get current and double check if the new v->cur_seg*/
1439 v->cur_seg = get_current_fragment(v);
1445 ret = read_from_url(v, v->cur_seg, buf, buf_size, READ_NORMAL);
1449 if (!v->is_restart_needed)
1451 v->is_restart_needed = 1;
1457 static int save_avio_options(AVFormatContext *s)
1459 DASHContext *c = s->priv_data;
1460 const char *opts[] = { "headers", "user_agent", "user-agent", "cookies", NULL }, **opt = opts;
1461 uint8_t *buf = NULL;
1465 if (av_opt_get(s->pb, *opt, AV_OPT_SEARCH_CHILDREN, &buf) >= 0) {
1466 if (buf[0] != '\0') {
1467 ret = av_dict_set(&c->avio_opts, *opt, buf, AV_DICT_DONT_STRDUP_VAL);
1482 static int nested_io_open(AVFormatContext *s, AVIOContext **pb, const char *url,
1483 int flags, AVDictionary **opts)
1485 av_log(s, AV_LOG_ERROR,
1486 "A DASH playlist item '%s' referred to an external file '%s'. "
1487 "Opening this file was forbidden for security reasons\n",
1489 return AVERROR(EPERM);
1492 static int reopen_demux_for_component(AVFormatContext *s, struct representation *pls)
1494 DASHContext *c = s->priv_data;
1495 AVInputFormat *in_fmt = NULL;
1496 AVDictionary *in_fmt_opts = NULL;
1497 uint8_t *avio_ctx_buffer = NULL;
1501 /* note: the internal buffer could have changed, and be != avio_ctx_buffer */
1502 av_freep(&pls->pb.buffer);
1503 memset(&pls->pb, 0x00, sizeof(AVIOContext));
1504 pls->ctx->pb = NULL;
1505 avformat_close_input(&pls->ctx);
1508 if (!(pls->ctx = avformat_alloc_context())) {
1509 ret = AVERROR(ENOMEM);
1513 avio_ctx_buffer = av_malloc(INITIAL_BUFFER_SIZE);
1514 if (!avio_ctx_buffer ) {
1515 ret = AVERROR(ENOMEM);
1516 avformat_free_context(pls->ctx);
1521 ffio_init_context(&pls->pb, avio_ctx_buffer , INITIAL_BUFFER_SIZE, 0, pls, read_data, NULL, NULL);
1523 ffio_init_context(&pls->pb, avio_ctx_buffer , INITIAL_BUFFER_SIZE, 0, pls, read_data, NULL, seek_data);
1525 pls->pb.seekable = 0;
1527 if ((ret = ff_copy_whiteblacklists(pls->ctx, s)) < 0)
1530 pls->ctx->flags = AVFMT_FLAG_CUSTOM_IO;
1531 pls->ctx->probesize = 1024 * 4;
1532 pls->ctx->max_analyze_duration = 4 * AV_TIME_BASE;
1533 ret = av_probe_input_buffer(&pls->pb, &in_fmt, "", NULL, 0, 0);
1535 av_log(s, AV_LOG_ERROR, "Error when loading first fragment, playlist %d\n", (int)pls->rep_idx);
1536 avformat_free_context(pls->ctx);
1541 pls->ctx->pb = &pls->pb;
1542 pls->ctx->io_open = nested_io_open;
1544 // provide additional information from mpd if available
1545 ret = avformat_open_input(&pls->ctx, "", in_fmt, &in_fmt_opts); //pls->init_section->url
1546 av_dict_free(&in_fmt_opts);
1549 if (pls->n_fragments) {
1550 ret = avformat_find_stream_info(pls->ctx, NULL);
1559 static int open_demux_for_component(AVFormatContext *s, struct representation *pls)
1565 pls->cur_seq_no = calc_cur_seg_no(s, pls);
1566 pls->last_seq_no = calc_max_seg_no(pls, s->priv_data);
1568 ret = reopen_demux_for_component(s, pls);
1572 for (i = 0; i < pls->ctx->nb_streams; i++) {
1573 AVStream *st = avformat_new_stream(s, NULL);
1574 AVStream *ist = pls->ctx->streams[i];
1576 ret = AVERROR(ENOMEM);
1580 avcodec_parameters_copy(st->codecpar, pls->ctx->streams[i]->codecpar);
1581 avpriv_set_pts_info(st, ist->pts_wrap_bits, ist->time_base.num, ist->time_base.den);
1589 static int dash_read_header(AVFormatContext *s)
1591 void *u = (s->flags & AVFMT_FLAG_CUSTOM_IO) ? NULL : s->pb;
1592 DASHContext *c = s->priv_data;
1594 int stream_index = 0;
1596 c->interrupt_callback = &s->interrupt_callback;
1597 // if the URL context is good, read important options we must broker later
1599 update_options(&c->user_agent, "user-agent", u);
1600 update_options(&c->cookies, "cookies", u);
1601 update_options(&c->headers, "headers", u);
1604 if ((ret = parse_manifest(s, s->filename, s->pb)) < 0)
1607 if ((ret = save_avio_options(s)) < 0)
1610 /* If this isn't a live stream, fill the total duration of the
1613 s->duration = (int64_t) c->media_presentation_duration * AV_TIME_BASE;
1616 /* Open the demuxer for curent video and current audio components if available */
1617 if (!ret && c->cur_video) {
1618 ret = open_demux_for_component(s, c->cur_video);
1620 c->cur_video->stream_index = stream_index;
1623 free_representation(c->cur_video);
1624 c->cur_video = NULL;
1628 if (!ret && c->cur_audio) {
1629 ret = open_demux_for_component(s, c->cur_audio);
1631 c->cur_audio->stream_index = stream_index;
1634 free_representation(c->cur_audio);
1635 c->cur_audio = NULL;
1639 if (!stream_index) {
1640 ret = AVERROR_INVALIDDATA;
1644 /* Create a program */
1647 program = av_new_program(s, 0);
1653 av_program_add_stream_index(s, 0, c->cur_video->stream_index);
1656 av_program_add_stream_index(s, 0, c->cur_audio->stream_index);
1665 static int dash_read_packet(AVFormatContext *s, AVPacket *pkt)
1667 DASHContext *c = s->priv_data;
1669 struct representation *cur = NULL;
1671 if (!c->cur_audio && !c->cur_video ) {
1672 return AVERROR_INVALIDDATA;
1674 if (c->cur_audio && !c->cur_video) {
1676 } else if (!c->cur_audio && c->cur_video) {
1678 } else if (c->cur_video->cur_timestamp < c->cur_audio->cur_timestamp) {
1685 while (!ff_check_interrupt(c->interrupt_callback) && !ret) {
1686 ret = av_read_frame(cur->ctx, pkt);
1688 /* If we got a packet, return it */
1689 cur->cur_timestamp = av_rescale(pkt->pts, (int64_t)cur->ctx->streams[0]->time_base.num * 90000, cur->ctx->streams[0]->time_base.den);
1690 pkt->stream_index = cur->stream_index;
1693 if (cur->is_restart_needed) {
1694 cur->cur_seg_offset = 0;
1695 cur->init_sec_buf_read_offset = 0;
1697 ff_format_io_close(cur->parent, &cur->input);
1698 ret = reopen_demux_for_component(s, cur);
1699 cur->is_restart_needed = 0;
1707 static int dash_close(AVFormatContext *s)
1709 DASHContext *c = s->priv_data;
1711 free_representation(c->cur_audio);
1714 free_representation(c->cur_video);
1717 av_freep(&c->cookies);
1718 av_freep(&c->user_agent);
1719 av_dict_free(&c->avio_opts);
1720 av_freep(&c->base_url);
1724 static int dash_seek(AVFormatContext *s, struct representation *pls, int64_t seek_pos_msec, int flags)
1729 int64_t duration = 0;
1731 av_log(pls->parent, AV_LOG_VERBOSE, "DASH seek pos[%"PRId64"ms], playlist %d\n", seek_pos_msec, pls->rep_idx);
1733 // single fragment mode
1734 if (pls->n_fragments == 1) {
1735 pls->cur_timestamp = 0;
1736 pls->cur_seg_offset = 0;
1737 ff_read_frame_flush(pls->ctx);
1738 return av_seek_frame(pls->ctx, -1, seek_pos_msec * 1000, flags);
1742 ff_format_io_close(pls->parent, &pls->input);
1744 // find the nearest fragment
1745 if (pls->n_timelines > 0 && pls->fragment_timescale > 0) {
1746 int64_t num = pls->first_seq_no;
1747 av_log(pls->parent, AV_LOG_VERBOSE, "dash_seek with SegmentTimeline start n_timelines[%d] "
1748 "last_seq_no[%"PRId64"], playlist %d.\n",
1749 (int)pls->n_timelines, (int64_t)pls->last_seq_no, (int)pls->rep_idx);
1750 for (i = 0; i < pls->n_timelines; i++) {
1751 if (pls->timelines[i]->starttime > 0) {
1752 duration = pls->timelines[i]->starttime;
1754 duration += pls->timelines[i]->duration;
1755 if (seek_pos_msec < ((duration * 1000) / pls->fragment_timescale)) {
1758 for (j = 0; j < pls->timelines[i]->repeat; j++) {
1759 duration += pls->timelines[i]->duration;
1761 if (seek_pos_msec < ((duration * 1000) / pls->fragment_timescale)) {
1769 pls->cur_seq_no = num > pls->last_seq_no ? pls->last_seq_no : num;
1770 av_log(pls->parent, AV_LOG_VERBOSE, "dash_seek with SegmentTimeline end cur_seq_no[%"PRId64"], playlist %d.\n",
1771 (int64_t)pls->cur_seq_no, (int)pls->rep_idx);
1772 } else if (pls->fragment_duration > 0) {
1773 pls->cur_seq_no = pls->first_seq_no + ((seek_pos_msec * pls->fragment_timescale) / pls->fragment_duration) / 1000;
1775 av_log(pls->parent, AV_LOG_ERROR, "dash_seek missing fragment_duration\n");
1776 pls->cur_seq_no = pls->first_seq_no;
1778 pls->cur_timestamp = 0;
1779 pls->cur_seg_offset = 0;
1780 pls->init_sec_buf_read_offset = 0;
1781 ret = reopen_demux_for_component(s, pls);
1786 static int dash_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
1789 DASHContext *c = s->priv_data;
1790 int64_t seek_pos_msec = av_rescale_rnd(timestamp, 1000,
1791 s->streams[stream_index]->time_base.den,
1792 flags & AVSEEK_FLAG_BACKWARD ?
1793 AV_ROUND_DOWN : AV_ROUND_UP);
1794 if ((flags & AVSEEK_FLAG_BYTE) || c->is_live)
1795 return AVERROR(ENOSYS);
1797 ret = dash_seek(s, c->cur_audio, seek_pos_msec, flags);
1799 if (!ret && c->cur_video) {
1800 ret = dash_seek(s, c->cur_video, seek_pos_msec, flags);
1805 static int dash_probe(AVProbeData *p)
1807 if (!av_stristr(p->buf, "<MPD"))
1810 if (av_stristr(p->buf, "dash:profile:isoff-on-demand:2011") ||
1811 av_stristr(p->buf, "dash:profile:isoff-live:2011") ||
1812 av_stristr(p->buf, "dash:profile:isoff-live:2012") ||
1813 av_stristr(p->buf, "dash:profile:isoff-main:2011")) {
1814 return AVPROBE_SCORE_MAX;
1816 if (av_stristr(p->buf, "dash:profile")) {
1817 return AVPROBE_SCORE_MAX;
1823 #define OFFSET(x) offsetof(DASHContext, x)
1824 #define FLAGS AV_OPT_FLAG_DECODING_PARAM
1825 static const AVOption dash_options[] = {
1826 {"allowed_extensions", "List of file extensions that dash is allowed to access",
1827 OFFSET(allowed_extensions), AV_OPT_TYPE_STRING,
1828 {.str = "aac,m4a,m4s,m4v,mov,mp4"},
1829 INT_MIN, INT_MAX, FLAGS},
1833 static const AVClass dash_class = {
1834 .class_name = "dash",
1835 .item_name = av_default_item_name,
1836 .option = dash_options,
1837 .version = LIBAVUTIL_VERSION_INT,
1840 AVInputFormat ff_dash_demuxer = {
1842 .long_name = NULL_IF_CONFIG_SMALL("Dynamic Adaptive Streaming over HTTP"),
1843 .priv_class = &dash_class,
1844 .priv_data_size = sizeof(DASHContext),
1845 .read_probe = dash_probe,
1846 .read_header = dash_read_header,
1847 .read_packet = dash_read_packet,
1848 .read_close = dash_close,
1849 .read_seek = dash_read_seek,
1850 .flags = AVFMT_NO_BYTE_SEEK,