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