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