Merge the tizen patch based on 1.12.2
[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., 51 Franklin St, Fifth Floor,
21  * Boston, MA 02110-1301, USA.
22  */
23 /**
24  * SECTION:element-filesink
25  * @title: filesink
26  * @see_also: #GstFileSrc
27  *
28  * Write incoming data to a file in the local file system.
29  *
30  * ## Example launch line
31  * |[
32  * gst-launch-1.0 v4l2src num-buffers=1 ! jpegenc ! filesink location=capture1.jpeg
33  * ]| Capture one frame from a v4l2 camera and save as jpeg image.
34  *
35  */
36
37 #ifdef HAVE_CONFIG_H
38 #  include "config.h"
39 #endif
40
41 #include "../../gst/gst-i18n-lib.h"
42
43 #include <gst/gst.h>
44 #include <stdio.h>              /* for fseeko() */
45 #ifdef HAVE_STDIO_EXT_H
46 #include <stdio_ext.h>          /* for __fbufsize, for debugging */
47 #endif
48 #include <errno.h>
49 #include "gstfilesink.h"
50 #include <string.h>
51 #include <sys/types.h>
52
53 #ifdef G_OS_WIN32
54 #include <io.h>                 /* lseek, open, close, read */
55 #undef lseek
56 #define lseek _lseeki64
57 #undef off_t
58 #define off_t guint64
59 #undef ftruncate
60 #define ftruncate _chsize
61 #undef fsync
62 #define fsync _commit
63 #ifdef _MSC_VER                 /* Check if we are using MSVC, fileno is deprecated in favour */
64 #define fileno _fileno          /* of _fileno */
65 #endif
66 #endif
67
68 #include <sys/stat.h>
69 #ifdef HAVE_UNISTD_H
70 #include <unistd.h>
71 #endif
72
73 #ifdef __BIONIC__               /* Android */
74 #undef lseek
75 #define lseek lseek64
76 #undef off_t
77 #define off_t guint64
78 #endif
79
80 #include "gstelements_private.h"
81 #include "gstfilesink.h"
82
83 static GstStaticPadTemplate sinktemplate = GST_STATIC_PAD_TEMPLATE ("sink",
84     GST_PAD_SINK,
85     GST_PAD_ALWAYS,
86     GST_STATIC_CAPS_ANY);
87
88 #define GST_TYPE_FILE_SINK_BUFFER_MODE (gst_file_sink_buffer_mode_get_type ())
89 static GType
90 gst_file_sink_buffer_mode_get_type (void)
91 {
92   static GType buffer_mode_type = 0;
93   static const GEnumValue buffer_mode[] = {
94     {GST_FILE_SINK_BUFFER_MODE_DEFAULT, "Default buffering", "default"},
95     {GST_FILE_SINK_BUFFER_MODE_FULL, "Fully buffered", "full"},
96     {GST_FILE_SINK_BUFFER_MODE_LINE, "Line buffered", "line"},
97     {GST_FILE_SINK_BUFFER_MODE_UNBUFFERED, "Unbuffered", "unbuffered"},
98     {0, NULL, NULL},
99   };
100
101   if (!buffer_mode_type) {
102     buffer_mode_type =
103         g_enum_register_static ("GstFileSinkBufferMode", buffer_mode);
104   }
105   return buffer_mode_type;
106 }
107
108 GST_DEBUG_CATEGORY_STATIC (gst_file_sink_debug);
109 #define GST_CAT_DEFAULT gst_file_sink_debug
110
111 #define DEFAULT_LOCATION        NULL
112 #define DEFAULT_BUFFER_MODE     GST_FILE_SINK_BUFFER_MODE_DEFAULT
113 #define DEFAULT_BUFFER_SIZE     64 * 1024
114 #define DEFAULT_APPEND          FALSE
115
116 enum
117 {
118   PROP_0,
119   PROP_LOCATION,
120   PROP_BUFFER_MODE,
121   PROP_BUFFER_SIZE,
122   PROP_APPEND,
123 #ifdef TIZEN_FEATURE_FILESINK_MODIFICATION
124   PROP_CURRENT_BYTES,
125 #endif
126   PROP_LAST
127 };
128
129 /* Copy of glib's g_fopen due to win32 libc/cross-DLL brokenness: we can't
130  * use the 'file pointer' opened in glib (and returned from this function)
131  * in this library, as they may have unrelated C runtimes. */
132 static FILE *
133 gst_fopen (const gchar * filename, const gchar * mode)
134 {
135 #ifdef G_OS_WIN32
136   wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
137   wchar_t *wmode;
138   FILE *retval;
139   int save_errno;
140
141   if (wfilename == NULL) {
142     errno = EINVAL;
143     return NULL;
144   }
145
146   wmode = g_utf8_to_utf16 (mode, -1, NULL, NULL, NULL);
147
148   if (wmode == NULL) {
149     g_free (wfilename);
150     errno = EINVAL;
151     return NULL;
152   }
153
154   retval = _wfopen (wfilename, wmode);
155   save_errno = errno;
156
157   g_free (wfilename);
158   g_free (wmode);
159
160   errno = save_errno;
161   return retval;
162 #else
163   return fopen (filename, mode);
164 #endif
165 }
166
167 static void gst_file_sink_dispose (GObject * object);
168
169 static void gst_file_sink_set_property (GObject * object, guint prop_id,
170     const GValue * value, GParamSpec * pspec);
171 static void gst_file_sink_get_property (GObject * object, guint prop_id,
172     GValue * value, GParamSpec * pspec);
173
174 static gboolean gst_file_sink_open_file (GstFileSink * sink);
175 static void gst_file_sink_close_file (GstFileSink * sink);
176
177 static gboolean gst_file_sink_start (GstBaseSink * sink);
178 static gboolean gst_file_sink_stop (GstBaseSink * sink);
179 static gboolean gst_file_sink_event (GstBaseSink * sink, GstEvent * event);
180 static GstFlowReturn gst_file_sink_render (GstBaseSink * sink,
181     GstBuffer * buffer);
182 static GstFlowReturn gst_file_sink_render_list (GstBaseSink * sink,
183     GstBufferList * list);
184
185 static gboolean gst_file_sink_do_seek (GstFileSink * filesink,
186     guint64 new_offset);
187 static gboolean gst_file_sink_get_current_offset (GstFileSink * filesink,
188     guint64 * p_pos);
189
190 static gboolean gst_file_sink_query (GstBaseSink * bsink, GstQuery * query);
191
192 static void gst_file_sink_uri_handler_init (gpointer g_iface,
193     gpointer iface_data);
194
195 #define _do_init \
196   G_IMPLEMENT_INTERFACE (GST_TYPE_URI_HANDLER, gst_file_sink_uri_handler_init); \
197   GST_DEBUG_CATEGORY_INIT (gst_file_sink_debug, "filesink", 0, "filesink element");
198 #define gst_file_sink_parent_class parent_class
199 G_DEFINE_TYPE_WITH_CODE (GstFileSink, gst_file_sink, GST_TYPE_BASE_SINK,
200     _do_init);
201
202 static void
203 gst_file_sink_class_init (GstFileSinkClass * klass)
204 {
205   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
206   GstElementClass *gstelement_class = GST_ELEMENT_CLASS (klass);
207   GstBaseSinkClass *gstbasesink_class = GST_BASE_SINK_CLASS (klass);
208
209   gobject_class->dispose = gst_file_sink_dispose;
210
211   gobject_class->set_property = gst_file_sink_set_property;
212   gobject_class->get_property = gst_file_sink_get_property;
213
214   g_object_class_install_property (gobject_class, PROP_LOCATION,
215       g_param_spec_string ("location", "File Location",
216           "Location of the file to write", NULL,
217           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
218
219   g_object_class_install_property (gobject_class, PROP_BUFFER_MODE,
220       g_param_spec_enum ("buffer-mode", "Buffering mode",
221           "The buffering mode to use", GST_TYPE_FILE_SINK_BUFFER_MODE,
222           DEFAULT_BUFFER_MODE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
223
224   g_object_class_install_property (gobject_class, PROP_BUFFER_SIZE,
225       g_param_spec_uint ("buffer-size", "Buffering size",
226           "Size of buffer in number of bytes for line or full buffer-mode", 0,
227           G_MAXUINT, DEFAULT_BUFFER_SIZE,
228           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
229 #ifdef TIZEN_FEATURE_FILESINK_MODIFICATION
230   g_object_class_install_property (gobject_class, PROP_CURRENT_BYTES,
231       g_param_spec_uint64 ("current-bytes", "Current bytes",
232           "downloaded bytes so far", 0,
233           G_MAXUINT64, 0,
234           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
235 #endif
236
237   /**
238    * GstFileSink:append
239    *
240    * Append to an already existing file.
241    */
242   g_object_class_install_property (gobject_class, PROP_APPEND,
243       g_param_spec_boolean ("append", "Append",
244           "Append to an already existing file", DEFAULT_APPEND,
245           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
246
247   gst_element_class_set_static_metadata (gstelement_class,
248       "File Sink",
249       "Sink/File", "Write stream to a file",
250       "Thomas Vander Stichele <thomas at apestaart dot org>");
251   gst_element_class_add_static_pad_template (gstelement_class, &sinktemplate);
252
253   gstbasesink_class->start = GST_DEBUG_FUNCPTR (gst_file_sink_start);
254   gstbasesink_class->stop = GST_DEBUG_FUNCPTR (gst_file_sink_stop);
255   gstbasesink_class->query = GST_DEBUG_FUNCPTR (gst_file_sink_query);
256   gstbasesink_class->render = GST_DEBUG_FUNCPTR (gst_file_sink_render);
257   gstbasesink_class->render_list =
258       GST_DEBUG_FUNCPTR (gst_file_sink_render_list);
259   gstbasesink_class->event = GST_DEBUG_FUNCPTR (gst_file_sink_event);
260
261   if (sizeof (off_t) < 8) {
262     GST_LOG ("No large file support, sizeof (off_t) = %" G_GSIZE_FORMAT "!",
263         sizeof (off_t));
264   }
265 }
266
267 static void
268 gst_file_sink_init (GstFileSink * filesink)
269 {
270   filesink->filename = NULL;
271   filesink->file = NULL;
272   filesink->current_pos = 0;
273   filesink->buffer_mode = DEFAULT_BUFFER_MODE;
274   filesink->buffer_size = DEFAULT_BUFFER_SIZE;
275   filesink->buffer = NULL;
276   filesink->append = FALSE;
277
278   gst_base_sink_set_sync (GST_BASE_SINK (filesink), FALSE);
279 }
280
281 static void
282 gst_file_sink_dispose (GObject * object)
283 {
284   GstFileSink *sink = GST_FILE_SINK (object);
285
286   G_OBJECT_CLASS (parent_class)->dispose (object);
287
288   g_free (sink->uri);
289   sink->uri = NULL;
290   g_free (sink->filename);
291   sink->filename = NULL;
292   g_free (sink->buffer);
293   sink->buffer = NULL;
294   sink->buffer_size = 0;
295 }
296
297 static gboolean
298 gst_file_sink_set_location (GstFileSink * sink, const gchar * location,
299     GError ** error)
300 {
301   if (sink->file)
302     goto was_open;
303
304   g_free (sink->filename);
305   g_free (sink->uri);
306   if (location != NULL) {
307     /* we store the filename as we received it from the application. On Windows
308      * this should be in UTF8 */
309     sink->filename = g_strdup (location);
310     sink->uri = gst_filename_to_uri (location, NULL);
311     GST_INFO_OBJECT (sink, "filename : %s", sink->filename);
312     GST_INFO_OBJECT (sink, "uri      : %s", sink->uri);
313   } else {
314     sink->filename = NULL;
315     sink->uri = NULL;
316   }
317
318   return TRUE;
319
320   /* ERRORS */
321 was_open:
322   {
323     g_warning ("Changing the `location' property on filesink when a file is "
324         "open is not supported.");
325     g_set_error (error, GST_URI_ERROR, GST_URI_ERROR_BAD_STATE,
326         "Changing the 'location' property on filesink when a file is "
327         "open is not supported");
328     return FALSE;
329   }
330 }
331
332 static void
333 gst_file_sink_set_property (GObject * object, guint prop_id,
334     const GValue * value, GParamSpec * pspec)
335 {
336   GstFileSink *sink = GST_FILE_SINK (object);
337
338   switch (prop_id) {
339     case PROP_LOCATION:
340       gst_file_sink_set_location (sink, g_value_get_string (value), NULL);
341       break;
342     case PROP_BUFFER_MODE:
343       sink->buffer_mode = g_value_get_enum (value);
344       break;
345     case PROP_BUFFER_SIZE:
346       sink->buffer_size = g_value_get_uint (value);
347       break;
348     case PROP_APPEND:
349       sink->append = g_value_get_boolean (value);
350       break;
351     default:
352       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
353       break;
354   }
355 }
356
357 static void
358 gst_file_sink_get_property (GObject * object, guint prop_id, GValue * value,
359     GParamSpec * pspec)
360 {
361   GstFileSink *sink = GST_FILE_SINK (object);
362
363   switch (prop_id) {
364     case PROP_LOCATION:
365       g_value_set_string (value, sink->filename);
366       break;
367     case PROP_BUFFER_MODE:
368       g_value_set_enum (value, sink->buffer_mode);
369       break;
370     case PROP_BUFFER_SIZE:
371       g_value_set_uint (value, sink->buffer_size);
372       break;
373     case PROP_APPEND:
374       g_value_set_boolean (value, sink->append);
375       break;
376 #ifdef TIZEN_FEATURE_FILESINK_MODIFICATION
377     case PROP_CURRENT_BYTES:
378       g_value_set_uint64(value, sink->current_pos);
379       break;
380 #endif
381     default:
382       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
383       break;
384   }
385 }
386
387 static gboolean
388 gst_file_sink_open_file (GstFileSink * sink)
389 {
390   gint mode;
391
392   /* open the file */
393   if (sink->filename == NULL || sink->filename[0] == '\0')
394     goto no_filename;
395
396   if (sink->append)
397     sink->file = gst_fopen (sink->filename, "ab");
398   else
399     sink->file = gst_fopen (sink->filename, "wb");
400   if (sink->file == NULL)
401     goto open_failed;
402
403   /* see if we are asked to perform a specific kind of buffering */
404   if ((mode = sink->buffer_mode) != -1) {
405     guint buffer_size;
406
407     /* free previous buffer if any */
408     g_free (sink->buffer);
409
410     if (mode == _IONBF) {
411       /* no buffering */
412       sink->buffer = NULL;
413       buffer_size = 0;
414     } else {
415       /* allocate buffer */
416       sink->buffer = g_malloc (sink->buffer_size);
417       buffer_size = sink->buffer_size;
418     }
419     /* Cygwin does not have __fbufsize */
420 #if defined(HAVE_STDIO_EXT_H) && !defined(__CYGWIN__)
421     GST_DEBUG_OBJECT (sink, "change buffer size %u to %u, mode %d",
422         (guint) __fbufsize (sink->file), buffer_size, mode);
423 #else
424     GST_DEBUG_OBJECT (sink, "change  buffer size to %u, mode %d",
425         sink->buffer_size, mode);
426 #endif
427     if (setvbuf (sink->file, sink->buffer, mode, buffer_size) != 0) {
428       GST_WARNING_OBJECT (sink, "warning: setvbuf failed: %s",
429           g_strerror (errno));
430     }
431   }
432
433   sink->current_pos = 0;
434   /* try to seek in the file to figure out if it is seekable */
435   sink->seekable = gst_file_sink_do_seek (sink, 0);
436
437   GST_DEBUG_OBJECT (sink, "opened file %s, seekable %d",
438       sink->filename, sink->seekable);
439
440   return TRUE;
441
442   /* ERRORS */
443 no_filename:
444   {
445     GST_ELEMENT_ERROR (sink, RESOURCE, NOT_FOUND,
446         (_("No file name specified for writing.")), (NULL));
447     return FALSE;
448   }
449 open_failed:
450   {
451     GST_ELEMENT_ERROR (sink, RESOURCE, OPEN_WRITE,
452         (_("Could not open file \"%s\" for writing."), sink->filename),
453         GST_ERROR_SYSTEM);
454     return FALSE;
455   }
456 }
457
458 static void
459 gst_file_sink_close_file (GstFileSink * sink)
460 {
461   if (sink->file) {
462     if (fclose (sink->file) != 0)
463       GST_ELEMENT_ERROR (sink, RESOURCE, CLOSE,
464           (_("Error closing file \"%s\"."), sink->filename), GST_ERROR_SYSTEM);
465
466     GST_DEBUG_OBJECT (sink, "closed file");
467     sink->file = NULL;
468
469     g_free (sink->buffer);
470     sink->buffer = NULL;
471   }
472 }
473
474 static gboolean
475 gst_file_sink_query (GstBaseSink * bsink, GstQuery * query)
476 {
477   gboolean res;
478   GstFileSink *self;
479   GstFormat format;
480
481   self = GST_FILE_SINK (bsink);
482
483   switch (GST_QUERY_TYPE (query)) {
484     case GST_QUERY_POSITION:
485       gst_query_parse_position (query, &format, NULL);
486
487       switch (format) {
488         case GST_FORMAT_DEFAULT:
489         case GST_FORMAT_BYTES:
490           gst_query_set_position (query, GST_FORMAT_BYTES, self->current_pos);
491           res = TRUE;
492           break;
493         default:
494           res = FALSE;
495           break;
496       }
497       break;
498
499     case GST_QUERY_FORMATS:
500       gst_query_set_formats (query, 2, GST_FORMAT_DEFAULT, GST_FORMAT_BYTES);
501       res = TRUE;
502       break;
503
504     case GST_QUERY_URI:
505       gst_query_set_uri (query, self->uri);
506       res = TRUE;
507       break;
508
509     case GST_QUERY_SEEKING:
510       gst_query_parse_seeking (query, &format, NULL, NULL, NULL);
511       if (format == GST_FORMAT_BYTES || format == GST_FORMAT_DEFAULT) {
512         gst_query_set_seeking (query, GST_FORMAT_BYTES, self->seekable, 0, -1);
513       } else {
514         gst_query_set_seeking (query, format, FALSE, 0, -1);
515       }
516       res = TRUE;
517       break;
518
519     default:
520       res = GST_BASE_SINK_CLASS (parent_class)->query (bsink, query);
521       break;
522   }
523   return res;
524 }
525
526 #ifdef HAVE_FSEEKO
527 # define __GST_STDIO_SEEK_FUNCTION "fseeko"
528 #elif defined (G_OS_UNIX) || defined (G_OS_WIN32)
529 # define __GST_STDIO_SEEK_FUNCTION "lseek"
530 #else
531 # define __GST_STDIO_SEEK_FUNCTION "fseek"
532 #endif
533
534 static gboolean
535 gst_file_sink_do_seek (GstFileSink * filesink, guint64 new_offset)
536 {
537   GST_DEBUG_OBJECT (filesink, "Seeking to offset %" G_GUINT64_FORMAT
538       " using " __GST_STDIO_SEEK_FUNCTION, new_offset);
539
540   if (fflush (filesink->file))
541     goto flush_failed;
542
543 #ifdef HAVE_FSEEKO
544   if (fseeko (filesink->file, (off_t) new_offset, SEEK_SET) != 0)
545     goto seek_failed;
546 #elif defined (G_OS_UNIX) || defined (G_OS_WIN32)
547   if (lseek (fileno (filesink->file), (off_t) new_offset,
548           SEEK_SET) == (off_t) - 1)
549     goto seek_failed;
550 #else
551   if (fseek (filesink->file, (long) new_offset, SEEK_SET) != 0)
552     goto seek_failed;
553 #endif
554
555   /* adjust position reporting after seek;
556    * presumably this should basically yield new_offset */
557   gst_file_sink_get_current_offset (filesink, &filesink->current_pos);
558
559   return TRUE;
560
561   /* ERRORS */
562 flush_failed:
563   {
564     GST_DEBUG_OBJECT (filesink, "Flush failed: %s", g_strerror (errno));
565     return FALSE;
566   }
567 seek_failed:
568   {
569     GST_DEBUG_OBJECT (filesink, "Seeking failed: %s", g_strerror (errno));
570     return FALSE;
571   }
572 }
573
574 /* handle events (search) */
575 static gboolean
576 gst_file_sink_event (GstBaseSink * sink, GstEvent * event)
577 {
578   GstEventType type;
579   GstFileSink *filesink;
580
581   filesink = GST_FILE_SINK (sink);
582
583   type = GST_EVENT_TYPE (event);
584
585   switch (type) {
586     case GST_EVENT_SEGMENT:
587     {
588       const GstSegment *segment;
589
590       gst_event_parse_segment (event, &segment);
591
592       if (segment->format == GST_FORMAT_BYTES) {
593         /* only try to seek and fail when we are going to a different
594          * position */
595         if (filesink->current_pos != segment->start) {
596           /* FIXME, the seek should be performed on the pos field, start/stop are
597            * just boundaries for valid bytes offsets. We should also fill the file
598            * with zeroes if the new position extends the current EOF (sparse streams
599            * and segment accumulation). */
600           if (!gst_file_sink_do_seek (filesink, (guint64) segment->start))
601             goto seek_failed;
602         } else {
603           GST_DEBUG_OBJECT (filesink, "Ignored SEGMENT, no seek needed");
604         }
605       } else {
606         GST_DEBUG_OBJECT (filesink,
607             "Ignored SEGMENT event of format %u (%s)", (guint) segment->format,
608             gst_format_get_name (segment->format));
609       }
610       break;
611     }
612     case GST_EVENT_FLUSH_STOP:
613       if (filesink->current_pos != 0 && filesink->seekable) {
614         gst_file_sink_do_seek (filesink, 0);
615         if (ftruncate (fileno (filesink->file), 0))
616           goto flush_failed;
617       }
618       break;
619     case GST_EVENT_EOS:
620       if (fflush (filesink->file))
621         goto flush_failed;
622       break;
623     default:
624       break;
625   }
626
627   return GST_BASE_SINK_CLASS (parent_class)->event (sink, event);
628
629   /* ERRORS */
630 seek_failed:
631   {
632     GST_ELEMENT_ERROR (filesink, RESOURCE, SEEK,
633         (_("Error while seeking in file \"%s\"."), filesink->filename),
634         GST_ERROR_SYSTEM);
635     gst_event_unref (event);
636     return FALSE;
637   }
638 flush_failed:
639   {
640     GST_ELEMENT_ERROR (filesink, RESOURCE, WRITE,
641         (_("Error while writing to file \"%s\"."), filesink->filename),
642         GST_ERROR_SYSTEM);
643     gst_event_unref (event);
644     return FALSE;
645   }
646 }
647
648 static gboolean
649 gst_file_sink_get_current_offset (GstFileSink * filesink, guint64 * p_pos)
650 {
651   off_t ret = -1;
652
653 #ifdef HAVE_FTELLO
654   ret = ftello (filesink->file);
655 #elif defined (G_OS_UNIX) || defined (G_OS_WIN32)
656   if (fflush (filesink->file)) {
657     GST_DEBUG_OBJECT (filesink, "Flush failed: %s", g_strerror (errno));
658     /* ignore and continue */
659   }
660   ret = lseek (fileno (filesink->file), 0, SEEK_CUR);
661 #else
662   ret = (off_t) ftell (filesink->file);
663 #endif
664
665   if (ret != (off_t) - 1)
666     *p_pos = (guint64) ret;
667
668   return (ret != (off_t) - 1);
669 }
670
671 static GstFlowReturn
672 gst_file_sink_render_buffers (GstFileSink * sink, GstBuffer ** buffers,
673     guint num_buffers, guint8 * mem_nums, guint total_mems)
674 {
675   GST_DEBUG_OBJECT (sink,
676       "writing %u buffers (%u memories) at position %" G_GUINT64_FORMAT,
677       num_buffers, total_mems, sink->current_pos);
678
679   return gst_writev_buffers (GST_OBJECT_CAST (sink), fileno (sink->file), NULL,
680       buffers, num_buffers, mem_nums, total_mems, &sink->current_pos, 0);
681 }
682
683 static GstFlowReturn
684 gst_file_sink_render_list (GstBaseSink * bsink, GstBufferList * buffer_list)
685 {
686   GstFlowReturn flow;
687   GstBuffer **buffers;
688   GstFileSink *sink;
689   guint8 *mem_nums;
690   guint total_mems;
691   guint i, num_buffers;
692   gboolean sync_after = FALSE;
693
694   sink = GST_FILE_SINK_CAST (bsink);
695
696   num_buffers = gst_buffer_list_length (buffer_list);
697   if (num_buffers == 0)
698     goto no_data;
699
700   /* extract buffers from list and count memories */
701   buffers = g_newa (GstBuffer *, num_buffers);
702   mem_nums = g_newa (guint8, num_buffers);
703   for (i = 0, total_mems = 0; i < num_buffers; ++i) {
704     buffers[i] = gst_buffer_list_get (buffer_list, i);
705     mem_nums[i] = gst_buffer_n_memory (buffers[i]);
706     total_mems += mem_nums[i];
707     if (GST_BUFFER_FLAG_IS_SET (buffers[i], GST_BUFFER_FLAG_SYNC_AFTER))
708       sync_after = TRUE;
709   }
710
711   flow =
712       gst_file_sink_render_buffers (sink, buffers, num_buffers, mem_nums,
713       total_mems);
714
715   if (flow == GST_FLOW_OK && sync_after) {
716     if (fflush (sink->file) || fsync (fileno (sink->file))) {
717       GST_ELEMENT_ERROR (sink, RESOURCE, WRITE,
718           (_("Error while writing to file \"%s\"."), sink->filename),
719           ("%s", g_strerror (errno)));
720       flow = GST_FLOW_ERROR;
721     }
722   }
723
724   return flow;
725
726 no_data:
727   {
728     GST_LOG_OBJECT (sink, "empty buffer list");
729     return GST_FLOW_OK;
730   }
731 }
732
733 static GstFlowReturn
734 gst_file_sink_render (GstBaseSink * sink, GstBuffer * buffer)
735 {
736   GstFileSink *filesink;
737   GstFlowReturn flow;
738   guint8 n_mem;
739
740   filesink = GST_FILE_SINK_CAST (sink);
741
742   n_mem = gst_buffer_n_memory (buffer);
743
744   if (n_mem > 0)
745     flow = gst_file_sink_render_buffers (filesink, &buffer, 1, &n_mem, n_mem);
746   else
747     flow = GST_FLOW_OK;
748
749   if (flow == GST_FLOW_OK &&
750       GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_SYNC_AFTER)) {
751     if (fflush (filesink->file) || fsync (fileno (filesink->file))) {
752       GST_ELEMENT_ERROR (filesink, RESOURCE, WRITE,
753           (_("Error while writing to file \"%s\"."), filesink->filename),
754           ("%s", g_strerror (errno)));
755       flow = GST_FLOW_ERROR;
756     }
757   }
758
759   return flow;
760 }
761
762 static gboolean
763 gst_file_sink_start (GstBaseSink * basesink)
764 {
765   return gst_file_sink_open_file (GST_FILE_SINK (basesink));
766 }
767
768 static gboolean
769 gst_file_sink_stop (GstBaseSink * basesink)
770 {
771   gst_file_sink_close_file (GST_FILE_SINK (basesink));
772   return TRUE;
773 }
774
775 /*** GSTURIHANDLER INTERFACE *************************************************/
776
777 static GstURIType
778 gst_file_sink_uri_get_type (GType type)
779 {
780   return GST_URI_SINK;
781 }
782
783 static const gchar *const *
784 gst_file_sink_uri_get_protocols (GType type)
785 {
786   static const gchar *protocols[] = { "file", NULL };
787
788   return protocols;
789 }
790
791 static gchar *
792 gst_file_sink_uri_get_uri (GstURIHandler * handler)
793 {
794   GstFileSink *sink = GST_FILE_SINK (handler);
795
796   /* FIXME: make thread-safe */
797   return g_strdup (sink->uri);
798 }
799
800 static gboolean
801 gst_file_sink_uri_set_uri (GstURIHandler * handler, const gchar * uri,
802     GError ** error)
803 {
804   gchar *location;
805   gboolean ret;
806   GstFileSink *sink = GST_FILE_SINK (handler);
807
808   /* allow file://localhost/foo/bar by stripping localhost but fail
809    * for every other hostname */
810   if (g_str_has_prefix (uri, "file://localhost/")) {
811     char *tmp;
812
813     /* 16 == strlen ("file://localhost") */
814     tmp = g_strconcat ("file://", uri + 16, NULL);
815     /* we use gst_uri_get_location() although we already have the
816      * "location" with uri + 16 because it provides unescaping */
817     location = gst_uri_get_location (tmp);
818     g_free (tmp);
819   } else if (strcmp (uri, "file://") == 0) {
820     /* Special case for "file://" as this is used by some applications
821      *  to test with gst_element_make_from_uri if there's an element
822      *  that supports the URI protocol. */
823     gst_file_sink_set_location (sink, NULL, NULL);
824     return TRUE;
825   } else {
826     location = gst_uri_get_location (uri);
827   }
828
829   if (!location) {
830     g_set_error_literal (error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI,
831         "File URI without location");
832     return FALSE;
833   }
834
835   if (!g_path_is_absolute (location)) {
836     g_set_error_literal (error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI,
837         "File URI location must be an absolute path");
838     g_free (location);
839     return FALSE;
840   }
841
842   ret = gst_file_sink_set_location (sink, location, error);
843   g_free (location);
844
845   return ret;
846 }
847
848 static void
849 gst_file_sink_uri_handler_init (gpointer g_iface, gpointer iface_data)
850 {
851   GstURIHandlerInterface *iface = (GstURIHandlerInterface *) g_iface;
852
853   iface->get_type = gst_file_sink_uri_get_type;
854   iface->get_protocols = gst_file_sink_uri_get_protocols;
855   iface->get_uri = gst_file_sink_uri_get_uri;
856   iface->set_uri = gst_file_sink_uri_set_uri;
857 }