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