v4l2bufferpool: Free orphaned allocator resources when buffers are released
[platform/upstream/gst-plugins-good.git] / ext / raw1394 / gstdv1394src.c
1 /* GStreamer
2  * Copyright (C) <1999> Erik Walthinsen <omega@cse.ogi.edu>
3  *               <2000> Daniel Fischer <dan@f3c.com>
4  *               <2004> Wim Taymans <wim@fluendo.com>
5  *               <2006> Zaheer Abbas Merali <zaheerabbas at merali dot org>
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Library General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Library General Public License for more details.
16  *
17  * You should have received a copy of the GNU Library General Public
18  * License along with this library; if not, write to the
19  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
20  * Boston, MA 02110-1301, USA.
21  */
22 /**
23  * SECTION:element-dv1394src
24  *
25  * Read DV (digital video) data from firewire port.
26  *
27  * <refsect2>
28  * <title>Example launch line</title>
29  * |[
30  * gst-launch-1.0 dv1394src ! queue ! dvdemux name=d ! queue ! dvdec ! xvimagesink d. ! queue ! alsasink
31  * ]| This pipeline captures from the firewire port and displays it (might need
32  * format converters for audio/video).
33  * </refsect2>
34  */
35
36 #ifdef HAVE_CONFIG_H
37 #include "config.h"
38 #endif
39 #include <unistd.h>
40 #include <poll.h>
41 #include <sys/socket.h>
42 #include <errno.h>
43 #include <fcntl.h>
44 #include <string.h>
45 #include <stdlib.h>
46
47 #include <libavc1394/avc1394.h>
48 #include <libavc1394/avc1394_vcr.h>
49 #include <libavc1394/rom1394.h>
50 #include <libraw1394/raw1394.h>
51 #ifdef HAVE_LIBIEC61883
52 #include <libiec61883/iec61883.h>
53 #endif
54
55 #include <gst/gst.h>
56
57 #include "gstdv1394src.h"
58 #include "gst1394probe.h"
59 #include "gst1394clock.h"
60
61
62 #define CONTROL_STOP            'S'     /* stop the select call */
63 #define CONTROL_SOCKETS(src)   src->control_sock
64 #define WRITE_SOCKET(src)      src->control_sock[1]
65 #define READ_SOCKET(src)       src->control_sock[0]
66
67 #define SEND_COMMAND(src, command)          \
68 G_STMT_START {                              \
69   int G_GNUC_UNUSED _res; unsigned char c; c = command;   \
70   _res = write (WRITE_SOCKET(src), &c, 1);  \
71 } G_STMT_END
72
73 #define READ_COMMAND(src, command, res)        \
74 G_STMT_START {                                 \
75   res = read(READ_SOCKET(src), &command, 1);   \
76 } G_STMT_END
77
78
79 GST_DEBUG_CATEGORY_STATIC (dv1394src_debug);
80 #define GST_CAT_DEFAULT (dv1394src_debug)
81
82 #define PAL_FRAMESIZE 144000
83 #define PAL_FRAMERATE 25
84
85 #define NTSC_FRAMESIZE 120000
86 #define NTSC_FRAMERATE 30
87
88 enum
89 {
90   SIGNAL_FRAME_DROPPED,
91   /* FILL ME */
92   LAST_SIGNAL
93 };
94
95 #define DEFAULT_PORT    -1
96 #define DEFAULT_CHANNEL   63
97 #define DEFAULT_CONSECUTIVE 1
98 #define DEFAULT_SKIP    0
99 #define DEFAULT_DROP_INCOMPLETE TRUE
100 #define DEFAULT_USE_AVC   TRUE
101 #define DEFAULT_GUID    0
102
103 enum
104 {
105   PROP_0,
106   PROP_PORT,
107   PROP_CHANNEL,
108   PROP_CONSECUTIVE,
109   PROP_SKIP,
110   PROP_DROP_INCOMPLETE,
111   PROP_USE_AVC,
112   PROP_GUID,
113   PROP_DEVICE_NAME
114 };
115
116 static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
117     GST_PAD_SRC,
118     GST_PAD_ALWAYS,
119     GST_STATIC_CAPS ("video/x-dv, "
120         "format = (string) { NTSC, PAL }, " "systemstream = (boolean) true")
121     );
122
123 static void gst_dv1394src_uri_handler_init (gpointer g_iface,
124     gpointer iface_data);
125
126 static void gst_dv1394src_set_property (GObject * object, guint prop_id,
127     const GValue * value, GParamSpec * pspec);
128 static void gst_dv1394src_get_property (GObject * object, guint prop_id,
129     GValue * value, GParamSpec * pspec);
130 static void gst_dv1394src_dispose (GObject * object);
131
132 static GstClock *gst_dv1394src_provide_clock (GstElement * element);
133 static GstStateChangeReturn gst_dv1394_src_change_state (GstElement * element,
134     GstStateChange transition);
135
136 static gboolean gst_dv1394src_start (GstBaseSrc * bsrc);
137 static gboolean gst_dv1394src_stop (GstBaseSrc * bsrc);
138 static gboolean gst_dv1394src_unlock (GstBaseSrc * bsrc);
139
140 static GstFlowReturn gst_dv1394src_create (GstPushSrc * psrc, GstBuffer ** buf);
141
142 static gboolean gst_dv1394src_query (GstBaseSrc * src, GstQuery * query);
143 static void gst_dv1394src_update_device_name (GstDV1394Src * src);
144
145 #define gst_dv1394src_parent_class parent_class
146 G_DEFINE_TYPE_WITH_CODE (GstDV1394Src, gst_dv1394src, GST_TYPE_PUSH_SRC,
147     G_IMPLEMENT_INTERFACE (GST_TYPE_URI_HANDLER,
148         gst_dv1394src_uri_handler_init));
149
150 static guint gst_dv1394src_signals[LAST_SIGNAL] = { 0 };
151
152 static void
153 gst_dv1394src_class_init (GstDV1394SrcClass * klass)
154 {
155   GObjectClass *gobject_class;
156   GstElementClass *gstelement_class;
157   GstBaseSrcClass *gstbasesrc_class;
158   GstPushSrcClass *gstpushsrc_class;
159
160   gobject_class = (GObjectClass *) klass;
161   gstelement_class = (GstElementClass *) klass;
162   gstbasesrc_class = (GstBaseSrcClass *) klass;
163   gstpushsrc_class = (GstPushSrcClass *) klass;
164
165   gobject_class->set_property = gst_dv1394src_set_property;
166   gobject_class->get_property = gst_dv1394src_get_property;
167   gobject_class->dispose = gst_dv1394src_dispose;
168
169   gstelement_class->provide_clock = gst_dv1394src_provide_clock;
170   gstelement_class->change_state = gst_dv1394_src_change_state;
171
172   gst_dv1394src_signals[SIGNAL_FRAME_DROPPED] =
173       g_signal_new ("frame-dropped", G_TYPE_FROM_CLASS (klass),
174       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstDV1394SrcClass, frame_dropped),
175       NULL, NULL, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);
176
177   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_PORT,
178       g_param_spec_int ("port", "Port", "Port number (-1 automatic)",
179           -1, 16, DEFAULT_PORT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
180   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_CHANNEL,
181       g_param_spec_int ("channel", "Channel", "Channel number for listening",
182           0, 64, DEFAULT_CHANNEL, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
183   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_CONSECUTIVE,
184       g_param_spec_int ("consecutive", "consecutive frames",
185           "send n consecutive frames after skipping", 1, G_MAXINT,
186           DEFAULT_CONSECUTIVE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
187   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_SKIP,
188       g_param_spec_int ("skip", "skip frames", "skip n frames",
189           0, G_MAXINT, DEFAULT_SKIP,
190           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
191   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_DROP_INCOMPLETE,
192       g_param_spec_boolean ("drop-incomplete", "drop incomplete",
193           "drop incomplete frames", DEFAULT_DROP_INCOMPLETE,
194           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
195   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_USE_AVC,
196       g_param_spec_boolean ("use-avc", "Use AV/C", "Use AV/C VTR control",
197           DEFAULT_USE_AVC, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
198   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_GUID,
199       g_param_spec_uint64 ("guid", "GUID",
200           "select one of multiple DV devices by its GUID. use a hexadecimal "
201           "like 0xhhhhhhhhhhhhhhhh. (0 = no guid)", 0, G_MAXUINT64,
202           DEFAULT_GUID, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
203   /**
204    * GstDV1394Src:device-name:
205    *
206    * Descriptive name of the currently opened device
207    */
208   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_DEVICE_NAME,
209       g_param_spec_string ("device-name", "device name",
210           "user-friendly name of the device", "Default",
211           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
212
213   gstbasesrc_class->negotiate = NULL;
214   gstbasesrc_class->start = gst_dv1394src_start;
215   gstbasesrc_class->stop = gst_dv1394src_stop;
216   gstbasesrc_class->unlock = gst_dv1394src_unlock;
217   gstbasesrc_class->query = gst_dv1394src_query;
218
219   gstpushsrc_class->create = gst_dv1394src_create;
220
221   gst_element_class_add_static_pad_template (gstelement_class, &src_factory);
222
223   gst_element_class_set_static_metadata (gstelement_class,
224       "Firewire (1394) DV video source", "Source/Video",
225       "Source for DV video data from firewire port",
226       "Erik Walthinsen <omega@temple-baptist.com>, "
227       "Daniel Fischer <dan@f3c.com>, " "Wim Taymans <wim@fluendo.com>, "
228       "Zaheer Abbas Merali <zaheerabbas at merali dot org>");
229
230   GST_DEBUG_CATEGORY_INIT (dv1394src_debug, "dv1394src", 0,
231       "DV firewire source");
232 }
233
234 static void
235 gst_dv1394src_init (GstDV1394Src * dv1394src)
236 {
237   GstPad *srcpad = GST_BASE_SRC_PAD (dv1394src);
238
239   gst_base_src_set_live (GST_BASE_SRC (dv1394src), TRUE);
240   gst_base_src_set_format (GST_BASE_SRC (dv1394src), GST_FORMAT_TIME);
241   gst_base_src_set_do_timestamp (GST_BASE_SRC (dv1394src), TRUE);
242   gst_pad_use_fixed_caps (srcpad);
243
244   dv1394src->port = DEFAULT_PORT;
245   dv1394src->channel = DEFAULT_CHANNEL;
246
247   dv1394src->consecutive = DEFAULT_CONSECUTIVE;
248   dv1394src->skip = DEFAULT_SKIP;
249   dv1394src->drop_incomplete = DEFAULT_DROP_INCOMPLETE;
250   dv1394src->use_avc = DEFAULT_USE_AVC;
251   dv1394src->guid = DEFAULT_GUID;
252   dv1394src->uri = g_strdup_printf ("dv://%d", dv1394src->port);
253   dv1394src->device_name = g_strdup_printf ("Default");
254
255   READ_SOCKET (dv1394src) = -1;
256   WRITE_SOCKET (dv1394src) = -1;
257
258   /* initialized when first header received */
259   dv1394src->frame_size = 0;
260
261   dv1394src->buf = NULL;
262   dv1394src->frame = NULL;
263   dv1394src->frame_sequence = 0;
264
265   dv1394src->provided_clock = gst_1394_clock_new ("dv1394clock");
266 }
267
268 static void
269 gst_dv1394src_dispose (GObject * object)
270 {
271   GstDV1394Src *src = GST_DV1394SRC (object);
272
273   if (src->provided_clock) {
274     g_object_unref (src->provided_clock);
275   }
276
277   g_free (src->uri);
278   src->uri = NULL;
279
280   g_free (src->device_name);
281   src->device_name = NULL;
282
283   G_OBJECT_CLASS (parent_class)->dispose (object);
284 }
285
286 static void
287 gst_dv1394src_set_property (GObject * object, guint prop_id,
288     const GValue * value, GParamSpec * pspec)
289 {
290   GstDV1394Src *filter = GST_DV1394SRC (object);
291
292   switch (prop_id) {
293     case PROP_PORT:
294       filter->port = g_value_get_int (value);
295       g_free (filter->uri);
296       filter->uri = g_strdup_printf ("dv://%d", filter->port);
297       break;
298     case PROP_CHANNEL:
299       filter->channel = g_value_get_int (value);
300       break;
301     case PROP_SKIP:
302       filter->skip = g_value_get_int (value);
303       break;
304     case PROP_CONSECUTIVE:
305       filter->consecutive = g_value_get_int (value);
306       break;
307     case PROP_DROP_INCOMPLETE:
308       filter->drop_incomplete = g_value_get_boolean (value);
309       break;
310     case PROP_USE_AVC:
311       filter->use_avc = g_value_get_boolean (value);
312       break;
313     case PROP_GUID:
314       filter->guid = g_value_get_uint64 (value);
315       gst_dv1394src_update_device_name (filter);
316       break;
317     default:
318       break;
319   }
320 }
321
322 static void
323 gst_dv1394src_get_property (GObject * object, guint prop_id, GValue * value,
324     GParamSpec * pspec)
325 {
326   GstDV1394Src *filter = GST_DV1394SRC (object);
327
328   switch (prop_id) {
329     case PROP_PORT:
330       g_value_set_int (value, filter->port);
331       break;
332     case PROP_CHANNEL:
333       g_value_set_int (value, filter->channel);
334       break;
335     case PROP_SKIP:
336       g_value_set_int (value, filter->skip);
337       break;
338     case PROP_CONSECUTIVE:
339       g_value_set_int (value, filter->consecutive);
340       break;
341     case PROP_DROP_INCOMPLETE:
342       g_value_set_boolean (value, filter->drop_incomplete);
343       break;
344     case PROP_USE_AVC:
345       g_value_set_boolean (value, filter->use_avc);
346       break;
347     case PROP_GUID:
348       g_value_set_uint64 (value, filter->guid);
349       break;
350     case PROP_DEVICE_NAME:
351       g_value_set_string (value, filter->device_name);
352       break;
353     default:
354       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
355       break;
356   }
357 }
358
359 static GstClock *
360 gst_dv1394src_provide_clock (GstElement * element)
361 {
362   GstDV1394Src *dv1394src = GST_DV1394SRC (element);
363
364   return GST_CLOCK_CAST (gst_object_ref (dv1394src->provided_clock));
365 }
366
367 static GstStateChangeReturn
368 gst_dv1394_src_change_state (GstElement * element, GstStateChange transition)
369 {
370   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
371   GstDV1394Src *src = GST_DV1394SRC (element);
372
373   switch (transition) {
374     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
375       gst_element_post_message (element,
376           gst_message_new_clock_lost (GST_OBJECT_CAST (element),
377               GST_CLOCK_CAST (src->provided_clock)));
378       break;
379     default:
380       break;
381   }
382
383   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
384   if (ret == GST_STATE_CHANGE_FAILURE)
385     return ret;
386
387   switch (transition) {
388     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
389       gst_element_post_message (element,
390           gst_message_new_clock_provide (GST_OBJECT_CAST (element),
391               GST_CLOCK_CAST (src->provided_clock), TRUE));
392       break;
393     default:
394       break;
395   }
396
397   return ret;
398 }
399
400 #ifdef HAVE_LIBIEC61883
401 static GstDV1394Src *
402 gst_dv1394src_from_raw1394handle (raw1394handle_t handle)
403 {
404   iec61883_dv_t dv = (iec61883_dv_t) raw1394_get_userdata (handle);
405   iec61883_dv_fb_t dv_fb =
406       (iec61883_dv_fb_t) iec61883_dv_get_callback_data (dv);
407   return GST_DV1394SRC (iec61883_dv_fb_get_callback_data (dv_fb));
408 }
409 #else /* HAVE_LIBIEC61883 */
410 static GstDV1394Src *
411 gst_dv1394src_from_raw1394handle (raw1394handle_t handle)
412 {
413   return GST_DV1394SRC (raw1394_get_userdata (handle));
414 }
415 #endif /* HAVE_LIBIEC61883 */
416
417 #ifdef HAVE_LIBIEC61883
418 static int
419 gst_dv1394src_iec61883_receive (unsigned char *data, int len,
420     int complete, void *cbdata)
421 {
422   GstDV1394Src *dv1394src = GST_DV1394SRC (cbdata);
423
424   if (G_UNLIKELY (!gst_pad_has_current_caps (GST_BASE_SRC_PAD (dv1394src)))) {
425     GstCaps *caps;
426     unsigned char *p = data;
427
428     // figure format (NTSC/PAL)
429     if (p[3] & 0x80) {
430       // PAL
431       dv1394src->frame_size = PAL_FRAMESIZE;
432       dv1394src->frame_rate = PAL_FRAMERATE;
433       GST_DEBUG ("PAL data");
434       caps = gst_caps_new_simple ("video/x-dv",
435           "format", G_TYPE_STRING, "PAL",
436           "systemstream", G_TYPE_BOOLEAN, TRUE, NULL);
437     } else {
438       // NTSC (untested)
439       dv1394src->frame_size = NTSC_FRAMESIZE;
440       dv1394src->frame_rate = NTSC_FRAMERATE;
441       GST_DEBUG
442           ("NTSC data [untested] - please report success/failure to <dan@f3c.com>");
443       caps = gst_caps_new_simple ("video/x-dv",
444           "format", G_TYPE_STRING, "NTSC",
445           "systemstream", G_TYPE_BOOLEAN, TRUE, NULL);
446     }
447     gst_pad_set_caps (GST_BASE_SRC_PAD (dv1394src), caps);
448     gst_caps_unref (caps);
449   }
450
451   dv1394src->frame = NULL;
452   if (G_LIKELY ((dv1394src->frame_sequence + 1) % (dv1394src->skip +
453               dv1394src->consecutive) < dv1394src->consecutive)) {
454     if (complete && len == dv1394src->frame_size) {
455       GstBuffer *buf;
456
457       buf = gst_buffer_new_and_alloc (dv1394src->frame_size);
458
459       GST_BUFFER_OFFSET (buf) = dv1394src->frame_sequence;
460       gst_buffer_fill (buf, 0, data, len);
461       dv1394src->buf = buf;
462     }
463   }
464   dv1394src->frame_sequence++;
465   return 0;
466 }
467
468 #else
469 static int
470 gst_dv1394src_iso_receive (raw1394handle_t handle, int channel, size_t len,
471     quadlet_t * data)
472 {
473   GstDV1394Src *dv1394src = gst_dv1394src_from_raw1394handle (handle);
474
475   if (len > 16) {
476     /*
477        the following code taken from kino-0.51 (Dan Dennedy/Charles Yates)
478        Kindly relicensed under the LGPL. See the commit log for version 1.6 of
479        this file in CVS.
480      */
481     unsigned char *p = (unsigned char *) &data[3];
482
483     int section_type = p[0] >> 5;       /* section type is in bits 5 - 7 */
484     int dif_sequence = p[1] >> 4;       /* dif sequence number is in bits 4 - 7 */
485     int dif_block = p[2];
486
487     /* if we are at the beginning of a frame, 
488        we set buf=frame, and alloc a new buffer for frame
489      */
490     if (section_type == 0 && dif_sequence == 0) {       // dif header
491       if (!GST_PAD_CAPS (GST_BASE_SRC_PAD (dv1394src))) {
492         GstCaps *caps;
493
494         // figure format (NTSC/PAL)
495         if (p[3] & 0x80) {
496           // PAL
497           dv1394src->frame_size = PAL_FRAMESIZE;
498           dv1394src->frame_rate = PAL_FRAMERATE;
499           GST_DEBUG ("PAL data");
500           caps = gst_caps_new_simple ("video/x-dv",
501               "format", G_TYPE_STRING, "PAL",
502               "systemstream", G_TYPE_BOOLEAN, TRUE, NULL);
503         } else {
504           // NTSC (untested)
505           dv1394src->frame_size = NTSC_FRAMESIZE;
506           dv1394src->frame_rate = NTSC_FRAMERATE;
507           GST_DEBUG
508               ("NTSC data [untested] - please report success/failure to <dan@f3c.com>");
509           caps = gst_caps_new_simple ("video/x-dv",
510               "format", G_TYPE_STRING, "NTSC",
511               "systemstream", G_TYPE_BOOLEAN, TRUE, NULL);
512         }
513         gst_pad_set_caps (GST_BASE_SRC_PAD (dv1394src), caps);
514         gst_caps_unref (caps);
515       }
516       // drop last frame when not complete
517       if (!dv1394src->drop_incomplete
518           || dv1394src->bytes_in_frame == dv1394src->frame_size) {
519         dv1394src->buf = dv1394src->frame;
520       } else {
521         GST_INFO_OBJECT (GST_ELEMENT (dv1394src), "incomplete frame dropped");
522         g_signal_emit (G_OBJECT (dv1394src),
523             gst_dv1394src_signals[SIGNAL_FRAME_DROPPED], 0);
524         if (dv1394src->frame) {
525           gst_buffer_unref (dv1394src->frame);
526         }
527       }
528       if ((dv1394src->frame_sequence + 1) % (dv1394src->skip +
529               dv1394src->consecutive) < dv1394src->consecutive) {
530         GstBuffer *buf;
531         gint64 i64;
532
533         buf = gst_buffer_new_and_alloc (dv1394src->frame_size);
534
535         /* fill in offset, duration, timestamp */
536         GST_BUFFER_OFFSET (buf) = dv1394src->frame_sequence;
537         dv1394src->frame = buf;
538       }
539       dv1394src->frame_sequence++;
540       dv1394src->bytes_in_frame = 0;
541     }
542
543     if (dv1394src->frame != NULL) {
544       guint8 *data = GST_BUFFER_DATA (dv1394src->frame);
545
546       switch (section_type) {
547         case 0:                /* 1 Header block */
548           /* p[3] |= 0x80; // hack to force PAL data */
549           memcpy (data + dif_sequence * 150 * 80, p, 480);
550           break;
551
552         case 1:                /* 2 Subcode blocks */
553           memcpy (data + dif_sequence * 150 * 80 + (1 + dif_block) * 80, p,
554               480);
555           break;
556
557         case 2:                /* 3 VAUX blocks */
558           memcpy (data + dif_sequence * 150 * 80 + (3 + dif_block) * 80, p,
559               480);
560           break;
561
562         case 3:                /* 9 Audio blocks interleaved with video */
563           memcpy (data + dif_sequence * 150 * 80 + (6 + dif_block * 16) * 80, p,
564               480);
565           break;
566
567         case 4:                /* 135 Video blocks interleaved with audio */
568           memcpy (data + dif_sequence * 150 * 80 + (7 + (dif_block / 15) +
569                   dif_block) * 80, p, 480);
570           break;
571
572         default:               /* we can't handle any other data */
573           break;
574       }
575       dv1394src->bytes_in_frame += 480;
576     }
577   }
578
579   return 0;
580 }
581 #endif
582 /*
583  * When an ieee1394 bus reset happens, usually a device has been removed
584  * or added.  We send a message on the message bus with the node count 
585  * and whether the capture device used in this element connected, disconnected 
586  * or was unchanged
587  * Message structure:
588  * nodecount - integer with number of nodes on bus
589  * current-device-change - integer (1 if device connected, 0 if no change to
590  *                         current device status, -1 if device disconnected)
591  */
592 static int
593 gst_dv1394src_bus_reset (raw1394handle_t handle, unsigned int generation)
594 {
595   GstDV1394Src *src;
596   gint nodecount;
597   GstMessage *message;
598   GstStructure *structure;
599   gint current_device_change;
600   gint i;
601
602   src = gst_dv1394src_from_raw1394handle (handle);
603
604   GST_INFO_OBJECT (src, "have bus reset");
605
606   /* update generation - told to do so by docs */
607   raw1394_update_generation (handle, generation);
608   nodecount = raw1394_get_nodecount (handle);
609   /* allocate memory for portinfo */
610
611   /* current_device_change is -1 if camera disconnected, 0 if other device
612    * connected or 1 if camera has now connected */
613   current_device_change = -1;
614   for (i = 0; i < nodecount; i++) {
615     if (src->guid == rom1394_get_guid (handle, i)) {
616       /* Camera is with us */
617       GST_DEBUG ("Camera is with us");
618       if (!src->connected) {
619         current_device_change = 1;
620         src->connected = TRUE;
621       } else
622         current_device_change = 0;
623     }
624   }
625   if (src->connected && current_device_change == -1) {
626     GST_DEBUG ("Camera has disconnected");
627     src->connected = FALSE;
628   } else if (!src->connected && current_device_change == -1) {
629     GST_DEBUG ("Camera is still not with us");
630     current_device_change = 0;
631   }
632
633   structure = gst_structure_new ("ieee1394-bus-reset", "nodecount", G_TYPE_INT,
634       nodecount, "current-device-change", G_TYPE_INT, current_device_change,
635       NULL);
636   message = gst_message_new_element (GST_OBJECT (src), structure);
637   gst_element_post_message (GST_ELEMENT (src), message);
638
639   return 0;
640 }
641
642 static GstFlowReturn
643 gst_dv1394src_create (GstPushSrc * psrc, GstBuffer ** buf)
644 {
645   GstDV1394Src *dv1394src = GST_DV1394SRC (psrc);
646   struct pollfd pollfds[2];
647
648   pollfds[0].fd = raw1394_get_fd (dv1394src->handle);
649   pollfds[0].events = POLLIN | POLLERR | POLLHUP | POLLPRI;
650   pollfds[1].fd = READ_SOCKET (dv1394src);
651   pollfds[1].events = POLLIN | POLLERR | POLLHUP | POLLPRI;
652
653   if (G_UNLIKELY (dv1394src->buf)) {
654     /* maybe we had an error before, and there's a stale buffer? */
655     gst_buffer_unref (dv1394src->buf);
656     dv1394src->buf = NULL;
657   }
658
659   while (TRUE) {
660     int res = poll (pollfds, 2, -1);
661
662     if (G_UNLIKELY (res < 0)) {
663       if (errno == EAGAIN || errno == EINTR)
664         continue;
665       else
666         goto error_while_polling;
667     }
668
669     if (G_UNLIKELY (pollfds[1].revents)) {
670       char command;
671
672       if (pollfds[1].revents & POLLIN)
673         READ_COMMAND (dv1394src, command, res);
674
675       goto told_to_stop;
676     } else if (G_LIKELY (pollfds[0].revents & POLLIN)) {
677       /* shouldn't block in theory */
678       raw1394_loop_iterate (dv1394src->handle);
679
680       if (dv1394src->buf)
681         break;
682     }
683   }
684
685   g_assert (dv1394src->buf);
686
687   *buf = dv1394src->buf;
688   dv1394src->buf = NULL;
689   return GST_FLOW_OK;
690
691 error_while_polling:
692   {
693     GST_ELEMENT_ERROR (dv1394src, RESOURCE, READ, (NULL), GST_ERROR_SYSTEM);
694     return GST_FLOW_EOS;
695   }
696 told_to_stop:
697   {
698     GST_DEBUG_OBJECT (dv1394src, "told to stop, shutting down");
699     return GST_FLOW_FLUSHING;
700   }
701 }
702
703 static int
704 gst_dv1394src_discover_avc_node (GstDV1394Src * src)
705 {
706   int node = -1;
707   int i, j = 0;
708   int m = src->num_ports;
709
710   if (src->port >= 0) {
711     /* search on explicit port */
712     j = src->port;
713     m = j + 1;
714   }
715
716   /* loop over all our ports */
717   for (; j < m && node == -1; j++) {
718     raw1394handle_t handle;
719     struct raw1394_portinfo pinf[16];
720
721     /* open the port */
722     handle = raw1394_new_handle ();
723     if (!handle) {
724       GST_WARNING ("raw1394 - failed to get handle: %s.\n", strerror (errno));
725       continue;
726     }
727     if (raw1394_get_port_info (handle, pinf, 16) < 0) {
728       GST_WARNING ("raw1394 - failed to get port info: %s.\n",
729           strerror (errno));
730       goto next;
731     }
732
733     /* tell raw1394 which host adapter to use */
734     if (raw1394_set_port (handle, j) < 0) {
735       GST_WARNING ("raw1394 - failed to set set port: %s.\n", strerror (errno));
736       goto next;
737     }
738
739     /* now loop over all the nodes */
740     for (i = 0; i < raw1394_get_nodecount (handle); i++) {
741       /* are we looking for an explicit GUID ? */
742       if (src->guid != 0) {
743         if (src->guid == rom1394_get_guid (handle, i)) {
744           node = i;
745           src->port = j;
746           g_free (src->uri);
747           src->uri = g_strdup_printf ("dv://%d", src->port);
748           break;
749         }
750       } else {
751         rom1394_directory rom_dir;
752
753         /* select first AV/C Tape Recorder Player node */
754         if (rom1394_get_directory (handle, i, &rom_dir) < 0) {
755           GST_WARNING ("error reading config rom directory for node %d\n", i);
756           continue;
757         }
758         if ((rom1394_get_node_type (&rom_dir) == ROM1394_NODE_TYPE_AVC) &&
759             avc1394_check_subunit_type (handle, i, AVC1394_SUBUNIT_TYPE_VCR)) {
760           node = i;
761           src->port = j;
762           src->guid = rom1394_get_guid (handle, i);
763           g_free (src->uri);
764           src->uri = g_strdup_printf ("dv://%d", src->port);
765           g_free (src->device_name);
766           src->device_name = g_strdup (rom_dir.label);
767           break;
768         }
769         rom1394_free_directory (&rom_dir);
770       }
771     }
772   next:
773     raw1394_destroy_handle (handle);
774   }
775   return node;
776 }
777
778 static gboolean
779 gst_dv1394src_start (GstBaseSrc * bsrc)
780 {
781   GstDV1394Src *src = GST_DV1394SRC (bsrc);
782   int control_sock[2];
783
784   src->connected = FALSE;
785
786   if (socketpair (PF_UNIX, SOCK_STREAM, 0, control_sock) < 0)
787     goto socket_pair;
788
789   READ_SOCKET (src) = control_sock[0];
790   WRITE_SOCKET (src) = control_sock[1];
791
792   if (fcntl (READ_SOCKET (src), F_SETFL, O_NONBLOCK) < 0)
793     GST_ERROR_OBJECT (src, "failed to make read socket non-blocking: %s",
794         g_strerror (errno));
795   if (fcntl (WRITE_SOCKET (src), F_SETFL, O_NONBLOCK) < 0)
796     GST_ERROR_OBJECT (src, "failed to make write socket non-blocking: %s",
797         g_strerror (errno));
798
799   src->handle = raw1394_new_handle ();
800
801   if (!src->handle) {
802     if (errno == EACCES)
803       goto permission_denied;
804     else if (errno == ENOENT)
805       goto not_found;
806     else
807       goto no_handle;
808   }
809
810   src->num_ports = raw1394_get_port_info (src->handle, src->pinfo, 16);
811
812   if (src->num_ports == 0)
813     goto no_ports;
814
815   if (src->use_avc || src->port == -1)
816     src->avc_node = gst_dv1394src_discover_avc_node (src);
817
818   /* lets destroy handle and create one on port
819      this is more reliable than setting port on
820      the existing handle */
821   raw1394_destroy_handle (src->handle);
822   src->handle = raw1394_new_handle_on_port (src->port);
823   if (!src->handle)
824     goto cannot_set_port;
825
826   raw1394_set_userdata (src->handle, src);
827   raw1394_set_bus_reset_handler (src->handle, gst_dv1394src_bus_reset);
828
829 #ifdef HAVE_LIBIEC61883
830   if ((src->iec61883dv =
831           iec61883_dv_fb_init (src->handle,
832               gst_dv1394src_iec61883_receive, src)) == NULL)
833     goto cannot_initialise_dv;
834
835 #else
836   raw1394_set_iso_handler (src->handle, src->channel,
837       gst_dv1394src_iso_receive);
838 #endif
839
840   GST_DEBUG_OBJECT (src, "successfully opened up 1394 connection");
841   src->connected = TRUE;
842
843 #ifdef HAVE_LIBIEC61883
844   if (iec61883_dv_fb_start (src->iec61883dv, src->channel) != 0)
845     goto cannot_start;
846 #else
847   if (raw1394_start_iso_rcv (src->handle, src->channel) < 0)
848     goto cannot_start;
849 #endif
850
851   if (src->use_avc) {
852     raw1394handle_t avc_handle = raw1394_new_handle_on_port (src->port);
853
854     /* start the VCR */
855     if (avc_handle) {
856       if (!avc1394_vcr_is_recording (avc_handle, src->avc_node)
857           && avc1394_vcr_is_playing (avc_handle, src->avc_node)
858           != AVC1394_VCR_OPERAND_PLAY_FORWARD)
859         avc1394_vcr_play (avc_handle, src->avc_node);
860       raw1394_destroy_handle (avc_handle);
861     } else {
862       GST_WARNING_OBJECT (src, "Starting VCR via avc1394 failed: %s",
863           g_strerror (errno));
864     }
865   }
866
867   gst_1394_clock_set_handle (src->provided_clock, src->handle);
868
869   return TRUE;
870
871 socket_pair:
872   {
873     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ_WRITE, (NULL),
874         GST_ERROR_SYSTEM);
875     return FALSE;
876   }
877 permission_denied:
878   {
879     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL), GST_ERROR_SYSTEM);
880     return FALSE;
881   }
882 not_found:
883   {
884     GST_ELEMENT_ERROR (src, RESOURCE, NOT_FOUND, (NULL), GST_ERROR_SYSTEM);
885     return FALSE;
886   }
887 no_handle:
888   {
889     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
890         ("can't get raw1394 handle (%s)", g_strerror (errno)));
891     return FALSE;
892   }
893 no_ports:
894   {
895     raw1394_destroy_handle (src->handle);
896     src->handle = NULL;
897     GST_ELEMENT_ERROR (src, RESOURCE, NOT_FOUND, (NULL),
898         ("no ports available for raw1394"));
899     return FALSE;
900   }
901 cannot_set_port:
902   {
903     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
904         ("can't set 1394 port %d", src->port));
905     return FALSE;
906   }
907 cannot_start:
908   {
909     raw1394_destroy_handle (src->handle);
910     src->handle = NULL;
911 #ifdef HAVE_LIBIEC61883
912     iec61883_dv_fb_close (src->iec61883dv);
913     src->iec61883dv = NULL;
914 #endif
915     GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
916         ("can't start 1394 iso receive"));
917     return FALSE;
918   }
919 #ifdef HAVE_LIBIEC61883
920 cannot_initialise_dv:
921   {
922     raw1394_destroy_handle (src->handle);
923     src->handle = NULL;
924     GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
925         ("can't initialise iec61883 dv"));
926     return FALSE;
927   }
928 #endif
929 }
930
931 static gboolean
932 gst_dv1394src_stop (GstBaseSrc * bsrc)
933 {
934   GstDV1394Src *src = GST_DV1394SRC (bsrc);
935
936   close (READ_SOCKET (src));
937   close (WRITE_SOCKET (src));
938   READ_SOCKET (src) = -1;
939   WRITE_SOCKET (src) = -1;
940 #ifdef HAVE_LIBIEC61883
941   iec61883_dv_fb_close (src->iec61883dv);
942 #else
943   raw1394_stop_iso_rcv (src->handle, src->channel);
944 #endif
945
946   if (src->use_avc) {
947     raw1394handle_t avc_handle = raw1394_new_handle_on_port (src->port);
948
949     /* pause and stop the VCR */
950     if (avc_handle) {
951       if (!avc1394_vcr_is_recording (avc_handle, src->avc_node)
952           && (avc1394_vcr_is_playing (avc_handle, src->avc_node)
953               != AVC1394_VCR_OPERAND_PLAY_FORWARD_PAUSE))
954         avc1394_vcr_pause (avc_handle, src->avc_node);
955       avc1394_vcr_stop (avc_handle, src->avc_node);
956       raw1394_destroy_handle (avc_handle);
957     } else {
958       GST_WARNING_OBJECT (src, "Starting VCR via avc1394 failed: %s",
959           g_strerror (errno));
960     }
961   }
962
963   gst_1394_clock_unset_handle (src->provided_clock);
964
965   raw1394_destroy_handle (src->handle);
966
967   return TRUE;
968 }
969
970 static gboolean
971 gst_dv1394src_unlock (GstBaseSrc * bsrc)
972 {
973   GstDV1394Src *src = GST_DV1394SRC (bsrc);
974
975   SEND_COMMAND (src, CONTROL_STOP);
976
977   return TRUE;
978 }
979
980 static gboolean
981 gst_dv1394src_query (GstBaseSrc * basesrc, GstQuery * query)
982 {
983   switch (GST_QUERY_TYPE (query)) {
984     case GST_QUERY_LATENCY:
985     {
986       gst_query_set_latency (query, TRUE, GST_SECOND / 25, GST_SECOND / 25);
987     }
988       break;
989     default:
990       goto not_supported;
991   }
992
993   return TRUE;
994
995 not_supported:
996   return GST_BASE_SRC_CLASS (parent_class)->query (basesrc, query);
997 }
998
999 static void
1000 gst_dv1394src_update_device_name (GstDV1394Src * src)
1001 {
1002   raw1394handle_t handle;
1003   gint portcount, port, nodecount, node;
1004   rom1394_directory directory;
1005
1006   g_free (src->device_name);
1007   src->device_name = NULL;
1008
1009   GST_LOG_OBJECT (src, "updating device name for current GUID");
1010
1011   handle = raw1394_new_handle ();
1012
1013   if (handle == NULL)
1014     goto gethandle_failed;
1015
1016   portcount = raw1394_get_port_info (handle, NULL, 0);
1017   for (port = 0; port < portcount; port++) {
1018     if (raw1394_set_port (handle, port) >= 0) {
1019       nodecount = raw1394_get_nodecount (handle);
1020       for (node = 0; node < nodecount; node++) {
1021         if (src->guid == rom1394_get_guid (handle, node)) {
1022           if (rom1394_get_directory (handle, node, &directory) >= 0) {
1023             g_free (src->device_name);
1024             src->device_name = g_strdup (directory.label);
1025             rom1394_free_directory (&directory);
1026             goto done;
1027           } else {
1028             GST_WARNING ("error reading rom directory for node %d", node);
1029           }
1030         }
1031       }
1032     }
1033   }
1034
1035   src->device_name = g_strdup ("Unknown");      /* FIXME: translate? */
1036
1037 done:
1038
1039   raw1394_destroy_handle (handle);
1040   return;
1041
1042 /* ERRORS */
1043 gethandle_failed:
1044   {
1045     GST_WARNING ("failed to get raw1394 handle: %s", g_strerror (errno));
1046     src->device_name = g_strdup ("Unknown");    /* FIXME: translate? */
1047     return;
1048   }
1049 }
1050
1051 /*** GSTURIHANDLER INTERFACE *************************************************/
1052
1053 static GstURIType
1054 gst_dv1394src_uri_get_type (GType type)
1055 {
1056   return GST_URI_SRC;
1057 }
1058
1059 static const gchar *const *
1060 gst_dv1394src_uri_get_protocols (GType type)
1061 {
1062   static const gchar *protocols[] = { (char *) "dv", NULL };
1063
1064   return protocols;
1065 }
1066
1067 static gchar *
1068 gst_dv1394src_uri_get_uri (GstURIHandler * handler)
1069 {
1070   GstDV1394Src *gst_dv1394src = GST_DV1394SRC (handler);
1071
1072   return gst_dv1394src->uri;
1073 }
1074
1075 static gboolean
1076 gst_dv1394src_uri_set_uri (GstURIHandler * handler, const gchar * uri,
1077     GError ** error)
1078 {
1079   gchar *protocol, *location;
1080   gboolean ret = TRUE;
1081   GstDV1394Src *gst_dv1394src = GST_DV1394SRC (handler);
1082
1083   protocol = gst_uri_get_protocol (uri);
1084   if (strcmp (protocol, "dv") != 0) {
1085     g_free (protocol);
1086     g_set_error (error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI, "Invalid DV URI");
1087     return FALSE;
1088   }
1089   g_free (protocol);
1090
1091   location = gst_uri_get_location (uri);
1092   if (location && *location != '\0')
1093     gst_dv1394src->port = strtol (location, NULL, 10);
1094   else
1095     gst_dv1394src->port = DEFAULT_PORT;
1096   g_free (location);
1097   g_free (gst_dv1394src->uri);
1098   gst_dv1394src->uri = g_strdup_printf ("dv://%d", gst_dv1394src->port);
1099
1100   return ret;
1101 }
1102
1103 static void
1104 gst_dv1394src_uri_handler_init (gpointer g_iface, gpointer iface_data)
1105 {
1106   GstURIHandlerInterface *iface = (GstURIHandlerInterface *) g_iface;
1107
1108   iface->get_type = gst_dv1394src_uri_get_type;
1109   iface->get_protocols = gst_dv1394src_uri_get_protocols;
1110   iface->get_uri = gst_dv1394src_uri_get_uri;
1111   iface->set_uri = gst_dv1394src_uri_set_uri;
1112 }