root/branches/streaming-rework/src/motu/motu_avdevice.cpp

Revision 409, 27.3 kB (checked in by jwoithe, 16 years ago)

MOTU: the calculated bandwidth is already a per channel figure.

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