]> git.sesse.net Git - ffmpeg/blob - libavformat/dashdec.c
dashdec: Support for multiple video/audio streams
[ffmpeg] / libavformat / dashdec.c
1 /*
2  * Dynamic Adaptive Streaming over HTTP demux
3  * Copyright (c) 2017 samsamsam@o2.pl based on HLS demux
4  * Copyright (c) 2017 Steven Liu
5  *
6  * This file is part of FFmpeg.
7  *
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.
12  *
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.
17  *
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
21  */
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"
27 #include "internal.h"
28 #include "avio_internal.h"
29 #include "dash.h"
30
31 #define INITIAL_BUFFER_SIZE 32768
32
33 struct fragment {
34     int64_t url_offset;
35     int64_t size;
36     char *url;
37 };
38
39 /*
40  * reference to : ISO_IEC_23009-1-DASH-2012
41  * Section: 5.3.9.6.2
42  * Table: Table 17 — Semantics of SegmentTimeline element
43  * */
44 struct timeline {
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)).
56      * */
57     int64_t starttime;
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).
62      * */
63     int64_t repeat;
64     /* duration: Element or Attribute Name
65      * specifies the Segment duration, in units of the value of the @timescale.
66      * */
67     int64_t duration;
68 };
69
70 /*
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.
74  */
75 struct representation {
76     char *url_template;
77     AVIOContext pb;
78     AVIOContext *input;
79     AVFormatContext *parent;
80     AVFormatContext *ctx;
81     AVPacket pkt;
82     int rep_idx;
83     int rep_count;
84     int stream_index;
85
86     enum AVMediaType type;
87     char id[20];
88     int bandwidth;
89     AVStream *assoc_stream; /* demuxer stream associated with this representation */
90
91     int n_fragments;
92     struct fragment **fragments; /* VOD list of fragment for profile */
93
94     int n_timelines;
95     struct timeline **timelines;
96
97     int64_t first_seq_no;
98     int64_t last_seq_no;
99     int64_t start_number; /* used in case when we have dynamic list of segment to know which segments are new one*/
100
101     int64_t fragment_duration;
102     int64_t fragment_timescale;
103
104     int64_t presentation_timeoffset;
105
106     int64_t cur_seq_no;
107     int64_t cur_seg_offset;
108     int64_t cur_seg_size;
109     struct fragment *cur_seg;
110
111     /* Currently active Media Initialization Section */
112     struct fragment *init_section;
113     uint8_t *init_sec_buf;
114     uint32_t init_sec_buf_size;
115     uint32_t init_sec_data_len;
116     uint32_t init_sec_buf_read_offset;
117     int64_t cur_timestamp;
118     int is_restart_needed;
119 };
120
121 typedef struct DASHContext {
122     const AVClass *class;
123     char *base_url;
124
125     int n_videos;
126     struct representation **videos;
127     int n_audios;
128     struct representation **audios;
129
130     /* MediaPresentationDescription Attribute */
131     uint64_t media_presentation_duration;
132     uint64_t suggested_presentation_delay;
133     uint64_t availability_start_time;
134     uint64_t publish_time;
135     uint64_t minimum_update_period;
136     uint64_t time_shift_buffer_depth;
137     uint64_t min_buffer_time;
138
139     /* Period Attribute */
140     uint64_t period_duration;
141     uint64_t period_start;
142
143     int is_live;
144     AVIOInterruptCB *interrupt_callback;
145     char *user_agent;                    ///< holds HTTP user agent set as an AVOption to the HTTP protocol context
146     char *cookies;                       ///< holds HTTP cookie values set in either the initial response or as an AVOption to the HTTP protocol context
147     char *headers;                       ///< holds HTTP headers set as an AVOption to the HTTP protocol context
148     char *allowed_extensions;
149     AVDictionary *avio_opts;
150 } DASHContext;
151
152 static uint64_t get_current_time_in_sec(void)
153 {
154     return  av_gettime() / 1000000;
155 }
156
157 static uint64_t get_utc_date_time_insec(AVFormatContext *s, const char *datetime)
158 {
159     struct tm timeinfo;
160     int year = 0;
161     int month = 0;
162     int day = 0;
163     int hour = 0;
164     int minute = 0;
165     int ret = 0;
166     float second = 0.0;
167
168     /* ISO-8601 date parser */
169     if (!datetime)
170         return 0;
171
172     ret = sscanf(datetime, "%d-%d-%dT%d:%d:%fZ", &year, &month, &day, &hour, &minute, &second);
173     /* year, month, day, hour, minute, second  6 arguments */
174     if (ret != 6) {
175         av_log(s, AV_LOG_WARNING, "get_utc_date_time_insec get a wrong time format\n");
176     }
177     timeinfo.tm_year = year - 1900;
178     timeinfo.tm_mon  = month - 1;
179     timeinfo.tm_mday = day;
180     timeinfo.tm_hour = hour;
181     timeinfo.tm_min  = minute;
182     timeinfo.tm_sec  = (int)second;
183
184     return av_timegm(&timeinfo);
185 }
186
187 static uint32_t get_duration_insec(AVFormatContext *s, const char *duration)
188 {
189     /* ISO-8601 duration parser */
190     uint32_t days = 0;
191     uint32_t hours = 0;
192     uint32_t mins = 0;
193     uint32_t secs = 0;
194     int size = 0;
195     float value = 0;
196     char type = '\0';
197     const char *ptr = duration;
198
199     while (*ptr) {
200         if (*ptr == 'P' || *ptr == 'T') {
201             ptr++;
202             continue;
203         }
204
205         if (sscanf(ptr, "%f%c%n", &value, &type, &size) != 2) {
206             av_log(s, AV_LOG_WARNING, "get_duration_insec get a wrong time format\n");
207             return 0; /* parser error */
208         }
209         switch (type) {
210             case 'D':
211                 days = (uint32_t)value;
212                 break;
213             case 'H':
214                 hours = (uint32_t)value;
215                 break;
216             case 'M':
217                 mins = (uint32_t)value;
218                 break;
219             case 'S':
220                 secs = (uint32_t)value;
221                 break;
222             default:
223                 // handle invalid type
224                 break;
225         }
226         ptr += size;
227     }
228     return  ((days * 24 + hours) * 60 + mins) * 60 + secs;
229 }
230
231 static int64_t get_segment_start_time_based_on_timeline(struct representation *pls, int64_t cur_seq_no)
232 {
233     int64_t start_time = 0;
234     int64_t i = 0;
235     int64_t j = 0;
236     int64_t num = 0;
237
238     if (pls->n_timelines) {
239         for (i = 0; i < pls->n_timelines; i++) {
240             if (pls->timelines[i]->starttime > 0) {
241                 start_time = pls->timelines[i]->starttime;
242             }
243             if (num == cur_seq_no)
244                 goto finish;
245
246             start_time += pls->timelines[i]->duration;
247             for (j = 0; j < pls->timelines[i]->repeat; j++) {
248                 num++;
249                 if (num == cur_seq_no)
250                     goto finish;
251                 start_time += pls->timelines[i]->duration;
252             }
253             num++;
254         }
255     }
256 finish:
257     return start_time;
258 }
259
260 static int64_t calc_next_seg_no_from_timelines(struct representation *pls, int64_t cur_time)
261 {
262     int64_t i = 0;
263     int64_t j = 0;
264     int64_t num = 0;
265     int64_t start_time = 0;
266
267     for (i = 0; i < pls->n_timelines; i++) {
268         if (pls->timelines[i]->starttime > 0) {
269             start_time = pls->timelines[i]->starttime;
270         }
271         if (start_time > cur_time)
272             goto finish;
273
274         start_time += pls->timelines[i]->duration;
275         for (j = 0; j < pls->timelines[i]->repeat; j++) {
276             num++;
277             if (start_time > cur_time)
278                 goto finish;
279             start_time += pls->timelines[i]->duration;
280         }
281         num++;
282     }
283
284     return -1;
285
286 finish:
287     return num;
288 }
289
290 static void free_fragment(struct fragment **seg)
291 {
292     if (!(*seg)) {
293         return;
294     }
295     av_freep(&(*seg)->url);
296     av_freep(seg);
297 }
298
299 static void free_fragment_list(struct representation *pls)
300 {
301     int i;
302
303     for (i = 0; i < pls->n_fragments; i++) {
304         free_fragment(&pls->fragments[i]);
305     }
306     av_freep(&pls->fragments);
307     pls->n_fragments = 0;
308 }
309
310 static void free_timelines_list(struct representation *pls)
311 {
312     int i;
313
314     for (i = 0; i < pls->n_timelines; i++) {
315         av_freep(&pls->timelines[i]);
316     }
317     av_freep(&pls->timelines);
318     pls->n_timelines = 0;
319 }
320
321 static void free_representation(struct representation *pls)
322 {
323     free_fragment_list(pls);
324     free_timelines_list(pls);
325     free_fragment(&pls->cur_seg);
326     free_fragment(&pls->init_section);
327     av_freep(&pls->init_sec_buf);
328     av_freep(&pls->pb.buffer);
329     if (pls->input)
330         ff_format_io_close(pls->parent, &pls->input);
331     if (pls->ctx) {
332         pls->ctx->pb = NULL;
333         avformat_close_input(&pls->ctx);
334     }
335
336     av_freep(&pls->url_template);
337     av_freep(&pls);
338 }
339
340 static void free_video_list(DASHContext *c)
341 {
342     int i;
343     for (i = 0; i < c->n_videos; i++) {
344         struct representation *pls = c->videos[i];
345         free_representation(pls);
346     }
347     av_freep(&c->videos);
348     c->n_videos = 0;
349 }
350
351 static void free_audio_list(DASHContext *c)
352 {
353     int i;
354     for (i = 0; i < c->n_audios; i++) {
355         struct representation *pls = c->audios[i];
356         free_representation(pls);
357     }
358     av_freep(&c->audios);
359     c->n_audios = 0;
360 }
361
362 static void set_httpheader_options(DASHContext *c, AVDictionary **opts)
363 {
364     // broker prior HTTP options that should be consistent across requests
365     av_dict_set(opts, "user-agent", c->user_agent, 0);
366     av_dict_set(opts, "cookies", c->cookies, 0);
367     av_dict_set(opts, "headers", c->headers, 0);
368     if (c->is_live) {
369         av_dict_set(opts, "seekable", "0", 0);
370     }
371 }
372 static void update_options(char **dest, const char *name, void *src)
373 {
374     av_freep(dest);
375     av_opt_get(src, name, AV_OPT_SEARCH_CHILDREN, (uint8_t**)dest);
376     if (*dest)
377         av_freep(dest);
378 }
379
380 static int open_url(AVFormatContext *s, AVIOContext **pb, const char *url,
381                     AVDictionary *opts, AVDictionary *opts2, int *is_http)
382 {
383     DASHContext *c = s->priv_data;
384     AVDictionary *tmp = NULL;
385     const char *proto_name = NULL;
386     int ret;
387
388     av_dict_copy(&tmp, opts, 0);
389     av_dict_copy(&tmp, opts2, 0);
390
391     if (av_strstart(url, "crypto", NULL)) {
392         if (url[6] == '+' || url[6] == ':')
393             proto_name = avio_find_protocol_name(url + 7);
394     }
395
396     if (!proto_name)
397         proto_name = avio_find_protocol_name(url);
398
399     if (!proto_name)
400         return AVERROR_INVALIDDATA;
401
402     // only http(s) & file are allowed
403     if (av_strstart(proto_name, "file", NULL)) {
404         if (strcmp(c->allowed_extensions, "ALL") && !av_match_ext(url, c->allowed_extensions)) {
405             av_log(s, AV_LOG_ERROR,
406                 "Filename extension of \'%s\' is not a common multimedia extension, blocked for security reasons.\n"
407                 "If you wish to override this adjust allowed_extensions, you can set it to \'ALL\' to allow all\n",
408                 url);
409             return AVERROR_INVALIDDATA;
410         }
411     } else if (av_strstart(proto_name, "http", NULL)) {
412         ;
413     } else
414         return AVERROR_INVALIDDATA;
415
416     if (!strncmp(proto_name, url, strlen(proto_name)) && url[strlen(proto_name)] == ':')
417         ;
418     else if (av_strstart(url, "crypto", NULL) && !strncmp(proto_name, url + 7, strlen(proto_name)) && url[7 + strlen(proto_name)] == ':')
419         ;
420     else if (strcmp(proto_name, "file") || !strncmp(url, "file,", 5))
421         return AVERROR_INVALIDDATA;
422
423     ret = s->io_open(s, pb, url, AVIO_FLAG_READ, &tmp);
424     if (ret >= 0) {
425         // update cookies on http response with setcookies.
426         char *new_cookies = NULL;
427
428         if (!(s->flags & AVFMT_FLAG_CUSTOM_IO))
429             av_opt_get(*pb, "cookies", AV_OPT_SEARCH_CHILDREN, (uint8_t**)&new_cookies);
430
431         if (new_cookies) {
432             av_free(c->cookies);
433             c->cookies = new_cookies;
434         }
435
436         av_dict_set(&opts, "cookies", c->cookies, 0);
437     }
438
439     av_dict_free(&tmp);
440
441     if (is_http)
442         *is_http = av_strstart(proto_name, "http", NULL);
443
444     return ret;
445 }
446
447 static char *get_content_url(xmlNodePtr *baseurl_nodes,
448                              int n_baseurl_nodes,
449                              char *rep_id_val,
450                              char *rep_bandwidth_val,
451                              char *val)
452 {
453     int i;
454     char *text;
455     char *url = NULL;
456     char tmp_str[MAX_URL_SIZE];
457     char tmp_str_2[MAX_URL_SIZE];
458
459     memset(tmp_str, 0, sizeof(tmp_str));
460
461     for (i = 0; i < n_baseurl_nodes; ++i) {
462         if (baseurl_nodes[i] &&
463             baseurl_nodes[i]->children &&
464             baseurl_nodes[i]->children->type == XML_TEXT_NODE) {
465             text = xmlNodeGetContent(baseurl_nodes[i]->children);
466             if (text) {
467                 memset(tmp_str, 0, sizeof(tmp_str));
468                 memset(tmp_str_2, 0, sizeof(tmp_str_2));
469                 ff_make_absolute_url(tmp_str_2, MAX_URL_SIZE, tmp_str, text);
470                 av_strlcpy(tmp_str, tmp_str_2, sizeof(tmp_str));
471                 xmlFree(text);
472             }
473         }
474     }
475
476     if (val)
477         av_strlcat(tmp_str, (const char*)val, sizeof(tmp_str));
478
479     if (rep_id_val) {
480         url = av_strireplace(tmp_str, "$RepresentationID$", (const char*)rep_id_val);
481         if (!url) {
482             return NULL;
483         }
484         av_strlcpy(tmp_str, url, sizeof(tmp_str));
485         av_free(url);
486     }
487     if (rep_bandwidth_val && tmp_str[0] != '\0') {
488         url = av_strireplace(tmp_str, "$Bandwidth$", (const char*)rep_bandwidth_val);
489         if (!url) {
490             return NULL;
491         }
492     }
493     return url;
494 }
495
496 static char *get_val_from_nodes_tab(xmlNodePtr *nodes, const int n_nodes, const char *attrname)
497 {
498     int i;
499     char *val;
500
501     for (i = 0; i < n_nodes; ++i) {
502         if (nodes[i]) {
503             val = xmlGetProp(nodes[i], attrname);
504             if (val)
505                 return val;
506         }
507     }
508
509     return NULL;
510 }
511
512 static xmlNodePtr find_child_node_by_name(xmlNodePtr rootnode, const char *nodename)
513 {
514     xmlNodePtr node = rootnode;
515     if (!node) {
516         return NULL;
517     }
518
519     node = xmlFirstElementChild(node);
520     while (node) {
521         if (!av_strcasecmp(node->name, nodename)) {
522             return node;
523         }
524         node = xmlNextElementSibling(node);
525     }
526     return NULL;
527 }
528
529 static enum AVMediaType get_content_type(xmlNodePtr node)
530 {
531     enum AVMediaType type = AVMEDIA_TYPE_UNKNOWN;
532     int i = 0;
533     const char *attr;
534     char *val = NULL;
535
536     if (node) {
537         for (i = 0; i < 2; i++) {
538             attr = i ? "mimeType" : "contentType";
539             val = xmlGetProp(node, attr);
540             if (val) {
541                 if (av_stristr((const char *)val, "video")) {
542                     type = AVMEDIA_TYPE_VIDEO;
543                 } else if (av_stristr((const char *)val, "audio")) {
544                     type = AVMEDIA_TYPE_AUDIO;
545                 }
546                 xmlFree(val);
547             }
548         }
549     }
550     return type;
551 }
552
553 static int parse_manifest_segmenturlnode(AVFormatContext *s, struct representation *rep,
554                                          xmlNodePtr fragmenturl_node,
555                                          xmlNodePtr *baseurl_nodes,
556                                          char *rep_id_val,
557                                          char *rep_bandwidth_val)
558 {
559     char *initialization_val = NULL;
560     char *media_val = NULL;
561
562     if (!av_strcasecmp(fragmenturl_node->name, (const char *)"Initialization")) {
563         initialization_val = xmlGetProp(fragmenturl_node, "sourceURL");
564         if (initialization_val) {
565             rep->init_section = av_mallocz(sizeof(struct fragment));
566             if (!rep->init_section) {
567                 xmlFree(initialization_val);
568                 return AVERROR(ENOMEM);
569             }
570             rep->init_section->url = get_content_url(baseurl_nodes, 4,
571                                                      rep_id_val,
572                                                      rep_bandwidth_val,
573                                                      initialization_val);
574             if (!rep->init_section->url) {
575                 av_free(rep->init_section);
576                 xmlFree(initialization_val);
577                 return AVERROR(ENOMEM);
578             }
579             rep->init_section->size = -1;
580             xmlFree(initialization_val);
581         }
582     } else if (!av_strcasecmp(fragmenturl_node->name, (const char *)"SegmentURL")) {
583         media_val = xmlGetProp(fragmenturl_node, "media");
584         if (media_val) {
585             struct fragment *seg = av_mallocz(sizeof(struct fragment));
586             if (!seg) {
587                 xmlFree(media_val);
588                 return AVERROR(ENOMEM);
589             }
590             seg->url = get_content_url(baseurl_nodes, 4,
591                                        rep_id_val,
592                                        rep_bandwidth_val,
593                                        media_val);
594             if (!seg->url) {
595                 av_free(seg);
596                 xmlFree(media_val);
597                 return AVERROR(ENOMEM);
598             }
599             seg->size = -1;
600             dynarray_add(&rep->fragments, &rep->n_fragments, seg);
601             xmlFree(media_val);
602         }
603     }
604
605     return 0;
606 }
607
608 static int parse_manifest_segmenttimeline(AVFormatContext *s, struct representation *rep,
609                                           xmlNodePtr fragment_timeline_node)
610 {
611     xmlAttrPtr attr = NULL;
612     char *val  = NULL;
613
614     if (!av_strcasecmp(fragment_timeline_node->name, (const char *)"S")) {
615         struct timeline *tml = av_mallocz(sizeof(struct timeline));
616         if (!tml) {
617             return AVERROR(ENOMEM);
618         }
619         attr = fragment_timeline_node->properties;
620         while (attr) {
621             val = xmlGetProp(fragment_timeline_node, attr->name);
622
623             if (!val) {
624                 av_log(s, AV_LOG_WARNING, "parse_manifest_segmenttimeline attr->name = %s val is NULL\n", attr->name);
625                 continue;
626             }
627
628             if (!av_strcasecmp(attr->name, (const char *)"t")) {
629                 tml->starttime = (int64_t)strtoll(val, NULL, 10);
630             } else if (!av_strcasecmp(attr->name, (const char *)"r")) {
631                 tml->repeat =(int64_t) strtoll(val, NULL, 10);
632             } else if (!av_strcasecmp(attr->name, (const char *)"d")) {
633                 tml->duration = (int64_t)strtoll(val, NULL, 10);
634             }
635             attr = attr->next;
636             xmlFree(val);
637         }
638         dynarray_add(&rep->timelines, &rep->n_timelines, tml);
639     }
640
641     return 0;
642 }
643
644 static int parse_manifest_representation(AVFormatContext *s, const char *url,
645                                          xmlNodePtr node,
646                                          xmlNodePtr adaptionset_node,
647                                          xmlNodePtr mpd_baseurl_node,
648                                          xmlNodePtr period_baseurl_node,
649                                          xmlNodePtr fragment_template_node,
650                                          xmlNodePtr content_component_node,
651                                          xmlNodePtr adaptionset_baseurl_node)
652 {
653     int32_t ret = 0;
654     int32_t audio_rep_idx = 0;
655     int32_t video_rep_idx = 0;
656     DASHContext *c = s->priv_data;
657     struct representation *rep = NULL;
658     struct fragment *seg = NULL;
659     xmlNodePtr representation_segmenttemplate_node = NULL;
660     xmlNodePtr representation_baseurl_node = NULL;
661     xmlNodePtr representation_segmentlist_node = NULL;
662     xmlNodePtr fragment_timeline_node = NULL;
663     xmlNodePtr fragment_templates_tab[2];
664     char *duration_val = NULL;
665     char *presentation_timeoffset_val = NULL;
666     char *startnumber_val = NULL;
667     char *timescale_val = NULL;
668     char *initialization_val = NULL;
669     char *media_val = NULL;
670     xmlNodePtr baseurl_nodes[4];
671     xmlNodePtr representation_node = node;
672     char *rep_id_val = xmlGetProp(representation_node, "id");
673     char *rep_bandwidth_val = xmlGetProp(representation_node, "bandwidth");
674     enum AVMediaType type = AVMEDIA_TYPE_UNKNOWN;
675
676     // try get information from representation
677     if (type == AVMEDIA_TYPE_UNKNOWN)
678         type = get_content_type(representation_node);
679     // try get information from contentComponen
680     if (type == AVMEDIA_TYPE_UNKNOWN)
681         type = get_content_type(content_component_node);
682     // try get information from adaption set
683     if (type == AVMEDIA_TYPE_UNKNOWN)
684         type = get_content_type(adaptionset_node);
685     if (type == AVMEDIA_TYPE_UNKNOWN) {
686         av_log(s, AV_LOG_VERBOSE, "Parsing '%s' - skipp not supported representation type\n", url);
687     } else if (type == AVMEDIA_TYPE_VIDEO || type == AVMEDIA_TYPE_AUDIO) {
688         // convert selected representation to our internal struct
689         rep = av_mallocz(sizeof(struct representation));
690         if (!rep) {
691             ret = AVERROR(ENOMEM);
692             goto end;
693         }
694         representation_segmenttemplate_node = find_child_node_by_name(representation_node, "SegmentTemplate");
695         representation_baseurl_node = find_child_node_by_name(representation_node, "BaseURL");
696         representation_segmentlist_node = find_child_node_by_name(representation_node, "SegmentList");
697
698         baseurl_nodes[0] = mpd_baseurl_node;
699         baseurl_nodes[1] = period_baseurl_node;
700         baseurl_nodes[2] = adaptionset_baseurl_node;
701         baseurl_nodes[3] = representation_baseurl_node;
702
703         if (representation_segmenttemplate_node || fragment_template_node) {
704             fragment_timeline_node = NULL;
705             fragment_templates_tab[0] = representation_segmenttemplate_node;
706             fragment_templates_tab[1] = fragment_template_node;
707
708             presentation_timeoffset_val = get_val_from_nodes_tab(fragment_templates_tab, 2, "presentationTimeOffset");
709             duration_val = get_val_from_nodes_tab(fragment_templates_tab, 2, "duration");
710             startnumber_val = get_val_from_nodes_tab(fragment_templates_tab, 2, "startNumber");
711             timescale_val = get_val_from_nodes_tab(fragment_templates_tab, 2, "timescale");
712             initialization_val = get_val_from_nodes_tab(fragment_templates_tab, 2, "initialization");
713             media_val = get_val_from_nodes_tab(fragment_templates_tab, 2, "media");
714
715             if (initialization_val) {
716                 rep->init_section = av_mallocz(sizeof(struct fragment));
717                 if (!rep->init_section) {
718                     av_free(rep);
719                     ret = AVERROR(ENOMEM);
720                     goto end;
721                 }
722                 rep->init_section->url = get_content_url(baseurl_nodes, 4, rep_id_val, rep_bandwidth_val, initialization_val);
723                 if (!rep->init_section->url) {
724                     av_free(rep->init_section);
725                     av_free(rep);
726                     ret = AVERROR(ENOMEM);
727                     goto end;
728                 }
729                 rep->init_section->size = -1;
730                 xmlFree(initialization_val);
731             }
732
733             if (media_val) {
734                 rep->url_template = get_content_url(baseurl_nodes, 4, rep_id_val, rep_bandwidth_val, media_val);
735                 xmlFree(media_val);
736             }
737
738             if (presentation_timeoffset_val) {
739                 rep->presentation_timeoffset = (int64_t) strtoll(presentation_timeoffset_val, NULL, 10);
740                 xmlFree(presentation_timeoffset_val);
741             }
742             if (duration_val) {
743                 rep->fragment_duration = (int64_t) strtoll(duration_val, NULL, 10);
744                 xmlFree(duration_val);
745             }
746             if (timescale_val) {
747                 rep->fragment_timescale = (int64_t) strtoll(timescale_val, NULL, 10);
748                 xmlFree(timescale_val);
749             }
750             if (startnumber_val) {
751                 rep->first_seq_no = (int64_t) strtoll(startnumber_val, NULL, 10);
752                 xmlFree(startnumber_val);
753             }
754
755             fragment_timeline_node = find_child_node_by_name(representation_segmenttemplate_node, "SegmentTimeline");
756
757             if (!fragment_timeline_node)
758                 fragment_timeline_node = find_child_node_by_name(fragment_template_node, "SegmentTimeline");
759             if (fragment_timeline_node) {
760                 fragment_timeline_node = xmlFirstElementChild(fragment_timeline_node);
761                 while (fragment_timeline_node) {
762                     ret = parse_manifest_segmenttimeline(s, rep, fragment_timeline_node);
763                     if (ret < 0) {
764                         return ret;
765                     }
766                     fragment_timeline_node = xmlNextElementSibling(fragment_timeline_node);
767                 }
768             }
769         } else if (representation_baseurl_node && !representation_segmentlist_node) {
770             seg = av_mallocz(sizeof(struct fragment));
771             if (!seg) {
772                 ret = AVERROR(ENOMEM);
773                 goto end;
774             }
775             seg->url = get_content_url(baseurl_nodes, 4, rep_id_val, rep_bandwidth_val, NULL);
776             if (!seg->url) {
777                 av_free(seg);
778                 ret = AVERROR(ENOMEM);
779                 goto end;
780             }
781             seg->size = -1;
782             dynarray_add(&rep->fragments, &rep->n_fragments, seg);
783         } else if (representation_segmentlist_node) {
784             // TODO: https://www.brendanlong.com/the-structure-of-an-mpeg-dash-mpd.html
785             // http://www-itec.uni-klu.ac.at/dash/ddash/mpdGenerator.php?fragmentlength=15&type=full
786             xmlNodePtr fragmenturl_node = NULL;
787             duration_val = xmlGetProp(representation_segmentlist_node, "duration");
788             timescale_val = xmlGetProp(representation_segmentlist_node, "timescale");
789             if (duration_val) {
790                 rep->fragment_duration = (int64_t) strtoll(duration_val, NULL, 10);
791                 xmlFree(duration_val);
792             }
793             if (timescale_val) {
794                 rep->fragment_timescale = (int64_t) strtoll(timescale_val, NULL, 10);
795                 xmlFree(timescale_val);
796             }
797             fragmenturl_node = xmlFirstElementChild(representation_segmentlist_node);
798             while (fragmenturl_node) {
799                 ret = parse_manifest_segmenturlnode(s, rep, fragmenturl_node,
800                                                     baseurl_nodes,
801                                                     rep_id_val,
802                                                     rep_bandwidth_val);
803                 if (ret < 0) {
804                     return ret;
805                 }
806                 fragmenturl_node = xmlNextElementSibling(fragmenturl_node);
807             }
808
809             fragment_timeline_node = find_child_node_by_name(representation_segmenttemplate_node, "SegmentTimeline");
810
811             if (!fragment_timeline_node)
812                 fragment_timeline_node = find_child_node_by_name(fragment_template_node, "SegmentTimeline");
813             if (fragment_timeline_node) {
814                 fragment_timeline_node = xmlFirstElementChild(fragment_timeline_node);
815                 while (fragment_timeline_node) {
816                     ret = parse_manifest_segmenttimeline(s, rep, fragment_timeline_node);
817                     if (ret < 0) {
818                         return ret;
819                     }
820                     fragment_timeline_node = xmlNextElementSibling(fragment_timeline_node);
821                 }
822             }
823         } else {
824             free_representation(rep);
825             rep = NULL;
826             av_log(s, AV_LOG_ERROR, "Unknown format of Representation node id[%s] \n", (const char *)rep_id_val);
827         }
828
829         if (rep) {
830             if (rep->fragment_duration > 0 && !rep->fragment_timescale)
831                 rep->fragment_timescale = 1;
832             rep->bandwidth = rep_bandwidth_val ? atoi(rep_bandwidth_val) : 0;
833             strncpy(rep->id, rep_id_val ? rep_id_val : "", sizeof(rep->id));
834             if (type == AVMEDIA_TYPE_VIDEO) {
835                 rep->rep_idx = video_rep_idx;
836                 dynarray_add(&c->videos, &c->n_videos, rep);
837             } else {
838                 rep->rep_idx = audio_rep_idx;
839                 dynarray_add(&c->audios, &c->n_audios, rep);
840             }
841         }
842     }
843
844     video_rep_idx += type == AVMEDIA_TYPE_VIDEO;
845     audio_rep_idx += type == AVMEDIA_TYPE_AUDIO;
846
847 end:
848     if (rep_id_val)
849         xmlFree(rep_id_val);
850     if (rep_bandwidth_val)
851         xmlFree(rep_bandwidth_val);
852
853     return ret;
854 }
855
856 static int parse_manifest_adaptationset(AVFormatContext *s, const char *url,
857                                         xmlNodePtr adaptionset_node,
858                                         xmlNodePtr mpd_baseurl_node,
859                                         xmlNodePtr period_baseurl_node)
860 {
861     int ret = 0;
862     xmlNodePtr fragment_template_node = NULL;
863     xmlNodePtr content_component_node = NULL;
864     xmlNodePtr adaptionset_baseurl_node = NULL;
865     xmlNodePtr node = NULL;
866
867     node = xmlFirstElementChild(adaptionset_node);
868     while (node) {
869         if (!av_strcasecmp(node->name, (const char *)"SegmentTemplate")) {
870             fragment_template_node = node;
871         } else if (!av_strcasecmp(node->name, (const char *)"ContentComponent")) {
872             content_component_node = node;
873         } else if (!av_strcasecmp(node->name, (const char *)"BaseURL")) {
874             adaptionset_baseurl_node = node;
875         } else if (!av_strcasecmp(node->name, (const char *)"Representation")) {
876             ret = parse_manifest_representation(s, url, node,
877                                                 adaptionset_node,
878                                                 mpd_baseurl_node,
879                                                 period_baseurl_node,
880                                                 fragment_template_node,
881                                                 content_component_node,
882                                                 adaptionset_baseurl_node);
883             if (ret < 0) {
884                 return ret;
885             }
886         }
887         node = xmlNextElementSibling(node);
888     }
889     return 0;
890 }
891
892 static int parse_manifest(AVFormatContext *s, const char *url, AVIOContext *in)
893 {
894     DASHContext *c = s->priv_data;
895     int ret = 0;
896     int close_in = 0;
897     uint8_t *new_url = NULL;
898     int64_t filesize = 0;
899     char *buffer = NULL;
900     AVDictionary *opts = NULL;
901     xmlDoc *doc = NULL;
902     xmlNodePtr root_element = NULL;
903     xmlNodePtr node = NULL;
904     xmlNodePtr period_node = NULL;
905     xmlNodePtr mpd_baseurl_node = NULL;
906     xmlNodePtr period_baseurl_node = NULL;
907     xmlNodePtr adaptionset_node = NULL;
908     xmlAttrPtr attr = NULL;
909     char *val  = NULL;
910     uint32_t perdiod_duration_sec = 0;
911     uint32_t perdiod_start_sec = 0;
912
913     if (!in) {
914         close_in = 1;
915
916         set_httpheader_options(c, &opts);
917         ret = avio_open2(&in, url, AVIO_FLAG_READ, c->interrupt_callback, &opts);
918         av_dict_free(&opts);
919         if (ret < 0)
920             return ret;
921     }
922
923     if (av_opt_get(in, "location", AV_OPT_SEARCH_CHILDREN, &new_url) >= 0) {
924         c->base_url = av_strdup(new_url);
925     } else {
926         c->base_url = av_strdup(url);
927     }
928
929     filesize = avio_size(in);
930     if (filesize <= 0) {
931         filesize = 8 * 1024;
932     }
933
934     buffer = av_mallocz(filesize);
935     if (!buffer) {
936         av_free(c->base_url);
937         return AVERROR(ENOMEM);
938     }
939
940     filesize = avio_read(in, buffer, filesize);
941     if (filesize <= 0) {
942         av_log(s, AV_LOG_ERROR, "Unable to read to offset '%s'\n", url);
943         ret = AVERROR_INVALIDDATA;
944     } else {
945         LIBXML_TEST_VERSION
946
947         doc = xmlReadMemory(buffer, filesize, c->base_url, NULL, 0);
948         root_element = xmlDocGetRootElement(doc);
949         node = root_element;
950
951         if (!node) {
952             ret = AVERROR_INVALIDDATA;
953             av_log(s, AV_LOG_ERROR, "Unable to parse '%s' - missing root node\n", url);
954             goto cleanup;
955         }
956
957         if (node->type != XML_ELEMENT_NODE ||
958             av_strcasecmp(node->name, (const char *)"MPD")) {
959             ret = AVERROR_INVALIDDATA;
960             av_log(s, AV_LOG_ERROR, "Unable to parse '%s' - wrong root node name[%s] type[%d]\n", url, node->name, (int)node->type);
961             goto cleanup;
962         }
963
964         val = xmlGetProp(node, "type");
965         if (!val) {
966             av_log(s, AV_LOG_ERROR, "Unable to parse '%s' - missing type attrib\n", url);
967             ret = AVERROR_INVALIDDATA;
968             goto cleanup;
969         }
970         if (!av_strcasecmp(val, (const char *)"dynamic"))
971             c->is_live = 1;
972         xmlFree(val);
973
974         attr = node->properties;
975         while (attr) {
976             val = xmlGetProp(node, attr->name);
977
978             if (!av_strcasecmp(attr->name, (const char *)"availabilityStartTime")) {
979                 c->availability_start_time = get_utc_date_time_insec(s, (const char *)val);
980             } else if (!av_strcasecmp(attr->name, (const char *)"publishTime")) {
981                 c->publish_time = get_utc_date_time_insec(s, (const char *)val);
982             } else if (!av_strcasecmp(attr->name, (const char *)"minimumUpdatePeriod")) {
983                 c->minimum_update_period = get_duration_insec(s, (const char *)val);
984             } else if (!av_strcasecmp(attr->name, (const char *)"timeShiftBufferDepth")) {
985                 c->time_shift_buffer_depth = get_duration_insec(s, (const char *)val);
986             } else if (!av_strcasecmp(attr->name, (const char *)"minBufferTime")) {
987                 c->min_buffer_time = get_duration_insec(s, (const char *)val);
988             } else if (!av_strcasecmp(attr->name, (const char *)"suggestedPresentationDelay")) {
989                 c->suggested_presentation_delay = get_duration_insec(s, (const char *)val);
990             } else if (!av_strcasecmp(attr->name, (const char *)"mediaPresentationDuration")) {
991                 c->media_presentation_duration = get_duration_insec(s, (const char *)val);
992             }
993             attr = attr->next;
994             xmlFree(val);
995         }
996
997         mpd_baseurl_node = find_child_node_by_name(node, "BaseURL");
998
999         // at now we can handle only one period, with the longest duration
1000         node = xmlFirstElementChild(node);
1001         while (node) {
1002             if (!av_strcasecmp(node->name, (const char *)"Period")) {
1003                 perdiod_duration_sec = 0;
1004                 perdiod_start_sec = 0;
1005                 attr = node->properties;
1006                 while (attr) {
1007                     val = xmlGetProp(node, attr->name);
1008                     if (!av_strcasecmp(attr->name, (const char *)"duration")) {
1009                         perdiod_duration_sec = get_duration_insec(s, (const char *)val);
1010                     } else if (!av_strcasecmp(attr->name, (const char *)"start")) {
1011                         perdiod_start_sec = get_duration_insec(s, (const char *)val);
1012                     }
1013                     attr = attr->next;
1014                     xmlFree(val);
1015                 }
1016                 if ((perdiod_duration_sec) >= (c->period_duration)) {
1017                     period_node = node;
1018                     c->period_duration = perdiod_duration_sec;
1019                     c->period_start = perdiod_start_sec;
1020                     if (c->period_start > 0)
1021                         c->media_presentation_duration = c->period_duration;
1022                 }
1023             }
1024             node = xmlNextElementSibling(node);
1025         }
1026         if (!period_node) {
1027             av_log(s, AV_LOG_ERROR, "Unable to parse '%s' - missing Period node\n", url);
1028             ret = AVERROR_INVALIDDATA;
1029             goto cleanup;
1030         }
1031
1032         adaptionset_node = xmlFirstElementChild(period_node);
1033         while (adaptionset_node) {
1034             if (!av_strcasecmp(adaptionset_node->name, (const char *)"BaseURL")) {
1035                 period_baseurl_node = adaptionset_node;
1036             } else if (!av_strcasecmp(adaptionset_node->name, (const char *)"AdaptationSet")) {
1037                 parse_manifest_adaptationset(s, url, adaptionset_node, mpd_baseurl_node, period_baseurl_node);
1038             }
1039             adaptionset_node = xmlNextElementSibling(adaptionset_node);
1040         }
1041 cleanup:
1042         /*free the document */
1043         xmlFreeDoc(doc);
1044         xmlCleanupParser();
1045     }
1046
1047     av_free(new_url);
1048     av_free(buffer);
1049     if (close_in) {
1050         avio_close(in);
1051     }
1052     return ret;
1053 }
1054
1055 static int64_t calc_cur_seg_no(AVFormatContext *s, struct representation *pls)
1056 {
1057     DASHContext *c = s->priv_data;
1058     int64_t num = 0;
1059     int64_t start_time_offset = 0;
1060
1061     if (c->is_live) {
1062         if (pls->n_fragments) {
1063             num = pls->first_seq_no;
1064         } else if (pls->n_timelines) {
1065             start_time_offset = get_segment_start_time_based_on_timeline(pls, 0xFFFFFFFF) - pls->timelines[pls->first_seq_no]->starttime; // total duration of playlist
1066             if (start_time_offset < 60 * pls->fragment_timescale)
1067                 start_time_offset = 0;
1068             else
1069                 start_time_offset = start_time_offset - 60 * pls->fragment_timescale;
1070
1071             num = calc_next_seg_no_from_timelines(pls, pls->timelines[pls->first_seq_no]->starttime + start_time_offset);
1072             if (num == -1)
1073                 num = pls->first_seq_no;
1074         } else if (pls->fragment_duration){
1075             if (pls->presentation_timeoffset) {
1076                 num = pls->presentation_timeoffset * pls->fragment_timescale / pls->fragment_duration;
1077             } else if (c->publish_time > 0 && !c->availability_start_time) {
1078                 num = pls->first_seq_no + (((c->publish_time - c->availability_start_time) - c->suggested_presentation_delay) * pls->fragment_timescale) / pls->fragment_duration;
1079             } else {
1080                 num = pls->first_seq_no + (((get_current_time_in_sec() - c->availability_start_time) - c->suggested_presentation_delay) * pls->fragment_timescale) / pls->fragment_duration;
1081             }
1082         }
1083     } else {
1084         num = pls->first_seq_no;
1085     }
1086     return num;
1087 }
1088
1089 static int64_t calc_min_seg_no(AVFormatContext *s, struct representation *pls)
1090 {
1091     DASHContext *c = s->priv_data;
1092     int64_t num = 0;
1093
1094     if (c->is_live && pls->fragment_duration) {
1095         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;
1096     } else {
1097         num = pls->first_seq_no;
1098     }
1099     return num;
1100 }
1101
1102 static int64_t calc_max_seg_no(struct representation *pls, DASHContext *c)
1103 {
1104     int64_t num = 0;
1105
1106     if (pls->n_fragments) {
1107         num = pls->first_seq_no + pls->n_fragments - 1;
1108     } else if (pls->n_timelines) {
1109         int i = 0;
1110         num = pls->first_seq_no + pls->n_timelines - 1;
1111         for (i = 0; i < pls->n_timelines; i++) {
1112             num += pls->timelines[i]->repeat;
1113         }
1114     } else if (c->is_live && pls->fragment_duration) {
1115         num = pls->first_seq_no + (((get_current_time_in_sec() - c->availability_start_time)) * pls->fragment_timescale)  / pls->fragment_duration;
1116     } else if (pls->fragment_duration) {
1117         num = pls->first_seq_no + (c->media_presentation_duration * pls->fragment_timescale) / pls->fragment_duration;
1118     }
1119
1120     return num;
1121 }
1122
1123 static void move_timelines(struct representation *rep_src, struct representation *rep_dest, DASHContext *c)
1124 {
1125     if (rep_dest && rep_src ) {
1126         free_timelines_list(rep_dest);
1127         rep_dest->timelines    = rep_src->timelines;
1128         rep_dest->n_timelines  = rep_src->n_timelines;
1129         rep_dest->first_seq_no = rep_src->first_seq_no;
1130         rep_dest->last_seq_no = calc_max_seg_no(rep_dest, c);
1131         rep_src->timelines = NULL;
1132         rep_src->n_timelines = 0;
1133         rep_dest->cur_seq_no = rep_src->cur_seq_no;
1134     }
1135 }
1136
1137 static void move_segments(struct representation *rep_src, struct representation *rep_dest, DASHContext *c)
1138 {
1139     if (rep_dest && rep_src ) {
1140         free_fragment_list(rep_dest);
1141         if (rep_src->start_number > (rep_dest->start_number + rep_dest->n_fragments))
1142             rep_dest->cur_seq_no = 0;
1143         else
1144             rep_dest->cur_seq_no += rep_src->start_number - rep_dest->start_number;
1145         rep_dest->fragments    = rep_src->fragments;
1146         rep_dest->n_fragments  = rep_src->n_fragments;
1147         rep_dest->parent  = rep_src->parent;
1148         rep_dest->last_seq_no = calc_max_seg_no(rep_dest, c);
1149         rep_src->fragments = NULL;
1150         rep_src->n_fragments = 0;
1151     }
1152 }
1153
1154
1155 static int refresh_manifest(AVFormatContext *s)
1156 {
1157
1158     int ret = 0, i;
1159     DASHContext *c = s->priv_data;
1160
1161     // save current context
1162     int n_videos = c->n_videos;
1163     struct representation **videos = c->videos;
1164     int n_audios = c->n_audios;
1165     struct representation **audios = c->audios;
1166     char *base_url = c->base_url;
1167
1168     c->base_url = NULL;
1169     c->n_videos = 0;
1170     c->videos = NULL;
1171     c->n_audios = 0;
1172     c->audios = NULL;
1173     ret = parse_manifest(s, s->filename, NULL);
1174     if (ret)
1175         goto finish;
1176
1177     if (c->n_videos != n_videos) {
1178         av_log(c, AV_LOG_ERROR,
1179             "new manifest has mismatched no. of video representations, %d -> %d\n",
1180             n_videos, c->n_videos);
1181         return AVERROR_INVALIDDATA;
1182     }
1183     if (c->n_audios != n_audios) {
1184         av_log(c, AV_LOG_ERROR,
1185             "new manifest has mismatched no. of audio representations, %d -> %d\n",
1186             n_audios, c->n_audios);
1187         return AVERROR_INVALIDDATA;
1188     }
1189
1190     for (i = 0; i < n_videos; i++) {
1191         struct representation *cur_video = videos[i];
1192         struct representation *ccur_video = c->videos[i];
1193         if (cur_video->timelines) {
1194             // calc current time
1195             int64_t currentTime = get_segment_start_time_based_on_timeline(cur_video, cur_video->cur_seq_no) / cur_video->fragment_timescale;
1196             // update segments
1197             ccur_video->cur_seq_no = calc_next_seg_no_from_timelines(ccur_video, currentTime * cur_video->fragment_timescale - 1);
1198             if (ccur_video->cur_seq_no >= 0) {
1199                 move_timelines(ccur_video, cur_video, c);
1200             }
1201         }
1202         if (cur_video->fragments) {
1203             move_segments(ccur_video, cur_video, c);
1204         }
1205     }
1206     for (i = 0; i < n_audios; i++) {
1207         struct representation *cur_audio = audios[i];
1208         struct representation *ccur_audio = c->audios[i];
1209         if (cur_audio->timelines) {
1210             // calc current time
1211             int64_t currentTime = get_segment_start_time_based_on_timeline(cur_audio, cur_audio->cur_seq_no) / cur_audio->fragment_timescale;
1212             // update segments
1213             ccur_audio->cur_seq_no = calc_next_seg_no_from_timelines(ccur_audio, currentTime * cur_audio->fragment_timescale - 1);
1214             if (ccur_audio->cur_seq_no >= 0) {
1215                 move_timelines(ccur_audio, cur_audio, c);
1216             }
1217         }
1218         if (cur_audio->fragments) {
1219             move_segments(ccur_audio, cur_audio, c);
1220         }
1221     }
1222
1223 finish:
1224     // restore context
1225     if (c->base_url)
1226         av_free(base_url);
1227     else
1228         c->base_url  = base_url;
1229     if (c->audios)
1230         free_audio_list(c);
1231     if (c->videos)
1232         free_video_list(c);
1233     c->n_audios = n_audios;
1234     c->audios = audios;
1235     c->n_videos = n_videos;
1236     c->videos = videos;
1237     return ret;
1238 }
1239
1240 static struct fragment *get_current_fragment(struct representation *pls)
1241 {
1242     int64_t min_seq_no = 0;
1243     int64_t max_seq_no = 0;
1244     struct fragment *seg = NULL;
1245     struct fragment *seg_ptr = NULL;
1246     DASHContext *c = pls->parent->priv_data;
1247
1248     while (( !ff_check_interrupt(c->interrupt_callback)&& pls->n_fragments > 0)) {
1249         if (pls->cur_seq_no < pls->n_fragments) {
1250             seg_ptr = pls->fragments[pls->cur_seq_no];
1251             seg = av_mallocz(sizeof(struct fragment));
1252             if (!seg) {
1253                 return NULL;
1254             }
1255             seg->url = av_strdup(seg_ptr->url);
1256             if (!seg->url) {
1257                 av_free(seg);
1258                 return NULL;
1259             }
1260             seg->size = seg_ptr->size;
1261             seg->url_offset = seg_ptr->url_offset;
1262             return seg;
1263         } else if (c->is_live) {
1264             refresh_manifest(pls->parent);
1265         } else {
1266             break;
1267         }
1268     }
1269     if (c->is_live) {
1270         min_seq_no = calc_min_seg_no(pls->parent, pls);
1271         max_seq_no = calc_max_seg_no(pls, c);
1272
1273         if (pls->timelines || pls->fragments) {
1274             refresh_manifest(pls->parent);
1275         }
1276         if (pls->cur_seq_no <= min_seq_no) {
1277             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);
1278             pls->cur_seq_no = calc_cur_seg_no(pls->parent, pls);
1279         } else if (pls->cur_seq_no > max_seq_no) {
1280             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);
1281         }
1282         seg = av_mallocz(sizeof(struct fragment));
1283         if (!seg) {
1284             return NULL;
1285         }
1286     } else if (pls->cur_seq_no <= pls->last_seq_no) {
1287         seg = av_mallocz(sizeof(struct fragment));
1288         if (!seg) {
1289             return NULL;
1290         }
1291     }
1292     if (seg) {
1293         char tmpfilename[MAX_URL_SIZE];
1294
1295         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));
1296         seg->url = av_strireplace(pls->url_template, pls->url_template, tmpfilename);
1297         if (!seg->url) {
1298             av_log(pls->parent, AV_LOG_WARNING, "Unable to resolve template url '%s', try to use origin template\n", pls->url_template);
1299             seg->url = av_strdup(pls->url_template);
1300             if (!seg->url) {
1301                 av_log(pls->parent, AV_LOG_ERROR, "Cannot resolve template url '%s'\n", pls->url_template);
1302                 return NULL;
1303             }
1304         }
1305
1306         seg->size = -1;
1307     }
1308
1309     return seg;
1310 }
1311
1312 enum ReadFromURLMode {
1313     READ_NORMAL,
1314     READ_COMPLETE,
1315 };
1316
1317 static int read_from_url(struct representation *pls, struct fragment *seg,
1318                          uint8_t *buf, int buf_size,
1319                          enum ReadFromURLMode mode)
1320 {
1321     int ret;
1322
1323     /* limit read if the fragment was only a part of a file */
1324     if (seg->size >= 0)
1325         buf_size = FFMIN(buf_size, pls->cur_seg_size - pls->cur_seg_offset);
1326
1327     if (mode == READ_COMPLETE) {
1328         ret = avio_read(pls->input, buf, buf_size);
1329         if (ret < buf_size) {
1330             av_log(pls->parent, AV_LOG_WARNING, "Could not read complete fragment.\n");
1331         }
1332     } else {
1333         ret = avio_read(pls->input, buf, buf_size);
1334     }
1335     if (ret > 0)
1336         pls->cur_seg_offset += ret;
1337
1338     return ret;
1339 }
1340
1341 static int open_input(DASHContext *c, struct representation *pls, struct fragment *seg)
1342 {
1343     AVDictionary *opts = NULL;
1344     char url[MAX_URL_SIZE];
1345     int ret;
1346
1347     set_httpheader_options(c, &opts);
1348     if (seg->size >= 0) {
1349         /* try to restrict the HTTP request to the part we want
1350          * (if this is in fact a HTTP request) */
1351         av_dict_set_int(&opts, "offset", seg->url_offset, 0);
1352         av_dict_set_int(&opts, "end_offset", seg->url_offset + seg->size, 0);
1353     }
1354
1355     ff_make_absolute_url(url, MAX_URL_SIZE, c->base_url, seg->url);
1356     av_log(pls->parent, AV_LOG_VERBOSE, "DASH request for url '%s', offset %"PRId64", playlist %d\n",
1357            url, seg->url_offset, pls->rep_idx);
1358     ret = open_url(pls->parent, &pls->input, url, c->avio_opts, opts, NULL);
1359     if (ret < 0) {
1360         goto cleanup;
1361     }
1362
1363     /* Seek to the requested position. If this was a HTTP request, the offset
1364      * should already be where want it to, but this allows e.g. local testing
1365      * without a HTTP server. */
1366     if (!ret && seg->url_offset) {
1367         int64_t seekret = avio_seek(pls->input, seg->url_offset, SEEK_SET);
1368         if (seekret < 0) {
1369             av_log(pls->parent, AV_LOG_ERROR, "Unable to seek to offset %"PRId64" of DASH fragment '%s'\n", seg->url_offset, seg->url);
1370             ret = (int) seekret;
1371             ff_format_io_close(pls->parent, &pls->input);
1372         }
1373     }
1374
1375 cleanup:
1376     av_dict_free(&opts);
1377     pls->cur_seg_offset = 0;
1378     pls->cur_seg_size = seg->size;
1379     return ret;
1380 }
1381
1382 static int update_init_section(struct representation *pls)
1383 {
1384     static const int max_init_section_size = 1024 * 1024;
1385     DASHContext *c = pls->parent->priv_data;
1386     int64_t sec_size;
1387     int64_t urlsize;
1388     int ret;
1389
1390     if (!pls->init_section || pls->init_sec_buf)
1391         return 0;
1392
1393     ret = open_input(c, pls, pls->init_section);
1394     if (ret < 0) {
1395         av_log(pls->parent, AV_LOG_WARNING,
1396                "Failed to open an initialization section in playlist %d\n",
1397                pls->rep_idx);
1398         return ret;
1399     }
1400
1401     if (pls->init_section->size >= 0)
1402         sec_size = pls->init_section->size;
1403     else if ((urlsize = avio_size(pls->input)) >= 0)
1404         sec_size = urlsize;
1405     else
1406         sec_size = max_init_section_size;
1407
1408     av_log(pls->parent, AV_LOG_DEBUG,
1409            "Downloading an initialization section of size %"PRId64"\n",
1410            sec_size);
1411
1412     sec_size = FFMIN(sec_size, max_init_section_size);
1413
1414     av_fast_malloc(&pls->init_sec_buf, &pls->init_sec_buf_size, sec_size);
1415
1416     ret = read_from_url(pls, pls->init_section, pls->init_sec_buf,
1417                         pls->init_sec_buf_size, READ_COMPLETE);
1418     ff_format_io_close(pls->parent, &pls->input);
1419
1420     if (ret < 0)
1421         return ret;
1422
1423     pls->init_sec_data_len = ret;
1424     pls->init_sec_buf_read_offset = 0;
1425
1426     return 0;
1427 }
1428
1429 static int64_t seek_data(void *opaque, int64_t offset, int whence)
1430 {
1431     struct representation *v = opaque;
1432     if (v->n_fragments && !v->init_sec_data_len) {
1433         return avio_seek(v->input, offset, whence);
1434     }
1435
1436     return AVERROR(ENOSYS);
1437 }
1438
1439 static int read_data(void *opaque, uint8_t *buf, int buf_size)
1440 {
1441     int ret = 0;
1442     struct representation *v = opaque;
1443     DASHContext *c = v->parent->priv_data;
1444
1445 restart:
1446     if (!v->input) {
1447         free_fragment(&v->cur_seg);
1448         v->cur_seg = get_current_fragment(v);
1449         if (!v->cur_seg) {
1450             ret = AVERROR_EOF;
1451             goto end;
1452         }
1453
1454         /* load/update Media Initialization Section, if any */
1455         ret = update_init_section(v);
1456         if (ret)
1457             goto end;
1458
1459         ret = open_input(c, v, v->cur_seg);
1460         if (ret < 0) {
1461             if (ff_check_interrupt(c->interrupt_callback)) {
1462                 goto end;
1463                 ret = AVERROR_EXIT;
1464             }
1465             av_log(v->parent, AV_LOG_WARNING, "Failed to open fragment of playlist %d\n", v->rep_idx);
1466             v->cur_seq_no++;
1467             goto restart;
1468         }
1469     }
1470
1471     if (v->init_sec_buf_read_offset < v->init_sec_data_len) {
1472         /* Push init section out first before first actual fragment */
1473         int copy_size = FFMIN(v->init_sec_data_len - v->init_sec_buf_read_offset, buf_size);
1474         memcpy(buf, v->init_sec_buf, copy_size);
1475         v->init_sec_buf_read_offset += copy_size;
1476         ret = copy_size;
1477         goto end;
1478     }
1479
1480     /* check the v->cur_seg, if it is null, get current and double check if the new v->cur_seg*/
1481     if (!v->cur_seg) {
1482         v->cur_seg = get_current_fragment(v);
1483     }
1484     if (!v->cur_seg) {
1485         ret = AVERROR_EOF;
1486         goto end;
1487     }
1488     ret = read_from_url(v, v->cur_seg, buf, buf_size, READ_NORMAL);
1489     if (ret > 0)
1490         goto end;
1491
1492     if (!v->is_restart_needed)
1493         v->cur_seq_no++;
1494     v->is_restart_needed = 1;
1495
1496 end:
1497     return ret;
1498 }
1499
1500 static int save_avio_options(AVFormatContext *s)
1501 {
1502     DASHContext *c = s->priv_data;
1503     const char *opts[] = { "headers", "user_agent", "user-agent", "cookies", NULL }, **opt = opts;
1504     uint8_t *buf = NULL;
1505     int ret = 0;
1506
1507     while (*opt) {
1508         if (av_opt_get(s->pb, *opt, AV_OPT_SEARCH_CHILDREN, &buf) >= 0) {
1509             if (buf[0] != '\0') {
1510                 ret = av_dict_set(&c->avio_opts, *opt, buf, AV_DICT_DONT_STRDUP_VAL);
1511                 if (ret < 0) {
1512                     av_freep(&buf);
1513                     return ret;
1514                 }
1515             } else {
1516                 av_freep(&buf);
1517             }
1518         }
1519         opt++;
1520     }
1521
1522     return ret;
1523 }
1524
1525 static int nested_io_open(AVFormatContext *s, AVIOContext **pb, const char *url,
1526                           int flags, AVDictionary **opts)
1527 {
1528     av_log(s, AV_LOG_ERROR,
1529            "A DASH playlist item '%s' referred to an external file '%s'. "
1530            "Opening this file was forbidden for security reasons\n",
1531            s->filename, url);
1532     return AVERROR(EPERM);
1533 }
1534
1535 static void close_demux_for_component(struct representation *pls)
1536 {
1537     /* note: the internal buffer could have changed */
1538     av_freep(&pls->pb.buffer);
1539     memset(&pls->pb, 0x00, sizeof(AVIOContext));
1540     pls->ctx->pb = NULL;
1541     avformat_close_input(&pls->ctx);
1542     pls->ctx = NULL;
1543 }
1544
1545 static int reopen_demux_for_component(AVFormatContext *s, struct representation *pls)
1546 {
1547     DASHContext *c = s->priv_data;
1548     AVInputFormat *in_fmt = NULL;
1549     AVDictionary  *in_fmt_opts = NULL;
1550     uint8_t *avio_ctx_buffer  = NULL;
1551     int ret = 0;
1552
1553     if (pls->ctx) {
1554         close_demux_for_component(pls);
1555     }
1556     if (!(pls->ctx = avformat_alloc_context())) {
1557         ret = AVERROR(ENOMEM);
1558         goto fail;
1559     }
1560
1561     avio_ctx_buffer  = av_malloc(INITIAL_BUFFER_SIZE);
1562     if (!avio_ctx_buffer ) {
1563         ret = AVERROR(ENOMEM);
1564         avformat_free_context(pls->ctx);
1565         pls->ctx = NULL;
1566         goto fail;
1567     }
1568     if (c->is_live) {
1569         ffio_init_context(&pls->pb, avio_ctx_buffer , INITIAL_BUFFER_SIZE, 0, pls, read_data, NULL, NULL);
1570     } else {
1571         ffio_init_context(&pls->pb, avio_ctx_buffer , INITIAL_BUFFER_SIZE, 0, pls, read_data, NULL, seek_data);
1572     }
1573     pls->pb.seekable = 0;
1574
1575     if ((ret = ff_copy_whiteblacklists(pls->ctx, s)) < 0)
1576         goto fail;
1577
1578     pls->ctx->flags = AVFMT_FLAG_CUSTOM_IO;
1579     pls->ctx->probesize = 1024 * 4;
1580     pls->ctx->max_analyze_duration = 4 * AV_TIME_BASE;
1581     ret = av_probe_input_buffer(&pls->pb, &in_fmt, "", NULL, 0, 0);
1582     if (ret < 0) {
1583         av_log(s, AV_LOG_ERROR, "Error when loading first fragment, playlist %d\n", (int)pls->rep_idx);
1584         avformat_free_context(pls->ctx);
1585         pls->ctx = NULL;
1586         goto fail;
1587     }
1588
1589     pls->ctx->pb = &pls->pb;
1590     pls->ctx->io_open  = nested_io_open;
1591
1592     // provide additional information from mpd if available
1593     ret = avformat_open_input(&pls->ctx, "", in_fmt, &in_fmt_opts); //pls->init_section->url
1594     av_dict_free(&in_fmt_opts);
1595     if (ret < 0)
1596         goto fail;
1597     if (pls->n_fragments) {
1598         ret = avformat_find_stream_info(pls->ctx, NULL);
1599         if (ret < 0)
1600             goto fail;
1601     }
1602
1603 fail:
1604     return ret;
1605 }
1606
1607 static int open_demux_for_component(AVFormatContext *s, struct representation *pls)
1608 {
1609     int ret = 0;
1610     int i;
1611
1612     pls->parent = s;
1613     pls->cur_seq_no  = calc_cur_seg_no(s, pls);
1614     pls->last_seq_no = calc_max_seg_no(pls, s->priv_data);
1615
1616     ret = reopen_demux_for_component(s, pls);
1617     if (ret < 0) {
1618         goto fail;
1619     }
1620     for (i = 0; i < pls->ctx->nb_streams; i++) {
1621         AVStream *st = avformat_new_stream(s, NULL);
1622         AVStream *ist = pls->ctx->streams[i];
1623         if (!st) {
1624             ret = AVERROR(ENOMEM);
1625             goto fail;
1626         }
1627         st->id = i;
1628         avcodec_parameters_copy(st->codecpar, pls->ctx->streams[i]->codecpar);
1629         avpriv_set_pts_info(st, ist->pts_wrap_bits, ist->time_base.num, ist->time_base.den);
1630     }
1631
1632     return 0;
1633 fail:
1634     return ret;
1635 }
1636
1637 static int dash_read_header(AVFormatContext *s)
1638 {
1639     void *u = (s->flags & AVFMT_FLAG_CUSTOM_IO) ? NULL : s->pb;
1640     DASHContext *c = s->priv_data;
1641     int ret = 0;
1642     int stream_index = 0;
1643     int i;
1644
1645     c->interrupt_callback = &s->interrupt_callback;
1646     // if the URL context is good, read important options we must broker later
1647     if (u) {
1648         update_options(&c->user_agent, "user-agent", u);
1649         update_options(&c->cookies, "cookies", u);
1650         update_options(&c->headers, "headers", u);
1651     }
1652
1653     if ((ret = parse_manifest(s, s->filename, s->pb)) < 0)
1654         goto fail;
1655
1656     if ((ret = save_avio_options(s)) < 0)
1657         goto fail;
1658
1659     /* If this isn't a live stream, fill the total duration of the
1660      * stream. */
1661     if (!c->is_live) {
1662         s->duration = (int64_t) c->media_presentation_duration * AV_TIME_BASE;
1663     }
1664
1665     /* Open the demuxer for video and audio components if available */
1666     for (i = 0; i < c->n_videos; i++) {
1667         struct representation *cur_video = c->videos[i];
1668         ret = open_demux_for_component(s, cur_video);
1669         if (ret)
1670             goto fail;
1671         cur_video->stream_index = stream_index;
1672         ++stream_index;
1673     }
1674
1675     for (i = 0; i < c->n_audios; i++) {
1676         struct representation *cur_audio = c->audios[i];
1677         ret = open_demux_for_component(s, cur_audio);
1678         if (ret)
1679             goto fail;
1680         cur_audio->stream_index = stream_index;
1681         ++stream_index;
1682     }
1683
1684     if (!stream_index) {
1685         ret = AVERROR_INVALIDDATA;
1686         goto fail;
1687     }
1688
1689     /* Create a program */
1690     if (!ret) {
1691         AVProgram *program;
1692         program = av_new_program(s, 0);
1693         if (!program) {
1694             goto fail;
1695         }
1696
1697         for (i = 0; i < c->n_videos; i++) {
1698             struct representation *pls = c->videos[i];
1699
1700             av_program_add_stream_index(s, 0, pls->stream_index);
1701             pls->assoc_stream = s->streams[pls->stream_index];
1702             if (pls->bandwidth > 0)
1703                 av_dict_set_int(&pls->assoc_stream->metadata, "variant_bitrate", pls->bandwidth, 0);
1704             if (pls->id[0])
1705                 av_dict_set(&pls->assoc_stream->metadata, "id", pls->id, 0);
1706          }
1707         for (i = 0; i < c->n_audios; i++) {
1708             struct representation *pls = c->audios[i];
1709
1710             av_program_add_stream_index(s, 0, pls->stream_index);
1711             pls->assoc_stream = s->streams[pls->stream_index];
1712             if (pls->bandwidth > 0)
1713                 av_dict_set_int(&pls->assoc_stream->metadata, "variant_bitrate", pls->bandwidth, 0);
1714             if (pls->id[0])
1715                 av_dict_set(&pls->assoc_stream->metadata, "id", pls->id, 0);
1716         }
1717     }
1718
1719     return 0;
1720 fail:
1721     return ret;
1722 }
1723
1724 static void recheck_discard_flags(AVFormatContext *s, struct representation **p, int n)
1725 {
1726     int i, j;
1727
1728     for (i = 0; i < n; i++) {
1729         struct representation *pls = p[i];
1730
1731         int needed = !pls->assoc_stream || pls->assoc_stream->discard < AVDISCARD_ALL;
1732         if (needed && !pls->ctx) {
1733             pls->cur_seg_offset = 0;
1734             pls->init_sec_buf_read_offset = 0;
1735             /* Catch up */
1736             for (j = 0; j < n; j++) {
1737                 pls->cur_seq_no = FFMAX(pls->cur_seq_no, p[j]->cur_seq_no);
1738             }
1739             reopen_demux_for_component(s, pls);
1740             av_log(s, AV_LOG_INFO, "Now receiving stream_index %d\n", pls->stream_index);
1741         } else if (!needed && pls->ctx) {
1742             close_demux_for_component(pls);
1743             if (pls->input)
1744                 ff_format_io_close(pls->parent, &pls->input);
1745             av_log(s, AV_LOG_INFO, "No longer receiving stream_index %d\n", pls->stream_index);
1746         }
1747     }
1748 }
1749
1750 static int dash_read_packet(AVFormatContext *s, AVPacket *pkt)
1751 {
1752     DASHContext *c = s->priv_data;
1753     int ret = 0, i;
1754     int64_t mints = 0;
1755     struct representation *cur = NULL;
1756
1757     recheck_discard_flags(s, c->videos, c->n_videos);
1758     recheck_discard_flags(s, c->audios, c->n_audios);
1759
1760     for (i = 0; i < c->n_videos; i++) {
1761         struct representation *pls = c->videos[i];
1762         if (!pls->ctx)
1763             continue;
1764         if (!cur || pls->cur_timestamp < mints) {
1765             cur = pls;
1766             mints = pls->cur_timestamp;
1767         }
1768     }
1769     for (i = 0; i < c->n_audios; i++) {
1770         struct representation *pls = c->audios[i];
1771         if (!pls->ctx)
1772             continue;
1773         if (!cur || pls->cur_timestamp < mints) {
1774             cur = pls;
1775             mints = pls->cur_timestamp;
1776         }
1777     }
1778
1779     if (!cur) {
1780         return AVERROR_INVALIDDATA;
1781     }
1782     while (!ff_check_interrupt(c->interrupt_callback) && !ret) {
1783         ret = av_read_frame(cur->ctx, pkt);
1784         if (ret >= 0) {
1785             /* If we got a packet, return it */
1786             cur->cur_timestamp = av_rescale(pkt->pts, (int64_t)cur->ctx->streams[0]->time_base.num * 90000, cur->ctx->streams[0]->time_base.den);
1787             pkt->stream_index = cur->stream_index;
1788             return 0;
1789         }
1790         if (cur->is_restart_needed) {
1791             cur->cur_seg_offset = 0;
1792             cur->init_sec_buf_read_offset = 0;
1793             if (cur->input)
1794                 ff_format_io_close(cur->parent, &cur->input);
1795             ret = reopen_demux_for_component(s, cur);
1796             cur->is_restart_needed = 0;
1797         }
1798     }
1799     return AVERROR_EOF;
1800 }
1801
1802 static int dash_close(AVFormatContext *s)
1803 {
1804     DASHContext *c = s->priv_data;
1805     free_audio_list(c);
1806     free_video_list(c);
1807
1808     av_freep(&c->cookies);
1809     av_freep(&c->user_agent);
1810     av_dict_free(&c->avio_opts);
1811     av_freep(&c->base_url);
1812     return 0;
1813 }
1814
1815 static int dash_seek(AVFormatContext *s, struct representation *pls, int64_t seek_pos_msec, int flags)
1816 {
1817     int ret = 0;
1818     int i = 0;
1819     int j = 0;
1820     int64_t duration = 0;
1821
1822     av_log(pls->parent, AV_LOG_VERBOSE, "DASH seek pos[%"PRId64"ms], playlist %d\n", seek_pos_msec, pls->rep_idx);
1823
1824     // single fragment mode
1825     if (pls->n_fragments == 1) {
1826         pls->cur_timestamp = 0;
1827         pls->cur_seg_offset = 0;
1828         ff_read_frame_flush(pls->ctx);
1829         return av_seek_frame(pls->ctx, -1, seek_pos_msec * 1000, flags);
1830     }
1831
1832     if (pls->input)
1833         ff_format_io_close(pls->parent, &pls->input);
1834
1835     // find the nearest fragment
1836     if (pls->n_timelines > 0 && pls->fragment_timescale > 0) {
1837         int64_t num = pls->first_seq_no;
1838         av_log(pls->parent, AV_LOG_VERBOSE, "dash_seek with SegmentTimeline start n_timelines[%d] "
1839                "last_seq_no[%"PRId64"], playlist %d.\n",
1840                (int)pls->n_timelines, (int64_t)pls->last_seq_no, (int)pls->rep_idx);
1841         for (i = 0; i < pls->n_timelines; i++) {
1842             if (pls->timelines[i]->starttime > 0) {
1843                 duration = pls->timelines[i]->starttime;
1844             }
1845             duration += pls->timelines[i]->duration;
1846             if (seek_pos_msec < ((duration * 1000) /  pls->fragment_timescale)) {
1847                 goto set_seq_num;
1848             }
1849             for (j = 0; j < pls->timelines[i]->repeat; j++) {
1850                 duration += pls->timelines[i]->duration;
1851                 num++;
1852                 if (seek_pos_msec < ((duration * 1000) /  pls->fragment_timescale)) {
1853                     goto set_seq_num;
1854                 }
1855             }
1856             num++;
1857         }
1858
1859 set_seq_num:
1860         pls->cur_seq_no = num > pls->last_seq_no ? pls->last_seq_no : num;
1861         av_log(pls->parent, AV_LOG_VERBOSE, "dash_seek with SegmentTimeline end cur_seq_no[%"PRId64"], playlist %d.\n",
1862                (int64_t)pls->cur_seq_no, (int)pls->rep_idx);
1863     } else if (pls->fragment_duration > 0) {
1864         pls->cur_seq_no = pls->first_seq_no + ((seek_pos_msec * pls->fragment_timescale) / pls->fragment_duration) / 1000;
1865     } else {
1866         av_log(pls->parent, AV_LOG_ERROR, "dash_seek missing fragment_duration\n");
1867         pls->cur_seq_no = pls->first_seq_no;
1868     }
1869     pls->cur_timestamp = 0;
1870     pls->cur_seg_offset = 0;
1871     pls->init_sec_buf_read_offset = 0;
1872     ret = reopen_demux_for_component(s, pls);
1873
1874     return ret;
1875 }
1876
1877 static int dash_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
1878 {
1879     int ret, i;
1880     DASHContext *c = s->priv_data;
1881     int64_t seek_pos_msec = av_rescale_rnd(timestamp, 1000,
1882                                            s->streams[stream_index]->time_base.den,
1883                                            flags & AVSEEK_FLAG_BACKWARD ?
1884                                            AV_ROUND_DOWN : AV_ROUND_UP);
1885     if ((flags & AVSEEK_FLAG_BYTE) || c->is_live)
1886         return AVERROR(ENOSYS);
1887
1888     ret = AVERROR_EOF;
1889     for (i = 0; i < c->n_videos; i++) {
1890         if (c->videos[i]->stream_index == stream_index) {
1891             ret = dash_seek(s, c->videos[i], seek_pos_msec, flags);
1892         }
1893     }
1894     for (i = 0; i < c->n_audios; i++) {
1895         if (c->audios[i]->stream_index == stream_index) {
1896             ret = dash_seek(s, c->audios[i], seek_pos_msec, flags);
1897         }
1898     }
1899
1900     return ret;
1901 }
1902
1903 static int dash_probe(AVProbeData *p)
1904 {
1905     if (!av_stristr(p->buf, "<MPD"))
1906         return 0;
1907
1908     if (av_stristr(p->buf, "dash:profile:isoff-on-demand:2011") ||
1909         av_stristr(p->buf, "dash:profile:isoff-live:2011") ||
1910         av_stristr(p->buf, "dash:profile:isoff-live:2012") ||
1911         av_stristr(p->buf, "dash:profile:isoff-main:2011")) {
1912         return AVPROBE_SCORE_MAX;
1913     }
1914     if (av_stristr(p->buf, "dash:profile")) {
1915         return AVPROBE_SCORE_MAX;
1916     }
1917
1918     return 0;
1919 }
1920
1921 #define OFFSET(x) offsetof(DASHContext, x)
1922 #define FLAGS AV_OPT_FLAG_DECODING_PARAM
1923 static const AVOption dash_options[] = {
1924     {"allowed_extensions", "List of file extensions that dash is allowed to access",
1925         OFFSET(allowed_extensions), AV_OPT_TYPE_STRING,
1926         {.str = "aac,m4a,m4s,m4v,mov,mp4"},
1927         INT_MIN, INT_MAX, FLAGS},
1928     {NULL}
1929 };
1930
1931 static const AVClass dash_class = {
1932     .class_name = "dash",
1933     .item_name  = av_default_item_name,
1934     .option     = dash_options,
1935     .version    = LIBAVUTIL_VERSION_INT,
1936 };
1937
1938 AVInputFormat ff_dash_demuxer = {
1939     .name           = "dash",
1940     .long_name      = NULL_IF_CONFIG_SMALL("Dynamic Adaptive Streaming over HTTP"),
1941     .priv_class     = &dash_class,
1942     .priv_data_size = sizeof(DASHContext),
1943     .read_probe     = dash_probe,
1944     .read_header    = dash_read_header,
1945     .read_packet    = dash_read_packet,
1946     .read_close     = dash_close,
1947     .read_seek      = dash_read_seek,
1948     .flags          = AVFMT_NO_BYTE_SEEK,
1949 };