root/trunk/libffado/src/rme/rme_avdevice.cpp

Revision 1993, 29.4 kB (checked in by jwoithe, 13 years ago)

rme: clean up debug output by replacing "temporary" printf() calls with debugOutput(). Remove unnecessary register reads used during early stages of development.

Line 
1 /*
2  * Copyright (C) 2005-2011 by Jonathan Woithe
3  * Copyright (C) 2005-2008 by Pieter Palmers
4  *
5  * This file is part of FFADO
6  * FFADO = Free Firewire (pro-)audio drivers for linux
7  *
8  * FFADO is based upon FreeBoB.
9  *
10  * This program is free software: you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation, either version 2 of the License, or
13  * (at your option) version 3 of the License.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
22  *
23  */
24
25 #warning RME support is at an early development stage and is not functional
26
27 #include "config.h"
28
29 #include "rme/rme_avdevice.h"
30 #include "rme/fireface_def.h"
31 #include "rme/fireface_settings_ctrls.h"
32
33 #include "libieee1394/configrom.h"
34 #include "libieee1394/ieee1394service.h"
35 #include "libieee1394/IsoHandlerManager.h"
36
37 #include "debugmodule/debugmodule.h"
38
39 #include "libstreaming/rme/RmePort.h"
40
41 #include "devicemanager.h"
42
43 #include <string>
44 #include <stdint.h>
45 #include <assert.h>
46 #include "libutil/ByteSwap.h"
47
48 #include <iostream>
49 #include <sstream>
50
51 #include <libraw1394/csr.h>
52
53 // Known values for the unit version of RME devices
54 #define RME_UNITVERSION_FF800  0x0001
55 #define RME_UNITVERSION_FF400  0x0002
56
57 namespace Rme {
58
59 // The RME devices expect async packet data in little endian format (as
60 // opposed to bus order, which is big endian).  Therefore define our own
61 // 32-bit byteswap function to do this.
62 #if __BYTE_ORDER == __BIG_ENDIAN
63 static inline uint32_t
64 ByteSwapToDevice32(uint32_t d)
65 {
66     return byteswap_32(d);
67 }
68 ByteSwapFromDevice32(uint32_t d)
69 {
70     return byteswap_32(d);
71 }
72 #else
73 static inline uint32_t
74 ByteSwapToDevice32(uint32_t d)
75 {
76     return d;
77 }
78 static inline uint32_t
79 ByteSwapFromDevice32(uint32_t d)
80 {
81     return d;
82 }
83 #endif
84
85 Device::Device( DeviceManager& d,
86                       std::auto_ptr<ConfigRom>( configRom ))
87     : FFADODevice( d, configRom )
88     , m_rme_model( RME_MODEL_NONE )
89     , num_channels( 0 )
90     , frames_per_packet( 0 )
91     , speed800( 0 )
92     , iso_tx_channel( -1 )
93     , iso_rx_channel( -1 )
94     , m_receiveProcessor( NULL )
95     , m_transmitProcessor( NULL )
96     , m_MixerContainer( NULL )
97     , m_ControlContainer( NULL )
98 {
99     debugOutput( DEBUG_LEVEL_VERBOSE, "Created Rme::Device (NodeID %d)\n",
100                  getConfigRom().getNodeId() );
101 }
102
103 Device::~Device()
104 {
105     delete m_receiveProcessor;
106     delete m_transmitProcessor;
107
108     if (iso_tx_channel>=0 && !get1394Service().freeIsoChannel(iso_tx_channel)) {
109         debugOutput(DEBUG_LEVEL_VERBOSE, "Could not free tx iso channel %d\n", iso_tx_channel);
110     }
111     if (iso_rx_channel>=0 && !get1394Service().freeIsoChannel(iso_rx_channel)) {
112         debugOutput(DEBUG_LEVEL_VERBOSE, "Could not free rx iso channel %d\n", iso_rx_channel);
113     }
114
115     destroyMixer();
116
117     if (dev_config != NULL) {
118         switch (rme_shm_close(dev_config)) {
119             case RSO_CLOSE:
120                 debugOutput( DEBUG_LEVEL_VERBOSE, "Configuration shared data object closed\n");
121                 break;
122             case RSO_CLOSE_DELETE:
123                 debugOutput( DEBUG_LEVEL_VERBOSE, "Configuration shared data object closed and deleted (no other users)\n");
124                 break;
125         }
126     }
127 }
128
129 bool
130 Device::buildMixer() {
131     signed int i;
132     bool result = true;
133
134     destroyMixer();
135     debugOutput(DEBUG_LEVEL_VERBOSE, "Building an RME mixer...\n");
136
137
138     // Non-mixer device controls
139     m_ControlContainer = new Control::Container(this, "Control");
140     if (!m_ControlContainer) {
141         debugError("Could not create control container\n");
142         destroyMixer();
143         return false;
144     }
145
146     result &= m_ControlContainer->addElement(
147         new RmeSettingsCtrl(*this, RME_CTRL_INFO_MODEL, 0,
148             "Model", "Model ID", ""));
149     result &= m_ControlContainer->addElement(
150         new RmeSettingsCtrl(*this, RME_CTRL_INFO_TCO_PRESENT, 0,
151             "TCO_present", "TCO is present", ""));
152
153     result &= m_ControlContainer->addElement(
154         new RmeSettingsCtrl(*this, RME_CTRL_PHANTOM_SW, 0,
155             "Phantom", "Phantom switches", ""));
156     result &= m_ControlContainer->addElement(
157         new RmeSettingsCtrl(*this, RME_CTRL_INPUT_LEVEL, 0,
158             "Input_level", "Input level", ""));
159     result &= m_ControlContainer->addElement(
160         new RmeSettingsCtrl(*this, RME_CTRL_OUTPUT_LEVEL, 0,
161             "Output_level", "Output level", ""));
162     result &= m_ControlContainer->addElement(
163         new RmeSettingsCtrl(*this, RME_CTRL_PHONES_LEVEL, 0,
164             "Phones_level", "Phones level", ""));
165
166     if (m_rme_model == RME_MODEL_FIREFACE400) {
167         // Instrument input options
168         for (i=3; i<=4; i++) {
169             char path[32], desc[64];
170             snprintf(path, sizeof(path), "Chan%d_opt_instr", i);
171             snprintf(desc, sizeof(desc), "Chan%d instrument option", i);
172             result &= m_ControlContainer->addElement(
173                 new RmeSettingsCtrl(*this, RME_CTRL_FF400_INSTR_SW, i,
174                     path, desc, ""));
175             snprintf(path, sizeof(path), "Chan%d_opt_pad", i);
176             snprintf(desc, sizeof(desc), "Chan%d pad option", i);
177             result &= m_ControlContainer->addElement(
178                 new RmeSettingsCtrl(*this, RME_CTRL_FF400_PAD_SW, i,
179                     path, desc, ""));
180         }
181
182         // Input/output gains
183         result &= m_ControlContainer->addElement(
184             new RmeSettingsMatrixCtrl(*this, RME_MATRIXCTRL_GAINS, "Gains"));
185     }
186
187     if (!result) {
188         debugWarning("One or more device control elements could not be created\n");
189         destroyMixer();
190         return false;
191     }
192
193     if (!addElement(m_ControlContainer)) {
194         debugWarning("Could not register mixer to device\n");
195         // clean up
196         destroyMixer();
197         return false;
198     }
199
200     return true;
201 }
202
203 bool
204 Device::destroyMixer() {
205     bool ret = true;
206     debugOutput(DEBUG_LEVEL_VERBOSE, "destroy mixer...\n");
207
208     if (m_MixerContainer == NULL) {
209         debugOutput(DEBUG_LEVEL_VERBOSE, "no mixer to destroy...\n");
210     } else
211     if (!deleteElement(m_MixerContainer)) {
212         debugError("Mixer present but not registered to the avdevice\n");
213         ret = false;
214     } else {
215         // remove and delete (as in free) child control elements
216         m_MixerContainer->clearElements(true);
217         delete m_MixerContainer;
218         m_MixerContainer = NULL;
219     }
220
221     // remove control container
222     if (m_ControlContainer == NULL) {
223         debugOutput(DEBUG_LEVEL_VERBOSE, "no controls to destroy...\n");
224     } else
225     if (!deleteElement(m_ControlContainer)) {
226         debugError("Controls present but not registered to the avdevice\n");
227         ret = false;
228     } else {
229         // remove and delete (as in free) child control elements
230         m_ControlContainer->clearElements(true);
231         delete m_ControlContainer;
232         m_ControlContainer = NULL;
233     }
234
235     return false;
236 }
237
238 bool
239 Device::probe( Util::Configuration& c, ConfigRom& configRom, bool generic )
240 {
241     if (generic) {
242         return false;
243     } else {
244         // check if device is in supported devices list.  Note that the RME
245         // devices use the unit version to identify the individual devices.
246         // To avoid having to extend the configuration file syntax to
247         // include this at this point, we'll use the configuration file
248         // model ID to test against the device unit version.  This can be
249         // tidied up if the configuration file is extended at some point to
250         // include the unit version.
251         unsigned int vendorId = configRom.getNodeVendorId();
252         unsigned int unitVersion = configRom.getUnitVersion();
253
254         Util::Configuration::VendorModelEntry vme = c.findDeviceVME( vendorId, unitVersion );
255         return c.isValid(vme) && vme.driver == Util::Configuration::eD_RME;
256     }
257 }
258
259 FFADODevice *
260 Device::createDevice(DeviceManager& d, std::auto_ptr<ConfigRom>( configRom ))
261 {
262     return new Device(d, configRom );
263 }
264
265 bool
266 Device::discover()
267 {
268     signed int i;
269     unsigned int vendorId = getConfigRom().getNodeVendorId();
270     // See note in Device::probe() about why we use the unit version here.
271     unsigned int unitVersion = getConfigRom().getUnitVersion();
272
273     Util::Configuration &c = getDeviceManager().getConfiguration();
274     Util::Configuration::VendorModelEntry vme = c.findDeviceVME( vendorId, unitVersion );
275
276     if (c.isValid(vme) && vme.driver == Util::Configuration::eD_RME) {
277         debugOutput( DEBUG_LEVEL_VERBOSE, "found %s %s\n",
278                      vme.vendor_name.c_str(),
279                      vme.model_name.c_str());
280     } else {
281         debugWarning("Device '%s %s' unsupported by RME driver (no generic RME support)\n",
282                      getConfigRom().getVendorName().c_str(), getConfigRom().getModelName().c_str());
283     }
284
285     if (unitVersion == RME_UNITVERSION_FF800) {
286         m_rme_model = RME_MODEL_FIREFACE800;
287     } else
288     if (unitVersion == RME_MODEL_FIREFACE400) {
289         m_rme_model = RME_MODEL_FIREFACE400;
290     } else {
291         debugError("Unsupported model\n");
292         return false;
293     }
294
295     // Set up the shared data object for configuration data
296     i = rme_shm_open(&dev_config);
297     if (i == RSO_OPEN_CREATED) {
298         debugOutput( DEBUG_LEVEL_VERBOSE, "New configuration shared data object created\n");
299     } else
300     if (i == RSO_OPEN_ATTACHED) {
301         debugOutput( DEBUG_LEVEL_VERBOSE, "Attached to existing configuration shared data object\n");
302     }
303     if (dev_config == NULL) {
304         debugOutput( DEBUG_LEVEL_WARNING, "Could not create/access shared configuration memory object, using process-local storage\n");
305         memset(&local_dev_config_obj, 0, sizeof(local_dev_config_obj));
306         dev_config = &local_dev_config_obj;
307     }
308     settings = &dev_config->settings;
309     tco_settings = &dev_config->tco_settings;
310
311     // If device is FF800, check to see if the TCO is fitted
312     if (m_rme_model == RME_MODEL_FIREFACE800) {
313         dev_config->tco_present = (read_tco(NULL, 0) == 0);
314     }
315     debugOutput(DEBUG_LEVEL_VERBOSE, "TCO present: %s\n",
316       dev_config->tco_present?"yes":"no");
317
318     init_hardware();
319
320     if (!buildMixer()) {
321         debugWarning("Could not build mixer\n");
322     }
323
324     // This is just for testing
325     read_device_flash_settings(NULL);
326
327     return true;
328 }
329
330 int
331 Device::getSamplingFrequency( ) {
332
333     // Retrieve the current sample rate.  For practical purposes this
334     // is the software rate currently in use.
335     return dev_config->software_freq;
336 }
337
338 int
339 Device::getConfigurationId()
340 {
341     return 0;
342 }
343
344 bool
345 Device::setDDSFrequency( int dds_freq )
346 {
347     // Set a fixed DDS frequency.  If the device is the clock master this
348     // will immediately be copied to the hardware DDS register.  Otherwise
349     // it will take effect as required at the time the sampling rate is
350     // changed or streaming is started.
351
352     // If the device is streaming, the new DDS rate must have the same
353     // multiplier as the software sample rate
354     if (hardware_is_streaming()) {
355         if (multiplier_of_freq(dds_freq) != multiplier_of_freq(dev_config->software_freq))
356             return false;
357     }
358
359     dev_config->dds_freq = dds_freq;
360     if (settings->clock_mode == FF_STATE_CLOCKMODE_MASTER) {
361         if (set_hardware_dds_freq(dds_freq) != 0)
362             return false;
363     }
364
365     return true;
366 }
367
368 bool
369 Device::setSamplingFrequency( int samplingFrequency )
370 {
371     // Request a sampling rate on behalf of software.  Software is limited
372     // to sample rates of 32k, 44.1k, 48k and the 2x/4x multiples of these.
373     // The user may lock the device to a much wider range of frequencies via
374     // the explicit DDS controls in the control panel.  If the explicit DDS
375     // control is active the software is limited to the "standard" speeds
376     // corresponding to the multiplier in use by the DDS.
377     //
378     // Similarly, if the device is externally clocked the software is
379     // limited to the external clock frequency.
380     //
381     // Otherwise the software has free choice of the software speeds noted
382     // above.
383
384     bool ret = -1;
385     signed int i, j;
386     signed int mult[3] = {1, 2, 4};
387     signed int base_freq[3] = {32000, 44100, 48000};
388     signed int freq = samplingFrequency;
389     FF_state_t state;
390     signed int fixed_freq = 0;
391
392     get_hardware_state(&state);
393
394     // If device is locked to a frequency via external clock, explicit
395     // setting of the DDS or by virtue of streaming being active, get that
396     // frequency.
397     if (state.clock_mode == FF_STATE_CLOCKMODE_AUTOSYNC) {
398         // FIXME: if synced to TCO, is autosync_freq valid?
399         fixed_freq = state.autosync_freq;
400     } else
401     if (dev_config->dds_freq > 0) {
402         fixed_freq = dev_config->dds_freq;
403     } else
404     if (hardware_is_streaming()) {
405         fixed_freq = dev_config->software_freq;
406     }
407
408     // If the device is running to a fixed frequency, software can only
409     // request frequencies with the same multiplier.  Similarly, the
410     // multiplier is locked in "master" clock mode if the device is
411     // streaming.
412     if (fixed_freq > 0) {
413         signed int fixed_mult = multiplier_of_freq(fixed_freq);
414         if (multiplier_of_freq(freq) != multiplier_of_freq(fixed_freq))
415             return -1;
416         for (j=0; j<3; j++) {
417             if (freq == base_freq[j]*fixed_mult) {
418                 ret = 0;
419                 break;
420             }
421         }
422     } else {
423         for (i=0; i<3; i++) {
424             for (j=0; j<3; j++) {
425                 if (freq == base_freq[j]*mult[i]) {
426                     ret = 0;
427                     break;
428                 }
429             }
430         }
431     }
432     // If requested frequency is unavailable, return -1
433     if (ret == -1)
434         return false;
435
436     // If a DDS frequency has been explicitly requested this is always
437     // used to programm the hardware DDS regardless of the rate requested
438     // by the software.  Otherwise we use the requested sampling rate.
439     if (dev_config->dds_freq > 0)
440         freq = dev_config->dds_freq;
441     if (set_hardware_dds_freq(freq) != 0)
442         return false;
443
444     dev_config->software_freq = samplingFrequency;
445     return true;
446 }
447
448 std::vector<int>
449 Device::getSupportedSamplingFrequencies()
450 {
451     std::vector<int> frequencies;
452     signed int i, j;
453     signed int mult[3] = {1, 2, 4};
454     signed int freq[3] = {32000, 44100, 48000};
455     FF_state_t state;
456
457     get_hardware_state(&state);
458
459     // Generate the list of supported frequencies.  If the device is
460     // externally clocked the frequency is limited to the external clock
461     // frequency.  If the device is running the multiplier is fixed.
462     if (state.clock_mode == FF_STATE_CLOCKMODE_AUTOSYNC) {
463         // FIXME: if synced to TCO, is autosync_freq valid?
464         frequencies.push_back(state.autosync_freq);
465     } else
466     if (state.is_streaming) {
467         unsigned int fixed_mult = multiplier_of_freq(dev_config->software_freq);
468         for (j=0; j<3; j++) {
469             frequencies.push_back(freq[j]*fixed_mult);
470         }
471     } else {
472         for (i=0; i<3; i++) {
473             for (j=0; j<3; j++) {
474                 frequencies.push_back(freq[j]*mult[i]);
475             }
476         }
477     }
478     return frequencies;
479 }
480
481 FFADODevice::ClockSourceVector
482 Device::getSupportedClockSources() {
483     FFADODevice::ClockSourceVector r;
484     return r;
485 }
486
487 bool
488 Device::setActiveClockSource(ClockSource s) {
489     return false;
490 }
491
492 FFADODevice::ClockSource
493 Device::getActiveClockSource() {
494     ClockSource s;
495     return s;
496 }
497
498 bool
499 Device::lock() {
500
501     return true;
502 }
503
504
505 bool
506 Device::unlock() {
507
508     return true;
509 }
510
511 void
512 Device::showDevice()
513 {
514     unsigned int vendorId = getConfigRom().getNodeVendorId();
515     unsigned int modelId = getConfigRom().getModelId();
516
517     Util::Configuration &c = getDeviceManager().getConfiguration();
518     Util::Configuration::VendorModelEntry vme = c.findDeviceVME( vendorId, modelId );
519
520     debugOutput(DEBUG_LEVEL_VERBOSE,
521         "%s %s at node %d\n", vme.vendor_name.c_str(), vme.model_name.c_str(), getNodeId());
522 }
523
524 bool
525 Device::prepare() {
526
527     signed int mult, bandwidth;
528     signed int freq, init_samplerate;
529     signed int err = 0;
530     unsigned int stat[4];
531
532     debugOutput(DEBUG_LEVEL_NORMAL, "Preparing Device...\n" );
533
534     // If there is no iso data to send in a given cycle the RMEs simply
535     // don't send anything.  This is in contrast to most other interfaces
536     // which at least send an empty packet.  As a result the IsoHandler
537     // contains code which detects missing packets as dropped packets.
538     // For RME devices we must turn this test off since missing packets
539     // are in fact to be expected.
540     get1394Service().getIsoHandlerManager().setMissedCyclesOK(true);
541
542     freq = getSamplingFrequency();
543     if (freq <= 0) {
544         debugOutput(DEBUG_LEVEL_ERROR, "Can't continue: sampling frequency not set\n");
545         return false;
546     }
547     mult = freq<68100?1:(freq<136200?2:4);
548
549     frames_per_packet = getFramesPerPacket();
550
551     // The number of active channels depends on sample rate and whether
552     // bandwidth limitation is active.  First set up the number of analog
553     // channels (which differs between devices), then add SPDIF channels if
554     // relevant.  Finally, the number of channels available from each ADAT
555     // interface depends on sample rate: 0 at 4x, 4 at 2x and 8 at 1x.
556     if (m_rme_model == RME_MODEL_FIREFACE800)
557         num_channels = 10;
558     else
559         num_channels = 8;
560     if (settings->limit_bandwidth != FF_SWPARAM_BWLIMIT_ANALOG_ONLY)
561         num_channels += 2;
562     if (settings->limit_bandwidth==FF_SWPARAM_BWLIMIT_SEND_ALL_CHANNELS)
563         num_channels += (mult==4?0:(mult==2?4:8));
564     if (m_rme_model==RME_MODEL_FIREFACE800 &&
565         settings->limit_bandwidth==FF_SWPARAM_BWLIMIT_SEND_ALL_CHANNELS)
566         num_channels += (mult==4?0:(mult==2?4:8));
567
568     // Bandwidth is calculated here.  For the moment we assume the device
569     // is connected at S400, so 1 allocation unit is 1 transmitted byte.
570     // There is 25 allocation units of protocol overhead per packet.  Each
571     // channel of audio data is sent/received as a 32 bit integer.
572     bandwidth = 25 + num_channels*4*frames_per_packet;
573
574     // Both the FF400 and FF800 require we allocate a tx iso channel and
575     // then initialise the device.  Device status is then read at least once
576     // regardless of which interface is in use.  The rx channel is then
577     // allocated for the FF400 or acquired from the device in the case of
578     // the FF800.  Even though the FF800 chooses the rx channel it does not
579     // handle the bus-level channel/bandwidth allocation so we must do that
580     // here.
581     if (iso_tx_channel < 0) {
582         iso_tx_channel = get1394Service().allocateIsoChannelGeneric(bandwidth);
583     }
584     if (iso_tx_channel < 0) {
585         debugFatal("Could not allocate iso tx channel\n");
586         return false;
587     }
588
589     err = hardware_init_streaming(dev_config->hardware_freq, iso_tx_channel) != 0;
590     if (err) {
591         debugFatal("Could not intialise device streaming system\n");
592     }
593
594     if (err == 0) {
595         signed int i;
596         for (i=0; i<100; i++) {
597             err = (get_hardware_streaming_status(stat, 4) != 0);
598             if (err) {
599                 debugFatal("error reading status register\n");
600                 break;
601             }
602
603 // FIXME: this can probably go once the driver matures.
604 debugOutput(DEBUG_LEVEL_NORMAL, "init stat: %08x %08x %08x %08x\n",
605   stat[0], stat[1], stat[2], stat[3]);
606
607             if (m_rme_model == RME_MODEL_FIREFACE400) {
608                 iso_rx_channel = get1394Service().allocateIsoChannelGeneric(bandwidth);
609                 break;
610             }
611             // The Fireface-800 chooses its tx channel (our rx channel).
612             if (stat[2] == 0xffffffff) {
613                 // Device not ready; wait 5 ms and try again
614                 usleep(5000);
615             } else {
616                 iso_rx_channel = stat[2] & 63;
617                 iso_rx_channel = get1394Service().allocateFixedIsoChannelGeneric(iso_rx_channel, bandwidth);
618             }
619         }
620         if (iso_rx_channel < 0) {
621             debugFatal("Could not allocate/determine iso rx channel\n");
622             err = 1;
623         }
624     }
625  
626     if (err) {
627         if (iso_tx_channel >= 0)
628             get1394Service().freeIsoChannel(iso_tx_channel);
629         if (iso_rx_channel >= 0)
630             get1394Service().freeIsoChannel(iso_rx_channel);
631         return false;
632     }
633
634     if ((stat[1] & SR1_CLOCK_MODE_MASTER) ||
635         (stat[0] & SR0_AUTOSYNC_FREQ_MASK)==0 ||
636         (stat[0] & SR0_AUTOSYNC_SRC_MASK)==SR0_AUTOSYNC_SRC_NONE) {
637         init_samplerate = dev_config->hardware_freq;
638     } else {
639         init_samplerate = (stat[0] & SR0_STREAMING_FREQ_MASK) * 250;
640     }
641
642     debugOutput(DEBUG_LEVEL_VERBOSE, "sample rate on start: %d\n",
643         init_samplerate);
644
645     // get the device specific and/or global SP configuration
646     Util::Configuration &config = getDeviceManager().getConfiguration();
647     // base value is the config.h value
648     float recv_sp_dll_bw = STREAMPROCESSOR_DLL_BW_HZ;
649     float xmit_sp_dll_bw = STREAMPROCESSOR_DLL_BW_HZ;
650
651     // we can override that globally
652     config.getValueForSetting("streaming.spm.recv_sp_dll_bw", recv_sp_dll_bw);
653     config.getValueForSetting("streaming.spm.xmit_sp_dll_bw", xmit_sp_dll_bw);
654
655     // or override in the device section
656     config.getValueForDeviceSetting(getConfigRom().getNodeVendorId(), getConfigRom().getModelId(), "recv_sp_dll_bw", recv_sp_dll_bw);
657     config.getValueForDeviceSetting(getConfigRom().getNodeVendorId(), getConfigRom().getModelId(), "xmit_sp_dll_bw", xmit_sp_dll_bw);
658
659     // Calculate the event size.  Each audio channel is allocated 4 bytes in
660     // the data stream.
661     /* FIXME: this will still require fine-tuning, but it's a start */
662     signed int event_size = num_channels * 4;
663
664     // Set up receive stream processor, initialise it and set DLL bw
665     m_receiveProcessor = new Streaming::RmeReceiveStreamProcessor(*this,
666       m_rme_model, event_size);
667     m_receiveProcessor->setVerboseLevel(getDebugLevel());
668     if (!m_receiveProcessor->init()) {
669         debugFatal("Could not initialize receive processor!\n");
670         return false;
671     }
672     if (!m_receiveProcessor->setDllBandwidth(recv_sp_dll_bw)) {
673         debugFatal("Could not set DLL bandwidth\n");
674         delete m_receiveProcessor;
675         m_receiveProcessor = NULL;
676         return false;
677     }
678
679     // Add ports to the processor - TODO
680     std::string id=std::string("dev?");
681     if (!getOption("id", id)) {
682         debugWarning("Could not retrieve id parameter, defaulting to 'dev?'\n");
683     }
684     addDirPorts(Streaming::Port::E_Capture);
685
686     /* Now set up the transmit stream processor */
687     m_transmitProcessor = new Streaming::RmeTransmitStreamProcessor(*this,
688       m_rme_model, event_size);
689     m_transmitProcessor->setVerboseLevel(getDebugLevel());
690     if (!m_transmitProcessor->init()) {
691         debugFatal("Could not initialise receive processor!\n");
692         return false;
693     }
694     if (!m_transmitProcessor->setDllBandwidth(xmit_sp_dll_bw)) {
695         debugFatal("Could not set DLL bandwidth\n");
696         delete m_transmitProcessor;
697         m_transmitProcessor = NULL;
698         return false;
699     }
700
701     // Other things to be done:
702     //  * add ports to transmit stream processor
703     addDirPorts(Streaming::Port::E_Playback);
704
705     return true;
706 }
707
708 int
709 Device::getStreamCount() {
710     return 2; // one receive, one transmit
711 }
712
713 Streaming::StreamProcessor *
714 Device::getStreamProcessorByIndex(int i) {
715     switch (i) {
716         case 0:
717             return m_receiveProcessor;
718         case 1:
719             return m_transmitProcessor;
720         default:
721             debugWarning("Invalid stream index %d\n", i);
722     }
723     return NULL;
724 }
725
726 bool
727 Device::startStreamByIndex(int i) {
728     // The RME does not allow separate enabling of the transmit and receive
729     // streams.  Therefore we start all streaming when index 0 is referenced
730     // and silently ignore the start requests for other streams
731     // (unconditionally flagging them as being successful).
732     if (i == 0) {
733         m_receiveProcessor->setChannel(iso_rx_channel);
734         m_transmitProcessor->setChannel(iso_tx_channel);
735         if (hardware_start_streaming(iso_rx_channel) != 0)
736             return false;
737     }
738     return true;
739 }
740
741 bool
742 Device::stopStreamByIndex(int i) {
743     // See comments in startStreamByIndex() as to why we act only when stream
744     // 0 is requested.
745     if (i == 0) {
746         if (hardware_stop_streaming() != 0)
747             return false;
748     }
749     return true;
750 }
751
752 signed int
753 Device::getFramesPerPacket(void) {
754     // The number of frames transmitted in a single packet is solely
755     // determined by the sample rate.
756     signed int freq = getSamplingFrequency();
757     signed int mult = multiplier_of_freq(freq);
758     switch (mult) {
759         case 2: return 15;
760         case 4: return 25;
761     default:
762         return 7;
763     }
764     return 7;
765 }
766
767 bool
768 Device::addPort(Streaming::StreamProcessor *s_processor,
769     char *name, enum Streaming::Port::E_Direction direction,
770     int position, int size) {
771
772     Streaming::Port *p;
773     p = new Streaming::RmeAudioPort(*s_processor, name, direction, position, size);
774     if (p == NULL) {
775         debugOutput(DEBUG_LEVEL_VERBOSE, "Skipped port %s\n",name);
776     }
777     return true;
778 }
779
780 bool
781 Device::addDirPorts(enum Streaming::Port::E_Direction direction) {
782
783     const char *mode_str = direction==Streaming::Port::E_Capture?"cap":"pbk";
784     Streaming::StreamProcessor *s_processor;
785     std::string id;
786     char name[128];
787     signed int i;
788     signed int n_analog, n_phones, n_adat, n_spdif;
789     signed int sample_rate = getSamplingFrequency();
790
791     /* Apply bandwidth limit if selected.  This effectively sets up the
792      * number of adat and spdif channels assuming single-rate speed.
793      */
794     n_spdif = 2;
795     switch (dev_config->settings.limit_bandwidth) {
796       case FF_SWPARAM_BWLIMIT_ANALOG_ONLY:
797         n_adat = n_spdif = 0;
798         break;
799       case FF_SWPARAM_BWLIMIT_ANALOG_SPDIF_ONLY:
800         n_adat = 0;
801         break;
802       case FF_SWPARAM_BWLIMIT_NO_ADAT2:
803         /* FF800 only */
804         n_adat = 8;
805         break;
806       default:
807         /* Send all channels */
808         n_adat = (m_rme_model==RME_MODEL_FIREFACE800)?16:8;
809     }
810
811     /* Work out the number of analog channels based on the device model and
812      * adjust the spdif and ADAT channels according to the current sample
813      * rate.
814      */
815     n_analog = (m_rme_model==RME_MODEL_FIREFACE800)?10:8;
816     n_phones = 0;
817     if (sample_rate>=MIN_DOUBLE_SPEED && sample_rate<MIN_QUAD_SPEED) {
818       n_adat /= 2;
819     } else
820     if (sample_rate >= MIN_QUAD_SPEED) {
821       n_adat = 0;
822       n_spdif = 0;
823     }
824
825     if (direction == Streaming::Port::E_Capture) {
826         s_processor = m_receiveProcessor;
827     } else {
828         s_processor = m_transmitProcessor;
829         /* Phones count as two of the analog outputs */
830         n_analog -= 2;
831         n_phones = 2;
832     }
833
834     id = std::string("dev?");
835     if (!getOption("id", id)) {
836         debugWarning("Could not retrieve id parameter, defaulting to 'dev?'\n");
837     }
838
839     for (i=0; i<n_analog; i++) {
840       snprintf(name, sizeof(name), "%s_%s_analog-%d", id.c_str(), mode_str, i+1);
841       addPort(s_processor, name, direction, i*4, 0);
842     }
843     for (i=0; i<n_phones; i++) {
844       snprintf(name, sizeof(name), "%s_%s_phones-%c", id.c_str(), mode_str,
845         i==0?'L':'R');
846       /* The headphone channels start at offset 24 */
847       addPort(s_processor, name, direction, 24+i*4, 0);
848     }
849     for (i=0; i<n_spdif; i++) {
850       snprintf(name, sizeof(name), "%s_%s_SPDIF-%d", id.c_str(), mode_str, i+1);
851       /* The SPDIF channels start at offset 32 */
852       addPort(s_processor, name, direction, 32+i*4, 0);
853     }
854     for (i=0; i<n_adat; i++) {
855       snprintf(name, sizeof(name), "%s_%s_adat-%d", id.c_str(), mode_str, i+1);
856       /* ADAT ports start at offset 40 */
857       addPort(s_processor, name, direction, 40+i*4, 0);
858     }
859
860     return true;
861 }
862
863 unsigned int
864 Device::readRegister(fb_nodeaddr_t reg) {
865
866     quadlet_t quadlet;
867    
868     quadlet = 0;
869     if (get1394Service().read(0xffc0 | getNodeId(), reg, 1, &quadlet) <= 0) {
870         debugError("Error doing RME read from register 0x%06llx\n",reg);
871     }
872     return ByteSwapFromDevice32(quadlet);
873 }
874
875 signed int
876 Device::readBlock(fb_nodeaddr_t reg, quadlet_t *buf, unsigned int n_quads) {
877
878     unsigned int i;
879
880     if (get1394Service().read(0xffc0 | getNodeId(), reg, n_quads, buf) <= 0) {
881         debugError("Error doing RME block read of %d quadlets from register 0x%06llx\n",
882             n_quads, reg);
883         return -1;
884     }
885     for (i=0; i<n_quads; i++) {
886        buf[i] = ByteSwapFromDevice32(buf[i]);
887     }
888
889     return 0;
890 }
891
892 signed int
893 Device::writeRegister(fb_nodeaddr_t reg, quadlet_t data) {
894
895     unsigned int err = 0;
896     data = ByteSwapToDevice32(data);
897     if (get1394Service().write(0xffc0 | getNodeId(), reg, 1, &data) <= 0) {
898         err = 1;
899         debugError("Error doing RME write to register 0x%06llx\n",reg);
900     }
901
902     return (err==0)?0:-1;
903 }
904
905 signed int
906 Device::writeBlock(fb_nodeaddr_t reg, quadlet_t *data, unsigned int n_quads) {
907 //
908 // Write a block of data to the device starting at address "reg".  Note that
909 // the conditional byteswap is done "in place" on data, so the contents of
910 // data may be modified by calling this function.
911 //
912     unsigned int err = 0;
913     unsigned int i;
914
915     for (i=0; i<n_quads; i++) {
916       data[i] = ByteSwapToDevice32(data[i]);
917     }
918     if (get1394Service().write(0xffc0 | getNodeId(), reg, n_quads, data) <= 0) {
919         err = 1;
920         debugError("Error doing RME block write of %d quadlets to register 0x%06llx\n",
921           n_quads, reg);
922     }
923
924     return (err==0)?0:-1;
925 }
926                  
927 }
Note: See TracBrowser for help on using the browser.