]> git.sesse.net Git - kdenlive/blob - src/jogshuttle.cpp
optimize jogshuttle code
[kdenlive] / src / jogshuttle.cpp
1 /***************************************************************************
2  *   Copyright (C) 2008 by Jean-Baptiste Mardelle (jb@kdenlive.org)        *
3  *   Based on code by Arendt David <admin@prnet.org>                       *
4  *                                                                         *
5  *   This program is free software; you can redistribute it and/or modify  *
6  *   it under the terms of the GNU General Public License as published by  *
7  *   the Free Software Foundation; either version 2 of the License, or     *
8  *   (at your option) any later version.                                   *
9  *                                                                         *
10  *   This program is distributed in the hope that it will be useful,       *
11  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
12  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
13  *   GNU General Public License for more details.                          *
14  *                                                                         *
15  *   You should have received a copy of the GNU General Public License     *
16  *   along with this program; if not, write to the                         *
17  *   Free Software Foundation, Inc.,                                       *
18  *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA          *
19  ***************************************************************************/
20
21
22 #include "jogshuttle.h"
23
24 #include <KDebug>
25 #include <kde_file.h>
26
27 #include <QApplication>
28 #include <QEvent>
29
30 #include <stdlib.h>
31 #include <stdio.h>
32 #include <unistd.h>
33 #include <fcntl.h>
34 #include <errno.h>
35 #include <string.h>
36 #include <linux/input.h>
37 #include <signal.h>
38
39 #define DELAY 10
40
41 #define KEY 1
42 #define KEY1 256
43 #define KEY2 257
44 #define KEY3 258
45 #define KEY4 259
46 #define KEY5 260
47 #define KEY6 261
48 #define KEY7 262
49 #define KEY8 263
50 #define KEY9 264
51 #define KEY10 265
52 #define KEY11 266
53 #define KEY12 267
54 #define KEY13 268
55 #define KEY14 269
56 #define KEY15 270
57
58 // Constants for the returned events when reading them from the device
59 #define JOGSHUTTLE 2
60 #define JOG 7
61 #define SHUTTLE 8
62
63 // Constants for the signals sent.
64 #define JOG_BACK1 10001
65 #define JOG_FWD1 10002
66 #define KEY_EVENT_OFFSET 20000
67
68 // middle value for shuttle, will be +/-MAX_SHUTTLE_RANGE
69 #define JOG_STOP 10020
70 #define MAX_SHUTTLE_RANGE 7
71
72 void ShuttleThread::init(QObject *parent, QString device)
73 {
74     m_parent = parent;
75     m_device = device;
76     stop_me = false;
77     m_isWorking = false;
78     shuttlevalue = 0xffff;
79     shuttlecounter = 0;
80     jogvalue = 0xffff;
81 }
82
83 bool ShuttleThread::isWorking()
84 {
85     return m_isWorking;
86 }
87
88 void catcher(int sig)
89 {
90    printf("   Signal catcher called for signal %d\n", sig);
91 }
92
93 void ShuttleThread::run()
94 {
95         kDebug() << "-------  STARTING SHUTTLE: " << m_device;
96         /* open file descriptor */
97         const int fd = KDE_open((char *) m_device.toUtf8().data(), O_RDONLY);
98         if (fd < 0) {
99                 perror("Can't open Jog Shuttle FILE DESCRIPTOR");
100                 return;
101         }
102
103         EV ev;
104
105         if (ioctl(fd, EVIOCGRAB, 1) < 0) {
106                 fprintf(stderr, "Can't get exclusive access on  Jog Shuttle FILE DESCRIPTOR\n");
107                 close(fd);
108                 return;
109         }
110
111         fd_set             readset;
112         struct timeval timeout;
113
114         int num_warnings, readResult = 0;
115         int result, iof = -1;
116
117         /* get fd settings */
118         if ((iof = fcntl(fd, F_GETFL, 0)) != -1) {
119                 /* set fd non blocking */
120                 fcntl(fd, F_SETFL, iof | O_NONBLOCK);
121         } else {
122                 fprintf(stderr, "Can't set Jog Shuttle FILE DESCRIPTOR to O_NONBLOCK and stop thread\n");
123                 return;
124         }
125
126         /* enter thread loop */
127         while (!stop_me) {
128                 /* reset the read set */
129                 FD_ZERO(&readset);
130                 FD_SET(fd, &readset);
131
132                 /* reinit the timeout structure */
133                 timeout.tv_sec  = 0;
134                 timeout.tv_usec = 400000; /* 400 ms */
135
136                 /* do select in blocked mode and wake up after timeout for eval stop_me */
137                 result = select(fd+1, &readset, NULL, NULL, &timeout);
138
139                 /* see if there was an error or timeout else process event */
140                 if (result < 0 && errno == EINTR) {
141                         /* EINTR event catched. This is not a problem - continue processing */
142                         kDebug() << strerror(errno) << "\n";
143                         /* continue processing */
144                         continue;
145                 } else if (result < 0) {
146                         /* stop thread */
147                         stop_me = true;
148                         kDebug() << strerror(errno) << "\n";
149                 } else if (result == 0) {
150                         /* do nothing. reserved for future purposes */
151                 } else {
152                         /* we have input */
153                         if (FD_ISSET(fd, &readset)) {
154                                 /* read input */
155                                 readResult = read(fd, &ev, sizeof(ev));
156                                 if (readResult < 0) {
157                                         if (num_warnings % 10000 == 0) {
158                                                 /* if device is not available anymore - dead or disconnected */
159                                                 fprintf(stderr, "Failed to read event from Jog Shuttle FILE DESCRIPTOR (repeated %d times)\n", num_warnings + 1);
160                                         }
161                                         /* exit if device is not available or the error occurs to long */
162                                         if (errno == ENODEV) {
163                                                 perror("Failed to read from Jog Shuttle FILE DESCRIPTOR. Stop thread");
164                                                 /* stop thread */
165                                                 stop_me = true;
166                                         } else if (num_warnings > 1000000) {
167                                                 perror("Failed to read from Jog Shuttle FILE DESCRIPTOR. Limit reached. Stop thread");
168                                                 /* stop thread */
169                                                 stop_me = true;
170                                         }
171                                         num_warnings++;
172                                 } else if (readResult == sizeof(ev)) {
173                                         /* process event */
174                                         handle_event(ev);
175                                 } else {
176                                         fprintf(stderr, "Read nr of bytes != sizeof(ev)\n");
177                                 }
178                         }
179                 }
180         }
181
182 //      kDebug() << "Close thread" << "\n";
183         /* close the handle and return thread */
184         close(fd);
185 }
186
187 void ShuttleThread::handle_event(EV ev)
188 {
189     switch (ev.type) {
190     case KEY :
191         key(ev.code, ev.value);
192         break;
193     case JOGSHUTTLE :
194         if (ev.code == JOG)
195             jog(ev.value);
196         if (ev.code == SHUTTLE)
197             shuttle(ev.value);
198         break;
199     }
200 }
201
202 void ShuttleThread::key(unsigned short code, unsigned int value)
203 {
204     if (value == 0) {
205         // Button release (ignored)
206         return;
207     }
208
209     // Check key index
210     code -= KEY1 - 1;
211     if (code > 16)
212         return;
213
214     //kDebug() << "Button PRESSED: " << code;
215     QApplication::postEvent(m_parent, new QEvent((QEvent::Type)(KEY_EVENT_OFFSET + code)));
216
217 }
218
219 void ShuttleThread::shuttle(int value)
220 {
221     //gettimeofday( &last_shuttle, 0 );
222     //need_synthetic_shuttle = value != 0;
223
224     if (value == shuttlevalue) {
225         shuttlecounter = 1;
226         return;
227     }
228
229     if (value > MAX_SHUTTLE_RANGE || value < -MAX_SHUTTLE_RANGE) {
230         fprintf(stderr, "Jog Shuttle returned value of %d (should be between -%d ad +%d)", value, MAX_SHUTTLE_RANGE, MAX_SHUTTLE_RANGE);
231         return;
232     }
233     shuttlevalue = value;
234     shuttlecounter = 1;
235     QApplication::postEvent(m_parent, new QEvent((QEvent::Type) (JOG_STOP + value)));
236 }
237
238 void ShuttleThread::jog(unsigned int value)
239 {
240     // generate a synthetic event for the shuttle going
241     // to the home position if we have not seen one recently.
242     //if (shuttlevalue != 0) {
243     //  QApplication::postEvent(m_parent, new QEvent((QEvent::Type) JOG_STOP));
244     //  shuttlevalue = 0;
245     //}
246
247     // This code takes care of wrapping around the limits of the jog dial number (it is represented as a single byte, hence
248     // wraps at the 0/255 boundary). I used 25 as the difference to make sure that even in heavy load, with the jog dial
249     // turning fast and we miss some events that we do not mistakenly reverse the direction.
250     // Note also that at least the Contour ShuttlePRO v2 does not send an event for the value 0, so at the wrap it will
251     // need 2 events to go forward. But that is nothing we can do about...
252     if (jogvalue != 0xffff) {
253         //fprintf(stderr, "value=%d jogvalue=%d\n", value, jogvalue);
254         bool wrap = abs(value - jogvalue) > 25;
255         bool rewind = value < jogvalue;
256         bool forward = value > jogvalue;
257         if ((rewind && !wrap) || (forward && wrap))
258             QApplication::postEvent(m_parent, new QEvent((QEvent::Type) JOG_BACK1));
259         else if ((forward && !wrap) || (rewind && wrap))
260             QApplication::postEvent(m_parent, new QEvent((QEvent::Type) JOG_FWD1));
261         else if (!forward && !rewind && shuttlecounter > 2) {
262             // An event without changing the jog value is sent after each shuttle change.
263             // As the shuttle rest position does not get a shuttle event, only a non-position-changing jog event.
264             // Hence we stop on this when we see 2 non-position-changing jog events in a row.
265             shuttlecounter = 0;
266             QApplication::postEvent(m_parent, new QEvent((QEvent::Type) JOG_STOP));
267         }
268     }
269     jogvalue = value;
270     if (shuttlecounter > 0) shuttlecounter++;
271 }
272
273
274 JogShuttle::JogShuttle(QString device, QObject *parent) :
275         QObject(parent)
276 {
277     initDevice(device);
278 }
279
280 JogShuttle::~JogShuttle()
281 {
282         stopDevice();
283 }
284
285 void JogShuttle::initDevice(QString device)
286 {
287     if (m_shuttleProcess.isRunning()) {
288         if (device == m_shuttleProcess.m_device) return;
289         stopDevice();
290     }
291     m_shuttleProcess.init(this, device);
292     m_shuttleProcess.start(QThread::LowestPriority);
293 }
294
295 void JogShuttle::stopDevice()
296 {
297     if (m_shuttleProcess.isRunning()) {
298         /* tell thread to stop */
299         m_shuttleProcess.stop_me = true;
300         m_shuttleProcess.exit();
301         /* give the thread some time (ms) to shutdown */
302         m_shuttleProcess.wait(600);
303
304         /* if still running - do it in the hardcore way */
305         if (m_shuttleProcess.isRunning()) {
306                 m_shuttleProcess.terminate();
307             kDebug() << "/// terminate jogshuttle process\n";
308         }
309     }
310 }
311
312 void JogShuttle::customEvent(QEvent* e)
313 {
314     int code = e->type();
315
316     // Handle simple job events
317     switch (code) {
318     case JOG_BACK1:
319         emit jogBack();
320         return;
321     case JOG_FWD1:
322         emit jogForward();
323         return;
324     }
325
326     int shuttle_pos = code - JOG_STOP;
327     if (shuttle_pos >= -MAX_SHUTTLE_RANGE && shuttle_pos <= MAX_SHUTTLE_RANGE) {
328         emit shuttlePos(shuttle_pos);
329         return;
330     }
331
332     // we've got a key event.
333     //fprintf(stderr, "Firing button event for #%d\n", e->type() - KEY_EVENT_OFFSET); // DBG
334     emit button(e->type() - KEY_EVENT_OFFSET);
335 }
336
337
338
339 // #include "jogshuttle.moc"
340