filesrc: enable large file support in Android
[platform/upstream/gstreamer.git] / plugins / elements / gstfilesrc.c
1 /* GStreamer
2  * Copyright (C) 1999,2000 Erik Walthinsen <omega@cse.ogi.edu>
3  *               2000,2005 Wim Taymans <wim@fluendo.com>
4  *
5  * gstfilesrc.c:
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Library General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This library 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  * Library General Public License for more details.
16  *
17  * You should have received a copy of the GNU Library General Public
18  * License along with this library; if not, write to the
19  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
20  * Boston, MA 02110-1301, USA.
21  */
22 /**
23  * SECTION:element-filesrc
24  * @see_also: #GstFileSrc
25  *
26  * Read data from a file in the local file system.
27  *
28  * <refsect2>
29  * <title>Example launch line</title>
30  * |[
31  * gst-launch-1.0 filesrc location=song.ogg ! decodebin ! audioconvert ! audioresample ! autoaudiosink
32  * ]| Play song.ogg audio file which must be in the current working directory.
33  * </refsect2>
34  */
35
36 #ifdef HAVE_CONFIG_H
37 #  include "config.h"
38 #endif
39
40 #include <gst/gst.h>
41 #include "gstfilesrc.h"
42
43 #include <stdio.h>
44 #include <sys/types.h>
45 #include <sys/stat.h>
46 #ifdef G_OS_WIN32
47 #include <io.h>                 /* lseek, open, close, read */
48 /* On win32, stat* default to 32 bit; we need the 64-bit
49  * variants, so explicitly define it that way. */
50 #undef stat
51 #define stat __stat64
52 #undef fstat
53 #define fstat _fstat64
54 #undef lseek
55 #define lseek _lseeki64
56 #undef off_t
57 #define off_t guint64
58 /* Prevent stat.h from defining the stat* functions as
59  * _stat*, since we're explicitly overriding that */
60 #undef _INC_STAT_INL
61 #endif
62 #include <fcntl.h>
63
64 #ifdef HAVE_UNISTD_H
65 #  include <unistd.h>
66 #endif
67
68 #ifdef __BIONIC__               /* Android */
69 #undef lseek
70 #define lseek lseek64
71 #undef fstat
72 #define fstat fstat64
73 #undef off_t
74 #define off_t guint64
75 #endif
76
77 #include <errno.h>
78 #include <string.h>
79
80 #include "../../gst/gst-i18n-lib.h"
81
82 static GstStaticPadTemplate srctemplate = GST_STATIC_PAD_TEMPLATE ("src",
83     GST_PAD_SRC,
84     GST_PAD_ALWAYS,
85     GST_STATIC_CAPS_ANY);
86
87 #ifndef S_ISREG
88 #define S_ISREG(mode) ((mode)&_S_IFREG)
89 #endif
90 #ifndef S_ISDIR
91 #define S_ISDIR(mode) ((mode)&_S_IFDIR)
92 #endif
93 #ifndef S_ISSOCK
94 #define S_ISSOCK(x) (0)
95 #endif
96 #ifndef O_BINARY
97 #define O_BINARY (0)
98 #endif
99
100 /* Copy of glib's g_open due to win32 libc/cross-DLL brokenness: we can't
101  * use the 'file descriptor' opened in glib (and returned from this function)
102  * in this library, as they may have unrelated C runtimes. */
103 static int
104 gst_open (const gchar * filename, int flags, int mode)
105 {
106 #ifdef G_OS_WIN32
107   wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
108   int retval;
109   int save_errno;
110
111   if (wfilename == NULL) {
112     errno = EINVAL;
113     return -1;
114   }
115
116   retval = _wopen (wfilename, flags, mode);
117   save_errno = errno;
118
119   g_free (wfilename);
120
121   errno = save_errno;
122   return retval;
123 #elif defined (__BIONIC__)
124   return open (filename, flags | O_LARGEFILE, mode);
125 #else
126   return open (filename, flags, mode);
127 #endif
128 }
129
130 GST_DEBUG_CATEGORY_STATIC (gst_file_src_debug);
131 #define GST_CAT_DEFAULT gst_file_src_debug
132
133 /* FileSrc signals and args */
134 enum
135 {
136   /* FILL ME */
137   LAST_SIGNAL
138 };
139
140 #define DEFAULT_BLOCKSIZE       4*1024
141
142 enum
143 {
144   PROP_0,
145   PROP_LOCATION
146 };
147
148 static void gst_file_src_finalize (GObject * object);
149
150 static void gst_file_src_set_property (GObject * object, guint prop_id,
151     const GValue * value, GParamSpec * pspec);
152 static void gst_file_src_get_property (GObject * object, guint prop_id,
153     GValue * value, GParamSpec * pspec);
154
155 static gboolean gst_file_src_start (GstBaseSrc * basesrc);
156 static gboolean gst_file_src_stop (GstBaseSrc * basesrc);
157
158 static gboolean gst_file_src_is_seekable (GstBaseSrc * src);
159 static gboolean gst_file_src_get_size (GstBaseSrc * src, guint64 * size);
160 static GstFlowReturn gst_file_src_fill (GstBaseSrc * src, guint64 offset,
161     guint length, GstBuffer * buf);
162
163 static void gst_file_src_uri_handler_init (gpointer g_iface,
164     gpointer iface_data);
165
166 #define _do_init \
167   G_IMPLEMENT_INTERFACE (GST_TYPE_URI_HANDLER, gst_file_src_uri_handler_init); \
168   GST_DEBUG_CATEGORY_INIT (gst_file_src_debug, "filesrc", 0, "filesrc element");
169 #define gst_file_src_parent_class parent_class
170 G_DEFINE_TYPE_WITH_CODE (GstFileSrc, gst_file_src, GST_TYPE_BASE_SRC, _do_init);
171
172 static void
173 gst_file_src_class_init (GstFileSrcClass * klass)
174 {
175   GObjectClass *gobject_class;
176   GstElementClass *gstelement_class;
177   GstBaseSrcClass *gstbasesrc_class;
178
179   gobject_class = G_OBJECT_CLASS (klass);
180   gstelement_class = GST_ELEMENT_CLASS (klass);
181   gstbasesrc_class = GST_BASE_SRC_CLASS (klass);
182
183   gobject_class->set_property = gst_file_src_set_property;
184   gobject_class->get_property = gst_file_src_get_property;
185
186   g_object_class_install_property (gobject_class, PROP_LOCATION,
187       g_param_spec_string ("location", "File Location",
188           "Location of the file to read", NULL,
189           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS |
190           GST_PARAM_MUTABLE_READY));
191
192   gobject_class->finalize = gst_file_src_finalize;
193
194   gst_element_class_set_static_metadata (gstelement_class,
195       "File Source",
196       "Source/File",
197       "Read from arbitrary point in a file",
198       "Erik Walthinsen <omega@cse.ogi.edu>");
199   gst_element_class_add_pad_template (gstelement_class,
200       gst_static_pad_template_get (&srctemplate));
201
202   gstbasesrc_class->start = GST_DEBUG_FUNCPTR (gst_file_src_start);
203   gstbasesrc_class->stop = GST_DEBUG_FUNCPTR (gst_file_src_stop);
204   gstbasesrc_class->is_seekable = GST_DEBUG_FUNCPTR (gst_file_src_is_seekable);
205   gstbasesrc_class->get_size = GST_DEBUG_FUNCPTR (gst_file_src_get_size);
206   gstbasesrc_class->fill = GST_DEBUG_FUNCPTR (gst_file_src_fill);
207
208   if (sizeof (off_t) < 8) {
209     GST_LOG ("No large file support, sizeof (off_t) = %" G_GSIZE_FORMAT "!",
210         sizeof (off_t));
211   }
212 }
213
214 static void
215 gst_file_src_init (GstFileSrc * src)
216 {
217   src->filename = NULL;
218   src->fd = 0;
219   src->uri = NULL;
220
221   src->is_regular = FALSE;
222
223   gst_base_src_set_blocksize (GST_BASE_SRC (src), DEFAULT_BLOCKSIZE);
224 }
225
226 static void
227 gst_file_src_finalize (GObject * object)
228 {
229   GstFileSrc *src;
230
231   src = GST_FILE_SRC (object);
232
233   g_free (src->filename);
234   g_free (src->uri);
235
236   G_OBJECT_CLASS (parent_class)->finalize (object);
237 }
238
239 static gboolean
240 gst_file_src_set_location (GstFileSrc * src, const gchar * location)
241 {
242   GstState state;
243
244   /* the element must be stopped in order to do this */
245   GST_OBJECT_LOCK (src);
246   state = GST_STATE (src);
247   if (state != GST_STATE_READY && state != GST_STATE_NULL)
248     goto wrong_state;
249   GST_OBJECT_UNLOCK (src);
250
251   g_free (src->filename);
252   g_free (src->uri);
253
254   /* clear the filename if we get a NULL */
255   if (location == NULL) {
256     src->filename = NULL;
257     src->uri = NULL;
258   } else {
259     /* we store the filename as received by the application. On Windows this
260      * should be UTF8 */
261     src->filename = g_strdup (location);
262     src->uri = gst_filename_to_uri (location, NULL);
263     GST_INFO ("filename : %s", src->filename);
264     GST_INFO ("uri      : %s", src->uri);
265   }
266   g_object_notify (G_OBJECT (src), "location");
267   /* FIXME 2.0: notify "uri" property once there is one */
268
269   return TRUE;
270
271   /* ERROR */
272 wrong_state:
273   {
274     g_warning ("Changing the `location' property on filesrc when a file is "
275         "open is not supported.");
276     GST_OBJECT_UNLOCK (src);
277     return FALSE;
278   }
279 }
280
281 static void
282 gst_file_src_set_property (GObject * object, guint prop_id,
283     const GValue * value, GParamSpec * pspec)
284 {
285   GstFileSrc *src;
286
287   g_return_if_fail (GST_IS_FILE_SRC (object));
288
289   src = GST_FILE_SRC (object);
290
291   switch (prop_id) {
292     case PROP_LOCATION:
293       gst_file_src_set_location (src, g_value_get_string (value));
294       break;
295     default:
296       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
297       break;
298   }
299 }
300
301 static void
302 gst_file_src_get_property (GObject * object, guint prop_id, GValue * value,
303     GParamSpec * pspec)
304 {
305   GstFileSrc *src;
306
307   g_return_if_fail (GST_IS_FILE_SRC (object));
308
309   src = GST_FILE_SRC (object);
310
311   switch (prop_id) {
312     case PROP_LOCATION:
313       g_value_set_string (value, src->filename);
314       break;
315     default:
316       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
317       break;
318   }
319 }
320
321 /***
322  * read code below
323  * that is to say, you shouldn't read the code below, but the code that reads
324  * stuff is below.  Well, you shouldn't not read the code below, feel free
325  * to read it of course.  It's just that "read code below" is a pretty crappy
326  * documentation string because it sounds like we're expecting you to read
327  * the code to understand what it does, which, while true, is really not
328  * the sort of attitude we want to be advertising.  No sir.
329  *
330  */
331 static GstFlowReturn
332 gst_file_src_fill (GstBaseSrc * basesrc, guint64 offset, guint length,
333     GstBuffer * buf)
334 {
335   GstFileSrc *src;
336   guint to_read, bytes_read;
337   int ret;
338   GstMapInfo info;
339   guint8 *data;
340
341   src = GST_FILE_SRC_CAST (basesrc);
342
343   if (G_UNLIKELY (offset != -1 && src->read_position != offset)) {
344     off_t res;
345
346     res = lseek (src->fd, offset, SEEK_SET);
347     if (G_UNLIKELY (res < 0 || res != offset))
348       goto seek_failed;
349
350     src->read_position = offset;
351   }
352
353   gst_buffer_map (buf, &info, GST_MAP_WRITE);
354   data = info.data;
355
356   bytes_read = 0;
357   to_read = length;
358   while (to_read > 0) {
359     GST_LOG_OBJECT (src, "Reading %d bytes at offset 0x%" G_GINT64_MODIFIER "x",
360         to_read, offset + bytes_read);
361     errno = 0;
362     ret = read (src->fd, data + bytes_read, to_read);
363     if (G_UNLIKELY (ret < 0)) {
364       if (errno == EAGAIN || errno == EINTR)
365         continue;
366       goto could_not_read;
367     }
368
369     /* files should eos if they read 0 and more was requested */
370     if (G_UNLIKELY (ret == 0)) {
371       /* .. but first we should return any remaining data */
372       if (bytes_read > 0)
373         break;
374       goto eos;
375     }
376
377     to_read -= ret;
378     bytes_read += ret;
379
380     src->read_position += ret;
381   }
382
383   gst_buffer_unmap (buf, &info);
384   if (bytes_read != length)
385     gst_buffer_resize (buf, 0, bytes_read);
386
387   GST_BUFFER_OFFSET (buf) = offset;
388   GST_BUFFER_OFFSET_END (buf) = offset + bytes_read;
389
390   return GST_FLOW_OK;
391
392   /* ERROR */
393 seek_failed:
394   {
395     GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL), GST_ERROR_SYSTEM);
396     return GST_FLOW_ERROR;
397   }
398 could_not_read:
399   {
400     GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL), GST_ERROR_SYSTEM);
401     gst_buffer_unmap (buf, &info);
402     gst_buffer_resize (buf, 0, 0);
403     return GST_FLOW_ERROR;
404   }
405 eos:
406   {
407     GST_DEBUG ("EOS");
408     gst_buffer_unmap (buf, &info);
409     gst_buffer_resize (buf, 0, 0);
410     return GST_FLOW_EOS;
411   }
412 }
413
414 static gboolean
415 gst_file_src_is_seekable (GstBaseSrc * basesrc)
416 {
417   GstFileSrc *src = GST_FILE_SRC (basesrc);
418
419   return src->seekable;
420 }
421
422 static gboolean
423 gst_file_src_get_size (GstBaseSrc * basesrc, guint64 * size)
424 {
425   struct stat stat_results;
426   GstFileSrc *src;
427
428   src = GST_FILE_SRC (basesrc);
429
430   if (!src->seekable) {
431     /* If it isn't seekable, we won't know the length (but fstat will still
432      * succeed, and wrongly say our length is zero. */
433     return FALSE;
434   }
435
436   if (fstat (src->fd, &stat_results) < 0)
437     goto could_not_stat;
438
439   *size = stat_results.st_size;
440
441   return TRUE;
442
443   /* ERROR */
444 could_not_stat:
445   {
446     return FALSE;
447   }
448 }
449
450 /* open the file, necessary to go to READY state */
451 static gboolean
452 gst_file_src_start (GstBaseSrc * basesrc)
453 {
454   GstFileSrc *src = GST_FILE_SRC (basesrc);
455   struct stat stat_results;
456
457   if (src->filename == NULL || src->filename[0] == '\0')
458     goto no_filename;
459
460   GST_INFO_OBJECT (src, "opening file %s", src->filename);
461
462   /* open the file */
463   src->fd = gst_open (src->filename, O_RDONLY | O_BINARY, 0);
464
465   if (src->fd < 0)
466     goto open_failed;
467
468   /* check if it is a regular file, otherwise bail out */
469   if (fstat (src->fd, &stat_results) < 0)
470     goto no_stat;
471
472   if (S_ISDIR (stat_results.st_mode))
473     goto was_directory;
474
475   if (S_ISSOCK (stat_results.st_mode))
476     goto was_socket;
477
478   src->read_position = 0;
479
480   /* record if it's a regular (hence seekable and lengthable) file */
481   if (S_ISREG (stat_results.st_mode))
482     src->is_regular = TRUE;
483
484   /* We need to check if the underlying file is seekable. */
485   {
486     off_t res = lseek (src->fd, 0, SEEK_END);
487
488     if (res < 0) {
489       GST_LOG_OBJECT (src, "disabling seeking, lseek failed: %s",
490           g_strerror (errno));
491       src->seekable = FALSE;
492     } else {
493       res = lseek (src->fd, 0, SEEK_SET);
494
495       if (res < 0) {
496         /* We really don't like not being able to go back to 0 */
497         src->seekable = FALSE;
498         goto lseek_wonky;
499       }
500
501       src->seekable = TRUE;
502     }
503   }
504
505   /* We can only really do seeking on regular files - for other file types, we
506    * don't know their length, so seeking isn't useful/meaningful */
507   src->seekable = src->seekable && src->is_regular;
508
509   gst_base_src_set_dynamic_size (basesrc, src->seekable);
510
511   return TRUE;
512
513   /* ERROR */
514 no_filename:
515   {
516     GST_ELEMENT_ERROR (src, RESOURCE, NOT_FOUND,
517         (_("No file name specified for reading.")), (NULL));
518     goto error_exit;
519   }
520 open_failed:
521   {
522     switch (errno) {
523       case ENOENT:
524         GST_ELEMENT_ERROR (src, RESOURCE, NOT_FOUND, (NULL),
525             ("No such file \"%s\"", src->filename));
526         break;
527       default:
528         GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ,
529             (_("Could not open file \"%s\" for reading."), src->filename),
530             GST_ERROR_SYSTEM);
531         break;
532     }
533     goto error_exit;
534   }
535 no_stat:
536   {
537     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ,
538         (_("Could not get info on \"%s\"."), src->filename), (NULL));
539     goto error_close;
540   }
541 was_directory:
542   {
543     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ,
544         (_("\"%s\" is a directory."), src->filename), (NULL));
545     goto error_close;
546   }
547 was_socket:
548   {
549     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ,
550         (_("File \"%s\" is a socket."), src->filename), (NULL));
551     goto error_close;
552   }
553 lseek_wonky:
554   {
555     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
556         ("Could not seek back to zero after seek test in file \"%s\"",
557             src->filename));
558     goto error_close;
559   }
560 error_close:
561   close (src->fd);
562 error_exit:
563   return FALSE;
564 }
565
566 /* unmap and close the file */
567 static gboolean
568 gst_file_src_stop (GstBaseSrc * basesrc)
569 {
570   GstFileSrc *src = GST_FILE_SRC (basesrc);
571
572   /* close the file */
573   close (src->fd);
574
575   /* zero out a lot of our state */
576   src->fd = 0;
577   src->is_regular = FALSE;
578
579   return TRUE;
580 }
581
582 /*** GSTURIHANDLER INTERFACE *************************************************/
583
584 static GstURIType
585 gst_file_src_uri_get_type (GType type)
586 {
587   return GST_URI_SRC;
588 }
589
590 static const gchar *const *
591 gst_file_src_uri_get_protocols (GType type)
592 {
593   static const gchar *protocols[] = { "file", NULL };
594
595   return protocols;
596 }
597
598 static gchar *
599 gst_file_src_uri_get_uri (GstURIHandler * handler)
600 {
601   GstFileSrc *src = GST_FILE_SRC (handler);
602
603   /* FIXME: make thread-safe */
604   return g_strdup (src->uri);
605 }
606
607 static gboolean
608 gst_file_src_uri_set_uri (GstURIHandler * handler, const gchar * uri,
609     GError ** err)
610 {
611   gchar *location, *hostname = NULL;
612   gboolean ret = FALSE;
613   GstFileSrc *src = GST_FILE_SRC (handler);
614
615   if (strcmp (uri, "file://") == 0) {
616     /* Special case for "file://" as this is used by some applications
617      *  to test with gst_element_make_from_uri if there's an element
618      *  that supports the URI protocol. */
619     gst_file_src_set_location (src, NULL);
620     return TRUE;
621   }
622
623   location = g_filename_from_uri (uri, &hostname, err);
624
625   if (!location || (err != NULL && *err != NULL)) {
626     GST_WARNING_OBJECT (src, "Invalid URI '%s' for filesrc: %s", uri,
627         (err != NULL && *err != NULL) ? (*err)->message : "unknown error");
628     goto beach;
629   }
630
631   if ((hostname) && (strcmp (hostname, "localhost"))) {
632     /* Only 'localhost' is permitted */
633     GST_WARNING_OBJECT (src, "Invalid hostname '%s' for filesrc", hostname);
634     g_set_error (err, GST_URI_ERROR, GST_URI_ERROR_BAD_URI,
635         "File URI with invalid hostname '%s'", hostname);
636     goto beach;
637   }
638 #ifdef G_OS_WIN32
639   /* Unfortunately, g_filename_from_uri() doesn't handle some UNC paths
640    * correctly on windows, it leaves them with an extra backslash
641    * at the start if they're of the mozilla-style file://///host/path/file 
642    * form. Correct this.
643    */
644   if (location[0] == '\\' && location[1] == '\\' && location[2] == '\\')
645     memmove (location, location + 1, strlen (location + 1) + 1);
646 #endif
647
648   ret = gst_file_src_set_location (src, location);
649
650 beach:
651   if (location)
652     g_free (location);
653   if (hostname)
654     g_free (hostname);
655
656   return ret;
657 }
658
659 static void
660 gst_file_src_uri_handler_init (gpointer g_iface, gpointer iface_data)
661 {
662   GstURIHandlerInterface *iface = (GstURIHandlerInterface *) g_iface;
663
664   iface->get_type = gst_file_src_uri_get_type;
665   iface->get_protocols = gst_file_src_uri_get_protocols;
666   iface->get_uri = gst_file_src_uri_get_uri;
667   iface->set_uri = gst_file_src_uri_set_uri;
668 }