]> git.sesse.net Git - ffmpeg/blob - libavformat/avio.c
mpegts: reanalyze packet size on mismatches
[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 "os_support.h"
27 #include "avformat.h"
28 #if CONFIG_NETWORK
29 #include "network.h"
30 #endif
31 #include "url.h"
32
33 static URLProtocol *first_protocol = NULL;
34
35 URLProtocol *ffurl_protocol_next(URLProtocol *prev)
36 {
37     return prev ? prev->next : first_protocol;
38 }
39
40 /** @name Logging context. */
41 /*@{*/
42 static const char *urlcontext_to_name(void *ptr)
43 {
44     URLContext *h = (URLContext *)ptr;
45     if(h->prot) return h->prot->name;
46     else        return "NULL";
47 }
48
49 static void *urlcontext_child_next(void *obj, void *prev)
50 {
51     URLContext *h = obj;
52     if (!prev && h->priv_data && h->prot->priv_data_class)
53         return h->priv_data;
54     return NULL;
55 }
56
57 static const AVClass *urlcontext_child_class_next(const AVClass *prev)
58 {
59     URLProtocol *p = NULL;
60
61     /* find the protocol that corresponds to prev */
62     while (prev && (p = ffurl_protocol_next(p)))
63         if (p->priv_data_class == prev)
64             break;
65
66     /* find next protocol with priv options */
67     while (p = ffurl_protocol_next(p))
68         if (p->priv_data_class)
69             return p->priv_data_class;
70     return NULL;
71
72 }
73
74 static const AVOption options[] = {{NULL}};
75 const AVClass ffurl_context_class = {
76     .class_name     = "URLContext",
77     .item_name      = urlcontext_to_name,
78     .option         = options,
79     .version        = LIBAVUTIL_VERSION_INT,
80     .child_next     = urlcontext_child_next,
81     .child_class_next = urlcontext_child_class_next,
82 };
83 /*@}*/
84
85
86 const char *avio_enum_protocols(void **opaque, int output)
87 {
88     URLProtocol *p;
89     *opaque = ffurl_protocol_next(*opaque);
90     if (!(p = *opaque)) return NULL;
91     if ((output && p->url_write) || (!output && p->url_read))
92         return p->name;
93     return avio_enum_protocols(opaque, output);
94 }
95
96 int ffurl_register_protocol(URLProtocol *protocol, int size)
97 {
98     URLProtocol **p;
99     if (size < sizeof(URLProtocol)) {
100         URLProtocol* temp = av_mallocz(sizeof(URLProtocol));
101         memcpy(temp, protocol, size);
102         protocol = temp;
103     }
104     p = &first_protocol;
105     while (*p != NULL) p = &(*p)->next;
106     *p = protocol;
107     protocol->next = NULL;
108     return 0;
109 }
110
111 static int url_alloc_for_protocol (URLContext **puc, struct URLProtocol *up,
112                                    const char *filename, int flags,
113                                    const AVIOInterruptCB *int_cb)
114 {
115     URLContext *uc;
116     int err;
117
118 #if CONFIG_NETWORK
119     if (up->flags & URL_PROTOCOL_FLAG_NETWORK && !ff_network_init())
120         return AVERROR(EIO);
121 #endif
122     if ((flags & AVIO_FLAG_READ) && !up->url_read) {
123         av_log(NULL, AV_LOG_ERROR,
124                "Impossible to open the '%s' protocol for reading\n", up->name);
125         return AVERROR(EIO);
126     }
127     if ((flags & AVIO_FLAG_WRITE) && !up->url_write) {
128         av_log(NULL, AV_LOG_ERROR,
129                "Impossible to open the '%s' protocol for writing\n", up->name);
130         return AVERROR(EIO);
131     }
132     uc = av_mallocz(sizeof(URLContext) + strlen(filename) + 1);
133     if (!uc) {
134         err = AVERROR(ENOMEM);
135         goto fail;
136     }
137     uc->av_class = &ffurl_context_class;
138     uc->filename = (char *) &uc[1];
139     strcpy(uc->filename, filename);
140     uc->prot = up;
141     uc->flags = flags;
142     uc->is_streamed = 0; /* default = not streamed */
143     uc->max_packet_size = 0; /* default: stream file */
144     if (up->priv_data_size) {
145         uc->priv_data = av_mallocz(up->priv_data_size);
146         if (up->priv_data_class) {
147             int proto_len= strlen(up->name);
148             char *start = strchr(uc->filename, ',');
149             *(const AVClass**)uc->priv_data = up->priv_data_class;
150             av_opt_set_defaults(uc->priv_data);
151             if(!strncmp(up->name, uc->filename, proto_len) && uc->filename + proto_len == start){
152                 int ret= 0;
153                 char *p= start;
154                 char sep= *++p;
155                 char *key, *val;
156                 p++;
157                 while(ret >= 0 && (key= strchr(p, sep)) && p<key && (val = strchr(key+1, sep))){
158                     *val= *key= 0;
159                     ret= av_opt_set(uc->priv_data, p, key+1, 0);
160                     if (ret == AVERROR_OPTION_NOT_FOUND)
161                         av_log(uc, AV_LOG_ERROR, "Key '%s' not found.\n", p);
162                     *val= *key= sep;
163                     p= val+1;
164                 }
165                 if(ret<0 || p!=key){
166                     av_log(uc, AV_LOG_ERROR, "Error parsing options string %s\n", start);
167                     av_freep(&uc->priv_data);
168                     av_freep(&uc);
169                     err = AVERROR(EINVAL);
170                     goto fail;
171                 }
172                 memmove(start, key+1, strlen(key));
173             }
174         }
175     }
176     if (int_cb)
177         uc->interrupt_callback = *int_cb;
178
179     *puc = uc;
180     return 0;
181  fail:
182     *puc = NULL;
183 #if CONFIG_NETWORK
184     if (up->flags & URL_PROTOCOL_FLAG_NETWORK)
185         ff_network_close();
186 #endif
187     return err;
188 }
189
190 int ffurl_connect(URLContext* uc, AVDictionary **options)
191 {
192     int err =
193         uc->prot->url_open2 ? uc->prot->url_open2(uc, uc->filename, uc->flags, options) :
194         uc->prot->url_open(uc, uc->filename, uc->flags);
195     if (err)
196         return err;
197     uc->is_connected = 1;
198     //We must be careful here as ffurl_seek() could be slow, for example for http
199     if(   (uc->flags & AVIO_FLAG_WRITE)
200        || !strcmp(uc->prot->name, "file"))
201         if(!uc->is_streamed && ffurl_seek(uc, 0, SEEK_SET) < 0)
202             uc->is_streamed= 1;
203     return 0;
204 }
205
206 #define URL_SCHEME_CHARS                        \
207     "abcdefghijklmnopqrstuvwxyz"                \
208     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"                \
209     "0123456789+-."
210
211 int ffurl_alloc(URLContext **puc, const char *filename, int flags,
212                 const AVIOInterruptCB *int_cb)
213 {
214     URLProtocol *up = NULL;
215     char proto_str[128], proto_nested[128], *ptr;
216     size_t proto_len = strspn(filename, URL_SCHEME_CHARS);
217
218     if (!first_protocol) {
219         av_log(NULL, AV_LOG_WARNING, "No URL Protocols are registered. "
220                                      "Missing call to av_register_all()?\n");
221     }
222
223     if (filename[proto_len] != ':' &&
224         (filename[proto_len] != ',' || !strchr(filename + proto_len + 1, ':')) ||
225         is_dos_path(filename))
226         strcpy(proto_str, "file");
227     else
228         av_strlcpy(proto_str, filename, FFMIN(proto_len+1, sizeof(proto_str)));
229
230     if ((ptr = strchr(proto_str, ',')))
231         *ptr = '\0';
232     av_strlcpy(proto_nested, proto_str, sizeof(proto_nested));
233     if ((ptr = strchr(proto_nested, '+')))
234         *ptr = '\0';
235
236     while (up = ffurl_protocol_next(up)) {
237         if (!strcmp(proto_str, up->name))
238             return url_alloc_for_protocol (puc, up, filename, flags, int_cb);
239         if (up->flags & URL_PROTOCOL_FLAG_NESTED_SCHEME &&
240             !strcmp(proto_nested, up->name))
241             return url_alloc_for_protocol (puc, up, filename, flags, int_cb);
242     }
243     *puc = NULL;
244     if (!strcmp("https", proto_str))
245         av_log(NULL, AV_LOG_WARNING, "https protocol not found, recompile with openssl or gnutls enabled.\n");
246     return AVERROR_PROTOCOL_NOT_FOUND;
247 }
248
249 int ffurl_open(URLContext **puc, const char *filename, int flags,
250                const AVIOInterruptCB *int_cb, AVDictionary **options)
251 {
252     int ret = ffurl_alloc(puc, filename, flags, int_cb);
253     if (ret)
254         return ret;
255     if (options && (*puc)->prot->priv_data_class &&
256         (ret = av_opt_set_dict((*puc)->priv_data, options)) < 0)
257         goto fail;
258     ret = ffurl_connect(*puc, options);
259     if (!ret)
260         return 0;
261 fail:
262     ffurl_close(*puc);
263     *puc = NULL;
264     return ret;
265 }
266
267 static inline int retry_transfer_wrapper(URLContext *h, unsigned char *buf, int size, int size_min,
268                                          int (*transfer_func)(URLContext *h, unsigned char *buf, int size))
269 {
270     int ret, len;
271     int fast_retries = 5;
272     int64_t wait_since = 0;
273
274     len = 0;
275     while (len < size_min) {
276         if (ff_check_interrupt(&h->interrupt_callback))
277             return AVERROR_EXIT;
278         ret = transfer_func(h, buf+len, size-len);
279         if (ret == AVERROR(EINTR))
280             continue;
281         if (h->flags & AVIO_FLAG_NONBLOCK)
282             return ret;
283         if (ret == AVERROR(EAGAIN)) {
284             ret = 0;
285             if (fast_retries) {
286                 fast_retries--;
287             } else {
288                 if (h->rw_timeout) {
289                     if (!wait_since)
290                         wait_since = av_gettime();
291                     else if (av_gettime() > wait_since + h->rw_timeout)
292                         return AVERROR(EIO);
293                 }
294                 av_usleep(1000);
295             }
296         } else if (ret < 1)
297             return (ret < 0 && ret != AVERROR_EOF) ? ret : len;
298         if (ret)
299            fast_retries = FFMAX(fast_retries, 2);
300         len += ret;
301     }
302     return len;
303 }
304
305 int ffurl_read(URLContext *h, unsigned char *buf, int size)
306 {
307     if (!(h->flags & AVIO_FLAG_READ))
308         return AVERROR(EIO);
309     return retry_transfer_wrapper(h, buf, size, 1, h->prot->url_read);
310 }
311
312 int ffurl_read_complete(URLContext *h, unsigned char *buf, int size)
313 {
314     if (!(h->flags & AVIO_FLAG_READ))
315         return AVERROR(EIO);
316     return retry_transfer_wrapper(h, buf, size, size, h->prot->url_read);
317 }
318
319 int ffurl_write(URLContext *h, const unsigned char *buf, int size)
320 {
321     if (!(h->flags & AVIO_FLAG_WRITE))
322         return AVERROR(EIO);
323     /* avoid sending too big packets */
324     if (h->max_packet_size && size > h->max_packet_size)
325         return AVERROR(EIO);
326
327     return retry_transfer_wrapper(h, (unsigned char *)buf, size, size, (void*)h->prot->url_write);
328 }
329
330 int64_t ffurl_seek(URLContext *h, int64_t pos, int whence)
331 {
332     int64_t ret;
333
334     if (!h->prot->url_seek)
335         return AVERROR(ENOSYS);
336     ret = h->prot->url_seek(h, pos, whence & ~AVSEEK_FORCE);
337     return ret;
338 }
339
340 int ffurl_closep(URLContext **hh)
341 {
342     URLContext *h= *hh;
343     int ret = 0;
344     if (!h) return 0; /* can happen when ffurl_open fails */
345
346     if (h->is_connected && h->prot->url_close)
347         ret = h->prot->url_close(h);
348 #if CONFIG_NETWORK
349     if (h->prot->flags & URL_PROTOCOL_FLAG_NETWORK)
350         ff_network_close();
351 #endif
352     if (h->prot->priv_data_size) {
353         if (h->prot->priv_data_class)
354             av_opt_free(h->priv_data);
355         av_freep(&h->priv_data);
356     }
357     av_freep(hh);
358     return ret;
359 }
360
361 int ffurl_close(URLContext *h)
362 {
363     return ffurl_closep(&h);
364 }
365
366
367 int avio_check(const char *url, int flags)
368 {
369     URLContext *h;
370     int ret = ffurl_alloc(&h, url, flags, NULL);
371     if (ret)
372         return ret;
373
374     if (h->prot->url_check) {
375         ret = h->prot->url_check(h, flags);
376     } else {
377         ret = ffurl_connect(h, NULL);
378         if (ret >= 0)
379             ret = flags;
380     }
381
382     ffurl_close(h);
383     return ret;
384 }
385
386 int64_t ffurl_size(URLContext *h)
387 {
388     int64_t pos, size;
389
390     size= ffurl_seek(h, 0, AVSEEK_SIZE);
391     if(size<0){
392         pos = ffurl_seek(h, 0, SEEK_CUR);
393         if ((size = ffurl_seek(h, -1, SEEK_END)) < 0)
394             return size;
395         size++;
396         ffurl_seek(h, pos, SEEK_SET);
397     }
398     return size;
399 }
400
401 int ffurl_get_file_handle(URLContext *h)
402 {
403     if (!h->prot->url_get_file_handle)
404         return -1;
405     return h->prot->url_get_file_handle(h);
406 }
407
408 int ffurl_get_multi_file_handle(URLContext *h, int **handles, int *numhandles)
409 {
410     if (!h->prot->url_get_multi_file_handle) {
411         if (!h->prot->url_get_file_handle)
412             return AVERROR(ENOSYS);
413         *handles = av_malloc(sizeof(**handles));
414         if (!*handles)
415             return AVERROR(ENOMEM);
416         *numhandles = 1;
417         *handles[0] = h->prot->url_get_file_handle(h);
418         return 0;
419     }
420     return h->prot->url_get_multi_file_handle(h, handles, numhandles);
421 }
422
423 int ffurl_shutdown(URLContext *h, int flags)
424 {
425     if (!h->prot->url_shutdown)
426         return AVERROR(EINVAL);
427     return h->prot->url_shutdown(h, flags);
428 }
429
430 int ff_check_interrupt(AVIOInterruptCB *cb)
431 {
432     int ret;
433     if (cb && cb->callback && (ret = cb->callback(cb->opaque)))
434         return ret;
435     return 0;
436 }