]> git.sesse.net Git - vlc/blob - modules/access/file.c
block_mmap_Alloc: commoditize block allocation from mmap
[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     p_sys->pagemask = sysconf (_SC_PAGE_SIZE) - 1;
207
208     /* Autodetect mmap() support */
209     if (p_sys->b_pace_control && S_ISREG (st.st_mode) && (st.st_size > 0))
210     {
211         void *addr = mmap (NULL, 1, PROT_READ, MAP_PRIVATE, fd, 0);
212         if (addr != MAP_FAILED)
213         {
214             /* Does the file system support mmap? */
215             munmap (addr, 1);
216             p_access->pf_read = NULL;
217             p_access->pf_block = mmapBlock;
218             msg_Dbg (p_this, "mmap enabled");
219         }
220         else
221             msg_Dbg (p_this, "mmap disabled (%m)");
222     }
223     else
224         msg_Dbg (p_this, "mmap disabled (non regular file)");
225 # endif
226 #else
227     p_sys->b_seekable = !b_stdin;
228 # warning File size not known!
229 #endif
230
231     if (p_sys->b_seekable && (p_access->info.i_size == 0))
232     {
233         /* FIXME that's bad because all others access will be probed */
234         msg_Err (p_access, "file is empty, aborting");
235         Close (p_this);
236         return VLC_EGENERIC;
237     }
238
239     return VLC_SUCCESS;
240 }
241
242 /*****************************************************************************
243  * Close: close the target
244  *****************************************************************************/
245 static void Close (vlc_object_t * p_this)
246 {
247     access_t     *p_access = (access_t*)p_this;
248     access_sys_t *p_sys = p_access->p_sys;
249
250     close (p_sys->fd);
251     free (p_sys);
252 }
253
254 /*****************************************************************************
255  * Read: standard read on a file descriptor.
256  *****************************************************************************/
257 static ssize_t Read( access_t *p_access, uint8_t *p_buffer, size_t i_len )
258 {
259     access_sys_t *p_sys = p_access->p_sys;
260     ssize_t i_ret;
261     int fd = p_sys->fd;
262
263 #if !defined(WIN32) && !defined(UNDER_CE)
264     if( !p_sys->b_pace_control )
265     {
266         if( !p_sys->b_kfir )
267         {
268             /* Find if some data is available. This won't work under Windows. */
269             do
270             {
271                 struct pollfd ufd;
272
273                 if( p_access->b_die )
274                     return 0;
275
276                 memset (&ufd, 0, sizeof (ufd));
277                 ufd.fd = fd;
278                 ufd.events = POLLIN;
279
280                 i_ret = poll (&ufd, 1, 500);
281             }
282             while (i_ret <= 0);
283
284             i_ret = read (fd, p_buffer, i_len);
285         }
286         else
287         {
288             /* b_kfir ; work around a buggy poll() driver implementation */
289             while (((i_ret = read (fd, p_buffer, i_len)) == 0)
290                 && !p_access->b_die)
291             {
292                 msleep( INPUT_ERROR_SLEEP );
293             }
294         }
295     }
296     else
297 #endif /* WIN32 || UNDER_CE */
298         /* b_pace_control || WIN32 */
299         i_ret = read( fd, p_buffer, i_len );
300
301     if( i_ret < 0 )
302     {
303         switch (errno)
304         {
305             case EINTR:
306             case EAGAIN:
307                 break;
308
309             default:
310                 msg_Err (p_access, "read failed (%m)");
311                 intf_UserFatal (p_access, VLC_FALSE, _("File reading failed"),
312                                 _("VLC could not read the file."));
313         }
314
315         /* Delay a bit to avoid consuming all the CPU. This is particularly
316          * useful when reading from an unconnected FIFO. */
317         msleep( INPUT_ERROR_SLEEP );
318     }
319
320     p_sys->i_nb_reads++;
321
322 #ifdef HAVE_SYS_STAT_H
323     if( p_access->info.i_size != 0 &&
324         (p_sys->i_nb_reads % INPUT_FSTAT_NB_READS) == 0 )
325     {
326         struct stat st;
327
328         if ((fstat (fd, &st) == 0)
329          && (p_access->info.i_size != st.st_size))
330         {
331             p_access->info.i_size = st.st_size;
332             p_access->info.i_update |= INPUT_UPDATE_SIZE;
333         }
334     }
335 #endif
336
337     if( i_ret > 0 )
338         p_access->info.i_pos += i_ret;
339     else if( i_ret == 0 )
340         p_access->info.b_eof = VLC_TRUE;
341
342     return i_ret;
343 }
344
345 #ifdef HAVE_MMAP
346 # define MMAP_SIZE (1 << 20)
347
348 static block_t *mmapBlock (access_t *p_access)
349 {
350     access_sys_t *p_sys = p_access->p_sys;
351
352     const int flags = MAP_SHARED;
353     off_t offset = p_access->info.i_pos & ~p_sys->pagemask;
354     size_t align = p_access->info.i_pos & p_sys->pagemask;
355     size_t length = (MMAP_SIZE > p_sys->pagemask) ? MMAP_SIZE : (p_sys->pagemask + 1);
356     void *addr;
357
358 #ifndef NDEBUG
359     int64_t dbgpos = lseek (p_sys->fd, 0, SEEK_CUR);
360     if (dbgpos != p_access->info.i_pos)
361         msg_Err (p_access, "position: 0x%08llx instead of 0x%08llx",
362                  p_access->info.i_pos, dbgpos);
363 #endif
364
365     if (p_access->info.i_pos >= p_access->info.i_size)
366     {
367         /* End of file - check if file size changed... */
368         struct stat st;
369
370         if ((fstat (p_sys->fd, &st) == 0)
371          && (st.st_size != p_access->info.i_size))
372         {
373             p_access->info.i_size = st.st_size;
374             p_access->info.i_update |= INPUT_UPDATE_SIZE;
375         }
376
377         /* Really at end of file then */
378         if (p_access->info.i_pos >= p_access->info.i_size)
379         {
380             p_access->info.b_eof = VLC_TRUE;
381             msg_Dbg (p_access, "at end of memory mapped file");
382             return NULL;
383         }
384     }
385
386     if (offset + length > p_access->info.i_size)
387         /* Don't mmap beyond end of file */
388         length = p_access->info.i_size - offset;
389
390     assert (offset <= p_access->info.i_pos);               /* and */
391     assert (p_access->info.i_pos < p_access->info.i_size); /* imply */
392     assert (offset < p_access->info.i_size);               /* imply */
393     assert (length > 0);
394
395     addr = mmap (NULL, length, PROT_READ, flags, p_sys->fd, offset);
396     if (addr == MAP_FAILED)
397     {
398         msg_Err (p_access, "memory mapping failed (%m)");
399         intf_UserFatal (p_access, VLC_FALSE, _("File reading failed"),
400                         _("VLC could not read the file."));
401         msleep( INPUT_ERROR_SLEEP );
402         return NULL;
403     }
404
405     p_access->info.i_pos = offset + length;
406
407     block_t *block = block_mmap_Alloc (addr, length);
408     if (block == NULL)
409         return NULL;
410
411     block->p_buffer += align;
412     block->i_buffer -= align;
413
414 #ifndef NDEBUG
415     msg_Dbg (p_access, "mapped 0x%lx bytes at %p from offset 0x%lx",
416              (unsigned long)length, addr, (unsigned long)offset);
417
418     /* Compare normal I/O with memory mapping */
419     char *buf = malloc (block->i_buffer);
420     ssize_t i_read = read (p_sys->fd, buf, block->i_buffer);
421
422     if (i_read != (ssize_t)block->i_buffer)
423         msg_Err (p_access, "read %u instead of %u bytes", (unsigned)i_read,
424                  (unsigned)block->i_buffer);
425     if (memcmp (buf, block->p_buffer, block->i_buffer))
426         msg_Err (p_access, "inconsistent data buffer");
427     free (buf);
428 #endif
429
430     return block;
431 }
432 #endif
433
434 /*****************************************************************************
435  * Seek: seek to a specific location in a file
436  *****************************************************************************/
437 static int Seek (access_t *p_access, int64_t i_pos)
438 {
439     /* FIXME: i_size should really be unsigned */
440     if ((uint64_t)i_pos > (uint64_t)p_access->info.i_size)
441     {
442         /* This should only happen with corrupted files.
443          * But it also seems to happen with buggy demuxes (ASF) */
444         msg_Err (p_access, "seeking too far (0x"I64Fx" / 0x"I64Fx")",
445                  i_pos, p_access->info.i_size);
446         i_pos = p_access->info.i_size;
447     }
448
449     p_access->info.i_pos = i_pos;
450     p_access->info.b_eof = VLC_FALSE;
451
452 #if defined (HAVE_MMAP) && defined (NDEBUG)
453     if (p_access->pf_block == NULL)
454 #endif
455         lseek (p_access->p_sys->fd, i_pos, SEEK_SET);
456     return VLC_SUCCESS;
457 }
458
459 /*****************************************************************************
460  * Control:
461  *****************************************************************************/
462 static int Control( access_t *p_access, int i_query, va_list args )
463 {
464     access_sys_t *p_sys = p_access->p_sys;
465     vlc_bool_t   *pb_bool;
466     int          *pi_int;
467     int64_t      *pi_64;
468
469     switch( i_query )
470     {
471         /* */
472         case ACCESS_CAN_SEEK:
473         case ACCESS_CAN_FASTSEEK:
474             pb_bool = (vlc_bool_t*)va_arg( args, vlc_bool_t* );
475             *pb_bool = p_sys->b_seekable;
476             break;
477
478         case ACCESS_CAN_PAUSE:
479         case ACCESS_CAN_CONTROL_PACE:
480             pb_bool = (vlc_bool_t*)va_arg( args, vlc_bool_t* );
481             *pb_bool = p_sys->b_pace_control;
482             break;
483
484         /* */
485         case ACCESS_GET_MTU:
486             pi_int = (int*)va_arg( args, int * );
487             *pi_int = 0;
488             break;
489
490         case ACCESS_GET_PTS_DELAY:
491             pi_64 = (int64_t*)va_arg( args, int64_t * );
492             *pi_64 = var_GetInteger( p_access, "file-caching" ) * I64C(1000);
493             break;
494
495         /* */
496         case ACCESS_SET_PAUSE_STATE:
497             /* Nothing to do */
498             break;
499
500         case ACCESS_GET_TITLE_INFO:
501         case ACCESS_SET_TITLE:
502         case ACCESS_SET_SEEKPOINT:
503         case ACCESS_SET_PRIVATE_ID_STATE:
504         case ACCESS_GET_META:
505         case ACCESS_GET_CONTENT_TYPE:
506             return VLC_EGENERIC;
507
508         default:
509             msg_Warn( p_access, "unimplemented query in control" );
510             return VLC_EGENERIC;
511
512     }
513     return VLC_SUCCESS;
514 }
515
516
517 static char *expand_path (const access_t *p_access, const char *path)
518 {
519     if (strncmp (path, "~/", 2) == 0)
520     {
521         char *res;
522
523          // TODO: we should also support the ~cmassiot/ syntax
524          if (asprintf (&res, "%s/%s", p_access->p_libvlc->psz_homedir, path + 2) == -1)
525              return NULL;
526          return res;
527     }
528
529 #if defined(WIN32)
530     if (!strcasecmp (p_access->psz_access, "file")
531       && ('/' == path[0]) && path[1] && (':' == path[2]) && ('/' == path[3]))
532         // Explorer can open path such as file:/C:/ or file:///C:/
533         // hence remove leading / if found
534         return strdup (path + 1);
535 #endif
536
537     return strdup (path);
538 }
539
540
541 /*****************************************************************************
542  * open_file: Opens a specific file
543  *****************************************************************************/
544 static int open_file (access_t *p_access, const char *psz_name)
545 {
546     char *path = expand_path (p_access, psz_name);
547
548 #ifdef UNDER_CE
549     p_sys->fd = utf8_fopen( path, "rb" );
550     if ( !p_sys->fd )
551     {
552         msg_Err( p_access, "cannot open file %s", psz_name );
553         intf_UserFatal( p_access, VLC_FALSE, _("File reading failed"),
554                         _("VLC could not open the file \"%s\"."), psz_name );
555         free (path);
556         return VLC_EGENERIC;
557     }
558
559     fseek( p_sys->fd, 0, SEEK_END );
560     p_access->info.i_size = ftell( p_sys->fd );
561     p_access->info.i_update |= INPUT_UPDATE_SIZE;
562     fseek( p_sys->fd, 0, SEEK_SET );
563 #else
564     int fd = utf8_open (path, O_RDONLY | O_NONBLOCK /* O_LARGEFILE*/, 0666);
565     free (path);
566     if (fd == -1)
567     {
568         msg_Err (p_access, "cannot open file %s (%m)", psz_name);
569         intf_UserFatal (p_access, VLC_FALSE, _("File reading failed"),
570                         _("VLC could not open the file \"%s\"."), psz_name);
571         return -1;
572     }
573
574 # if defined(HAVE_FCNTL_H) && defined(F_FDAHEAD) && defined(F_NOCACHE)
575     /* We'd rather use any available memory for reading ahead
576      * than for caching what we've already seen/heard */
577     fcntl (fd, F_RDAHEAD, 1);
578     fcntl (fd, F_NOCACHE, 1);
579 # endif
580 #endif
581
582     return fd;
583 }