fdsrc: allow specifying the size in bytes on the uri
[platform/upstream/gstreamer.git] / plugins / elements / gstfdsrc.c
1 /* GStreamer
2  * Copyright (C) 1999,2000 Erik Walthinsen <omega@cse.ogi.edu>
3  *                    2000 Wim Taymans <wtay@chello.be>
4  *                    2005 Philippe Khalaf <burger@speedy.org>
5  *
6  * gstfdsrc.c:
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public
19  * License along with this library; if not, write to the
20  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
21  * Boston, MA 02111-1307, USA.
22  */
23 /**
24  * SECTION:element-fdsrc
25  * @see_also: #GstFdSink
26  *
27  * Read data from a unix file descriptor.
28  * 
29  * To generate data, enter some data on the console folowed by enter.
30  * The above mentioned pipeline should dump data packets to the console.
31  * 
32  * If the #GstFdSrc:timeout property is set to a value bigger than 0, fdsrc will
33  * generate an element message named
34  * <classname>&quot;GstFdSrcTimeout&quot;</classname>
35  * if no data was recieved in the given timeout.
36  * The message's structure contains one field:
37  * <itemizedlist>
38  * <listitem>
39  *   <para>
40  *   #guint64
41  *   <classname>&quot;timeout&quot;</classname>: the timeout in microseconds that
42  *   expired when waiting for data.
43  *   </para>
44  * </listitem>
45  * </itemizedlist>
46  * 
47  * <refsect2>
48  * <title>Example launch line</title>
49  * |[
50  * echo "Hello GStreamer" | gst-launch -v fdsrc ! fakesink dump=true
51  * ]| A simple pipeline to read from the standard input and dump the data
52  * with a fakesink as hex ascii block.
53  * </refsect2>
54  * 
55  * Last reviewed on 2008-06-20 (0.10.21)
56  */
57
58 #ifdef HAVE_CONFIG_H
59 #  include "config.h"
60 #endif
61 #include "gst/gst_private.h"
62
63 #include <sys/types.h>
64
65 #ifdef G_OS_WIN32
66 #include <io.h>                 /* lseek, open, close, read */
67 #undef lseek
68 #define lseek _lseeki64
69 #undef off_t
70 #define off_t guint64
71 #endif
72
73 #include <sys/stat.h>
74 #ifdef HAVE_SYS_SOCKET_H
75 #include <sys/socket.h>
76 #endif
77 #include <fcntl.h>
78 #include <stdio.h>
79 #ifdef HAVE_UNISTD_H
80 #include <unistd.h>
81 #endif
82 #ifdef _MSC_VER
83 #undef stat
84 #define stat _stat
85 #define fstat _fstat
86 #define S_ISREG(m)      (((m)&S_IFREG)==S_IFREG)
87 #endif
88 #include <stdlib.h>
89 #include <errno.h>
90
91 #include "gstfdsrc.h"
92
93 static GstStaticPadTemplate srctemplate = GST_STATIC_PAD_TEMPLATE ("src",
94     GST_PAD_SRC,
95     GST_PAD_ALWAYS,
96     GST_STATIC_CAPS_ANY);
97
98 GST_DEBUG_CATEGORY_STATIC (gst_fd_src_debug);
99 #define GST_CAT_DEFAULT gst_fd_src_debug
100
101 #define DEFAULT_FD              0
102 #define DEFAULT_TIMEOUT         0
103
104 enum
105 {
106   PROP_0,
107
108   PROP_FD,
109   PROP_TIMEOUT,
110
111   PROP_LAST
112 };
113
114 static void gst_fd_src_uri_handler_init (gpointer g_iface, gpointer iface_data);
115
116 static void
117 _do_init (GType fd_src_type)
118 {
119   static const GInterfaceInfo urihandler_info = {
120     gst_fd_src_uri_handler_init,
121     NULL,
122     NULL
123   };
124
125   g_type_add_interface_static (fd_src_type, GST_TYPE_URI_HANDLER,
126       &urihandler_info);
127
128   GST_DEBUG_CATEGORY_INIT (gst_fd_src_debug, "fdsrc", 0, "fdsrc element");
129 }
130
131 GST_BOILERPLATE_FULL (GstFdSrc, gst_fd_src, GstPushSrc, GST_TYPE_PUSH_SRC,
132     _do_init);
133
134 static void gst_fd_src_set_property (GObject * object, guint prop_id,
135     const GValue * value, GParamSpec * pspec);
136 static void gst_fd_src_get_property (GObject * object, guint prop_id,
137     GValue * value, GParamSpec * pspec);
138 static void gst_fd_src_dispose (GObject * obj);
139
140 static gboolean gst_fd_src_start (GstBaseSrc * bsrc);
141 static gboolean gst_fd_src_stop (GstBaseSrc * bsrc);
142 static gboolean gst_fd_src_unlock (GstBaseSrc * bsrc);
143 static gboolean gst_fd_src_unlock_stop (GstBaseSrc * bsrc);
144 static gboolean gst_fd_src_is_seekable (GstBaseSrc * bsrc);
145 static gboolean gst_fd_src_get_size (GstBaseSrc * src, guint64 * size);
146 static gboolean gst_fd_src_do_seek (GstBaseSrc * src, GstSegment * segment);
147 static gboolean gst_fd_src_query (GstBaseSrc * src, GstQuery * query);
148
149 static GstFlowReturn gst_fd_src_create (GstPushSrc * psrc, GstBuffer ** outbuf);
150
151 static void
152 gst_fd_src_base_init (gpointer g_class)
153 {
154   GstElementClass *gstelement_class = GST_ELEMENT_CLASS (g_class);
155
156   gst_element_class_set_details_simple (gstelement_class,
157       "Filedescriptor Source",
158       "Source/File",
159       "Read from a file descriptor", "Erik Walthinsen <omega@cse.ogi.edu>");
160   gst_element_class_add_pad_template (gstelement_class,
161       gst_static_pad_template_get (&srctemplate));
162 }
163
164 static void
165 gst_fd_src_class_init (GstFdSrcClass * klass)
166 {
167   GObjectClass *gobject_class;
168   GstBaseSrcClass *gstbasesrc_class;
169   GstPushSrcClass *gstpush_src_class;
170
171   gobject_class = G_OBJECT_CLASS (klass);
172   gstbasesrc_class = GST_BASE_SRC_CLASS (klass);
173   gstpush_src_class = GST_PUSH_SRC_CLASS (klass);
174
175   parent_class = g_type_class_peek_parent (klass);
176
177   gobject_class->set_property = gst_fd_src_set_property;
178   gobject_class->get_property = gst_fd_src_get_property;
179   gobject_class->dispose = gst_fd_src_dispose;
180
181   g_object_class_install_property (gobject_class, PROP_FD,
182       g_param_spec_int ("fd", "fd", "An open file descriptor to read from",
183           0, G_MAXINT, DEFAULT_FD, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
184   /**
185    * GstFdSrc:timeout
186    *
187    * Post a message after timeout microseconds
188    *
189    * Since: 0.10.21
190    */
191   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_TIMEOUT,
192       g_param_spec_uint64 ("timeout", "Timeout",
193           "Post a message after timeout microseconds (0 = disabled)", 0,
194           G_MAXUINT64, DEFAULT_TIMEOUT,
195           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
196
197   gstbasesrc_class->start = GST_DEBUG_FUNCPTR (gst_fd_src_start);
198   gstbasesrc_class->stop = GST_DEBUG_FUNCPTR (gst_fd_src_stop);
199   gstbasesrc_class->unlock = GST_DEBUG_FUNCPTR (gst_fd_src_unlock);
200   gstbasesrc_class->unlock_stop = GST_DEBUG_FUNCPTR (gst_fd_src_unlock_stop);
201   gstbasesrc_class->is_seekable = GST_DEBUG_FUNCPTR (gst_fd_src_is_seekable);
202   gstbasesrc_class->get_size = GST_DEBUG_FUNCPTR (gst_fd_src_get_size);
203   gstbasesrc_class->do_seek = GST_DEBUG_FUNCPTR (gst_fd_src_do_seek);
204   gstbasesrc_class->query = GST_DEBUG_FUNCPTR (gst_fd_src_query);
205
206   gstpush_src_class->create = GST_DEBUG_FUNCPTR (gst_fd_src_create);
207 }
208
209 static void
210 gst_fd_src_init (GstFdSrc * fdsrc, GstFdSrcClass * klass)
211 {
212   fdsrc->new_fd = DEFAULT_FD;
213   fdsrc->seekable_fd = FALSE;
214   fdsrc->fd = -1;
215   fdsrc->size = -1;
216   fdsrc->timeout = DEFAULT_TIMEOUT;
217   fdsrc->uri = g_strdup_printf ("fd://0");
218   fdsrc->curoffset = 0;
219 }
220
221 static void
222 gst_fd_src_dispose (GObject * obj)
223 {
224   GstFdSrc *src = GST_FD_SRC (obj);
225
226   g_free (src->uri);
227   src->uri = NULL;
228
229   G_OBJECT_CLASS (parent_class)->dispose (obj);
230 }
231
232 static void
233 gst_fd_src_update_fd (GstFdSrc * src, guint64 size)
234 {
235   struct stat stat_results;
236
237   GST_DEBUG_OBJECT (src, "fdset %p, old_fd %d, new_fd %d", src->fdset, src->fd,
238       src->new_fd);
239
240   /* we need to always update the fdset since it may not have existed when
241    * gst_fd_src_update_fd () was called earlier */
242   if (src->fdset != NULL) {
243     GstPollFD fd = GST_POLL_FD_INIT;
244
245     if (src->fd >= 0) {
246       fd.fd = src->fd;
247       /* this will log a harmless warning, if it was never added */
248       gst_poll_remove_fd (src->fdset, &fd);
249     }
250
251     fd.fd = src->new_fd;
252     gst_poll_add_fd (src->fdset, &fd);
253     gst_poll_fd_ctl_read (src->fdset, &fd, TRUE);
254   }
255
256
257   if (src->fd != src->new_fd) {
258     GST_INFO_OBJECT (src, "Updating to fd %d", src->new_fd);
259
260     src->fd = src->new_fd;
261
262     GST_INFO_OBJECT (src, "Setting size to fd %" G_GUINT64_FORMAT, size);
263     src->size = size;
264
265     g_free (src->uri);
266     src->uri = g_strdup_printf ("fd://%d", src->fd);
267
268     if (fstat (src->fd, &stat_results) < 0)
269       goto not_seekable;
270
271     if (!S_ISREG (stat_results.st_mode))
272       goto not_seekable;
273
274     /* Try a seek of 0 bytes offset to check for seekability */
275     if (lseek (src->fd, 0, SEEK_CUR) < 0)
276       goto not_seekable;
277
278     GST_INFO_OBJECT (src, "marking fd %d as seekable", src->fd);
279     src->seekable_fd = TRUE;
280   }
281   return;
282
283 not_seekable:
284   {
285     GST_INFO_OBJECT (src, "marking fd %d as NOT seekable", src->fd);
286     src->seekable_fd = FALSE;
287   }
288 }
289
290 static gboolean
291 gst_fd_src_start (GstBaseSrc * bsrc)
292 {
293   GstFdSrc *src = GST_FD_SRC (bsrc);
294
295   src->curoffset = 0;
296
297   if ((src->fdset = gst_poll_new (TRUE)) == NULL)
298     goto socket_pair;
299
300   gst_fd_src_update_fd (src, -1);
301
302   return TRUE;
303
304   /* ERRORS */
305 socket_pair:
306   {
307     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ_WRITE, (NULL),
308         GST_ERROR_SYSTEM);
309     return FALSE;
310   }
311 }
312
313 static gboolean
314 gst_fd_src_stop (GstBaseSrc * bsrc)
315 {
316   GstFdSrc *src = GST_FD_SRC (bsrc);
317
318   if (src->fdset) {
319     gst_poll_free (src->fdset);
320     src->fdset = NULL;
321   }
322
323   return TRUE;
324 }
325
326 static gboolean
327 gst_fd_src_unlock (GstBaseSrc * bsrc)
328 {
329   GstFdSrc *src = GST_FD_SRC (bsrc);
330
331   GST_LOG_OBJECT (src, "Flushing");
332   GST_OBJECT_LOCK (src);
333   gst_poll_set_flushing (src->fdset, TRUE);
334   GST_OBJECT_UNLOCK (src);
335
336   return TRUE;
337 }
338
339 static gboolean
340 gst_fd_src_unlock_stop (GstBaseSrc * bsrc)
341 {
342   GstFdSrc *src = GST_FD_SRC (bsrc);
343
344   GST_LOG_OBJECT (src, "No longer flushing");
345   GST_OBJECT_LOCK (src);
346   gst_poll_set_flushing (src->fdset, FALSE);
347   GST_OBJECT_UNLOCK (src);
348
349   return TRUE;
350 }
351
352 static void
353 gst_fd_src_set_property (GObject * object, guint prop_id, const GValue * value,
354     GParamSpec * pspec)
355 {
356   GstFdSrc *src = GST_FD_SRC (object);
357
358   switch (prop_id) {
359     case PROP_FD:
360       src->new_fd = g_value_get_int (value);
361
362       /* If state is ready or below, update the current fd immediately
363        * so it is reflected in get_properties and uri */
364       GST_OBJECT_LOCK (object);
365       if (GST_STATE (GST_ELEMENT (src)) <= GST_STATE_READY) {
366         GST_DEBUG_OBJECT (src, "state ready or lower, updating to use new fd");
367         gst_fd_src_update_fd (src, -1);
368       } else {
369         GST_DEBUG_OBJECT (src, "state above ready, not updating to new fd yet");
370       }
371       GST_OBJECT_UNLOCK (object);
372       break;
373     case PROP_TIMEOUT:
374       src->timeout = g_value_get_uint64 (value);
375       GST_DEBUG_OBJECT (src, "poll timeout set to %" GST_TIME_FORMAT,
376           GST_TIME_ARGS (src->timeout));
377       break;
378     default:
379       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
380       break;
381   }
382 }
383
384 static void
385 gst_fd_src_get_property (GObject * object, guint prop_id, GValue * value,
386     GParamSpec * pspec)
387 {
388   GstFdSrc *src = GST_FD_SRC (object);
389
390   switch (prop_id) {
391     case PROP_FD:
392       g_value_set_int (value, src->fd);
393       break;
394     case PROP_TIMEOUT:
395       g_value_set_uint64 (value, src->timeout);
396       break;
397     default:
398       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
399       break;
400   }
401 }
402
403 static GstFlowReturn
404 gst_fd_src_create (GstPushSrc * psrc, GstBuffer ** outbuf)
405 {
406   GstFdSrc *src;
407   GstBuffer *buf;
408   gssize readbytes;
409   guint blocksize;
410   GstClockTime timeout;
411
412 #ifndef HAVE_WIN32
413   gboolean try_again;
414   gint retval;
415 #endif
416
417   src = GST_FD_SRC (psrc);
418
419   if (src->timeout > 0) {
420     timeout = src->timeout * GST_USECOND;
421   } else {
422     timeout = GST_CLOCK_TIME_NONE;
423   }
424
425 #ifndef HAVE_WIN32
426   do {
427     try_again = FALSE;
428
429     GST_LOG_OBJECT (src, "doing poll, timeout %" GST_TIME_FORMAT,
430         GST_TIME_ARGS (src->timeout));
431
432     retval = gst_poll_wait (src->fdset, timeout);
433     GST_LOG_OBJECT (src, "poll returned %d", retval);
434
435     if (G_UNLIKELY (retval == -1)) {
436       if (errno == EINTR || errno == EAGAIN) {
437         /* retry if interrupted */
438         try_again = TRUE;
439       } else if (errno == EBUSY) {
440         goto stopped;
441       } else {
442         goto poll_error;
443       }
444     } else if (G_UNLIKELY (retval == 0)) {
445       try_again = TRUE;
446       /* timeout, post element message */
447       gst_element_post_message (GST_ELEMENT_CAST (src),
448           gst_message_new_element (GST_OBJECT_CAST (src),
449               gst_structure_new ("GstFdSrcTimeout",
450                   "timeout", G_TYPE_UINT64, src->timeout, NULL)));
451     }
452   } while (G_UNLIKELY (try_again));     /* retry if interrupted or timeout */
453 #endif
454
455   blocksize = GST_BASE_SRC (src)->blocksize;
456
457   /* create the buffer */
458   buf = gst_buffer_try_new_and_alloc (blocksize);
459   if (G_UNLIKELY (buf == NULL)) {
460     GST_ERROR_OBJECT (src, "Failed to allocate %u bytes", blocksize);
461     return GST_FLOW_ERROR;
462   }
463
464   do {
465     readbytes = read (src->fd, GST_BUFFER_DATA (buf), blocksize);
466     GST_LOG_OBJECT (src, "read %" G_GSSIZE_FORMAT, readbytes);
467   } while (readbytes == -1 && errno == EINTR);  /* retry if interrupted */
468
469   if (readbytes < 0)
470     goto read_error;
471
472   if (readbytes == 0)
473     goto eos;
474
475   GST_BUFFER_OFFSET (buf) = src->curoffset;
476   GST_BUFFER_SIZE (buf) = readbytes;
477   GST_BUFFER_TIMESTAMP (buf) = GST_CLOCK_TIME_NONE;
478   src->curoffset += readbytes;
479
480   GST_LOG_OBJECT (psrc, "Read buffer of size %" G_GSSIZE_FORMAT, readbytes);
481
482   /* we're done, return the buffer */
483   *outbuf = buf;
484
485   return GST_FLOW_OK;
486
487   /* ERRORS */
488 #ifndef HAVE_WIN32
489 poll_error:
490   {
491     GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
492         ("poll on file descriptor: %s.", g_strerror (errno)));
493     GST_DEBUG_OBJECT (psrc, "Error during poll");
494     return GST_FLOW_ERROR;
495   }
496 stopped:
497   {
498     GST_DEBUG_OBJECT (psrc, "Poll stopped");
499     return GST_FLOW_WRONG_STATE;
500   }
501 #endif
502 eos:
503   {
504     GST_DEBUG_OBJECT (psrc, "Read 0 bytes. EOS.");
505     gst_buffer_unref (buf);
506     return GST_FLOW_UNEXPECTED;
507   }
508 read_error:
509   {
510     GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
511         ("read on file descriptor: %s.", g_strerror (errno)));
512     GST_DEBUG_OBJECT (psrc, "Error reading from fd");
513     gst_buffer_unref (buf);
514     return GST_FLOW_ERROR;
515   }
516 }
517
518 static gboolean
519 gst_fd_src_query (GstBaseSrc * basesrc, GstQuery * query)
520 {
521   gboolean ret = FALSE;
522   GstFdSrc *src = GST_FD_SRC (basesrc);
523
524   switch (GST_QUERY_TYPE (query)) {
525     case GST_QUERY_URI:
526       gst_query_set_uri (query, src->uri);
527       ret = TRUE;
528       break;
529     default:
530       ret = FALSE;
531       break;
532   }
533
534   if (!ret)
535     ret = GST_BASE_SRC_CLASS (parent_class)->query (basesrc, query);
536
537   return ret;
538 }
539
540 static gboolean
541 gst_fd_src_is_seekable (GstBaseSrc * bsrc)
542 {
543   GstFdSrc *src = GST_FD_SRC (bsrc);
544
545   return src->seekable_fd;
546 }
547
548 static gboolean
549 gst_fd_src_get_size (GstBaseSrc * bsrc, guint64 * size)
550 {
551   GstFdSrc *src = GST_FD_SRC (bsrc);
552   struct stat stat_results;
553
554   if (src->size != -1) {
555     *size = src->size;
556     return TRUE;
557   }
558
559   if (!src->seekable_fd) {
560     /* If it isn't seekable, we won't know the length (but fstat will still
561      * succeed, and wrongly say our length is zero. */
562     return FALSE;
563   }
564
565   if (fstat (src->fd, &stat_results) < 0)
566     goto could_not_stat;
567
568   *size = stat_results.st_size;
569
570   return TRUE;
571
572   /* ERROR */
573 could_not_stat:
574   {
575     return FALSE;
576   }
577 }
578
579 static gboolean
580 gst_fd_src_do_seek (GstBaseSrc * bsrc, GstSegment * segment)
581 {
582   gint res;
583   gint64 offset;
584   GstFdSrc *src = GST_FD_SRC (bsrc);
585
586   offset = segment->start;
587
588   /* No need to seek to the current position */
589   if (offset == src->curoffset)
590     return TRUE;
591
592   res = lseek (src->fd, offset, SEEK_SET);
593   if (G_UNLIKELY (res < 0 || res != offset))
594     goto seek_failed;
595
596   segment->last_stop = segment->start;
597   segment->time = segment->start;
598
599   return TRUE;
600
601 seek_failed:
602   GST_DEBUG_OBJECT (src, "lseek returned %" G_GINT64_FORMAT, offset);
603   return FALSE;
604 }
605
606 /*** GSTURIHANDLER INTERFACE *************************************************/
607
608 static GstURIType
609 gst_fd_src_uri_get_type (void)
610 {
611   return GST_URI_SRC;
612 }
613
614 static gchar **
615 gst_fd_src_uri_get_protocols (void)
616 {
617   static gchar *protocols[] = { (char *) "fd", NULL };
618
619   return protocols;
620 }
621
622 static const gchar *
623 gst_fd_src_uri_get_uri (GstURIHandler * handler)
624 {
625   GstFdSrc *src = GST_FD_SRC (handler);
626
627   return src->uri;
628 }
629
630 static gboolean
631 gst_fd_src_uri_set_uri (GstURIHandler * handler, const gchar * uri)
632 {
633   gchar *protocol, *q;
634   GstFdSrc *src = GST_FD_SRC (handler);
635   gint fd;
636   guint64 size = -1;
637
638   GST_INFO_OBJECT (src, "checking uri %s", uri);
639
640   protocol = gst_uri_get_protocol (uri);
641   if (strcmp (protocol, "fd") != 0) {
642     g_free (protocol);
643     return FALSE;
644   }
645   g_free (protocol);
646
647   if (sscanf (uri, "fd://%d", &fd) != 1 || fd < 0)
648     return FALSE;
649
650   if ((q = g_strstr_len (uri, -1, "?"))) {
651     gchar *sp;
652
653     GST_INFO_OBJECT (src, "found ?");
654
655     if ((sp = g_strstr_len (q, -1, "size="))) {
656       if (sscanf (sp, "size=%" G_GUINT64_FORMAT, &size) != 1) {
657         GST_INFO_OBJECT (src, "parsing size failed");
658         size = -1;
659       } else {
660         GST_INFO_OBJECT (src, "found size %" G_GUINT64_FORMAT, size);
661       }
662     }
663   }
664
665   src->new_fd = fd;
666
667   GST_OBJECT_LOCK (src);
668   if (GST_STATE (GST_ELEMENT (src)) <= GST_STATE_READY) {
669     gst_fd_src_update_fd (src, size);
670   }
671   GST_OBJECT_UNLOCK (src);
672
673   return TRUE;
674 }
675
676 static void
677 gst_fd_src_uri_handler_init (gpointer g_iface, gpointer iface_data)
678 {
679   GstURIHandlerInterface *iface = (GstURIHandlerInterface *) g_iface;
680
681   iface->get_type = gst_fd_src_uri_get_type;
682   iface->get_protocols = gst_fd_src_uri_get_protocols;
683   iface->get_uri = gst_fd_src_uri_get_uri;
684   iface->set_uri = gst_fd_src_uri_set_uri;
685 }