]> git.sesse.net Git - ffmpeg/blob - libavformat/avio.c
Merge commit '75c1ed2e4c7250f5e75a11d0140727054ff0136b'
[ffmpeg] / libavformat / avio.c
1 /*
2  * unbuffered I/O
3  * Copyright (c) 2001 Fabrice Bellard
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 #include "libavutil/avstring.h"
23 #include "libavutil/dict.h"
24 #include "libavutil/opt.h"
25 #include "libavutil/time.h"
26 #include "libavutil/avassert.h"
27 #include "os_support.h"
28 #include "avformat.h"
29 #if CONFIG_NETWORK
30 #include "network.h"
31 #endif
32 #include "url.h"
33
34 static URLProtocol *first_protocol = NULL;
35
36 URLProtocol *ffurl_protocol_next(const URLProtocol *prev)
37 {
38     return prev ? prev->next : first_protocol;
39 }
40
41 /** @name Logging context. */
42 /*@{*/
43 static const char *urlcontext_to_name(void *ptr)
44 {
45     URLContext *h = (URLContext *)ptr;
46     if (h->prot)
47         return h->prot->name;
48     else
49         return "NULL";
50 }
51
52 static void *urlcontext_child_next(void *obj, void *prev)
53 {
54     URLContext *h = obj;
55     if (!prev && h->priv_data && h->prot->priv_data_class)
56         return h->priv_data;
57     return NULL;
58 }
59
60 static const AVClass *urlcontext_child_class_next(const AVClass *prev)
61 {
62     URLProtocol *p = NULL;
63
64     /* find the protocol that corresponds to prev */
65     while (prev && (p = ffurl_protocol_next(p)))
66         if (p->priv_data_class == prev)
67             break;
68
69     /* find next protocol with priv options */
70     while (p = ffurl_protocol_next(p))
71         if (p->priv_data_class)
72             return p->priv_data_class;
73     return NULL;
74 }
75
76 static const AVOption options[] = { { NULL } };
77 const AVClass ffurl_context_class = {
78     .class_name       = "URLContext",
79     .item_name        = urlcontext_to_name,
80     .option           = options,
81     .version          = LIBAVUTIL_VERSION_INT,
82     .child_next       = urlcontext_child_next,
83     .child_class_next = urlcontext_child_class_next,
84 };
85 /*@}*/
86
87 const char *avio_enum_protocols(void **opaque, int output)
88 {
89     URLProtocol *p;
90     *opaque = ffurl_protocol_next(*opaque);
91     if (!(p = *opaque))
92         return NULL;
93     if ((output && p->url_write) || (!output && p->url_read))
94         return p->name;
95     return avio_enum_protocols(opaque, output);
96 }
97
98 int ffurl_register_protocol(URLProtocol *protocol)
99 {
100     URLProtocol **p;
101     p = &first_protocol;
102     while (*p)
103         p = &(*p)->next;
104     *p             = protocol;
105     protocol->next = NULL;
106     return 0;
107 }
108
109 static int url_alloc_for_protocol(URLContext **puc, struct URLProtocol *up,
110                                   const char *filename, int flags,
111                                   const AVIOInterruptCB *int_cb)
112 {
113     URLContext *uc;
114     int err;
115
116 #if CONFIG_NETWORK
117     if (up->flags & URL_PROTOCOL_FLAG_NETWORK && !ff_network_init())
118         return AVERROR(EIO);
119 #endif
120     if ((flags & AVIO_FLAG_READ) && !up->url_read) {
121         av_log(NULL, AV_LOG_ERROR,
122                "Impossible to open the '%s' protocol for reading\n", up->name);
123         return AVERROR(EIO);
124     }
125     if ((flags & AVIO_FLAG_WRITE) && !up->url_write) {
126         av_log(NULL, AV_LOG_ERROR,
127                "Impossible to open the '%s' protocol for writing\n", up->name);
128         return AVERROR(EIO);
129     }
130     uc = av_mallocz(sizeof(URLContext) + strlen(filename) + 1);
131     if (!uc) {
132         err = AVERROR(ENOMEM);
133         goto fail;
134     }
135     uc->av_class = &ffurl_context_class;
136     uc->filename = (char *)&uc[1];
137     strcpy(uc->filename, filename);
138     uc->prot            = up;
139     uc->flags           = flags;
140     uc->is_streamed     = 0; /* default = not streamed */
141     uc->max_packet_size = 0; /* default: stream file */
142     if (up->priv_data_size) {
143         uc->priv_data = av_mallocz(up->priv_data_size);
144         if (!uc->priv_data) {
145             err = AVERROR(ENOMEM);
146             goto fail;
147         }
148         if (up->priv_data_class) {
149             int proto_len= strlen(up->name);
150             char *start = strchr(uc->filename, ',');
151             *(const AVClass **)uc->priv_data = up->priv_data_class;
152             av_opt_set_defaults(uc->priv_data);
153             if(!strncmp(up->name, uc->filename, proto_len) && uc->filename + proto_len == start){
154                 int ret= 0;
155                 char *p= start;
156                 char sep= *++p;
157                 char *key, *val;
158                 p++;
159                 while(ret >= 0 && (key= strchr(p, sep)) && p<key && (val = strchr(key+1, sep))){
160                     *val= *key= 0;
161                     ret= av_opt_set(uc->priv_data, p, key+1, 0);
162                     if (ret == AVERROR_OPTION_NOT_FOUND)
163                         av_log(uc, AV_LOG_ERROR, "Key '%s' not found.\n", p);
164                     *val= *key= sep;
165                     p= val+1;
166                 }
167                 if(ret<0 || p!=key){
168                     av_log(uc, AV_LOG_ERROR, "Error parsing options string %s\n", start);
169                     av_freep(&uc->priv_data);
170                     av_freep(&uc);
171                     err = AVERROR(EINVAL);
172                     goto fail;
173                 }
174                 memmove(start, key+1, strlen(key));
175             }
176         }
177     }
178     if (int_cb)
179         uc->interrupt_callback = *int_cb;
180
181     *puc = uc;
182     return 0;
183 fail:
184     *puc = NULL;
185     if (uc)
186         av_freep(&uc->priv_data);
187     av_freep(&uc);
188 #if CONFIG_NETWORK
189     if (up->flags & URL_PROTOCOL_FLAG_NETWORK)
190         ff_network_close();
191 #endif
192     return err;
193 }
194
195 int ffurl_connect(URLContext *uc, AVDictionary **options)
196 {
197     int err =
198         uc->prot->url_open2 ? uc->prot->url_open2(uc,
199                                                   uc->filename,
200                                                   uc->flags,
201                                                   options) :
202         uc->prot->url_open(uc, uc->filename, uc->flags);
203     if (err)
204         return err;
205     uc->is_connected = 1;
206     /* We must be careful here as ffurl_seek() could be slow,
207      * for example for http */
208     if ((uc->flags & AVIO_FLAG_WRITE) || !strcmp(uc->prot->name, "file"))
209         if (!uc->is_streamed && ffurl_seek(uc, 0, SEEK_SET) < 0)
210             uc->is_streamed = 1;
211     return 0;
212 }
213
214 #define URL_SCHEME_CHARS                        \
215     "abcdefghijklmnopqrstuvwxyz"                \
216     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"                \
217     "0123456789+-."
218
219 static struct URLProtocol *url_find_protocol(const char *filename)
220 {
221     URLProtocol *up = NULL;
222     char proto_str[128], proto_nested[128], *ptr;
223     size_t proto_len = strspn(filename, URL_SCHEME_CHARS);
224
225     if (filename[proto_len] != ':' &&
226         (filename[proto_len] != ',' || !strchr(filename + proto_len + 1, ':')) ||
227         is_dos_path(filename))
228         strcpy(proto_str, "file");
229     else
230         av_strlcpy(proto_str, filename,
231                    FFMIN(proto_len + 1, sizeof(proto_str)));
232
233     if ((ptr = strchr(proto_str, ',')))
234         *ptr = '\0';
235     av_strlcpy(proto_nested, proto_str, sizeof(proto_nested));
236     if ((ptr = strchr(proto_nested, '+')))
237         *ptr = '\0';
238
239     while (up = ffurl_protocol_next(up)) {
240         if (!strcmp(proto_str, up->name))
241             break;
242         if (up->flags & URL_PROTOCOL_FLAG_NESTED_SCHEME &&
243             !strcmp(proto_nested, up->name))
244             break;
245     }
246
247     return up;
248 }
249
250 int ffurl_alloc(URLContext **puc, const char *filename, int flags,
251                 const AVIOInterruptCB *int_cb)
252 {
253     URLProtocol *p = NULL;
254
255     if (!first_protocol) {
256         av_log(NULL, AV_LOG_WARNING, "No URL Protocols are registered. "
257                                      "Missing call to av_register_all()?\n");
258     }
259
260     p = url_find_protocol(filename);
261     if (p)
262        return url_alloc_for_protocol(puc, p, filename, flags, int_cb);
263
264     *puc = NULL;
265     if (av_strstart(filename, "https:", NULL))
266         av_log(NULL, AV_LOG_WARNING, "https protocol not found, recompile FFmpeg with "
267                                      "openssl, gnutls,\n"
268                                      "or securetransport enabled.\n");
269     return AVERROR_PROTOCOL_NOT_FOUND;
270 }
271
272 int ffurl_open(URLContext **puc, const char *filename, int flags,
273                const AVIOInterruptCB *int_cb, AVDictionary **options)
274 {
275     int ret = ffurl_alloc(puc, filename, flags, int_cb);
276     if (ret < 0)
277         return ret;
278     if (options && (*puc)->prot->priv_data_class &&
279         (ret = av_opt_set_dict((*puc)->priv_data, options)) < 0)
280         goto fail;
281     if ((ret = av_opt_set_dict(*puc, options)) < 0)
282         goto fail;
283     ret = ffurl_connect(*puc, options);
284     if (!ret)
285         return 0;
286 fail:
287     ffurl_close(*puc);
288     *puc = NULL;
289     return ret;
290 }
291
292 static inline int retry_transfer_wrapper(URLContext *h, uint8_t *buf,
293                                          int size, int size_min,
294                                          int (*transfer_func)(URLContext *h,
295                                                               uint8_t *buf,
296                                                               int size))
297 {
298     int ret, len;
299     int fast_retries = 5;
300     int64_t wait_since = 0;
301
302     len = 0;
303     while (len < size_min) {
304         if (ff_check_interrupt(&h->interrupt_callback))
305             return AVERROR_EXIT;
306         ret = transfer_func(h, buf + len, size - len);
307         if (ret == AVERROR(EINTR))
308             continue;
309         if (h->flags & AVIO_FLAG_NONBLOCK)
310             return ret;
311         if (ret == AVERROR(EAGAIN)) {
312             ret = 0;
313             if (fast_retries) {
314                 fast_retries--;
315             } else {
316                 if (h->rw_timeout) {
317                     if (!wait_since)
318                         wait_since = av_gettime_relative();
319                     else if (av_gettime_relative() > wait_since + h->rw_timeout)
320                         return AVERROR(EIO);
321                 }
322                 av_usleep(1000);
323             }
324         } else if (ret < 1)
325             return (ret < 0 && ret != AVERROR_EOF) ? ret : len;
326         if (ret)
327             fast_retries = FFMAX(fast_retries, 2);
328         len += ret;
329     }
330     return len;
331 }
332
333 int ffurl_read(URLContext *h, unsigned char *buf, int size)
334 {
335     if (!(h->flags & AVIO_FLAG_READ))
336         return AVERROR(EIO);
337     return retry_transfer_wrapper(h, buf, size, 1, h->prot->url_read);
338 }
339
340 int ffurl_read_complete(URLContext *h, unsigned char *buf, int size)
341 {
342     if (!(h->flags & AVIO_FLAG_READ))
343         return AVERROR(EIO);
344     return retry_transfer_wrapper(h, buf, size, size, h->prot->url_read);
345 }
346
347 int ffurl_write(URLContext *h, const unsigned char *buf, int size)
348 {
349     if (!(h->flags & AVIO_FLAG_WRITE))
350         return AVERROR(EIO);
351     /* avoid sending too big packets */
352     if (h->max_packet_size && size > h->max_packet_size)
353         return AVERROR(EIO);
354
355     return retry_transfer_wrapper(h, (unsigned char *)buf, size, size,
356                                   (int (*)(struct URLContext *, uint8_t *, int))
357                                   h->prot->url_write);
358 }
359
360 int64_t ffurl_seek(URLContext *h, int64_t pos, int whence)
361 {
362     int64_t ret;
363
364     if (!h->prot->url_seek)
365         return AVERROR(ENOSYS);
366     ret = h->prot->url_seek(h, pos, whence & ~AVSEEK_FORCE);
367     return ret;
368 }
369
370 int ffurl_closep(URLContext **hh)
371 {
372     URLContext *h= *hh;
373     int ret = 0;
374     if (!h)
375         return 0;     /* can happen when ffurl_open fails */
376
377     if (h->is_connected && h->prot->url_close)
378         ret = h->prot->url_close(h);
379 #if CONFIG_NETWORK
380     if (h->prot->flags & URL_PROTOCOL_FLAG_NETWORK)
381         ff_network_close();
382 #endif
383     if (h->prot->priv_data_size) {
384         if (h->prot->priv_data_class)
385             av_opt_free(h->priv_data);
386         av_freep(&h->priv_data);
387     }
388     av_freep(hh);
389     return ret;
390 }
391
392 int ffurl_close(URLContext *h)
393 {
394     return ffurl_closep(&h);
395 }
396
397
398 const char *avio_find_protocol_name(const char *url)
399 {
400     URLProtocol *p = url_find_protocol(url);
401
402     return p ? p->name : NULL;
403 }
404
405 int avio_check(const char *url, int flags)
406 {
407     URLContext *h;
408     int ret = ffurl_alloc(&h, url, flags, NULL);
409     if (ret < 0)
410         return ret;
411
412     if (h->prot->url_check) {
413         ret = h->prot->url_check(h, flags);
414     } else {
415         ret = ffurl_connect(h, NULL);
416         if (ret >= 0)
417             ret = flags;
418     }
419
420     ffurl_close(h);
421     return ret;
422 }
423
424 int avpriv_io_move(const char *url_src, const char *url_dst)
425 {
426     URLContext *h_src, *h_dst;
427     int ret = ffurl_alloc(&h_src, url_src, AVIO_FLAG_READ_WRITE, NULL);
428     if (ret < 0)
429         return ret;
430     ret = ffurl_alloc(&h_dst, url_dst, AVIO_FLAG_WRITE, NULL);
431     if (ret < 0) {
432         ffurl_close(h_src);
433         return ret;
434     }
435
436     if (h_src->prot == h_dst->prot && h_src->prot->url_move)
437         ret = h_src->prot->url_move(h_src, h_dst);
438     else
439         ret = AVERROR(ENOSYS);
440
441     ffurl_close(h_src);
442     ffurl_close(h_dst);
443     return ret;
444 }
445
446 int avpriv_io_delete(const char *url)
447 {
448     URLContext *h;
449     int ret = ffurl_alloc(&h, url, AVIO_FLAG_WRITE, NULL);
450     if (ret < 0)
451         return ret;
452
453     if (h->prot->url_delete)
454         ret = h->prot->url_delete(h);
455     else
456         ret = AVERROR(ENOSYS);
457
458     ffurl_close(h);
459     return ret;
460 }
461
462 int avio_open_dir(AVIODirContext **s, const char *url, AVDictionary **options)
463 {
464     URLContext *h = NULL;
465     AVIODirContext *ctx = NULL;
466     int ret;
467     av_assert0(s);
468
469     ctx = av_mallocz(sizeof(*ctx));
470     if (!ctx) {
471         ret = AVERROR(ENOMEM);
472         goto fail;
473     }
474
475     if ((ret = ffurl_alloc(&h, url, AVIO_FLAG_READ, NULL)) < 0)
476         goto fail;
477
478     if (h->prot->url_open_dir && h->prot->url_read_dir && h->prot->url_close_dir) {
479         if (options && h->prot->priv_data_class &&
480             (ret = av_opt_set_dict(h->priv_data, options)) < 0)
481             goto fail;
482         ret = h->prot->url_open_dir(h);
483     } else
484         ret = AVERROR(ENOSYS);
485     if (ret < 0)
486         goto fail;
487
488     h->is_connected = 1;
489     ctx->url_context = h;
490     *s = ctx;
491     return 0;
492
493   fail:
494     av_free(ctx);
495     *s = NULL;
496     ffurl_close(h);
497     return ret;
498 }
499
500 int avio_read_dir(AVIODirContext *s, AVIODirEntry **next)
501 {
502     URLContext *h;
503     int ret;
504
505     if (!s || !s->url_context)
506         return AVERROR(EINVAL);
507     h = s->url_context;
508     if ((ret = h->prot->url_read_dir(h, next)) < 0)
509         avio_free_directory_entry(next);
510     return ret;
511 }
512
513 int avio_close_dir(AVIODirContext **s)
514 {
515     URLContext *h;
516
517     av_assert0(s);
518     if (!(*s) || !(*s)->url_context)
519         return AVERROR(EINVAL);
520     h = (*s)->url_context;
521     h->prot->url_close_dir(h);
522     ffurl_close(h);
523     av_freep(s);
524     *s = NULL;
525     return 0;
526 }
527
528 void avio_free_directory_entry(AVIODirEntry **entry)
529 {
530     if (!entry || !*entry)
531         return;
532     av_free((*entry)->name);
533     av_freep(entry);
534 }
535
536 int64_t ffurl_size(URLContext *h)
537 {
538     int64_t pos, size;
539
540     size = ffurl_seek(h, 0, AVSEEK_SIZE);
541     if (size < 0) {
542         pos = ffurl_seek(h, 0, SEEK_CUR);
543         if ((size = ffurl_seek(h, -1, SEEK_END)) < 0)
544             return size;
545         size++;
546         ffurl_seek(h, pos, SEEK_SET);
547     }
548     return size;
549 }
550
551 int ffurl_get_file_handle(URLContext *h)
552 {
553     if (!h->prot->url_get_file_handle)
554         return -1;
555     return h->prot->url_get_file_handle(h);
556 }
557
558 int ffurl_get_multi_file_handle(URLContext *h, int **handles, int *numhandles)
559 {
560     if (!h->prot->url_get_multi_file_handle) {
561         if (!h->prot->url_get_file_handle)
562             return AVERROR(ENOSYS);
563         *handles = av_malloc(sizeof(**handles));
564         if (!*handles)
565             return AVERROR(ENOMEM);
566         *numhandles = 1;
567         *handles[0] = h->prot->url_get_file_handle(h);
568         return 0;
569     }
570     return h->prot->url_get_multi_file_handle(h, handles, numhandles);
571 }
572
573 int ffurl_shutdown(URLContext *h, int flags)
574 {
575     if (!h->prot->url_shutdown)
576         return AVERROR(EINVAL);
577     return h->prot->url_shutdown(h, flags);
578 }
579
580 int ff_check_interrupt(AVIOInterruptCB *cb)
581 {
582     int ret;
583     if (cb && cb->callback && (ret = cb->callback(cb->opaque)))
584         return ret;
585     return 0;
586 }