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