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