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