]> git.sesse.net Git - kdenlive/blob - src/jogshuttle.cpp
jogshuttle: enumerate devices using mediactrl
[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 #include <QDir>
30
31 #include <stdlib.h>
32 #include <stdio.h>
33 #include <unistd.h>
34 #include <fcntl.h>
35 #include <errno.h>
36 #include <string.h>
37 #include <linux/input.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, const 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 ShuttleThread::run()
89 {
90         kDebug() << "-------  STARTING SHUTTLE: " << m_device;
91         struct media_ctrl mc;
92     media_ctrl_open2(&mc, m_device.toUtf8().data());
93
94     /* open file descriptor */
95         //const int fd = KDE_open((char *) m_device.toUtf8().data(), O_RDONLY);
96         if (mc.fd < 0) {
97                 perror("Can't open Jog Shuttle FILE DESCRIPTOR");
98                 return;
99         }
100
101         EV ev[64];
102 #if 0
103         if (ioctl(fd, EVIOCGRAB, 1) < 0) {
104                 fprintf(stderr, "Can't get exclusive access on  Jog Shuttle FILE DESCRIPTOR\n");
105                 close(fd);
106                 return;
107         }
108 #endif
109
110         fd_set             readset;
111         struct timeval timeout;
112
113         int num_warnings = 0, readResult = 0;
114         int result, iof = -1;
115 #if 0
116         /* get fd settings */
117     if ((iof = fcntl(fd, F_GETFL, 0)) == -1) {
118         fprintf(stderr, "Can't get Jog Shuttle file status\n");
119         close(fd);
120         return;
121     }
122 #endif
123 #if 0
124     else if (fcntl(fd, F_SETFL, iof | O_NONBLOCK) == -1) {
125         fprintf(stderr, "Can't set Jog Shuttle FILE DESCRIPTOR to O_NONBLOCK and stop thread\n");
126         close(fd);
127         return;
128     }
129 #endif
130     struct media_ctrl_event mev;
131
132         /* enter thread loop */
133         while (!stop_me) {
134                 /* reset the read set */
135                 FD_ZERO(&readset);
136                 FD_SET(mc.fd, &readset);
137
138                 /* reinit the timeout structure */
139                 timeout.tv_sec  = 0;
140                 timeout.tv_usec = 400000; /* 400 ms */
141
142                 /* do select in blocked mode and wake up after timeout for eval stop_me */
143                 result = select(mc.fd+1, &readset, NULL, NULL, &timeout);
144
145                 /* see if there was an error or timeout else process event */
146                 if (result < 0 && errno == EINTR) {
147                         /* EINTR event catched. This is not a problem - continue processing */
148                         kDebug() << strerror(errno) << "\n";
149                         /* continue processing */
150                         continue;
151                 } else if (result < 0) {
152                         /* stop thread */
153                         stop_me = true;
154                         kDebug() << strerror(errno) << "\n";
155                 } else if (result == 0) {
156                         /* do nothing. reserved for future purposes */
157                 } else {
158                         /* we have input */
159                         if (FD_ISSET(mc.fd, &readset)) {
160                                 /* read input */
161                             mev.type = MEDIA_CTRL_EVENT_NONE;
162                                 //readResult = read(fd, ev, sizeof(EV) * 64);
163                                 media_ctrl_read_event(&mc, &mev);
164                 /* process event */
165                 handle_event(mev);
166 #if 0
167                                 if (readResult < 0) {
168                                         if (num_warnings % 10000 == 0) {
169                                                 /* if device is not available anymore - dead or disconnected */
170                                                 fprintf(stderr, "Failed to read event from Jog Shuttle FILE DESCRIPTOR (repeated %d times)\n", num_warnings + 1);
171                                         }
172                                         /* exit if device is not available or the error occurs to long */
173                                         if (errno == ENODEV) {
174                                                 perror("Failed to read from Jog Shuttle FILE DESCRIPTOR. Stop thread");
175                                                 /* stop thread */
176                                                 stop_me = true;
177                                         } else if (num_warnings > 1000000) {
178                                                 perror("Failed to read from Jog Shuttle FILE DESCRIPTOR. Limit reached. Stop thread");
179                                                 /* stop thread */
180                                                 stop_me = true;
181                                         }
182                                         num_warnings++;
183                                 } else if (readResult < (int)sizeof(EV)) {
184                                         fprintf(stderr, "readResult < (int)sizeof(EV)\n");
185                                         /* stop thread */
186                                         stop_me = true;
187                                 } else if (readResult % (int)sizeof(EV) != 0) {
188                                         fprintf(stderr, "readResult mod (int)sizeof(EV) != 0\n");
189                                         /* stop thread */
190                                         stop_me = true;
191                                 } else {
192                                         for (int i = 0; i < readResult / (int)sizeof(EV); i++) {
193                                                 /* process event */
194                                                 handle_event(ev[i]);
195                                         }
196                                 }
197 #endif
198                         }
199                 }
200         }
201
202     kDebug() << "-------  STOPPING SHUTTLE: ";
203         /* close the handle and return thread */
204         //close(fd);
205     media_ctrl_close(&mc);
206 }
207
208 void ShuttleThread::handle_event(struct media_ctrl_event ev)
209 {
210     if (ev.type == MEDIA_CTRL_EVENT_KEY)
211         key(ev);
212     else if (ev.type == MEDIA_CTRL_EVENT_JOG)
213         jog(ev);
214     else if (ev.type == MEDIA_CTRL_EVENT_SHUTTLE)
215         shuttle(ev);
216 }
217
218 void ShuttleThread::handle_event(EV ev)
219 {
220     switch (ev.type) {
221     case KEY :
222         key(ev.code, ev.value);
223         break;
224     case JOGSHUTTLE :
225         if (ev.code == JOG)
226             jog(ev.value);
227         if (ev.code == SHUTTLE)
228             shuttle(ev.value);
229         break;
230     }
231 }
232
233 void ShuttleThread::key(struct media_ctrl_event ev)
234 {
235     if (ev.value == KEY_PRESS) {
236         int code = ev.index + 1;
237         QApplication::postEvent(m_parent, new QEvent((QEvent::Type)(KEY_EVENT_OFFSET + code)));
238     }
239 }
240
241 void ShuttleThread::key(unsigned short code, unsigned int value)
242 {
243     if (value == 0) {
244         // Button release (ignored)
245         return;
246     }
247
248     // Check key index
249     code -= KEY1 - 1;
250     if (code > 16)
251         return;
252
253     //kDebug() << "Button PRESSED: " << code;
254     QApplication::postEvent(m_parent, new QEvent((QEvent::Type)(KEY_EVENT_OFFSET + code)));
255
256 }
257
258 void ShuttleThread::shuttle(struct media_ctrl_event ev)
259 {
260     QApplication::postEvent(m_parent, new QEvent((QEvent::Type) (JOG_STOP + (ev.value/2))));
261 }
262
263 void ShuttleThread::shuttle(int value)
264 {
265     //gettimeofday( &last_shuttle, 0 );
266     //need_synthetic_shuttle = value != 0;
267
268     if (value == shuttlevalue) {
269         shuttlecounter = 1;
270         return;
271     }
272
273     if (value > MAX_SHUTTLE_RANGE || value < -MAX_SHUTTLE_RANGE) {
274         fprintf(stderr, "Jog Shuttle returned value of %d (should be between -%d ad +%d)", value, MAX_SHUTTLE_RANGE, MAX_SHUTTLE_RANGE);
275         return;
276     }
277     shuttlevalue = value;
278     shuttlecounter = 1;
279     QApplication::postEvent(m_parent, new QEvent((QEvent::Type) (JOG_STOP + value)));
280 }
281
282 void ShuttleThread::jog(struct media_ctrl_event ev)
283 {
284     if (ev.value < 0)
285         QApplication::postEvent(m_parent, new QEvent((QEvent::Type) JOG_BACK1));
286     else if (ev.value > 0)
287         QApplication::postEvent(m_parent, new QEvent((QEvent::Type) JOG_FWD1));
288 }
289
290 void ShuttleThread::jog(unsigned int value)
291 {
292     // generate a synthetic event for the shuttle going
293     // to the home position if we have not seen one recently.
294     //if (shuttlevalue != 0) {
295     //  QApplication::postEvent(m_parent, new QEvent((QEvent::Type) JOG_STOP));
296     //  shuttlevalue = 0;
297     //}
298
299     // This code takes care of wrapping around the limits of the jog dial number (it is represented as a single byte, hence
300     // wraps at the 0/255 boundary). I used 25 as the difference to make sure that even in heavy load, with the jog dial
301     // turning fast and we miss some events that we do not mistakenly reverse the direction.
302     // Note also that at least the Contour ShuttlePRO v2 does not send an event for the value 0, so at the wrap it will
303     // need 2 events to go forward. But that is nothing we can do about...
304     if (jogvalue != 0xffff) {
305         //fprintf(stderr, "value=%d jogvalue=%d\n", value, jogvalue);
306         bool wrap = abs(value - jogvalue) > 25;
307         bool rewind = value < jogvalue;
308         bool forward = value > jogvalue;
309         if ((rewind && !wrap) || (forward && wrap))
310             QApplication::postEvent(m_parent, new QEvent((QEvent::Type) JOG_BACK1));
311         else if ((forward && !wrap) || (rewind && wrap))
312             QApplication::postEvent(m_parent, new QEvent((QEvent::Type) JOG_FWD1));
313         else if (!forward && !rewind && shuttlecounter > 2) {
314             // An event without changing the jog value is sent after each shuttle change.
315             // As the shuttle rest position does not get a shuttle event, only a non-position-changing jog event.
316             // Hence we stop on this when we see 2 non-position-changing jog events in a row.
317             shuttlecounter = 0;
318             QApplication::postEvent(m_parent, new QEvent((QEvent::Type) JOG_STOP));
319         }
320     }
321     jogvalue = value;
322     if (shuttlecounter > 0) shuttlecounter++;
323 }
324
325
326 JogShuttle::JogShuttle(const QString &device, QObject *parent) :
327         QObject(parent)
328 {
329     initDevice(device);
330 }
331
332 JogShuttle::~JogShuttle()
333 {
334         stopDevice();
335 }
336
337 void JogShuttle::initDevice(const QString &device)
338 {
339     if (m_shuttleProcess.isRunning()) {
340         if (device == m_shuttleProcess.m_device) return;
341         stopDevice();
342     }
343     m_shuttleProcess.init(this, device);
344     m_shuttleProcess.start(QThread::LowestPriority);
345 }
346
347 void JogShuttle::stopDevice()
348 {
349     if (m_shuttleProcess.isRunning()) {
350         /* tell thread to stop */
351         m_shuttleProcess.stop_me = true;
352         m_shuttleProcess.exit();
353         /* give the thread some time (ms) to shutdown */
354         m_shuttleProcess.wait(600);
355
356         /* if still running - do it in the hardcore way */
357         if (m_shuttleProcess.isRunning()) {
358                 m_shuttleProcess.terminate();
359             kDebug() << "/// terminate jogshuttle process\n";
360         }
361     }
362 }
363
364 void JogShuttle::customEvent(QEvent* e)
365 {
366     int code = e->type();
367
368     // Handle simple job events
369     switch (code) {
370     case JOG_BACK1:
371         emit jogBack();
372         return;
373     case JOG_FWD1:
374         emit jogForward();
375         return;
376     }
377
378     int shuttle_pos = code - JOG_STOP;
379     if (shuttle_pos >= -MAX_SHUTTLE_RANGE && shuttle_pos <= MAX_SHUTTLE_RANGE) {
380         emit shuttlePos(shuttle_pos);
381         return;
382     }
383
384     // we've got a key event.
385     //fprintf(stderr, "Firing button event for #%d\n", e->type() - KEY_EVENT_OFFSET); // DBG
386     emit button(e->type() - KEY_EVENT_OFFSET);
387 }
388
389 QString JogShuttle::enumerateDevice(const QString& device)
390 {
391     return QDir(device).canonicalPath();
392 }
393
394 DeviceMap JogShuttle::enumerateDevices(const QString& devPath)
395 {
396     DeviceMap devs;
397     QDir devDir(devPath);
398
399     if (!devDir.exists()) {
400         return devs;
401     }
402
403     QStringList fileList = devDir.entryList(QDir::System | QDir::Files);
404     foreach (const QString &fileName, fileList) {
405         QString devFullPath = devDir.absoluteFilePath(fileName);
406         QString fileLink = JogShuttle::enumerateDevice(devFullPath);
407         kDebug() << QString(" [%1] ").arg(fileName);
408         kDebug() << QString(" [%1] ").arg(fileLink);
409
410         struct media_ctrl mc;
411         media_ctrl_open2(&mc, (char*)fileLink.toUtf8().data());
412         if (mc.fd > 0 && mc.device) {
413             devs.insert(QString(mc.device->name), devFullPath);
414         }
415         media_ctrl_close(&mc);
416     }
417
418     return devs;
419 }
420
421
422 // #include "jogshuttle.moc"
423
424
425 #include "jogshuttle.moc"