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

Revision 2005, 30.1 kB (checked in by jwoithe, 9 years ago)

rme: initial experiments to hook the MatrixMixer? widget into the RME ffado-mixer module. More to be done.

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