summaryrefslogtreecommitdiff
path: root/libs/surfaces/contourdesign/contourdesign.cc
blob: 1e4471b56b87430baea070b35985817d4ef80fda (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
/*
 * Copyright (C) 2019 Johannes Mueller <github@johannes-mueller.org>
 * Copyright (C) 2019 Robin Gareus <robin@gareus.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include <iostream>

#include <libusb.h>

#include <glibmm.h>

#include "pbd/compose.h"
#include "pbd/error.h"
#include "ardour/debug.h"
#include "ardour/session.h"
#include "ardour/tempo.h"
#include "pbd/i18n.h"

#include "contourdesign.h"

using namespace ARDOUR;
using namespace PBD;
using namespace Glib;
using namespace std;
using namespace ArdourSurface;

#include "pbd/abstract_ui.cc" // instantiate template

static const uint16_t ContourDesign = 0x0b33;
static const uint16_t ShuttlePRO_id = 0x0030;
static const uint16_t ShuttleXpress_id = 0x0020;

static void LIBUSB_CALL event_callback (struct libusb_transfer* transfer);


ContourDesignControlProtocol::ContourDesignControlProtocol (Session& session)
	: ControlProtocol (session, X_("ContourDesign"))
	,  AbstractUI<ContourDesignControlUIRequest> ("contourdesign")
	, _io_source (0)
	, _dev_handle (0)
	, _usb_transfer (0)
	, _supposed_to_quit (false)
	, _device_type (None)
	, _shuttle_was_zero (true)
	, _was_rolling_before_shuttle (false)
	, _test_mode (false)
	, _keep_rolling (true)
	, _shuttle_speeds ()
	, _jog_distance ()
	, _gui (0)
{
	libusb_init (0);
//	libusb_set_debug(0, LIBUSB_LOG_LEVEL_WARNING);

	_shuttle_speeds.push_back (0.50);
	_shuttle_speeds.push_back (0.75);
	_shuttle_speeds.push_back (1.0);
	_shuttle_speeds.push_back (1.5);
	_shuttle_speeds.push_back (2.0);
	_shuttle_speeds.push_back (5.0);
	_shuttle_speeds.push_back (10.0);

	setup_default_button_actions ();
	BaseUI::run();
}

ContourDesignControlProtocol::~ContourDesignControlProtocol ()
{
	stop ();
	libusb_exit (0);
	BaseUI::quit();
	tear_down_gui ();
}

bool
ContourDesignControlProtocol::probe ()
{
	bool rv = LIBUSB_SUCCESS == libusb_init (0);
	if (rv) {
		libusb_exit (0);
	}
	return rv;
}

void*
ContourDesignControlProtocol::request_factory (uint32_t num_requests)
{
	/* AbstractUI<T>::request_buffer_factory() is a template method only
	 * instantiated in this source module. To provide something visible for
	 * use in the interface/descriptor, we have this static method that is
	 * template-free.
	 */
	return request_buffer_factory (num_requests);
}

int
ContourDesignControlProtocol::set_active (bool yn)
{
	DEBUG_TRACE (DEBUG::ContourDesignControl, string_compose ("set_active() init with yn: '%1'\n", yn));

	if (yn == active()) {
		return 0;
	}

	if (yn) {
		start ();
	} else {
		stop ();
	}

	ControlProtocol::set_active (yn);

	return _error;
}

XMLNode&
ContourDesignControlProtocol::get_state ()
{
	XMLNode& node (ControlProtocol::get_state());
	node.set_property (X_("keep-rolling"), _keep_rolling);

	ostringstream os;
	vector<double>::const_iterator it = _shuttle_speeds.begin ();
	os << *(it++);
	for (; it != _shuttle_speeds.end (); ++it) {
		os << ' ' << *it;
	}
	string s = os.str ();
	node.set_property (X_("shuttle-speeds"), s);

	node.set_property (X_("jog-distance"), _jog_distance.value);
	switch (_jog_distance.unit) {
	case SECONDS: s = X_("seconds"); break;
	case BARS: s = X_("bars"); break;
	case BEATS:
	default: s = X_("beats");
	}
	node.set_property (X_("jog-unit"), s);

	for (unsigned int i=0; i<_button_actions.size(); ++i) {
		XMLNode* child = new XMLNode (string_compose (X_("button-%1"), i+1));
		node.add_child_nocopy (_button_actions[i]->get_state (*child));
	}

	return node;
}

int
ContourDesignControlProtocol::set_state (const XMLNode& node, int version)
{
	if (ControlProtocol::set_state (node, version)) {
		return -1;
	}
	node.get_property (X_("keep-rolling"), _keep_rolling);

	string s;
	node.get_property (X_("shuttle-speeds"), s);
	istringstream is (s);
	for (vector<double>::iterator it = _shuttle_speeds.begin (); it != _shuttle_speeds.end (); ++it) {
		is >> *it;
	}

	node.get_property (X_("jog-distance"), _jog_distance.value);
	node.get_property (X_("jog-unit"), s);
	if (s == "seconds") {
		_jog_distance.unit = SECONDS;
	} else if (s == "bars") {
		_jog_distance.unit = BARS;
	} else {
		_jog_distance.unit = BEATS;
	}

	XMLNode* child;
	for (unsigned int i=0; i<_button_actions.size(); ++i) {
		if ((child = node.child (string_compose(X_("button-%1"), i+1).c_str())) == 0) {
			continue;
		}
		string type;
		child->get_property (X_("type"), type);
		if (type == X_("action")) {
			string path ("");
			child->get_property (X_("path"), path);
			boost::shared_ptr<ButtonBase> b (new ButtonAction (path, *this));
			_button_actions[i] = b;
		} else {
			double value;
			string s;

			if (!child->get_property(X_("value"), value)) {
				continue;
			}
			if (!child->get_property(X_("unit"), s)) {
				continue;
			}

			JumpUnit unit;
			if (s == X_("seconds")) {
				unit = SECONDS;
			} else if (s == X_("bars")) {
				unit = BARS;
			} else {
				unit = BEATS;
			}

			boost::shared_ptr<ButtonBase> b (new ButtonJump (JumpDistance (value, unit), *this));
		}
	}

	return 0;
}

void
ContourDesignControlProtocol::do_request (ContourDesignControlUIRequest* req)
{
	if (req->type == CallSlot) {
		DEBUG_TRACE (DEBUG::ContourDesignControl, "do_request type CallSlot\n");
		call_slot (MISSING_INVALIDATOR, req->the_slot);
	} else if (req->type == Quit) {
		DEBUG_TRACE (DEBUG::ContourDesignControl, "do_request type Quit\n");
		stop ();
	}
}

void
ContourDesignControlProtocol::thread_init ()
{
	DEBUG_TRACE (DEBUG::ContourDesignControl, "thread_init()\n");

	pthread_set_name (X_("contourdesign"));
	PBD::notify_event_loops_about_thread_creation (pthread_self (), X_("contourdesign"), 2048);
	ARDOUR::SessionEvent::create_per_thread_pool (X_("contourdesign"), 128);

	set_thread_priority ();
}

bool
ContourDesignControlProtocol::wait_for_event ()
{
	DEBUG_TRACE (DEBUG::ContourDesignControl, "wait_for_event\n");
	if (!_supposed_to_quit) {
		libusb_handle_events (0);
	}

	return true;
}

int
get_usb_device (uint16_t vendor_id, uint16_t product_id, libusb_device** device)
{
	struct libusb_device **devs;
	struct libusb_device *dev;
	size_t i = 0;
	int r = LIBUSB_ERROR_NO_DEVICE;

	*device = 0;

	if (libusb_get_device_list (0, &devs) < 0) {
		return LIBUSB_ERROR_NO_DEVICE;
	}

	while ((dev = devs[i++])) {
		struct libusb_device_descriptor desc;
		r = libusb_get_device_descriptor (dev, &desc);
		if (r != LIBUSB_SUCCESS) {
			goto out;
		}
		if (desc.idVendor == vendor_id && desc.idProduct == product_id) {
			*device = dev;
			break;
		}
	}

out:
	libusb_free_device_list(devs, 1);
	if (!dev && r == LIBUSB_SUCCESS) {
		return LIBUSB_ERROR_NO_DEVICE;
	}
	return r;
}

int
ContourDesignControlProtocol::acquire_device ()
{
	DEBUG_TRACE (DEBUG::ContourDesignControl, "acquire_device()\n");

	int err;

	if (_dev_handle) {
		DEBUG_TRACE (DEBUG::ContourDesignControl, "already have a device handle\n");
		return LIBUSB_SUCCESS;
	}

	libusb_device* dev;


	if ((err = get_usb_device (ContourDesign, ShuttleXpress_id, &dev)) == LIBUSB_SUCCESS) {
		_device_type = ShuttleXpress;
	}
	else if ((err = get_usb_device (ContourDesign, ShuttlePRO_id, &dev)) == LIBUSB_SUCCESS) {
		_device_type = ShuttlePRO;
	} else {
		_device_type = None;
		return err;
	}

	err = libusb_open (dev, &_dev_handle);
	if (err != LIBUSB_SUCCESS) {
		return err;
	}

	libusb_set_auto_detach_kernel_driver (_dev_handle, true);

	if ((err = libusb_claim_interface (_dev_handle, 0x00)) != LIBUSB_SUCCESS) {
		DEBUG_TRACE (DEBUG::ContourDesignControl, "failed to claim USB device\n");
		goto usb_close;
	}

	_usb_transfer = libusb_alloc_transfer (0);
	if (!_usb_transfer) {
		DEBUG_TRACE (DEBUG::ContourDesignControl, "failed to alloc usb transfer\n");
		err = LIBUSB_ERROR_NO_MEM;
		goto usb_close;
	}

	libusb_fill_interrupt_transfer (_usb_transfer, _dev_handle, 1 | LIBUSB_ENDPOINT_IN, _buf, sizeof(_buf),
				       event_callback, this, 0);

	DEBUG_TRACE (DEBUG::ContourDesignControl, "callback installed\n");

	if ((err = libusb_submit_transfer (_usb_transfer)) != LIBUSB_SUCCESS) {
		DEBUG_TRACE (DEBUG::ContourDesignControl, string_compose ("failed to submit tansfer: %1\n", err));
		goto free_transfer;
	}

	return LIBUSB_SUCCESS;

 free_transfer:
	libusb_free_transfer (_usb_transfer);

 usb_close:
	libusb_close (_dev_handle);
	_dev_handle = 0;
	return err;
}

void
ContourDesignControlProtocol::release_device ()
{
	if (!_dev_handle) {
		return;
	}

	libusb_close (_dev_handle);
	libusb_free_transfer (_usb_transfer);
	libusb_release_interface (_dev_handle, 0);
	_usb_transfer = 0;
	_dev_handle = 0;
}

void
ContourDesignControlProtocol::start ()
{
	DEBUG_TRACE (DEBUG::ContourDesignControl, "start()\n");

	_supposed_to_quit = false;

	_error = acquire_device();
	if (_error != LIBUSB_SUCCESS) {
		return;
	}

	if (!_dev_handle) { // can this actually happen?
		_error = -1;
		return;
	}

	_state.shuttle = 0;
	_state.jog = 0;
	_state.buttons = 0;

	Glib::RefPtr<Glib::IdleSource> source = Glib::IdleSource::create ();
	source->connect (sigc::mem_fun (*this, &ContourDesignControlProtocol::wait_for_event));
	source->attach (_main_loop->get_context ());

	_io_source = source->gobj ();
	g_source_ref (_io_source);
}


void
ContourDesignControlProtocol::stop ()
{
	DEBUG_TRACE (DEBUG::ContourDesignControl, "stop()\n");

	_supposed_to_quit = true;

	if (_io_source) {
		g_source_destroy (_io_source);
		g_source_unref (_io_source);
		_io_source = 0;
	}

	if (_dev_handle) {
		release_device ();
	}
}

void
ContourDesignControlProtocol::handle_event () {
	if (_usb_transfer->status == LIBUSB_TRANSFER_TIMED_OUT) {
		goto resubmit;
	}
	if (_usb_transfer->status != LIBUSB_TRANSFER_COMPLETED) {
		DEBUG_TRACE (DEBUG::ContourDesignControl, string_compose("libusb_transfer not completed: %1\n", _usb_transfer->status));
		_error = LIBUSB_ERROR_NO_DEVICE;
		return;
	}

	State new_state;
	new_state.shuttle = _buf[0];
	new_state.jog = _buf[1];
	new_state.buttons = (_buf[4] << 8) + _buf[3];

//	cout << "event " << (int)new_state.shuttle << " " << (int)new_state.jog << " " << (int)new_state.buttons << endl;;

	for (uint8_t btn=0; btn<16; btn++) {
                if ( (new_state.buttons & (1<<btn)) && !(_state.buttons & (1<<btn)) ) {
                        handle_button_press (btn);
                } else if ( !(new_state.buttons & (1<<btn)) && (_state.buttons & (1<<btn)) ) {
                        handle_button_release (btn);
                }
        }

	if (new_state.jog == 255 && _state.jog == 0) {
		jog_event_backward ();
	} else if (new_state.jog == 0 && _state.jog == 255) {
		jog_event_forward();
	} else if (new_state.jog < _state.jog) {
		jog_event_backward();
	} else if (new_state.jog > _state.jog) {
		jog_event_forward();
	}

	if (new_state.shuttle != _state.shuttle) {
		shuttle_event(new_state.shuttle);
	}

	_state = new_state;

 resubmit:
	if (libusb_submit_transfer (_usb_transfer)) {
		DEBUG_TRACE (DEBUG::ContourDesignControl, "failed to resubmit usb transfer after callback\n");
		stop ();
	}
}


boost::shared_ptr<ButtonBase>
ContourDesignControlProtocol::make_button_action (string action_string)
{
	return boost::shared_ptr<ButtonBase> (new ButtonAction (action_string, *this));
}

/* The buttons have the following layout
 *
 *          00  01  02  03
 *        04  05  06  07  08
 *
 *          13   Jog   14
 *
 *            09     10
 *            11     12
 */

void
ContourDesignControlProtocol::setup_default_button_actions ()
{
 	_button_actions.push_back (make_button_action ("MIDI/panic"));
	_button_actions.push_back (make_button_action ("Editor/remove-last-capture"));
	_button_actions.push_back (make_button_action ("Editor/undo"));
	_button_actions.push_back (make_button_action ("Editor/redo"));
	_button_actions.push_back (make_button_action ("Common/jump-backward-to-mark"));
	_button_actions.push_back (make_button_action ("Transport/Record"));
	_button_actions.push_back (make_button_action ("Transport/Stop"));
	_button_actions.push_back (make_button_action ("Transport/Roll"));
	_button_actions.push_back (make_button_action ("Common/jump-forward-to-mark"));
	_button_actions.push_back (boost::shared_ptr<ButtonBase> (new ButtonJump (JumpDistance (-4.0, BARS), *this)));
	_button_actions.push_back (boost::shared_ptr<ButtonBase> (new ButtonJump (JumpDistance (+4.0, BARS), *this)));
	_button_actions.push_back (make_button_action (""));
	_button_actions.push_back (make_button_action ("Common/add-location-from-playhead"));
	_button_actions.push_back (make_button_action ("Transport/GotoStart"));
	_button_actions.push_back (make_button_action ("Transport/GotoEnd"));
}

const boost::shared_ptr<ButtonBase>
ContourDesignControlProtocol::get_button_action (unsigned int index) const
{
	if (index >= _button_actions.size()) {
		return boost::shared_ptr<ButtonBase>();
	}
	return _button_actions[index];
}

void
ContourDesignControlProtocol::set_button_action (unsigned int index, const boost::shared_ptr<ButtonBase> btn_act)
{
	if (index >= _button_actions.size()) {
		return;
	}
	_button_actions[index] = btn_act;
}


void
ContourDesignControlProtocol::handle_button_press (unsigned short btn)
{
	if (_test_mode) {
		ButtonPress (btn); /* emit signal */
		return;
	}
	if (btn >= _button_actions.size ()) {
		DEBUG_TRACE (DEBUG::ContourDesignControl,
			     string_compose ("ContourDesign button number out of bounds %1, max is %2\n",
					     btn, _button_actions.size ()));
		return;
	}

	_button_actions[btn]->execute ();
}

void
ContourDesignControlProtocol::handle_button_release (unsigned short btn)
{
	if (_test_mode) {
		ButtonRelease (btn); /* emit signal */
	}
}


void
ContourDesignControlProtocol::prev_marker_keep_rolling ()
{
	samplepos_t pos = session->locations()->first_mark_before (session->transport_sample());

	if (pos >= 0) {
		session->request_locate (pos, _keep_rolling && session->transport_rolling());
	} else {
		session->goto_start ();
	}
}

void
ContourDesignControlProtocol::next_marker_keep_rolling ()
{
	samplepos_t pos = session->locations()->first_mark_after (session->transport_sample());

	if (pos >= 0) {
		session->request_locate (pos, _keep_rolling && session->transport_rolling());
	} else {
		session->goto_end();
	}
}

void
ContourDesignControlProtocol::jog_event_backward ()
{
	DEBUG_TRACE (DEBUG::ContourDesignControl, "jog event backward\n");
	jump_backward (_jog_distance);
}

void
ContourDesignControlProtocol::jog_event_forward ()
{
	DEBUG_TRACE (DEBUG::ContourDesignControl, "jog event forward\n");
	jump_forward (_jog_distance);
}

void
ContourDesignControlProtocol::jump_forward (JumpDistance dist)
{
	bool kr = _keep_rolling && session->transport_rolling ();
	switch (dist.unit) {
	case SECONDS: jump_by_seconds (dist.value, kr); break;
	case BEATS: jump_by_beats (dist.value, kr); break;
	case BARS: jump_by_bars (dist.value, kr); break;
	default: break;
	}
}

void ContourDesignControlProtocol::jump_backward (JumpDistance dist)
{
	JumpDistance bw = dist;
	bw.value = -bw.value;
	jump_forward(bw);
}

void
ContourDesignControlProtocol::set_shuttle_speed (unsigned int index, double speed)
{
	if (index >= _shuttle_speeds.size()) {
		return;
	}
	_shuttle_speeds[index] = speed;
}

void
ContourDesignControlProtocol::shuttle_event (int position)
{
	if (abs(position) > num_shuttle_speeds) {
		DEBUG_TRACE (DEBUG::ContourDesignControl, "received invalid shuttle position... ignoring.\n");
		return;
	}

	if (position != 0) {
		if (_shuttle_was_zero) {
			_was_rolling_before_shuttle = session->transport_rolling ();
		}
		const vector<double>& spds = _shuttle_speeds;
		const double speed = position > 0 ? spds[position-1] : -spds[-position-1];
		set_transport_speed (speed);
		_shuttle_was_zero = false;
	} else {
		if (_keep_rolling && _was_rolling_before_shuttle) {
			set_transport_speed (1.0);
		} else {
			transport_stop ();
		}
		_shuttle_was_zero = true;
	}
}

void
ButtonJump::execute ()
{
	_spc.jump_forward (_dist);
}

XMLNode&
ButtonJump::get_state (XMLNode& node) const
{
	string ts (X_("jump"));
	node.set_property (X_("type"), ts);
	node.set_property (X_("distance"), _dist.value);

	string s;
	switch (_dist.unit) {
	case SECONDS: s = X_("seconds"); break;
	case BARS: s = X_("bars"); break;
	case BEATS:
	default: s = X_("beats");
	}
	node.set_property (X_("unit"), s);

	return node;
}

void
ButtonAction::execute ()
{
	_spc.access_action (_action_string);
}


XMLNode&
ButtonAction::get_state (XMLNode& node) const
{
	string ts (X_("action"));
	node.set_property (X_("type"), ts);
	node.set_property (X_("path"), _action_string);

	return node;
}

static void LIBUSB_CALL event_callback (libusb_transfer* transfer)
{
	ContourDesignControlProtocol* spc = static_cast<ContourDesignControlProtocol*> (transfer->user_data);
	spc->handle_event();
}