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