souphttpsrc: fix SCHEDULING query support
[platform/upstream/gstreamer.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 <sys/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    * Since: 0.10.7
209    **/
210   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_DEVICE_NAME,
211       g_param_spec_string ("device-name", "device name",
212           "user-friendly name of the device", "Default",
213           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
214
215   gstbasesrc_class->negotiate = NULL;
216   gstbasesrc_class->start = gst_dv1394src_start;
217   gstbasesrc_class->stop = gst_dv1394src_stop;
218   gstbasesrc_class->unlock = gst_dv1394src_unlock;
219   gstbasesrc_class->query = gst_dv1394src_query;
220
221   gstpushsrc_class->create = gst_dv1394src_create;
222
223   gst_element_class_add_pad_template (gstelement_class,
224       gst_static_pad_template_get (&src_factory));
225
226   gst_element_class_set_static_metadata (gstelement_class,
227       "Firewire (1394) DV video source", "Source/Video",
228       "Source for DV video data from firewire port",
229       "Erik Walthinsen <omega@temple-baptist.com>, "
230       "Daniel Fischer <dan@f3c.com>, " "Wim Taymans <wim@fluendo.com>, "
231       "Zaheer Abbas Merali <zaheerabbas at merali dot org>");
232
233   GST_DEBUG_CATEGORY_INIT (dv1394src_debug, "dv1394src", 0,
234       "DV firewire source");
235 }
236
237 static void
238 gst_dv1394src_init (GstDV1394Src * dv1394src)
239 {
240   GstPad *srcpad = GST_BASE_SRC_PAD (dv1394src);
241
242   gst_base_src_set_live (GST_BASE_SRC (dv1394src), TRUE);
243   gst_base_src_set_format (GST_BASE_SRC (dv1394src), GST_FORMAT_TIME);
244   gst_base_src_set_do_timestamp (GST_BASE_SRC (dv1394src), TRUE);
245   gst_pad_use_fixed_caps (srcpad);
246
247   dv1394src->port = DEFAULT_PORT;
248   dv1394src->channel = DEFAULT_CHANNEL;
249
250   dv1394src->consecutive = DEFAULT_CONSECUTIVE;
251   dv1394src->skip = DEFAULT_SKIP;
252   dv1394src->drop_incomplete = DEFAULT_DROP_INCOMPLETE;
253   dv1394src->use_avc = DEFAULT_USE_AVC;
254   dv1394src->guid = DEFAULT_GUID;
255   dv1394src->uri = g_strdup_printf ("dv://%d", dv1394src->port);
256   dv1394src->device_name = g_strdup_printf ("Default");
257
258   READ_SOCKET (dv1394src) = -1;
259   WRITE_SOCKET (dv1394src) = -1;
260
261   /* initialized when first header received */
262   dv1394src->frame_size = 0;
263
264   dv1394src->buf = NULL;
265   dv1394src->frame = NULL;
266   dv1394src->frame_sequence = 0;
267
268   dv1394src->provided_clock = gst_1394_clock_new ("dv1394clock");
269 }
270
271 static void
272 gst_dv1394src_dispose (GObject * object)
273 {
274   GstDV1394Src *src = GST_DV1394SRC (object);
275
276   if (src->provided_clock) {
277     g_object_unref (src->provided_clock);
278   }
279
280   g_free (src->uri);
281   src->uri = NULL;
282
283   g_free (src->device_name);
284   src->device_name = NULL;
285
286   G_OBJECT_CLASS (parent_class)->dispose (object);
287 }
288
289 static void
290 gst_dv1394src_set_property (GObject * object, guint prop_id,
291     const GValue * value, GParamSpec * pspec)
292 {
293   GstDV1394Src *filter = GST_DV1394SRC (object);
294
295   switch (prop_id) {
296     case PROP_PORT:
297       filter->port = g_value_get_int (value);
298       g_free (filter->uri);
299       filter->uri = g_strdup_printf ("dv://%d", filter->port);
300       break;
301     case PROP_CHANNEL:
302       filter->channel = g_value_get_int (value);
303       break;
304     case PROP_SKIP:
305       filter->skip = g_value_get_int (value);
306       break;
307     case PROP_CONSECUTIVE:
308       filter->consecutive = g_value_get_int (value);
309       break;
310     case PROP_DROP_INCOMPLETE:
311       filter->drop_incomplete = g_value_get_boolean (value);
312       break;
313     case PROP_USE_AVC:
314       filter->use_avc = g_value_get_boolean (value);
315       break;
316     case PROP_GUID:
317       filter->guid = g_value_get_uint64 (value);
318       gst_dv1394src_update_device_name (filter);
319       break;
320     default:
321       break;
322   }
323 }
324
325 static void
326 gst_dv1394src_get_property (GObject * object, guint prop_id, GValue * value,
327     GParamSpec * pspec)
328 {
329   GstDV1394Src *filter = GST_DV1394SRC (object);
330
331   switch (prop_id) {
332     case PROP_PORT:
333       g_value_set_int (value, filter->port);
334       break;
335     case PROP_CHANNEL:
336       g_value_set_int (value, filter->channel);
337       break;
338     case PROP_SKIP:
339       g_value_set_int (value, filter->skip);
340       break;
341     case PROP_CONSECUTIVE:
342       g_value_set_int (value, filter->consecutive);
343       break;
344     case PROP_DROP_INCOMPLETE:
345       g_value_set_boolean (value, filter->drop_incomplete);
346       break;
347     case PROP_USE_AVC:
348       g_value_set_boolean (value, filter->use_avc);
349       break;
350     case PROP_GUID:
351       g_value_set_uint64 (value, filter->guid);
352       break;
353     case PROP_DEVICE_NAME:
354       g_value_set_string (value, filter->device_name);
355       break;
356     default:
357       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
358       break;
359   }
360 }
361
362 static GstClock *
363 gst_dv1394src_provide_clock (GstElement * element)
364 {
365   GstDV1394Src *dv1394src = GST_DV1394SRC (element);
366
367   return GST_CLOCK_CAST (gst_object_ref (dv1394src->provided_clock));
368 }
369
370 static GstStateChangeReturn
371 gst_dv1394_src_change_state (GstElement * element, GstStateChange transition)
372 {
373   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
374   GstDV1394Src *src = GST_DV1394SRC (element);
375
376   switch (transition) {
377     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
378       gst_element_post_message (element,
379           gst_message_new_clock_lost (GST_OBJECT_CAST (element),
380               GST_CLOCK_CAST (src->provided_clock)));
381       break;
382     default:
383       break;
384   }
385
386   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
387   if (ret == GST_STATE_CHANGE_FAILURE)
388     return ret;
389
390   switch (transition) {
391     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
392       gst_element_post_message (element,
393           gst_message_new_clock_provide (GST_OBJECT_CAST (element),
394               GST_CLOCK_CAST (src->provided_clock), TRUE));
395       break;
396     default:
397       break;
398   }
399
400   return ret;
401 }
402
403 #ifdef HAVE_LIBIEC61883
404 static GstDV1394Src *
405 gst_dv1394src_from_raw1394handle (raw1394handle_t handle)
406 {
407   iec61883_dv_t dv = (iec61883_dv_t) raw1394_get_userdata (handle);
408   iec61883_dv_fb_t dv_fb =
409       (iec61883_dv_fb_t) iec61883_dv_get_callback_data (dv);
410   return GST_DV1394SRC (iec61883_dv_fb_get_callback_data (dv_fb));
411 }
412 #else /* HAVE_LIBIEC61883 */
413 static GstDV1394Src *
414 gst_dv1394src_from_raw1394handle (raw1394handle_t handle)
415 {
416   return GST_DV1394SRC (raw1394_get_userdata (handle));
417 }
418 #endif /* HAVE_LIBIEC61883 */
419
420 #ifdef HAVE_LIBIEC61883
421 static int
422 gst_dv1394src_iec61883_receive (unsigned char *data, int len,
423     int complete, void *cbdata)
424 {
425   GstDV1394Src *dv1394src = GST_DV1394SRC (cbdata);
426
427   if (G_UNLIKELY (!gst_pad_has_current_caps (GST_BASE_SRC_PAD (dv1394src)))) {
428     GstCaps *caps;
429     unsigned char *p = data;
430
431     // figure format (NTSC/PAL)
432     if (p[3] & 0x80) {
433       // PAL
434       dv1394src->frame_size = PAL_FRAMESIZE;
435       dv1394src->frame_rate = PAL_FRAMERATE;
436       GST_DEBUG ("PAL data");
437       caps = gst_caps_new_simple ("video/x-dv",
438           "format", G_TYPE_STRING, "PAL",
439           "systemstream", G_TYPE_BOOLEAN, TRUE, NULL);
440     } else {
441       // NTSC (untested)
442       dv1394src->frame_size = NTSC_FRAMESIZE;
443       dv1394src->frame_rate = NTSC_FRAMERATE;
444       GST_DEBUG
445           ("NTSC data [untested] - please report success/failure to <dan@f3c.com>");
446       caps = gst_caps_new_simple ("video/x-dv",
447           "format", G_TYPE_STRING, "NTSC",
448           "systemstream", G_TYPE_BOOLEAN, TRUE, NULL);
449     }
450     gst_pad_set_caps (GST_BASE_SRC_PAD (dv1394src), caps);
451     gst_caps_unref (caps);
452   }
453
454   dv1394src->frame = NULL;
455   if (G_LIKELY ((dv1394src->frame_sequence + 1) % (dv1394src->skip +
456               dv1394src->consecutive) < dv1394src->consecutive)) {
457     if (complete && len == dv1394src->frame_size) {
458       GstBuffer *buf;
459
460       buf = gst_buffer_new_and_alloc (dv1394src->frame_size);
461
462       GST_BUFFER_OFFSET (buf) = dv1394src->frame_sequence;
463       gst_buffer_fill (buf, 0, data, len);
464       dv1394src->buf = buf;
465     }
466   }
467   dv1394src->frame_sequence++;
468   return 0;
469 }
470
471 #else
472 static int
473 gst_dv1394src_iso_receive (raw1394handle_t handle, int channel, size_t len,
474     quadlet_t * data)
475 {
476   GstDV1394Src *dv1394src = gst_dv1394src_from_raw1394handle (handle);
477
478   if (len > 16) {
479     /*
480        the following code taken from kino-0.51 (Dan Dennedy/Charles Yates)
481        Kindly relicensed under the LGPL. See the commit log for version 1.6 of
482        this file in CVS.
483      */
484     unsigned char *p = (unsigned char *) &data[3];
485
486     int section_type = p[0] >> 5;       /* section type is in bits 5 - 7 */
487     int dif_sequence = p[1] >> 4;       /* dif sequence number is in bits 4 - 7 */
488     int dif_block = p[2];
489
490     /* if we are at the beginning of a frame, 
491        we set buf=frame, and alloc a new buffer for frame
492      */
493     if (section_type == 0 && dif_sequence == 0) {       // dif header
494       if (!GST_PAD_CAPS (GST_BASE_SRC_PAD (dv1394src))) {
495         GstCaps *caps;
496
497         // figure format (NTSC/PAL)
498         if (p[3] & 0x80) {
499           // PAL
500           dv1394src->frame_size = PAL_FRAMESIZE;
501           dv1394src->frame_rate = PAL_FRAMERATE;
502           GST_DEBUG ("PAL data");
503           caps = gst_caps_new_simple ("video/x-dv",
504               "format", G_TYPE_STRING, "PAL",
505               "systemstream", G_TYPE_BOOLEAN, TRUE, NULL);
506         } else {
507           // NTSC (untested)
508           dv1394src->frame_size = NTSC_FRAMESIZE;
509           dv1394src->frame_rate = NTSC_FRAMERATE;
510           GST_DEBUG
511               ("NTSC data [untested] - please report success/failure to <dan@f3c.com>");
512           caps = gst_caps_new_simple ("video/x-dv",
513               "format", G_TYPE_STRING, "NTSC",
514               "systemstream", G_TYPE_BOOLEAN, TRUE, NULL);
515         }
516         gst_pad_set_caps (GST_BASE_SRC_PAD (dv1394src), caps);
517         gst_caps_unref (caps);
518       }
519       // drop last frame when not complete
520       if (!dv1394src->drop_incomplete
521           || dv1394src->bytes_in_frame == dv1394src->frame_size) {
522         dv1394src->buf = dv1394src->frame;
523       } else {
524         GST_INFO_OBJECT (GST_ELEMENT (dv1394src), "incomplete frame dropped");
525         g_signal_emit (G_OBJECT (dv1394src),
526             gst_dv1394src_signals[SIGNAL_FRAME_DROPPED], 0);
527         if (dv1394src->frame) {
528           gst_buffer_unref (dv1394src->frame);
529         }
530       }
531       if ((dv1394src->frame_sequence + 1) % (dv1394src->skip +
532               dv1394src->consecutive) < dv1394src->consecutive) {
533         GstBuffer *buf;
534         gint64 i64;
535
536         buf = gst_buffer_new_and_alloc (dv1394src->frame_size);
537
538         /* fill in offset, duration, timestamp */
539         GST_BUFFER_OFFSET (buf) = dv1394src->frame_sequence;
540         dv1394src->frame = buf;
541       }
542       dv1394src->frame_sequence++;
543       dv1394src->bytes_in_frame = 0;
544     }
545
546     if (dv1394src->frame != NULL) {
547       guint8 *data = GST_BUFFER_DATA (dv1394src->frame);
548
549       switch (section_type) {
550         case 0:                /* 1 Header block */
551           /* p[3] |= 0x80; // hack to force PAL data */
552           memcpy (data + dif_sequence * 150 * 80, p, 480);
553           break;
554
555         case 1:                /* 2 Subcode blocks */
556           memcpy (data + dif_sequence * 150 * 80 + (1 + dif_block) * 80, p,
557               480);
558           break;
559
560         case 2:                /* 3 VAUX blocks */
561           memcpy (data + dif_sequence * 150 * 80 + (3 + dif_block) * 80, p,
562               480);
563           break;
564
565         case 3:                /* 9 Audio blocks interleaved with video */
566           memcpy (data + dif_sequence * 150 * 80 + (6 + dif_block * 16) * 80, p,
567               480);
568           break;
569
570         case 4:                /* 135 Video blocks interleaved with audio */
571           memcpy (data + dif_sequence * 150 * 80 + (7 + (dif_block / 15) +
572                   dif_block) * 80, p, 480);
573           break;
574
575         default:               /* we can't handle any other data */
576           break;
577       }
578       dv1394src->bytes_in_frame += 480;
579     }
580   }
581
582   return 0;
583 }
584 #endif
585 /*
586  * When an ieee1394 bus reset happens, usually a device has been removed
587  * or added.  We send a message on the message bus with the node count 
588  * and whether the capture device used in this element connected, disconnected 
589  * or was unchanged
590  * Message structure:
591  * nodecount - integer with number of nodes on bus
592  * current-device-change - integer (1 if device connected, 0 if no change to
593  *                         current device status, -1 if device disconnected)
594  */
595 static int
596 gst_dv1394src_bus_reset (raw1394handle_t handle, unsigned int generation)
597 {
598   GstDV1394Src *src;
599   gint nodecount;
600   GstMessage *message;
601   GstStructure *structure;
602   gint current_device_change;
603   gint i;
604
605   src = gst_dv1394src_from_raw1394handle (handle);
606
607   GST_INFO_OBJECT (src, "have bus reset");
608
609   /* update generation - told to do so by docs */
610   raw1394_update_generation (handle, generation);
611   nodecount = raw1394_get_nodecount (handle);
612   /* allocate memory for portinfo */
613
614   /* current_device_change is -1 if camera disconnected, 0 if other device
615    * connected or 1 if camera has now connected */
616   current_device_change = -1;
617   for (i = 0; i < nodecount; i++) {
618     if (src->guid == rom1394_get_guid (handle, i)) {
619       /* Camera is with us */
620       GST_DEBUG ("Camera is with us");
621       if (!src->connected) {
622         current_device_change = 1;
623         src->connected = TRUE;
624       } else
625         current_device_change = 0;
626     }
627   }
628   if (src->connected && current_device_change == -1) {
629     GST_DEBUG ("Camera has disconnected");
630     src->connected = FALSE;
631   } else if (!src->connected && current_device_change == -1) {
632     GST_DEBUG ("Camera is still not with us");
633     current_device_change = 0;
634   }
635
636   structure = gst_structure_new ("ieee1394-bus-reset", "nodecount", G_TYPE_INT,
637       nodecount, "current-device-change", G_TYPE_INT, current_device_change,
638       NULL);
639   message = gst_message_new_element (GST_OBJECT (src), structure);
640   gst_element_post_message (GST_ELEMENT (src), message);
641
642   return 0;
643 }
644
645 static GstFlowReturn
646 gst_dv1394src_create (GstPushSrc * psrc, GstBuffer ** buf)
647 {
648   GstDV1394Src *dv1394src = GST_DV1394SRC (psrc);
649   struct pollfd pollfds[2];
650
651   pollfds[0].fd = raw1394_get_fd (dv1394src->handle);
652   pollfds[0].events = POLLIN | POLLERR | POLLHUP | POLLPRI;
653   pollfds[1].fd = READ_SOCKET (dv1394src);
654   pollfds[1].events = POLLIN | POLLERR | POLLHUP | POLLPRI;
655
656   if (G_UNLIKELY (dv1394src->buf)) {
657     /* maybe we had an error before, and there's a stale buffer? */
658     gst_buffer_unref (dv1394src->buf);
659     dv1394src->buf = NULL;
660   }
661
662   while (TRUE) {
663     int res = poll (pollfds, 2, -1);
664
665     if (G_UNLIKELY (res < 0)) {
666       if (errno == EAGAIN || errno == EINTR)
667         continue;
668       else
669         goto error_while_polling;
670     }
671
672     if (G_UNLIKELY (pollfds[1].revents)) {
673       char command;
674
675       if (pollfds[1].revents & POLLIN)
676         READ_COMMAND (dv1394src, command, res);
677
678       goto told_to_stop;
679     } else if (G_LIKELY (pollfds[0].revents & POLLIN)) {
680       /* shouldn't block in theory */
681       raw1394_loop_iterate (dv1394src->handle);
682
683       if (dv1394src->buf)
684         break;
685     }
686   }
687
688   g_assert (dv1394src->buf);
689
690   *buf = dv1394src->buf;
691   dv1394src->buf = NULL;
692   return GST_FLOW_OK;
693
694 error_while_polling:
695   {
696     GST_ELEMENT_ERROR (dv1394src, RESOURCE, READ, (NULL), GST_ERROR_SYSTEM);
697     return GST_FLOW_EOS;
698   }
699 told_to_stop:
700   {
701     GST_DEBUG_OBJECT (dv1394src, "told to stop, shutting down");
702     return GST_FLOW_FLUSHING;
703   }
704 }
705
706 static int
707 gst_dv1394src_discover_avc_node (GstDV1394Src * src)
708 {
709   int node = -1;
710   int i, j = 0;
711   int m = src->num_ports;
712
713   if (src->port >= 0) {
714     /* search on explicit port */
715     j = src->port;
716     m = j + 1;
717   }
718
719   /* loop over all our ports */
720   for (; j < m && node == -1; j++) {
721     raw1394handle_t handle;
722     struct raw1394_portinfo pinf[16];
723
724     /* open the port */
725     handle = raw1394_new_handle ();
726     if (!handle) {
727       GST_WARNING ("raw1394 - failed to get handle: %s.\n", strerror (errno));
728       continue;
729     }
730     if (raw1394_get_port_info (handle, pinf, 16) < 0) {
731       GST_WARNING ("raw1394 - failed to get port info: %s.\n",
732           strerror (errno));
733       goto next;
734     }
735
736     /* tell raw1394 which host adapter to use */
737     if (raw1394_set_port (handle, j) < 0) {
738       GST_WARNING ("raw1394 - failed to set set port: %s.\n", strerror (errno));
739       goto next;
740     }
741
742     /* now loop over all the nodes */
743     for (i = 0; i < raw1394_get_nodecount (handle); i++) {
744       /* are we looking for an explicit GUID ? */
745       if (src->guid != 0) {
746         if (src->guid == rom1394_get_guid (handle, i)) {
747           node = i;
748           src->port = j;
749           g_free (src->uri);
750           src->uri = g_strdup_printf ("dv://%d", src->port);
751           break;
752         }
753       } else {
754         rom1394_directory rom_dir;
755
756         /* select first AV/C Tape Recorder Player node */
757         if (rom1394_get_directory (handle, i, &rom_dir) < 0) {
758           GST_WARNING ("error reading config rom directory for node %d\n", i);
759           continue;
760         }
761         if ((rom1394_get_node_type (&rom_dir) == ROM1394_NODE_TYPE_AVC) &&
762             avc1394_check_subunit_type (handle, i, AVC1394_SUBUNIT_TYPE_VCR)) {
763           node = i;
764           src->port = j;
765           src->guid = rom1394_get_guid (handle, i);
766           g_free (src->uri);
767           src->uri = g_strdup_printf ("dv://%d", src->port);
768           g_free (src->device_name);
769           src->device_name = g_strdup (rom_dir.label);
770           break;
771         }
772         rom1394_free_directory (&rom_dir);
773       }
774     }
775   next:
776     raw1394_destroy_handle (handle);
777   }
778   return node;
779 }
780
781 static gboolean
782 gst_dv1394src_start (GstBaseSrc * bsrc)
783 {
784   GstDV1394Src *src = GST_DV1394SRC (bsrc);
785   int control_sock[2];
786
787   src->connected = FALSE;
788
789   if (socketpair (PF_UNIX, SOCK_STREAM, 0, control_sock) < 0)
790     goto socket_pair;
791
792   READ_SOCKET (src) = control_sock[0];
793   WRITE_SOCKET (src) = control_sock[1];
794
795   fcntl (READ_SOCKET (src), F_SETFL, O_NONBLOCK);
796   fcntl (WRITE_SOCKET (src), F_SETFL, O_NONBLOCK);
797
798   src->handle = raw1394_new_handle ();
799
800   if (!src->handle) {
801     if (errno == EACCES)
802       goto permission_denied;
803     else if (errno == ENOENT)
804       goto not_found;
805     else
806       goto no_handle;
807   }
808
809   src->num_ports = raw1394_get_port_info (src->handle, src->pinfo, 16);
810
811   if (src->num_ports == 0)
812     goto no_ports;
813
814   if (src->use_avc || src->port == -1)
815     src->avc_node = gst_dv1394src_discover_avc_node (src);
816
817   /* lets destroy handle and create one on port
818      this is more reliable than setting port on
819      the existing handle */
820   raw1394_destroy_handle (src->handle);
821   src->handle = raw1394_new_handle_on_port (src->port);
822   if (!src->handle)
823     goto cannot_set_port;
824
825   raw1394_set_userdata (src->handle, src);
826   raw1394_set_bus_reset_handler (src->handle, gst_dv1394src_bus_reset);
827
828 #ifdef HAVE_LIBIEC61883
829   if ((src->iec61883dv =
830           iec61883_dv_fb_init (src->handle,
831               gst_dv1394src_iec61883_receive, src)) == NULL)
832     goto cannot_initialise_dv;
833
834 #else
835   raw1394_set_iso_handler (src->handle, src->channel,
836       gst_dv1394src_iso_receive);
837 #endif
838
839   GST_DEBUG_OBJECT (src, "successfully opened up 1394 connection");
840   src->connected = TRUE;
841
842 #ifdef HAVE_LIBIEC61883
843   if (iec61883_dv_fb_start (src->iec61883dv, src->channel) != 0)
844     goto cannot_start;
845 #else
846   if (raw1394_start_iso_rcv (src->handle, src->channel) < 0)
847     goto cannot_start;
848 #endif
849
850   if (src->use_avc) {
851     raw1394handle_t avc_handle = raw1394_new_handle_on_port (src->port);
852
853     /* start the VCR */
854     if (avc_handle) {
855       if (!avc1394_vcr_is_recording (avc_handle, src->avc_node)
856           && avc1394_vcr_is_playing (avc_handle, src->avc_node)
857           != AVC1394_VCR_OPERAND_PLAY_FORWARD)
858         avc1394_vcr_play (avc_handle, src->avc_node);
859       raw1394_destroy_handle (avc_handle);
860     } else {
861       GST_WARNING_OBJECT (src, "Starting VCR via avc1394 failed: %s",
862           g_strerror (errno));
863     }
864   }
865
866   gst_1394_clock_set_handle (src->provided_clock, src->handle);
867
868   return TRUE;
869
870 socket_pair:
871   {
872     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ_WRITE, (NULL),
873         GST_ERROR_SYSTEM);
874     return FALSE;
875   }
876 permission_denied:
877   {
878     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL), GST_ERROR_SYSTEM);
879     return FALSE;
880   }
881 not_found:
882   {
883     GST_ELEMENT_ERROR (src, RESOURCE, NOT_FOUND, (NULL), GST_ERROR_SYSTEM);
884     return FALSE;
885   }
886 no_handle:
887   {
888     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (NULL),
889         ("can't get raw1394 handle (%s)", g_strerror (errno)));
890     return FALSE;
891   }
892 no_ports:
893   {
894     raw1394_destroy_handle (src->handle);
895     src->handle = NULL;
896     GST_ELEMENT_ERROR (src, RESOURCE, NOT_FOUND, (NULL),
897         ("no ports available for raw1394"));
898     return FALSE;
899   }
900 cannot_set_port:
901   {
902     GST_ELEMENT_ERROR (src, RESOURCE, SETTINGS, (NULL),
903         ("can't set 1394 port %d", src->port));
904     return FALSE;
905   }
906 cannot_start:
907   {
908     raw1394_destroy_handle (src->handle);
909     src->handle = NULL;
910 #ifdef HAVE_LIBIEC61883
911     iec61883_dv_fb_close (src->iec61883dv);
912     src->iec61883dv = NULL;
913 #endif
914     GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
915         ("can't start 1394 iso receive"));
916     return FALSE;
917   }
918 #ifdef HAVE_LIBIEC61883
919 cannot_initialise_dv:
920   {
921     raw1394_destroy_handle (src->handle);
922     src->handle = NULL;
923     GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL),
924         ("can't initialise iec61883 dv"));
925     return FALSE;
926   }
927 #endif
928 }
929
930 static gboolean
931 gst_dv1394src_stop (GstBaseSrc * bsrc)
932 {
933   GstDV1394Src *src = GST_DV1394SRC (bsrc);
934
935   close (READ_SOCKET (src));
936   close (WRITE_SOCKET (src));
937   READ_SOCKET (src) = -1;
938   WRITE_SOCKET (src) = -1;
939 #ifdef HAVE_LIBIEC61883
940   iec61883_dv_fb_close (src->iec61883dv);
941 #else
942   raw1394_stop_iso_rcv (src->handle, src->channel);
943 #endif
944
945   if (src->use_avc) {
946     raw1394handle_t avc_handle = raw1394_new_handle_on_port (src->port);
947
948     /* pause and stop the VCR */
949     if (avc_handle) {
950       if (!avc1394_vcr_is_recording (avc_handle, src->avc_node)
951           && (avc1394_vcr_is_playing (avc_handle, src->avc_node)
952               != AVC1394_VCR_OPERAND_PLAY_FORWARD_PAUSE))
953         avc1394_vcr_pause (avc_handle, src->avc_node);
954       avc1394_vcr_stop (avc_handle, src->avc_node);
955       raw1394_destroy_handle (avc_handle);
956     } else {
957       GST_WARNING_OBJECT (src, "Starting VCR via avc1394 failed: %s",
958           g_strerror (errno));
959     }
960   }
961
962   gst_1394_clock_unset_handle (src->provided_clock);
963
964   raw1394_destroy_handle (src->handle);
965
966   return TRUE;
967 }
968
969 static gboolean
970 gst_dv1394src_unlock (GstBaseSrc * bsrc)
971 {
972   GstDV1394Src *src = GST_DV1394SRC (bsrc);
973
974   SEND_COMMAND (src, CONTROL_STOP);
975
976   return TRUE;
977 }
978
979 static gboolean
980 gst_dv1394src_query (GstBaseSrc * basesrc, GstQuery * query)
981 {
982   switch (GST_QUERY_TYPE (query)) {
983     case GST_QUERY_LATENCY:
984     {
985       gst_query_set_latency (query, TRUE, GST_SECOND / 25, GST_CLOCK_TIME_NONE);
986     }
987       break;
988     default:
989       goto not_supported;
990   }
991
992   return TRUE;
993
994 not_supported:
995   return GST_BASE_SRC_CLASS (parent_class)->query (basesrc, query);
996 }
997
998 static void
999 gst_dv1394src_update_device_name (GstDV1394Src * src)
1000 {
1001   raw1394handle_t handle;
1002   gint portcount, port, nodecount, node;
1003   rom1394_directory directory;
1004
1005   g_free (src->device_name);
1006   src->device_name = NULL;
1007
1008   GST_LOG_OBJECT (src, "updating device name for current GUID");
1009
1010   handle = raw1394_new_handle ();
1011
1012   if (handle == NULL)
1013     goto gethandle_failed;
1014
1015   portcount = raw1394_get_port_info (handle, NULL, 0);
1016   for (port = 0; port < portcount; port++) {
1017     if (raw1394_set_port (handle, port) >= 0) {
1018       nodecount = raw1394_get_nodecount (handle);
1019       for (node = 0; node < nodecount; node++) {
1020         if (src->guid == rom1394_get_guid (handle, node)) {
1021           if (rom1394_get_directory (handle, node, &directory) >= 0) {
1022             g_free (src->device_name);
1023             src->device_name = g_strdup (directory.label);
1024             rom1394_free_directory (&directory);
1025             goto done;
1026           } else {
1027             GST_WARNING ("error reading rom directory for node %d", node);
1028           }
1029         }
1030       }
1031     }
1032   }
1033
1034   src->device_name = g_strdup ("Unknown");      /* FIXME: translate? */
1035
1036 done:
1037
1038   raw1394_destroy_handle (handle);
1039   return;
1040
1041 /* ERRORS */
1042 gethandle_failed:
1043   {
1044     GST_WARNING ("failed to get raw1394 handle: %s", g_strerror (errno));
1045     src->device_name = g_strdup ("Unknown");    /* FIXME: translate? */
1046     return;
1047   }
1048 }
1049
1050 /*** GSTURIHANDLER INTERFACE *************************************************/
1051
1052 static GstURIType
1053 gst_dv1394src_uri_get_type (GType type)
1054 {
1055   return GST_URI_SRC;
1056 }
1057
1058 static const gchar *const *
1059 gst_dv1394src_uri_get_protocols (GType type)
1060 {
1061   static const gchar *protocols[] = { (char *) "dv", NULL };
1062
1063   return protocols;
1064 }
1065
1066 static gchar *
1067 gst_dv1394src_uri_get_uri (GstURIHandler * handler)
1068 {
1069   GstDV1394Src *gst_dv1394src = GST_DV1394SRC (handler);
1070
1071   return gst_dv1394src->uri;
1072 }
1073
1074 static gboolean
1075 gst_dv1394src_uri_set_uri (GstURIHandler * handler, const gchar * uri,
1076     GError ** error)
1077 {
1078   gchar *protocol, *location;
1079   gboolean ret = TRUE;
1080   GstDV1394Src *gst_dv1394src = GST_DV1394SRC (handler);
1081
1082   protocol = gst_uri_get_protocol (uri);
1083   if (strcmp (protocol, "dv") != 0) {
1084     g_free (protocol);
1085     g_set_error (error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI, "Invalid DV URI");
1086     return FALSE;
1087   }
1088   g_free (protocol);
1089
1090   location = gst_uri_get_location (uri);
1091   if (location && *location != '\0')
1092     gst_dv1394src->port = strtol (location, NULL, 10);
1093   else
1094     gst_dv1394src->port = DEFAULT_PORT;
1095   g_free (location);
1096   g_free (gst_dv1394src->uri);
1097   gst_dv1394src->uri = g_strdup_printf ("dv://%d", gst_dv1394src->port);
1098
1099   return ret;
1100 }
1101
1102 static void
1103 gst_dv1394src_uri_handler_init (gpointer g_iface, gpointer iface_data)
1104 {
1105   GstURIHandlerInterface *iface = (GstURIHandlerInterface *) g_iface;
1106
1107   iface->get_type = gst_dv1394src_uri_get_type;
1108   iface->get_protocols = gst_dv1394src_uri_get_protocols;
1109   iface->get_uri = gst_dv1394src_uri_get_uri;
1110   iface->set_uri = gst_dv1394src_uri_set_uri;
1111 }