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