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