plugins/elements/: Small cleanups. Add note adbout g_fopen() on windows and why we...
[platform/upstream/gstreamer.git] / plugins / elements / gstfilesink.c
1 /* GStreamer
2  * Copyright (C) 1999,2000 Erik Walthinsen <omega@cse.ogi.edu>
3  *                    2000 Wim Taymans <wtay@chello.be>
4  *                    2006 Wim Taymans <wim@fluendo.com>
5  *
6  * gstfilesink.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-filesink
25  * @short_description: write stream to a file
26  * @see_also: #GstFileSrc
27  *
28  * Write incoming data to a file in the local file system.
29  */
30
31 #ifdef HAVE_CONFIG_H
32 #  include "config.h"
33 #endif
34
35 #include "../../gst/gst-i18n-lib.h"
36
37 #include <gst/gst.h>
38 #include <stdio.h>              /* for fseeko() */
39 #ifdef HAVE_STDIO_EXT_H
40 #include <stdio_ext.h>          /* for __fbufsize, for debugging */
41 #endif
42 #include <errno.h>
43 #include "gstfilesink.h"
44 #include <string.h>
45 #include <sys/stat.h>
46 #include <sys/types.h>
47 #ifdef HAVE_UNISTD_H
48 #include <unistd.h>
49 #endif
50
51 static GstStaticPadTemplate sinktemplate = GST_STATIC_PAD_TEMPLATE ("sink",
52     GST_PAD_SINK,
53     GST_PAD_ALWAYS,
54     GST_STATIC_CAPS_ANY);
55
56 #define GST_TYPE_BUFFER_MODE (buffer_mode_get_type ())
57 static GType
58 buffer_mode_get_type (void)
59 {
60   static GType buffer_mode_type = 0;
61   static const GEnumValue buffer_mode[] = {
62     {-1, "Default buffering", "default"},
63     {_IOFBF, "Fully buffered", "full"},
64     {_IOLBF, "Line buffered", "line"},
65     {_IONBF, "Unbuffered", "unbuffered"},
66     {0, NULL, NULL},
67   };
68
69   if (!buffer_mode_type) {
70     buffer_mode_type =
71         g_enum_register_static ("GstFileSinkBufferMode", buffer_mode);
72   }
73   return buffer_mode_type;
74 }
75
76 GST_DEBUG_CATEGORY_STATIC (gst_file_sink_debug);
77 #define GST_CAT_DEFAULT gst_file_sink_debug
78
79 #define DEFAULT_LOCATION        NULL
80 #define DEFAULT_BUFFER_MODE     -1
81 #define DEFAULT_BUFFER_SIZE     64 * 1024
82
83 enum
84 {
85   PROP_0,
86   PROP_LOCATION,
87   PROP_BUFFER_MODE,
88   PROP_BUFFER_SIZE,
89   PROP_LAST
90 };
91
92 static void gst_file_sink_dispose (GObject * object);
93
94 static void gst_file_sink_set_property (GObject * object, guint prop_id,
95     const GValue * value, GParamSpec * pspec);
96 static void gst_file_sink_get_property (GObject * object, guint prop_id,
97     GValue * value, GParamSpec * pspec);
98
99 static gboolean gst_file_sink_open_file (GstFileSink * sink);
100 static void gst_file_sink_close_file (GstFileSink * sink);
101
102 static gboolean gst_file_sink_start (GstBaseSink * sink);
103 static gboolean gst_file_sink_stop (GstBaseSink * sink);
104 static gboolean gst_file_sink_event (GstBaseSink * sink, GstEvent * event);
105 static GstFlowReturn gst_file_sink_render (GstBaseSink * sink,
106     GstBuffer * buffer);
107
108 static gboolean gst_file_sink_do_seek (GstFileSink * filesink,
109     guint64 new_offset);
110 static gboolean gst_file_sink_get_current_offset (GstFileSink * filesink,
111     guint64 * p_pos);
112
113 static gboolean gst_file_sink_query (GstPad * pad, GstQuery * query);
114
115 static void gst_file_sink_uri_handler_init (gpointer g_iface,
116     gpointer iface_data);
117
118
119 static void
120 _do_init (GType filesink_type)
121 {
122   static const GInterfaceInfo urihandler_info = {
123     gst_file_sink_uri_handler_init,
124     NULL,
125     NULL
126   };
127
128   g_type_add_interface_static (filesink_type, GST_TYPE_URI_HANDLER,
129       &urihandler_info);
130   GST_DEBUG_CATEGORY_INIT (gst_file_sink_debug, "filesink", 0,
131       "filesink element");
132 }
133
134 GST_BOILERPLATE_FULL (GstFileSink, gst_file_sink, GstBaseSink,
135     GST_TYPE_BASE_SINK, _do_init);
136
137 static void
138 gst_file_sink_base_init (gpointer g_class)
139 {
140   GstElementClass *gstelement_class = GST_ELEMENT_CLASS (g_class);
141
142   gst_element_class_set_details_simple (gstelement_class,
143       "File Sink",
144       "Sink/File", "Write stream to a file", "Thomas <thomas@apestaart.org>");
145   gst_element_class_add_pad_template (gstelement_class,
146       gst_static_pad_template_get (&sinktemplate));
147 }
148
149 static void
150 gst_file_sink_class_init (GstFileSinkClass * klass)
151 {
152   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
153   GstBaseSinkClass *gstbasesink_class = GST_BASE_SINK_CLASS (klass);
154
155   gobject_class->dispose = gst_file_sink_dispose;
156
157   gobject_class->set_property = gst_file_sink_set_property;
158   gobject_class->get_property = gst_file_sink_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 write", NULL,
163           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
164
165   g_object_class_install_property (gobject_class, PROP_BUFFER_MODE,
166       g_param_spec_enum ("buffer-mode", "Buffering mode",
167           "The buffering mode to use", GST_TYPE_BUFFER_MODE,
168           DEFAULT_BUFFER_MODE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
169
170   g_object_class_install_property (gobject_class, PROP_BUFFER_SIZE,
171       g_param_spec_uint ("buffer-size", "Buffering size",
172           "Size of buffer in number of bytes for line or full buffer-mode", 0,
173           G_MAXUINT, DEFAULT_BUFFER_SIZE,
174           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
175
176   gstbasesink_class->get_times = NULL;
177   gstbasesink_class->start = GST_DEBUG_FUNCPTR (gst_file_sink_start);
178   gstbasesink_class->stop = GST_DEBUG_FUNCPTR (gst_file_sink_stop);
179   gstbasesink_class->render = GST_DEBUG_FUNCPTR (gst_file_sink_render);
180   gstbasesink_class->event = GST_DEBUG_FUNCPTR (gst_file_sink_event);
181
182   if (sizeof (off_t) < 8) {
183     GST_LOG ("No large file support, sizeof (off_t) = %" G_GSIZE_FORMAT "!",
184         sizeof (off_t));
185   }
186 }
187
188 static void
189 gst_file_sink_init (GstFileSink * filesink, GstFileSinkClass * g_class)
190 {
191   GstPad *pad;
192
193   pad = GST_BASE_SINK_PAD (filesink);
194
195   gst_pad_set_query_function (pad, GST_DEBUG_FUNCPTR (gst_file_sink_query));
196
197   filesink->filename = NULL;
198   filesink->file = NULL;
199   filesink->buffer_mode = DEFAULT_BUFFER_MODE;
200   filesink->buffer_size = DEFAULT_BUFFER_SIZE;
201   filesink->buffer = NULL;
202
203   gst_base_sink_set_sync (GST_BASE_SINK (filesink), FALSE);
204 }
205
206 static void
207 gst_file_sink_dispose (GObject * object)
208 {
209   GstFileSink *sink = GST_FILE_SINK (object);
210
211   G_OBJECT_CLASS (parent_class)->dispose (object);
212
213   g_free (sink->uri);
214   sink->uri = NULL;
215   g_free (sink->filename);
216   sink->filename = NULL;
217   g_free (sink->buffer);
218   sink->buffer = NULL;
219   sink->buffer_size = 0;
220 }
221
222 static gboolean
223 gst_file_sink_set_location (GstFileSink * sink, const gchar * location)
224 {
225   if (sink->file)
226     goto was_open;
227
228   g_free (sink->filename);
229   g_free (sink->uri);
230   if (location != NULL) {
231     /* we store the filename as we received it from the application. On Windows
232      * this should be in UTF8 */
233     sink->filename = g_strdup (location);
234     sink->uri = gst_uri_construct ("file", sink->filename);
235   } else {
236     sink->filename = NULL;
237     sink->uri = NULL;
238   }
239
240   return TRUE;
241
242   /* ERRORS */
243 was_open:
244   {
245     g_warning ("Changing the `location' property on filesink when "
246         "a file is open not supported.");
247     return FALSE;
248   }
249 }
250 static void
251 gst_file_sink_set_property (GObject * object, guint prop_id,
252     const GValue * value, GParamSpec * pspec)
253 {
254   GstFileSink *sink = GST_FILE_SINK (object);
255
256   switch (prop_id) {
257     case PROP_LOCATION:
258       gst_file_sink_set_location (sink, g_value_get_string (value));
259       break;
260     case PROP_BUFFER_MODE:
261       sink->buffer_mode = g_value_get_enum (value);
262       break;
263     case PROP_BUFFER_SIZE:
264       sink->buffer_size = g_value_get_uint (value);
265       break;
266     default:
267       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
268       break;
269   }
270 }
271
272 static void
273 gst_file_sink_get_property (GObject * object, guint prop_id, GValue * value,
274     GParamSpec * pspec)
275 {
276   GstFileSink *sink = GST_FILE_SINK (object);
277
278   switch (prop_id) {
279     case PROP_LOCATION:
280       g_value_set_string (value, sink->filename);
281       break;
282     case PROP_BUFFER_MODE:
283       g_value_set_enum (value, sink->buffer_mode);
284       break;
285     case PROP_BUFFER_SIZE:
286       g_value_set_uint (value, sink->buffer_size);
287       break;
288     default:
289       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
290       break;
291   }
292 }
293
294 static gboolean
295 gst_file_sink_open_file (GstFileSink * sink)
296 {
297   gint mode;
298
299   /* open the file */
300   if (sink->filename == NULL || sink->filename[0] == '\0')
301     goto no_filename;
302
303   /* FIXME, can we use g_fopen here? some people say that the FILE object is
304    * local to the .so that performed the fopen call, which would not be us when
305    * we use g_fopen. */
306   sink->file = fopen (sink->filename, "wb");
307   if (sink->file == NULL)
308     goto open_failed;
309
310   /* see if we are asked to perform a specific kind of buffering */
311   if ((mode = sink->buffer_mode) != -1) {
312     gsize buffer_size;
313
314     /* free previous buffer if any */
315     g_free (sink->buffer);
316
317     if (mode == _IONBF) {
318       /* no buffering */
319       sink->buffer = NULL;
320       buffer_size = 0;
321     } else {
322       /* allocate buffer */
323       sink->buffer = g_malloc (sink->buffer_size);
324       buffer_size = sink->buffer_size;
325     }
326 #ifdef HAVE_STDIO_EXT_H
327     GST_DEBUG_OBJECT (sink, "change buffer size %d to %d, mode %d",
328         __fbufsize (sink->file), buffer_size, mode);
329 #else
330     GST_DEBUG_OBJECT (sink, "change  buffer size to %d, mode %d",
331         sink->buffer_size, mode);
332 #endif
333     if (setvbuf (sink->file, sink->buffer, mode, buffer_size) != 0) {
334       GST_WARNING_OBJECT (sink, "warning: setvbuf failed: %s",
335           g_strerror (errno));
336     }
337   }
338
339   sink->current_pos = 0;
340   /* try to seek in the file to figure out if it is seekable */
341   sink->seekable = gst_file_sink_do_seek (sink, 0);
342
343   GST_DEBUG_OBJECT (sink, "opened file %s, seekable %d",
344       sink->filename, sink->seekable);
345
346   return TRUE;
347
348   /* ERRORS */
349 no_filename:
350   {
351     GST_ELEMENT_ERROR (sink, RESOURCE, NOT_FOUND,
352         (_("No file name specified for writing.")), (NULL));
353     return FALSE;
354   }
355 open_failed:
356   {
357     GST_ELEMENT_ERROR (sink, RESOURCE, OPEN_WRITE,
358         (_("Could not open file \"%s\" for writing."), sink->filename),
359         GST_ERROR_SYSTEM);
360     return FALSE;
361   }
362 }
363
364 static void
365 gst_file_sink_close_file (GstFileSink * sink)
366 {
367   if (sink->file) {
368     if (fclose (sink->file) != 0)
369       goto close_failed;
370
371     GST_DEBUG_OBJECT (sink, "closed file");
372     sink->file = NULL;
373
374     g_free (sink->buffer);
375     sink->buffer = NULL;
376   }
377   return;
378
379   /* ERRORS */
380 close_failed:
381   {
382     GST_ELEMENT_ERROR (sink, RESOURCE, CLOSE,
383         (_("Error closing file \"%s\"."), sink->filename), GST_ERROR_SYSTEM);
384     return;
385   }
386 }
387
388 static gboolean
389 gst_file_sink_query (GstPad * pad, GstQuery * query)
390 {
391   GstFileSink *self;
392   GstFormat format;
393
394   self = GST_FILE_SINK (GST_PAD_PARENT (pad));
395
396   switch (GST_QUERY_TYPE (query)) {
397     case GST_QUERY_POSITION:
398       gst_query_parse_position (query, &format, NULL);
399       switch (format) {
400         case GST_FORMAT_DEFAULT:
401         case GST_FORMAT_BYTES:
402           gst_query_set_position (query, GST_FORMAT_BYTES, self->current_pos);
403           return TRUE;
404         default:
405           return FALSE;
406       }
407
408     case GST_QUERY_FORMATS:
409       gst_query_set_formats (query, 2, GST_FORMAT_DEFAULT, GST_FORMAT_BYTES);
410       return TRUE;
411
412     default:
413       return gst_pad_query_default (pad, query);
414   }
415 }
416
417 #ifdef HAVE_FSEEKO
418 # define __GST_STDIO_SEEK_FUNCTION "fseeko"
419 #elif defined (G_OS_UNIX)
420 # define __GST_STDIO_SEEK_FUNCTION "lseek"
421 #else
422 # define __GST_STDIO_SEEK_FUNCTION "fseek"
423 #endif
424
425 static gboolean
426 gst_file_sink_do_seek (GstFileSink * filesink, guint64 new_offset)
427 {
428   GST_DEBUG_OBJECT (filesink, "Seeking to offset %" G_GUINT64_FORMAT
429       " using " __GST_STDIO_SEEK_FUNCTION, new_offset);
430
431   if (fflush (filesink->file))
432     goto flush_failed;
433
434 #ifdef HAVE_FSEEKO
435   if (fseeko (filesink->file, (off_t) new_offset, SEEK_SET) != 0)
436     goto seek_failed;
437 #elif defined (G_OS_UNIX)
438   if (lseek (fileno (filesink->file), (off_t) new_offset,
439           SEEK_SET) == (off_t) - 1)
440     goto seek_failed;
441 #else
442   if (fseek (filesink->file, (long) new_offset, SEEK_SET) != 0)
443     goto seek_failed;
444 #endif
445
446   /* adjust position reporting after seek;
447    * presumably this should basically yield new_offset */
448   gst_file_sink_get_current_offset (filesink, &filesink->current_pos);
449
450   return TRUE;
451
452   /* ERRORS */
453 flush_failed:
454   {
455     GST_DEBUG_OBJECT (filesink, "Flush failed: %s", g_strerror (errno));
456     return FALSE;
457   }
458 seek_failed:
459   {
460     GST_DEBUG_OBJECT (filesink, "Seeking failed: %s", g_strerror (errno));
461     return FALSE;
462   }
463 }
464
465 /* handle events (search) */
466 static gboolean
467 gst_file_sink_event (GstBaseSink * sink, GstEvent * event)
468 {
469   GstEventType type;
470   GstFileSink *filesink;
471
472   filesink = GST_FILE_SINK (sink);
473
474   type = GST_EVENT_TYPE (event);
475
476   switch (type) {
477     case GST_EVENT_NEWSEGMENT:
478     {
479       gint64 start, stop, pos;
480       GstFormat format;
481
482       gst_event_parse_new_segment (event, NULL, NULL, &format, &start,
483           &stop, &pos);
484
485       if (format == GST_FORMAT_BYTES) {
486         /* only try to seek and fail when we are going to a different
487          * position */
488         if (filesink->current_pos != start) {
489           /* FIXME, the seek should be performed on the pos field, start/stop are
490            * just boundaries for valid bytes offsets. We should also fill the file
491            * with zeroes if the new position extends the current EOF (sparse streams
492            * and segment accumulation). */
493           if (!gst_file_sink_do_seek (filesink, (guint64) start))
494             goto seek_failed;
495         } else {
496           GST_DEBUG_OBJECT (filesink, "Ignored NEWSEGMENT, no seek needed");
497         }
498       } else {
499         GST_DEBUG_OBJECT (filesink,
500             "Ignored NEWSEGMENT event of format %u (%s)", (guint) format,
501             gst_format_get_name (format));
502       }
503       break;
504     }
505     case GST_EVENT_EOS:
506       if (fflush (filesink->file))
507         goto flush_failed;
508       break;
509     default:
510       break;
511   }
512
513   return TRUE;
514
515   /* ERRORS */
516 seek_failed:
517   {
518     GST_ELEMENT_ERROR (filesink, RESOURCE, SEEK,
519         (_("Error while seeking in file \"%s\"."), filesink->filename),
520         GST_ERROR_SYSTEM);
521     return FALSE;
522   }
523 flush_failed:
524   {
525     GST_ELEMENT_ERROR (filesink, RESOURCE, WRITE,
526         (_("Error while writing to file \"%s\"."), filesink->filename),
527         GST_ERROR_SYSTEM);
528     return FALSE;
529   }
530 }
531
532 static gboolean
533 gst_file_sink_get_current_offset (GstFileSink * filesink, guint64 * p_pos)
534 {
535   off_t ret;
536
537 #ifdef HAVE_FTELLO
538   ret = ftello (filesink->file);
539 #elif defined (G_OS_UNIX)
540   if (fflush (filesink->file)) {
541     GST_DEBUG_OBJECT (filesink, "Flush failed: %s", g_strerror (errno));
542     /* ignore and continue */
543   }
544   ret = lseek (fileno (filesink->file), 0, SEEK_CUR);
545 #else
546   ret = (off_t) ftell (filesink->file);
547 #endif
548
549   if (ret != (off_t) - 1)
550     *p_pos = (guint64) ret;
551
552   return (ret != (off_t) - 1);
553 }
554
555 static GstFlowReturn
556 gst_file_sink_render (GstBaseSink * sink, GstBuffer * buffer)
557 {
558   GstFileSink *filesink;
559   guint size;
560   guint8 *data;
561
562   filesink = GST_FILE_SINK (sink);
563
564   size = GST_BUFFER_SIZE (buffer);
565   data = GST_BUFFER_DATA (buffer);
566
567   GST_DEBUG_OBJECT (filesink, "writing %u bytes at %" G_GUINT64_FORMAT,
568       size, filesink->current_pos);
569
570   if (size > 0 && data != NULL) {
571     if (fwrite (data, size, 1, filesink->file) != 1)
572       goto handle_error;
573
574     filesink->current_pos += size;
575   }
576
577   return GST_FLOW_OK;
578
579 handle_error:
580   {
581     switch (errno) {
582       case ENOSPC:{
583         GST_ELEMENT_ERROR (filesink, RESOURCE, NO_SPACE_LEFT, (NULL), (NULL));
584         break;
585       }
586       default:{
587         GST_ELEMENT_ERROR (filesink, RESOURCE, WRITE,
588             (_("Error while writing to file \"%s\"."), filesink->filename),
589             ("%s", g_strerror (errno)));
590       }
591     }
592     return GST_FLOW_ERROR;
593   }
594 }
595
596 static gboolean
597 gst_file_sink_start (GstBaseSink * basesink)
598 {
599   return gst_file_sink_open_file (GST_FILE_SINK (basesink));
600 }
601
602 static gboolean
603 gst_file_sink_stop (GstBaseSink * basesink)
604 {
605   gst_file_sink_close_file (GST_FILE_SINK (basesink));
606   return TRUE;
607 }
608
609 /*** GSTURIHANDLER INTERFACE *************************************************/
610
611 static GstURIType
612 gst_file_sink_uri_get_type (void)
613 {
614   return GST_URI_SINK;
615 }
616 static gchar **
617 gst_file_sink_uri_get_protocols (void)
618 {
619   static gchar *protocols[] = { "file", NULL };
620
621   return protocols;
622 }
623 static const gchar *
624 gst_file_sink_uri_get_uri (GstURIHandler * handler)
625 {
626   GstFileSink *sink = GST_FILE_SINK (handler);
627
628   return sink->uri;
629 }
630
631 static gboolean
632 gst_file_sink_uri_set_uri (GstURIHandler * handler, const gchar * uri)
633 {
634   gchar *protocol, *location;
635   gboolean ret;
636   GstFileSink *sink = GST_FILE_SINK (handler);
637
638   protocol = gst_uri_get_protocol (uri);
639   if (strcmp (protocol, "file") != 0) {
640     g_free (protocol);
641     return FALSE;
642   }
643   g_free (protocol);
644
645   /* allow file://localhost/foo/bar by stripping localhost but fail
646    * for every other hostname */
647   if (g_str_has_prefix (uri, "file://localhost/")) {
648     char *tmp;
649
650     /* 16 == strlen ("file://localhost") */
651     tmp = g_strconcat ("file://", uri + 16, NULL);
652     /* we use gst_uri_get_location() although we already have the
653      * "location" with uri + 16 because it provides unescaping */
654     location = gst_uri_get_location (tmp);
655     g_free (tmp);
656   } else if (strcmp (uri, "file://") == 0) {
657     /* Special case for "file://" as this is used by some applications
658      *  to test with gst_element_make_from_uri if there's an element
659      *  that supports the URI protocol. */
660     gst_file_sink_set_location (sink, NULL);
661     return TRUE;
662   } else {
663     location = gst_uri_get_location (uri);
664   }
665
666   if (!location)
667     return FALSE;
668   if (!g_path_is_absolute (location)) {
669     g_free (location);
670     return FALSE;
671   }
672
673   ret = gst_file_sink_set_location (sink, location);
674   g_free (location);
675
676   return ret;
677 }
678
679 static void
680 gst_file_sink_uri_handler_init (gpointer g_iface, gpointer iface_data)
681 {
682   GstURIHandlerInterface *iface = (GstURIHandlerInterface *) g_iface;
683
684   iface->get_type = gst_file_sink_uri_get_type;
685   iface->get_protocols = gst_file_sink_uri_get_protocols;
686   iface->get_uri = gst_file_sink_uri_get_uri;
687   iface->set_uri = gst_file_sink_uri_set_uri;
688 }