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