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