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