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