root/trunk/libfreebob/src/motu/motu_avdevice.cpp

Revision 373, 29.1 kB (checked in by jwoithe, 17 years ago)

Make detection of RME and MOTU devices work again.

Line 
1 /* motu_avdevice.cpp
2  * Copyright (C) 2006 by Pieter Palmers
3  * Copyright (C) 2006 by Jonathan Woithe
4  *
5  * This file is part of FreeBob.
6  *
7  * FreeBob is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  * FreeBob is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with FreeBob; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
19  * MA 02111-1307 USA.
20  */
21
22 #include "motu/motu_avdevice.h"
23 #include "configrom.h"
24
25 #include "libfreebobavc/ieee1394service.h"
26 #include "libfreebobavc/avc_definitions.h"
27
28 #include "debugmodule/debugmodule.h"
29
30 #include "libstreaming/MotuStreamProcessor.h"
31 #include "libstreaming/MotuPort.h"
32
33 #include "libutil/DelayLockedLoop.h"
34
35 #include <string>
36 #include <stdint.h>
37 #include <assert.h>
38 #include <netinet/in.h>
39
40 #include <libraw1394/csr.h>
41
42 namespace Motu {
43
44 IMPL_DEBUG_MODULE( MotuDevice, MotuDevice, DEBUG_LEVEL_NORMAL );
45
46 char *motufw_modelname[] = {"[unknown]","828MkII", "Traveler"};
47
48 /* ======================================================================= */
49 /* Provide a mechanism for allocating iso channels and bandwidth to MOTU
50  * interfaces.
51  */
52
53 static signed int allocate_iso_channel(raw1394handle_t handle) {
54 /*
55  * Allocates an iso channel for use by the interface in a similar way to
56  * libiec61883.  Returns -1 on error (due to there being no free channels)
57  * or an allocated channel number.
58  * FIXME: As in libiec61883, channel 63 is not requested; this is either a
59  * bug or it's omitted since that's the channel preferred by video devices.
60  */
61         int c = -1;
62         for (c = 0; c < 63; c++)
63                 if (raw1394_channel_modify (handle, c, RAW1394_MODIFY_ALLOC) == 0)
64                         break;
65         if (c < 63)
66                 return c;
67         return -1;
68 }
69
70 static signed int free_iso_channel(raw1394handle_t handle, signed int channel) {
71 /*
72  * Deallocates an iso channel.  Returns -1 on error or 0 on success.  Silently
73  * ignores a request to deallocate a negative channel number.
74  */
75         if (channel < 0)
76                 return 0;
77         if (raw1394_channel_modify (handle, channel, RAW1394_MODIFY_FREE)!=0)
78                 return -1;
79         return 0;
80 }
81
82 static signed int get_iso_bandwidth_avail(raw1394handle_t handle) {
83 /*
84  * Returns the current value of the `bandwidth available' register on
85  * the IRM, or -1 on error.
86  */
87 quadlet_t buffer;
88 signed int result = raw1394_read (handle, raw1394_get_irm_id (handle),
89         CSR_REGISTER_BASE + CSR_BANDWIDTH_AVAILABLE,
90         sizeof (quadlet_t), &buffer);
91
92         if (result < 0)
93                 return -1;
94         return ntohl(buffer);
95 }
96 /* ======================================================================= */
97
98 MotuDevice::MotuDevice( std::auto_ptr< ConfigRom >( configRom ),
99                     Ieee1394Service& ieee1394service,
100                     int nodeId,
101                     int verboseLevel )
102     : m_configRom( configRom )
103     , m_1394Service( &ieee1394service )
104     , m_motu_model( MOTUFW_MODEL_NONE )
105     , m_nodeId( nodeId )
106     , m_verboseLevel( verboseLevel )
107     , m_id(0)
108     , m_iso_recv_channel ( -1 )
109     , m_iso_send_channel ( -1 )
110     , m_bandwidth ( -1 )
111     , m_receiveProcessor ( 0 )
112     , m_transmitProcessor ( 0 )
113    
114 {
115     setDebugLevel( verboseLevel );
116    
117     debugOutput( DEBUG_LEVEL_VERBOSE, "Created Motu::MotuDevice (NodeID %d)\n",
118                  nodeId );
119
120 }
121
122 MotuDevice::~MotuDevice()
123 {
124         // Free ieee1394 bus resources if they have been allocated
125         if (m_1394Service != NULL) {
126                 raw1394handle_t handle = m_1394Service->getHandle();
127                 if (m_bandwidth >= 0)
128                         if (raw1394_bandwidth_modify(handle, m_bandwidth, RAW1394_MODIFY_FREE) < 0)
129                                 debugOutput(DEBUG_LEVEL_VERBOSE, "Could not free bandwidth of %d\n", m_bandwidth);
130                 if (m_iso_recv_channel >= 0)
131                         if (raw1394_channel_modify(handle, m_iso_recv_channel, RAW1394_MODIFY_FREE) < 0)
132                                 debugOutput(DEBUG_LEVEL_VERBOSE, "Could not free recv iso channel %d\n", m_iso_recv_channel);
133                 if (m_iso_send_channel >= 0)
134                         if (raw1394_channel_modify(handle, m_iso_send_channel, RAW1394_MODIFY_FREE) < 0)
135                                 debugOutput(DEBUG_LEVEL_VERBOSE, "Could not free send iso channel %d\n", m_iso_send_channel);
136         }
137 }
138
139 ConfigRom&
140 MotuDevice::getConfigRom() const
141 {
142     return *m_configRom;
143 }
144
145 struct VendorModelEntry {
146     unsigned int vendor_id;
147     unsigned int model_id;
148 };
149
150 static VendorModelEntry supportedDeviceList[] =
151 {
152     {0x0001f2, 0x00000000},  // Motu device, model entry not used
153
154 };
155
156 bool
157 MotuDevice::probe( ConfigRom& configRom )
158 {
159     unsigned int vendorId = configRom.getNodeVendorId();
160     unsigned int modelId = configRom.getModelId();
161
162     for ( unsigned int i = 0;
163           i < ( sizeof( supportedDeviceList )/sizeof( VendorModelEntry ) );
164           ++i )
165     {
166         if ( ( supportedDeviceList[i].vendor_id == vendorId )
167              //&& ( supportedDeviceList[i].model_id == modelId )
168              )
169         {
170             switch (configRom.getUnitVersion()) {
171                 case MOTUFW_UNITVER_828mkII:
172                     return true;
173                 case MOTUFW_UNITVER_TRAVELER:
174                     return true;
175             }
176         }
177     }
178
179     return false;
180 }
181
182 bool
183 MotuDevice::discover()
184 {
185         // Find out if this device is one we know about
186         if (m_configRom->getUnitSpecifierId() == MOTUFW_VENDOR_MOTU) {
187                 switch (m_configRom->getUnitVersion()) {
188                     case MOTUFW_UNITVER_828mkII:
189                         m_motu_model = MOTUFW_MODEL_828mkII;
190                         break;
191                     case MOTUFW_UNITVER_TRAVELER:
192                         m_motu_model = MOTUFW_MODEL_TRAVELER;
193                         break;
194                 }
195         }
196
197         if (m_motu_model != MOTUFW_MODEL_NONE) {
198                 debugOutput( DEBUG_LEVEL_VERBOSE, "found MOTU %s\n",
199                         motufw_modelname[m_motu_model]);
200                 return true;
201         }
202
203         return false;
204 }
205
206 int
207 MotuDevice::getSamplingFrequency( ) {
208 /*
209  * Retrieve the current sample rate from the MOTU device.
210  */
211         quadlet_t q = ReadRegister(MOTUFW_REG_CLK_CTRL);
212         int rate = 0;
213
214         switch (q & MOTUFW_RATE_BASE_MASK) {
215                 case MOTUFW_RATE_BASE_44100:
216                         rate = 44100;
217                         break;
218                 case MOTUFW_RATE_BASE_48000:
219                         rate = 48000;
220                         break;
221         }
222         switch (q & MOTUFW_RATE_MULTIPLIER_MASK) {
223                 case MOTUFW_RATE_MULTIPLIER_2X:
224                         rate *= 2;
225                         break;
226                 case MOTUFW_RATE_MULTIPLIER_4X:
227                         rate *= 4;
228                         break;
229         }
230         return rate;
231 }
232
233 bool
234 MotuDevice::setSamplingFrequency( ESamplingFrequency samplingFrequency )
235 {
236 /*
237  * Set the MOTU device's samplerate.
238  */
239         char *src_name;
240         quadlet_t q, new_rate=0;
241         int i, supported=true, cancel_adat=false;
242
243         switch ( samplingFrequency ) {
244                 case eSF_22050Hz:
245                         supported=false;
246                         break;
247                 case eSF_24000Hz:
248                         supported=false;
249                         break;
250                 case eSF_32000Hz:
251                         supported=false;
252                         break;
253                 case eSF_44100Hz:
254                         new_rate = MOTUFW_RATE_BASE_44100 | MOTUFW_RATE_MULTIPLIER_1X;
255                         break;
256                 case eSF_48000Hz:
257                         new_rate = MOTUFW_RATE_BASE_48000 | MOTUFW_RATE_MULTIPLIER_1X;
258                         break;
259                 case eSF_88200Hz:
260                         new_rate = MOTUFW_RATE_BASE_44100 | MOTUFW_RATE_MULTIPLIER_2X;
261                         break;
262                 case eSF_96000Hz:
263                         new_rate = MOTUFW_RATE_BASE_48000 | MOTUFW_RATE_MULTIPLIER_2X;
264                         break;
265                 case eSF_176400Hz:
266                         // Currently only the Traveler supports 4x sample rates
267                         if (m_motu_model == MOTUFW_MODEL_TRAVELER) {
268                                 new_rate = MOTUFW_RATE_BASE_44100 | MOTUFW_RATE_MULTIPLIER_4X;
269                                 cancel_adat = true;
270                         } else
271                                 supported=false;
272                         break;
273                 case eSF_192000Hz:
274                         // Currently only the Traveler supports 4x sample rates
275                         if (m_motu_model == MOTUFW_MODEL_TRAVELER) {
276                                 new_rate = MOTUFW_RATE_BASE_48000 | MOTUFW_RATE_MULTIPLIER_4X;
277                                 cancel_adat = true;
278                         } else
279                                 supported=false;
280                         break;
281                 default:
282                         supported=false;
283         }
284
285         // Update the clock control register.  FIXME: while this is now rather
286         // comprehensive there may still be a need to manipulate MOTUFW_REG_CLK_CTRL
287         // a little more than we do.
288         if (supported) {
289                 quadlet_t value=ReadRegister(MOTUFW_REG_CLK_CTRL);
290
291                 // If optical port must be disabled (because a 4x sample rate has
292                 // been selected) then do so before changing the sample rate.  At
293                 // this stage it will be up to the user to re-enable the optical
294                 // port if the sample rate is set to a 1x or 2x rate later.
295                 if (cancel_adat) {
296                         setOpticalMode(MOTUFW_DIR_INOUT, MOTUFW_OPTICAL_MODE_OFF);
297                 }
298
299                 value &= ~(MOTUFW_RATE_BASE_MASK|MOTUFW_RATE_MULTIPLIER_MASK);
300                 value |= new_rate;
301
302                 // In other OSes bit 26 of MOTUFW_REG_CLK_CTRL always seems
303                 // to be set when this register is written to although the
304                 // reason isn't currently known.  When we set it, it appears
305                 // to prevent output being produced so we'll leave it unset
306                 // until we work out what's going on.  Other systems write
307                 // to MOTUFW_REG_CLK_CTRL multiple times, so that may be
308                 // part of the mystery.
309                 //   value |= 0x04000000;
310                 if (WriteRegister(MOTUFW_REG_CLK_CTRL, value) == 0) {
311                         supported=true;
312                 } else {
313                         supported=false;
314                 }
315                 // A write to the rate/clock control register requires the
316                 // textual name of the current clock source be sent to the
317                 // clock source name registers.
318                 switch (value & MOTUFW_CLKSRC_MASK) {
319                         case MOTUFW_CLKSRC_INTERNAL:
320                                 src_name = "Internal        ";
321                                 break;
322                         case MOTUFW_CLKSRC_ADAT_OPTICAL:
323                                 src_name = "ADAT Optical    ";
324                                 break;
325                         case MOTUFW_CLKSRC_SPDIF_TOSLINK:
326                                 if (getOpticalMode(MOTUFW_DIR_IN)  == MOTUFW_OPTICAL_MODE_TOSLINK)
327                                         src_name = "TOSLink         ";
328                                 else
329                                         src_name = "SPDIF           ";
330                                 break;
331                         case MOTUFW_CLKSRC_SMTPE:
332                                 src_name = "SMPTE           ";
333                                 break;
334                         case MOTUFW_CLKSRC_WORDCLOCK:
335                                 src_name = "Word Clock In   ";
336                                 break;
337                         case MOTUFW_CLKSRC_ADAT_9PIN:
338                                 src_name = "ADAT 9-pin      ";
339                                 break;
340                         case MOTUFW_CLKSRC_AES_EBU:
341                                 src_name = "AES-EBU         ";
342                                 break;
343                         default:
344                                 src_name = "Unknown         ";
345                 }
346                 for (i=0; i<16; i+=4) {
347                         q = (src_name[i]<<24) | (src_name[i+1]<<16) |
348                                 (src_name[i+2]<<8) | src_name[i+3];
349                         WriteRegister(MOTUFW_REG_CLKSRC_NAME0+i, q);
350                 }
351         }
352         return supported;
353 }
354
355 bool MotuDevice::setId( unsigned int id) {
356         debugOutput( DEBUG_LEVEL_VERBOSE, "Set id to %d...\n", id);
357         m_id=id;
358         return true;
359 }
360
361 void
362 MotuDevice::showDevice() const
363 {
364         debugOutput(DEBUG_LEVEL_VERBOSE,
365                 "MOTU %s at node %d\n", motufw_modelname[m_motu_model],
366                 m_nodeId);
367 }
368
369 bool
370 MotuDevice::prepare() {
371
372         int samp_freq = getSamplingFrequency();
373         unsigned int optical_in_mode = getOpticalMode(MOTUFW_DIR_IN);
374         unsigned int optical_out_mode = getOpticalMode(MOTUFW_DIR_OUT);
375         unsigned int event_size_in = getEventSize(MOTUFW_DIR_IN);
376         unsigned int event_size_out= getEventSize(MOTUFW_DIR_OUT);
377
378         raw1394handle_t handle = m_1394Service->getHandle();
379
380         debugOutput(DEBUG_LEVEL_NORMAL, "Preparing MotuDevice...\n" );
381
382         // Assign iso channels if not already done
383         if (m_iso_recv_channel < 0)
384                 m_iso_recv_channel = allocate_iso_channel(handle);
385         if (m_iso_send_channel < 0)
386                 m_iso_send_channel = allocate_iso_channel(handle);
387
388         debugOutput(DEBUG_LEVEL_VERBOSE, "recv channel = %d, send channel = %d\n",
389                 m_iso_recv_channel, m_iso_send_channel);
390
391         if (m_iso_recv_channel<0 || m_iso_send_channel<0) {
392                 debugFatal("Could not allocate iso channels!\n");
393                 return false;
394         }
395
396         // Allocate bandwidth if not previously done.
397         // FIXME: The bandwidth allocation calculation can probably be
398         // refined somewhat since this is currently based on a rudimentary
399         // understanding of the iso protocol.
400         // Currently we assume the following.
401         //   * Ack/iso gap = 0.05 us
402         //   * DATA_PREFIX = 0.16 us
403         //   * DATA_END    = 0.26 us
404         // These numbers are the worst-case figures given in the ieee1394
405         // standard.  This gives approximately 0.5 us of overheads per
406         // packet - around 25 bandwidth allocation units (from the ieee1394
407         // standard 1 bandwidth allocation unit is 125/6144 us).  We further
408         // assume the MOTU is running at S400 (which it should be) so one
409         // allocation unit is equivalent to 1 transmitted byte; thus the
410         // bandwidth allocation required for the packets themselves is just
411         // the size of the packet.  We allocate based on the maximum packet
412         // size (1160 bytes at 192 kHz) so the sampling frequency can be
413         // changed dynamically if this ends up being useful in future.
414         m_bandwidth = 25 + 1160;
415         debugOutput(DEBUG_LEVEL_VERBOSE, "Available bandwidth: %d\n",
416                 get_iso_bandwidth_avail(handle));
417         if (raw1394_bandwidth_modify(handle, m_bandwidth, RAW1394_MODIFY_ALLOC) < 0) {
418                 debugFatal("Could not allocate bandwidth of %d\n", m_bandwidth);
419                 m_bandwidth = -1;
420                 return false;
421         }
422         debugOutput(DEBUG_LEVEL_VERBOSE,
423                 "allocated bandwidth of %d for MOTU device\n", m_bandwidth);
424         debugOutput(DEBUG_LEVEL_VERBOSE,
425                 "remaining bandwidth: %d\n", get_iso_bandwidth_avail(handle));
426
427         m_receiveProcessor=new FreebobStreaming::MotuReceiveStreamProcessor(
428                 m_1394Service->getPort(), samp_freq, event_size_in);
429
430         // The first thing is to initialize the processor.  This creates the
431         // data structures.
432         if(!m_receiveProcessor->init()) {
433                 debugFatal("Could not initialize receive processor!\n");
434                 return false;
435         }
436         m_receiveProcessor->setVerboseLevel(getDebugLevel());
437
438         // Now we add ports to the processor
439         debugOutput(DEBUG_LEVEL_VERBOSE,"Adding ports to receive processor\n");
440        
441         char *buff;
442         FreebobStreaming::Port *p=NULL;
443
444         // Add audio capture ports
445         if (!addDirPorts(FreebobStreaming::Port::E_Capture, samp_freq, optical_in_mode)) {
446                 return false;
447         }
448
449         // Add MIDI port.  The MOTU only has one MIDI input port, with each
450         // MIDI byte sent using a 3 byte sequence starting at byte 4 of the
451         // event data.
452         asprintf(&buff,"dev%d_cap_MIDI0",m_id);
453         p = new FreebobStreaming::MotuMidiPort(buff,
454                 FreebobStreaming::Port::E_Capture, 4);
455         if (!p) {
456                 debugOutput(DEBUG_LEVEL_VERBOSE, "Skipped port %s\n", buff);
457         } else {
458                 if (!m_receiveProcessor->addPort(p)) {
459                         debugWarning("Could not register port with stream processor\n");
460                         free(buff);
461                         return false;
462                 } else {
463                         debugOutput(DEBUG_LEVEL_VERBOSE, "Added port %s\n", buff);
464                 }
465         }
466         free(buff);
467
468         // example of adding an control port:
469 //    asprintf(&buff,"dev%d_cap_%s",m_id,"myportnamehere");
470 //    p=new FreebobStreaming::MotuControlPort(
471 //            buff,
472 //            FreebobStreaming::Port::E_Capture,
473 //            0 // you can add all other port specific stuff you
474 //              // need to pass by extending MotuXXXPort and MotuPortInfo
475 //    );
476 //    free(buff);
477 //
478 //    if (!p) {
479 //        debugOutput(DEBUG_LEVEL_VERBOSE, "Skipped port %s\n",buff);
480 //    } else {
481 //
482 //        if (!m_receiveProcessor->addPort(p)) {
483 //            debugWarning("Could not register port with stream processor\n");
484 //            return false;
485 //        } else {
486 //            debugOutput(DEBUG_LEVEL_VERBOSE, "Added port %s\n",buff);
487 //        }
488 //    }
489
490         // Do the same for the transmit processor
491         m_transmitProcessor=new FreebobStreaming::MotuTransmitStreamProcessor(
492                 m_1394Service->getPort(), getSamplingFrequency(), event_size_out);
493
494         m_transmitProcessor->setVerboseLevel(getDebugLevel());
495        
496         if(!m_transmitProcessor->init()) {
497                 debugFatal("Could not initialize transmit processor!\n");
498                 return false;
499         }
500
501         // Connect the transmit stream ticks-per-frame hook to the
502         // ticks-per-frame DLL integrator in the receive stream.
503         m_transmitProcessor->setTicksPerFrameDLL(m_receiveProcessor->getTicksPerFrameDLL());
504
505         // Now we add ports to the processor
506         debugOutput(DEBUG_LEVEL_VERBOSE,"Adding ports to transmit processor\n");
507
508         // Add audio playback ports
509         if (!addDirPorts(FreebobStreaming::Port::E_Playback, samp_freq, optical_out_mode)) {
510                 return false;
511         }
512
513         // Add MIDI port.  The MOTU only has one output MIDI port, with each
514         // MIDI byte transmitted using a 3 byte sequence starting at byte 4
515         // of the event data.
516         asprintf(&buff,"dev%d_pbk_MIDI0",m_id);
517         p = new FreebobStreaming::MotuMidiPort(buff,
518                 FreebobStreaming::Port::E_Capture, 4);
519         if (!p) {
520                 debugOutput(DEBUG_LEVEL_VERBOSE, "Skipped port %s\n", buff);
521         } else {
522                 if (!m_receiveProcessor->addPort(p)) {
523                         debugWarning("Could not register port with stream processor\n");
524                         free(buff);
525                         return false;
526                 } else {
527                         debugOutput(DEBUG_LEVEL_VERBOSE, "Added port %s\n", buff);
528                 }
529         }
530         free(buff);
531
532         // example of adding an control port:
533 //    asprintf(&buff,"dev%d_pbk_%s",m_id,"myportnamehere");
534 //   
535 //    p=new FreebobStreaming::MotuControlPort(
536 //            buff,
537 //            FreebobStreaming::Port::E_Playback,
538 //            0 // you can add all other port specific stuff you
539 //              // need to pass by extending MotuXXXPort and MotuPortInfo
540 //    );
541 //    free(buff);
542 //
543 //    if (!p) {
544 //        debugOutput(DEBUG_LEVEL_VERBOSE, "Skipped port %s\n",buff);
545 //    } else {
546 //        if (!m_transmitProcessor->addPort(p)) {
547 //            debugWarning("Could not register port with stream processor\n");
548 //            return false;
549 //        } else {
550 //            debugOutput(DEBUG_LEVEL_VERBOSE, "Added port %s\n",buff);
551 //        }
552 //    }
553        
554         return true;
555 }
556
557 int
558 MotuDevice::getStreamCount() {
559         return 2; // one receive, one transmit
560 }
561
562 FreebobStreaming::StreamProcessor *
563 MotuDevice::getStreamProcessorByIndex(int i) {
564         switch (i) {
565         case 0:
566                 return m_receiveProcessor;
567         case 1:
568                 return m_transmitProcessor;
569         default:
570                 return NULL;
571         }
572         return 0;
573 }
574
575 int
576 MotuDevice::startStreamByIndex(int i) {
577
578 quadlet_t isoctrl = ReadRegister(MOTUFW_REG_ISOCTRL);
579
580         // NOTE: this assumes that you have two streams
581         switch (i) {
582         case 0:
583                 // TODO: do the stuff that is nescessary to make the device
584                 // transmit a stream
585
586                 // Set the streamprocessor channel to the one obtained by
587                 // the connection management
588                 m_receiveProcessor->setChannel(m_iso_recv_channel);
589
590                 // Mask out current transmit settings of the MOTU and replace
591                 // with new ones.  Turn bit 24 on to enable changes to the
592                 // MOTU's iso transmit settings when the iso control register
593                 // is written.  Bit 23 enables iso transmit from the MOTU.
594                 isoctrl &= 0xff00ffff;
595                 isoctrl |= (m_iso_recv_channel << 16);
596                 isoctrl |= 0x00c00000;
597                 WriteRegister(MOTUFW_REG_ISOCTRL, isoctrl);
598                 break;
599         case 1:
600                 // TODO: do the stuff that is nescessary to make the device
601                 // receive a stream
602
603                 // Set the streamprocessor channel to the one obtained by
604                 // the connection management
605                 m_transmitProcessor->setChannel(m_iso_send_channel);
606
607                 // Mask out current receive settings of the MOTU and replace
608                 // with new ones.  Turn bit 31 on to enable changes to the
609                 // MOTU's iso receive settings when the iso control register
610                 // is written.  Bit 30 enables iso receive by the MOTU.
611                 isoctrl &= 0x00ffffff;
612                 isoctrl |= (m_iso_send_channel << 24);
613                 isoctrl |= 0xc0000000;
614                 WriteRegister(MOTUFW_REG_ISOCTRL, isoctrl);
615                 break;
616                
617         default: // Invalid stream index
618                 return -1;
619         }
620
621         return 0;
622 }
623
624 int
625 MotuDevice::stopStreamByIndex(int i) {
626
627 quadlet_t isoctrl = ReadRegister(MOTUFW_REG_ISOCTRL);
628
629         // TODO: connection management: break connection
630         // cfr the start function
631
632         // NOTE: this assumes that you have two streams
633         switch (i) {
634         case 0:
635                 // Turn bit 22 off to disable iso send by the MOTU.  Turn
636                 // bit 23 on to enable changes to the MOTU's iso transmit
637                 // settings when the iso control register is written.
638                 isoctrl &= 0xffbfffff;
639                 isoctrl |= 0x00800000;
640                 WriteRegister(MOTUFW_REG_ISOCTRL, isoctrl);
641                 break;
642         case 1:
643                 // Turn bit 30 off to disable iso receive by the MOTU.  Turn
644                 // bit 31 on to enable changes to the MOTU's iso receive
645                 // settings when the iso control register is written.
646                 isoctrl &= 0xbfffffff;
647                 isoctrl |= 0x80000000;
648                 WriteRegister(MOTUFW_REG_ISOCTRL, isoctrl);
649                 break;
650                
651         default: // Invalid stream index
652                 return -1;
653         }
654
655         return 0;
656 }
657
658 signed int MotuDevice::getIsoRecvChannel(void) {
659         return m_iso_recv_channel;
660 }
661
662 signed int MotuDevice::getIsoSendChannel(void) {
663         return m_iso_send_channel;
664 }
665
666 unsigned int MotuDevice::getOpticalMode(unsigned int dir) {
667         unsigned int reg = ReadRegister(MOTUFW_REG_ROUTE_PORT_CONF);
668
669 debugOutput(DEBUG_LEVEL_VERBOSE, "optical mode: %x %x %x %x\n",dir, reg, reg & MOTUFW_OPTICAL_IN_MODE_MASK,
670 reg & MOTUFW_OPTICAL_OUT_MODE_MASK);
671
672         if (dir == MOTUFW_DIR_IN)
673                 return (reg & MOTUFW_OPTICAL_IN_MODE_MASK) >> 8;
674         else
675                 return (reg & MOTUFW_OPTICAL_OUT_MODE_MASK) >> 10;
676 }
677
678 signed int MotuDevice::setOpticalMode(unsigned int dir, unsigned int mode) {
679         unsigned int reg = ReadRegister(MOTUFW_REG_ROUTE_PORT_CONF);
680         unsigned int opt_ctrl = 0x0000002;
681
682         // Set up the optical control register value according to the current
683         // optical port modes.  At this stage it's not completely understood
684         // what the "Optical control" register does, so the values it's set to
685         // are more or less "magic" numbers.
686         if (reg & MOTUFW_OPTICAL_IN_MODE_MASK != (MOTUFW_OPTICAL_MODE_ADAT<<8))
687                 opt_ctrl |= 0x00000080;
688         if (reg & MOTUFW_OPTICAL_OUT_MODE_MASK != (MOTUFW_OPTICAL_MODE_ADAT<<10))
689                 opt_ctrl |= 0x00000040;
690
691         if (mode & MOTUFW_DIR_IN) {
692                 reg &= ~MOTUFW_OPTICAL_IN_MODE_MASK;
693                 reg |= (mode << 8) & MOTUFW_OPTICAL_IN_MODE_MASK;
694                 if (mode != MOTUFW_OPTICAL_MODE_ADAT)
695                         opt_ctrl |= 0x00000080;
696                 else
697                         opt_ctrl &= ~0x00000080;
698         }
699         if (mode & MOTUFW_DIR_OUT) {
700                 reg &= ~MOTUFW_OPTICAL_OUT_MODE_MASK;
701                 reg |= (mode <<10) & MOTUFW_OPTICAL_OUT_MODE_MASK;
702                 if (mode != MOTUFW_OPTICAL_MODE_ADAT)
703                         opt_ctrl |= 0x00000040;
704                 else
705                         opt_ctrl &= ~0x00000040;
706         }
707
708         // FIXME: there seems to be more to it than this, but for
709         // the moment at least this seems to work.
710         WriteRegister(MOTUFW_REG_ROUTE_PORT_CONF, reg);
711         return WriteRegister(MOTUFW_REG_OPTICAL_CTRL, opt_ctrl);
712 }
713
714 signed int MotuDevice::getEventSize(unsigned int dir) {
715 //
716 // Return the size in bytes of a single event sent to (dir==MOTUFW_OUT) or
717 // from (dir==MOTUFW_IN) the MOTU as part of an iso data packet.
718 //
719 // FIXME: for performance it may turn out best to calculate the event
720 // size in setOpticalMode and cache the result in a data field.  However,
721 // as it stands this will not adapt to dynamic changes in sample rate - we'd
722 // need a setFrameRate() for that.
723 //
724 // At the very least an event consists of the SPH (4 bytes), the control/MIDI
725 // bytes (6 bytes) and 8 analog audio channels (each 3 bytes long).  Note that
726 // all audio channels are sent using 3 bytes.
727 signed int sample_rate = getSamplingFrequency();
728 signed int optical_mode = getOpticalMode(dir);
729 signed int size = 4+6+8*3;
730
731         // 2 channels of AES/EBU is present if a 1x or 2x sample rate is in
732         // use
733         if (sample_rate <= 96000)
734                 size += 2*3;
735
736         // 2 channels of (coax) SPDIF is present for 1x or 2x sample rates so
737         // long as the optical mode is not TOSLINK.  If the optical mode is 
738         // TOSLINK the coax SPDIF channels are replaced by optical TOSLINK   
739         // channels.  Thus between these options we always have an addition 
740         // 2 channels here for 1x or 2x sample rates regardless of the optical
741         // mode.
742         if (sample_rate <= 96000)
743                 size += 2*3;
744
745         // ADAT channels 1-4 are present for 1x or 2x sample rates so long
746         // as the optical mode is ADAT.
747         if (sample_rate<=96000 && optical_mode==MOTUFW_OPTICAL_MODE_ADAT)
748                 size += 4*3;
749
750         // ADAT channels 5-8 are present for 1x sample rates so long as the
751         // optical mode is ADAT.
752         if (sample_rate<=48000 && optical_mode==MOTUFW_OPTICAL_MODE_ADAT)
753                 size += 4*3;
754
755         // When 1x or 2x sample rate is active there are an additional
756         // 2 channels sent in an event.  For capture it is a Mix1 return,
757         // while for playback it is a separate headphone mix.
758         if (sample_rate<=96000)
759                 size += 2*3;
760
761         // Finally round size up to the next quadlet boundary
762         return ((size+3)/4)*4;
763 }
764 /* ======================================================================= */
765
766 bool MotuDevice::addPort(FreebobStreaming::StreamProcessor *s_processor,
767   char *name, enum FreebobStreaming::Port::E_Direction direction,
768   int position, int size) {
769 /*
770  * Internal helper function to add a MOTU port to a given stream processor.
771  * This just saves the unnecessary replication of what is essentially
772  * boilerplate code.  Note that the port name is freed by this function
773  * prior to exit.
774  */
775 FreebobStreaming::Port *p=NULL;
776
777         p = new FreebobStreaming::MotuAudioPort(name, direction, position, size);
778
779         if (!p) {
780                 debugOutput(DEBUG_LEVEL_VERBOSE, "Skipped port %s\n",name);
781         } else {
782                 if (!s_processor->addPort(p)) {
783                         debugWarning("Could not register port with stream processor\n");
784                         free(name);
785                         return false;
786                 } else {
787                         debugOutput(DEBUG_LEVEL_VERBOSE, "Added port %s\n",name);
788                 }
789                 p->enable();
790         }
791         free(name);
792         return true;
793 }
794 /* ======================================================================= */
795
796 bool MotuDevice::addDirPorts(
797   enum FreebobStreaming::Port::E_Direction direction,
798   unsigned int sample_rate, unsigned int optical_mode) {
799 /*
800  * Internal helper method: adds all required ports for the given direction
801  * based on the indicated sample rate and optical mode.
802  *
803  * Notes: currently ports are not created if they are disabled due to sample
804  * rate or optical mode.  However, it might be better to unconditionally
805  * create all ports and just disable those which are not active.
806  */
807 const char *mode_str = direction==FreebobStreaming::Port::E_Capture?"cap":"pbk";
808 const char *aux_str = direction==FreebobStreaming::Port::E_Capture?"Mix1":"Phones";
809 FreebobStreaming::StreamProcessor *s_processor;
810 unsigned int i, ofs;
811 char *buff;
812
813         if (direction == FreebobStreaming::Port::E_Capture) {
814                 s_processor = m_receiveProcessor;
815         } else {
816                 s_processor = m_transmitProcessor;
817         }
818         // Offset into an event's data of the first audio data
819         ofs = 10;
820
821         // Add ports for the Mix1 return / Phones send which is present for
822         // 1x and 2x sampling rates.
823         if (sample_rate<=96000) {
824                 for (i=0; i<2; i++, ofs+=3) {
825                         asprintf(&buff,"dev%d_%s_%s-%c", m_id, mode_str,
826                           aux_str, i==0?'L':'R');
827                         if (!addPort(s_processor, buff, direction, ofs, 0))
828                                 return false;
829                 }
830         }
831
832         // Unconditionally add the 8 analog capture ports since they are
833         // always present no matter what the device configuration is.
834         for (i=0; i<8; i++, ofs+=3) {
835                 asprintf(&buff,"dev%d_%s_Analog%d", m_id, mode_str, i+1);
836                 if (!addPort(s_processor, buff, direction, ofs, 0))
837                         return false;
838         }
839
840         // AES/EBU ports are present for 1x and 2x sampling rates on the
841         // Traveler.  On earlier interfaces (for example, 828 MkII) this
842         // space was taken up with a separate "main out" send.
843         // FIXME: what is in this position of incoming data on an 828 MkII?
844         if (sample_rate <= 96000) {
845                 for (i=0; i<2; i++, ofs+=3) {
846                         if (m_motu_model == MOTUFW_MODEL_TRAVELER) {
847                                 asprintf(&buff,"dev%d_%s_AES/EBU%d", m_id, mode_str, i+1);
848                         } else {
849                                 if (direction == FreebobStreaming::Port::E_Capture)
850                                         asprintf(&buff,"dev%d_%s_Mic%d", m_id, mode_str, i+1);
851                                 else
852                                         asprintf(&buff,"dev%d_%s_MainOut-%c", m_id, mode_str, i==0?'L':'R');
853                         }
854                         if (!addPort(s_processor, buff, direction, ofs, 0))
855                                 return false;
856                 }
857         }
858
859         // SPDIF ports are present for 1x and 2x sampling rates so long
860         // as the optical mode is not TOSLINK.
861         if (sample_rate<=96000 && optical_mode!=MOTUFW_OPTICAL_MODE_TOSLINK) {
862                 for (i=0; i<2; i++, ofs+=3) {
863                         asprintf(&buff,"dev%d_%s_SPDIF%d", m_id, mode_str, i+1);
864                         if (!addPort(s_processor, buff, direction, ofs, 0))
865                                 return false;
866                 }
867         }
868
869         // TOSLINK ports are present for 1x and 2x sampling rates so long
870         // as the optical mode is set to TOSLINK.
871         if (sample_rate<=96000 && optical_mode==MOTUFW_OPTICAL_MODE_TOSLINK) {
872                 for (i=0; i<2; i++, ofs+=3) {
873                         asprintf(&buff,"dev%d_%s_TOSLINK%d", m_id, mode_str, i+1);
874                         if (!addPort(s_processor, buff, direction, ofs, 0))
875                                 return false;
876                 }
877         }
878
879         // ADAT ports 1-4 are present for 1x and 2x sampling rates so long
880         // as the optical mode is set to ADAT.
881         if (sample_rate<=96000 && optical_mode==MOTUFW_OPTICAL_MODE_ADAT) {
882                 for (i=0; i<4; i++, ofs+=3) {
883                         asprintf(&buff,"dev%d_%s_ADAT%d", m_id, mode_str, i+1);
884                         if (!addPort(s_processor, buff, direction, ofs, 0))
885                                 return false;
886                 }
887         }
888
889         // ADAT ports 5-8 are present for 1x sampling rates so long as the
890         // optical mode is set to ADAT.
891         if (sample_rate<=48000 && optical_mode==MOTUFW_OPTICAL_MODE_ADAT) {
892                 for (i=4; i<8; i++, ofs+=3) {
893                         asprintf(&buff,"dev%d_%s_ADAT%d", m_id, mode_str, i+1);
894                         if (!addPort(s_processor, buff, direction, ofs, 0))
895                                 return false;
896                 }
897         }
898
899         return true;
900 }
901 /* ======================================================================== */
902
903 unsigned int MotuDevice::ReadRegister(unsigned int reg) {
904 /*
905  * Attempts to read the requested register from the MOTU.
906  */
907
908 quadlet_t quadlet;
909 assert(m_1394Service);
910        
911   quadlet = 0;
912   // Note: 1394Service::read() expects a physical ID, not the node id
913   if (m_1394Service->read(0xffc0 | m_nodeId, MOTUFW_BASE_ADDR+reg, 4, &quadlet) < 0) {
914     debugError("Error doing motu read from register 0x%06x\n",reg);
915   }
916
917   return ntohl(quadlet);
918 }
919
920 signed int MotuDevice::WriteRegister(unsigned int reg, quadlet_t data) {
921 /*
922  * Attempts to write the given data to the requested MOTU register.
923  */
924
925   unsigned int err = 0;
926   data = htonl(data);
927
928   // Note: 1394Service::write() expects a physical ID, not the node id
929   if (m_1394Service->write(0xffc0 | m_nodeId, MOTUFW_BASE_ADDR+reg, 4, &data) < 0) {
930     err = 1;
931     debugError("Error doing motu write to register 0x%06x\n",reg);
932   }
933
934   usleep(100);
935   return (err==0)?0:-1;
936 }
937
938 }
Note: See TracBrowser for help on using the browser.