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