]> git.sesse.net Git - vlc/blob - modules/access/file.c
* mmap is broken on Darwin. Disabled it for now to have basic file access functionali...
[vlc] / modules / access / file.c
1 /*****************************************************************************
2  * file.c: file input (file: access plug-in)
3  *****************************************************************************
4  * Copyright (C) 2001-2006 the VideoLAN team
5  * Copyright © 2006-2007 Rémi Denis-Courmont
6  * $Id$
7  *
8  * Authors: Christophe Massiot <massiot@via.ecp.fr>
9  *          Rémi Denis-Courmont <rem # videolan # org>
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
24  *****************************************************************************/
25
26 /*****************************************************************************
27  * Preamble
28  *****************************************************************************/
29 #include <vlc/vlc.h>
30 #include <vlc_input.h>
31 #include <vlc_access.h>
32 #include <vlc_interface.h>
33
34 #include <assert.h>
35 #include <errno.h>
36 #ifdef HAVE_SYS_TYPES_H
37 #   include <sys/types.h>
38 #endif
39 #ifdef HAVE_SYS_STAT_H
40 #   include <sys/stat.h>
41 #endif
42 #ifdef HAVE_FCNTL_H
43 #   include <fcntl.h>
44 #endif
45
46 #if defined( WIN32 ) && !defined( UNDER_CE )
47 #   include <io.h>
48 #else
49 #   include <unistd.h>
50 #   include <poll.h>
51 #endif
52 #ifdef HAVE_MMAP
53 #   include <sys/mman.h>
54 #endif
55
56 #if defined( WIN32 ) && !defined( UNDER_CE )
57 #   ifdef lseek
58 #      undef lseek
59 #   endif
60 #   define lseek _lseeki64
61 #elif defined( UNDER_CE )
62 #   ifdef read
63 #      undef read
64 #   endif
65 #   define read(a,b,c) fread(b,1,c,a)
66 #   define close(a) fclose(a)
67 #   ifdef lseek
68 #      undef lseek
69 #   endif
70 #   define lseek fseek
71 #endif
72
73 #include <vlc_charset.h>
74
75 /*****************************************************************************
76  * Module descriptor
77  *****************************************************************************/
78 static int  Open ( vlc_object_t * );
79 static void Close( vlc_object_t * );
80
81 #define CACHING_TEXT N_("Caching value in ms")
82 #define CACHING_LONGTEXT N_( \
83     "Caching value for files. This " \
84     "value should be set in milliseconds." )
85 #define CAT_TEXT N_("Concatenate with additional files")
86 #define CAT_LONGTEXT N_( \
87     "Play split files as if they were part of a unique file. " \
88     "You need to specify a comma-separated list of files." )
89
90 vlc_module_begin();
91     set_description( _("File input") );
92     set_shortname( _("File") );
93     set_category( CAT_INPUT );
94     set_subcategory( SUBCAT_INPUT_ACCESS );
95     add_integer( "file-caching", DEFAULT_PTS_DELAY / 1000, NULL, CACHING_TEXT, CACHING_LONGTEXT, VLC_TRUE );
96     add_obsolete_string( "file-cat" );
97     set_capability( "access2", 50 );
98     add_shortcut( "file" );
99     add_shortcut( "stream" );
100     add_shortcut( "kfir" );
101     set_callbacks( Open, Close );
102 vlc_module_end();
103
104
105 /*****************************************************************************
106  * Exported prototypes
107  *****************************************************************************/
108 static int  Seek( access_t *, int64_t );
109 static ssize_t Read( access_t *, uint8_t *, size_t );
110 static int  Control( access_t *, int, va_list );
111 #ifdef HAVE_MMAP
112 static block_t *mmapBlock( access_t * );
113 #endif
114
115 static int  open_file( access_t *, const char * );
116
117 struct access_sys_t
118 {
119     uint64_t     pagemask;
120     unsigned int i_nb_reads;
121     vlc_bool_t   b_kfir;
122
123     int fd;
124
125     /* */
126     vlc_bool_t b_seekable;
127     vlc_bool_t b_pace_control;
128 };
129
130 /*****************************************************************************
131  * Open: open the file
132  *****************************************************************************/
133 static int Open( vlc_object_t *p_this )
134 {
135     access_t     *p_access = (access_t*)p_this;
136     access_sys_t *p_sys;
137
138     vlc_bool_t    b_stdin = !strcmp (p_access->psz_path, "-");
139
140     /* Update default_pts to a suitable value for file access */
141     var_Create( p_access, "file-caching", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
142
143     STANDARD_READ_ACCESS_INIT;
144     p_sys->i_nb_reads = 0;
145     p_sys->b_kfir = VLC_FALSE;
146     int fd = p_sys->fd = -1;
147
148     if (!strcasecmp (p_access->psz_access, "stream"))
149     {
150         p_sys->b_seekable = VLC_FALSE;
151         p_sys->b_pace_control = VLC_FALSE;
152     }
153     else if (!strcasecmp (p_access->psz_access, "kfir"))
154     {
155         p_sys->b_seekable = VLC_FALSE;
156         p_sys->b_pace_control = VLC_FALSE;
157         p_sys->b_kfir = VLC_TRUE;
158     }
159     else
160     {
161         p_sys->b_seekable = VLC_TRUE;
162         p_sys->b_pace_control = VLC_TRUE;
163     }
164
165     /* Open file */
166     msg_Dbg (p_access, "opening file `%s'", p_access->psz_path);
167
168     if (b_stdin)
169         fd = dup (0);
170     else
171         fd = open_file (p_access, p_access->psz_path);
172
173 #ifdef HAVE_SYS_STAT_H
174     struct stat st;
175
176     while (fd != -1)
177     {
178         if (fstat (fd, &st))
179             msg_Err (p_access, "fstat(%d): %m", fd);
180         else
181         if (S_ISDIR (st.st_mode))
182             /* The directory plugin takes care of that */
183             msg_Dbg (p_access, "file is a directory, aborting");
184         else
185             break; // success
186
187         close (fd);
188         fd = -1;
189     }
190 #endif
191
192     if (fd == -1)
193     {
194         free (p_sys);
195         return VLC_EGENERIC;
196     }
197     p_sys->fd = fd;
198
199 #ifdef HAVE_SYS_STAT_H
200     p_access->info.i_size = st.st_size;
201     if (!S_ISREG (st.st_mode) && !S_ISBLK (st.st_mode)
202      && (!S_ISCHR (st.st_mode) || (st.st_size == 0)))
203         p_sys->b_seekable = VLC_FALSE;
204
205 # ifdef HAVE_MMAP
206 # ifndef __APPLE__
207     p_sys->pagemask = sysconf (_SC_PAGE_SIZE) - 1;
208
209     /* Autodetect mmap() support */
210     if (p_sys->b_pace_control && S_ISREG (st.st_mode) && (st.st_size > 0))
211     {
212         void *addr = mmap (NULL, 1, PROT_READ, MAP_PRIVATE, fd, 0);
213         if (addr != MAP_FAILED)
214         {
215             /* Does the file system support mmap? */
216             munmap (addr, 1);
217             p_access->pf_read = NULL;
218             p_access->pf_block = mmapBlock;
219             msg_Dbg (p_this, "mmap enabled");
220         }
221         else
222             msg_Dbg (p_this, "mmap disabled (%m)");
223     }
224     else
225         msg_Dbg (p_this, "mmap disabled (non regular file)");
226 # endif
227 # endif
228 #else
229     p_sys->b_seekable = !b_stdin;
230 # warning File size not known!
231 #endif
232
233     if (p_sys->b_seekable && (p_access->info.i_size == 0))
234     {
235         /* FIXME that's bad because all others access will be probed */
236         msg_Err (p_access, "file is empty, aborting");
237         Close (p_this);
238         return VLC_EGENERIC;
239     }
240
241     return VLC_SUCCESS;
242 }
243
244 /*****************************************************************************
245  * Close: close the target
246  *****************************************************************************/
247 static void Close (vlc_object_t * p_this)
248 {
249     access_t     *p_access = (access_t*)p_this;
250     access_sys_t *p_sys = p_access->p_sys;
251
252     close (p_sys->fd);
253     free (p_sys);
254 }
255
256 /*****************************************************************************
257  * Read: standard read on a file descriptor.
258  *****************************************************************************/
259 static ssize_t Read( access_t *p_access, uint8_t *p_buffer, size_t i_len )
260 {
261     access_sys_t *p_sys = p_access->p_sys;
262     ssize_t i_ret;
263     int fd = p_sys->fd;
264
265 #if !defined(WIN32) && !defined(UNDER_CE)
266     if( !p_sys->b_pace_control )
267     {
268         if( !p_sys->b_kfir )
269         {
270             /* Find if some data is available. This won't work under Windows. */
271             do
272             {
273                 struct pollfd ufd;
274
275                 if( p_access->b_die )
276                     return 0;
277
278                 memset (&ufd, 0, sizeof (ufd));
279                 ufd.fd = fd;
280                 ufd.events = POLLIN;
281
282                 i_ret = poll (&ufd, 1, 500);
283             }
284             while (i_ret <= 0);
285
286             i_ret = read (fd, p_buffer, i_len);
287         }
288         else
289         {
290             /* b_kfir ; work around a buggy poll() driver implementation */
291             while (((i_ret = read (fd, p_buffer, i_len)) == 0)
292                 && !p_access->b_die)
293             {
294                 msleep( INPUT_ERROR_SLEEP );
295             }
296         }
297     }
298     else
299 #endif /* WIN32 || UNDER_CE */
300         /* b_pace_control || WIN32 */
301         i_ret = read( fd, p_buffer, i_len );
302
303     if( i_ret < 0 )
304     {
305         switch (errno)
306         {
307             case EINTR:
308             case EAGAIN:
309                 break;
310
311             default:
312                 msg_Err (p_access, "read failed (%m)");
313                 intf_UserFatal (p_access, VLC_FALSE, _("File reading failed"),
314                                 _("VLC could not read the file."));
315         }
316
317         /* Delay a bit to avoid consuming all the CPU. This is particularly
318          * useful when reading from an unconnected FIFO. */
319         msleep( INPUT_ERROR_SLEEP );
320     }
321
322     p_sys->i_nb_reads++;
323
324 #ifdef HAVE_SYS_STAT_H
325     if( p_access->info.i_size != 0 &&
326         (p_sys->i_nb_reads % INPUT_FSTAT_NB_READS) == 0 )
327     {
328         struct stat st;
329
330         if ((fstat (fd, &st) == 0)
331          && (p_access->info.i_size != st.st_size))
332         {
333             p_access->info.i_size = st.st_size;
334             p_access->info.i_update |= INPUT_UPDATE_SIZE;
335         }
336     }
337 #endif
338
339     if( i_ret > 0 )
340         p_access->info.i_pos += i_ret;
341     else if( i_ret == 0 )
342         p_access->info.b_eof = VLC_TRUE;
343
344     return i_ret;
345 }
346
347 #ifdef HAVE_MMAP
348 # define MMAP_SIZE (1 << 20)
349
350 struct block_sys_t
351 {
352     block_t self;
353     //vlc_object_t *owner;
354     void *base_addr;
355     size_t length;
356 };
357
358 static void mmapRelease (block_t *block)
359 {
360     block_sys_t *p_sys = (block_sys_t *)block;
361
362     munmap (p_sys->base_addr, p_sys->length);
363     //vlc_object_release (p_sys->owner);
364     free (p_sys);
365 }
366
367 static block_t *mmapBlock (access_t *p_access)
368 {
369     access_sys_t *p_sys = p_access->p_sys;
370
371     const int flags = MAP_SHARED;
372     off_t offset = p_access->info.i_pos & ~p_sys->pagemask;
373     size_t align = p_access->info.i_pos & p_sys->pagemask;
374     size_t length = (MMAP_SIZE > p_sys->pagemask) ? MMAP_SIZE : (p_sys->pagemask + 1);
375     void *addr;
376
377 #ifndef NDEBUG
378     int64_t dbgpos = lseek (p_sys->fd, 0, SEEK_CUR);
379     if (dbgpos != p_access->info.i_pos)
380         msg_Err (p_access, "position: 0x%08llx instead of 0x%08llx",
381                  p_access->info.i_pos, dbgpos);
382 #endif
383
384     if (p_access->info.i_pos >= p_access->info.i_size)
385     {
386         /* End of file - check if file size changed... */
387         struct stat st;
388
389         if ((fstat (p_sys->fd, &st) == 0)
390          && (st.st_size != p_access->info.i_size))
391         {
392             p_access->info.i_size = st.st_size;
393             p_access->info.i_update |= INPUT_UPDATE_SIZE;
394         }
395
396         /* Really at end of file then */
397         if (p_access->info.i_pos >= p_access->info.i_size)
398         {
399             p_access->info.b_eof = VLC_TRUE;
400             msg_Dbg (p_access, "at end of memory mapped file");
401             return NULL;
402         }
403     }
404
405     if (offset + length > p_access->info.i_size)
406         /* Don't mmap beyond end of file */
407         length = p_access->info.i_size - offset;
408
409     assert (offset <= p_access->info.i_pos);               /* and */
410     assert (p_access->info.i_pos < p_access->info.i_size); /* imply */
411     assert (offset < p_access->info.i_size);               /* imply */
412     assert (length > 0);
413
414     addr = mmap (NULL, length, PROT_READ, flags, p_sys->fd, offset);
415     if (addr == MAP_FAILED)
416     {
417         msg_Err (p_access, "memory mapping failed (%m)");
418         intf_UserFatal (p_access, VLC_FALSE, _("File reading failed"),
419                         _("VLC could not read the file."));
420         msleep( INPUT_ERROR_SLEEP );
421         return NULL;
422     }
423
424     p_access->info.i_pos = offset + length;
425
426     msg_Dbg (p_access, "mapped 0x%lx bytes at %p from offset 0x%lx",
427              (unsigned long)length, addr, (unsigned long)offset);
428     block_sys_t *block = malloc (sizeof (*block));
429     if (block == NULL)
430     {
431         munmap (addr, length);
432         return NULL;
433     }
434
435     block_Init (&block->self, ((uint8_t *)addr) + align, length - align);
436     block->self.pf_release = mmapRelease;
437     block->base_addr = addr;
438     block->length = length;
439     //vlc_object_yield (block->owner = VLC_OBJECT (p_access));
440
441 #ifndef NDEBUG
442     /* Compare normal I/O with memory mapping */
443     char buf[block->self.i_buffer];
444     ssize_t i_read = read (p_sys->fd, buf, block->self.i_buffer);
445
446     if (i_read != (ssize_t)block->self.i_buffer)
447         msg_Err (p_access, "read %u instead of %u bytes", (unsigned)i_read,
448                  (unsigned)block->self.i_buffer);
449     if (memcmp (buf, block->self.p_buffer, block->self.i_buffer))
450         msg_Err (p_access, "inconsistent data buffer");
451 #endif
452
453     return &block->self;
454 }
455 #endif
456
457 /*****************************************************************************
458  * Seek: seek to a specific location in a file
459  *****************************************************************************/
460 static int Seek (access_t *p_access, int64_t i_pos)
461 {
462     /* FIXME: i_size should really be unsigned */
463     if ((uint64_t)i_pos > (uint64_t)p_access->info.i_size)
464     {
465         /* This should only happen with corrupted files.
466          * But it also seems to happen with buggy demuxes (ASF) */
467         msg_Err (p_access, "seeking too far (0x"I64Fx" / 0x"I64Fx")",
468                  i_pos, p_access->info.i_size);
469         i_pos = p_access->info.i_size;
470     }
471
472     p_access->info.i_pos = i_pos;
473     p_access->info.b_eof = VLC_FALSE;
474
475 #if defined (HAVE_MMAP) && defined (NDEBUG)
476     if (p_access->pf_block == NULL)
477 #endif
478         lseek (p_access->p_sys->fd, i_pos, SEEK_SET);
479     return VLC_SUCCESS;
480 }
481
482 /*****************************************************************************
483  * Control:
484  *****************************************************************************/
485 static int Control( access_t *p_access, int i_query, va_list args )
486 {
487     access_sys_t *p_sys = p_access->p_sys;
488     vlc_bool_t   *pb_bool;
489     int          *pi_int;
490     int64_t      *pi_64;
491
492     switch( i_query )
493     {
494         /* */
495         case ACCESS_CAN_SEEK:
496         case ACCESS_CAN_FASTSEEK:
497             pb_bool = (vlc_bool_t*)va_arg( args, vlc_bool_t* );
498             *pb_bool = p_sys->b_seekable;
499             break;
500
501         case ACCESS_CAN_PAUSE:
502         case ACCESS_CAN_CONTROL_PACE:
503             pb_bool = (vlc_bool_t*)va_arg( args, vlc_bool_t* );
504             *pb_bool = p_sys->b_pace_control;
505             break;
506
507         /* */
508         case ACCESS_GET_MTU:
509             pi_int = (int*)va_arg( args, int * );
510             *pi_int = 0;
511             break;
512
513         case ACCESS_GET_PTS_DELAY:
514             pi_64 = (int64_t*)va_arg( args, int64_t * );
515             *pi_64 = var_GetInteger( p_access, "file-caching" ) * I64C(1000);
516             break;
517
518         /* */
519         case ACCESS_SET_PAUSE_STATE:
520             /* Nothing to do */
521             break;
522
523         case ACCESS_GET_TITLE_INFO:
524         case ACCESS_SET_TITLE:
525         case ACCESS_SET_SEEKPOINT:
526         case ACCESS_SET_PRIVATE_ID_STATE:
527         case ACCESS_GET_META:
528         case ACCESS_GET_CONTENT_TYPE:
529             return VLC_EGENERIC;
530
531         default:
532             msg_Warn( p_access, "unimplemented query in control" );
533             return VLC_EGENERIC;
534
535     }
536     return VLC_SUCCESS;
537 }
538
539
540 static char *expand_path (const access_t *p_access, const char *path)
541 {
542     if (strncmp (path, "~/", 2) == 0)
543     {
544         char *res;
545
546          // TODO: we should also support the ~cmassiot/ syntax
547          if (asprintf (&res, "%s/%s", p_access->p_libvlc->psz_homedir, path + 2) == -1)
548              return NULL;
549          return res;
550     }
551
552 #if defined(WIN32)
553     if (!strcasecmp (p_access->psz_access, "file")
554       && ('/' == path[0]) && path[1] && (':' == path[2]) && ('/' == path[3]))
555         // Explorer can open path such as file:/C:/ or file:///C:/
556         // hence remove leading / if found
557         return strdup (path + 1);
558 #endif
559
560     return strdup (path);
561 }
562
563
564 /*****************************************************************************
565  * open_file: Opens a specific file
566  *****************************************************************************/
567 static int open_file (access_t *p_access, const char *psz_name)
568 {
569     char *path = expand_path (p_access, psz_name);
570
571 #ifdef UNDER_CE
572     p_sys->fd = utf8_fopen( path, "rb" );
573     if ( !p_sys->fd )
574     {
575         msg_Err( p_access, "cannot open file %s", psz_name );
576         intf_UserFatal( p_access, VLC_FALSE, _("File reading failed"),
577                         _("VLC could not open the file \"%s\"."), psz_name );
578         free (path);
579         return VLC_EGENERIC;
580     }
581
582     fseek( p_sys->fd, 0, SEEK_END );
583     p_access->info.i_size = ftell( p_sys->fd );
584     p_access->info.i_update |= INPUT_UPDATE_SIZE;
585     fseek( p_sys->fd, 0, SEEK_SET );
586 #else
587     int fd = utf8_open (path, O_RDONLY | O_NONBLOCK /* O_LARGEFILE*/, 0666);
588     free (path);
589     if (fd == -1)
590     {
591         msg_Err (p_access, "cannot open file %s (%m)", psz_name);
592         intf_UserFatal (p_access, VLC_FALSE, _("File reading failed"),
593                         _("VLC could not open the file \"%s\"."), psz_name);
594         return -1;
595     }
596
597 # if defined(HAVE_FCNTL_H) && defined(F_FDAHEAD) && defined(F_NOCACHE)
598     /* We'd rather use any available memory for reading ahead
599      * than for caching what we've already seen/heard */
600     fcntl (fd, F_RDAHEAD, 1);
601     fcntl (fd, F_NOCACHE, 1);
602 # endif
603 #endif
604
605     return fd;
606 }