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