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