rme: fix 'analog 1-8' bandwidth limit mode for the FF800.
[ffado.git] / libffado / src / rme / rme_avdevice.cpp
blob3e0b928d77958843f262575fd2e969398e2e5f7c
1 /*
2 * Copyright (C) 2005-2012 by Jonathan Woithe
3 * Copyright (C) 2005-2008 by Pieter Palmers
5 * This file is part of FFADO
6 * FFADO = Free Firewire (pro-)audio drivers for linux
8 * FFADO is based upon FreeBoB.
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.
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.
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/>.
25 #warning RME support is reasonably functional but some bugs undoubtedly remain. Please report experiences on the ffado-devel mailing list.
27 #include "config.h"
29 #include "rme/rme_avdevice.h"
30 #include "rme/fireface_def.h"
31 #include "rme/fireface_settings_ctrls.h"
33 #include "libieee1394/configrom.h"
34 #include "libieee1394/ieee1394service.h"
35 #include "libieee1394/IsoHandlerManager.h"
37 #include "debugmodule/debugmodule.h"
39 #include "libstreaming/rme/RmePort.h"
41 #include "devicemanager.h"
43 #include <string>
44 #include <stdint.h>
45 #include <assert.h>
46 #include <unistd.h>
47 #include "libutil/ByteSwap.h"
49 #include <iostream>
50 #include <sstream>
52 #include <libraw1394/csr.h>
54 // Known values for the unit version of RME devices
55 #define RME_UNITVERSION_FF800 0x0001
56 #define RME_UNITVERSION_FF400 0x0002
57 #define RME_UNITVERSION_UFX 0x0003
58 #define RME_UNITVERSION_UCX 0x0004
60 namespace Rme {
62 // The RME devices expect packet data in little endian format (as
63 // opposed to bus order, which is big endian). Therefore define our own
64 // 32-bit byteswap function to account for this.
65 #if __BYTE_ORDER == __BIG_ENDIAN
66 #define RME_BYTESWAP32(x) ByteSwap32(x)
67 #else
68 #define RME_BYTESWAP32(x) (x)
69 #endif
71 static inline uint32_t
72 ByteSwapToDevice32(uint32_t d)
74 return RME_BYTESWAP32(d);
76 static inline uint32_t
77 ByteSwapFromDevice32(uint32_t d)
79 return RME_BYTESWAP32(d);
82 Device::Device( DeviceManager& d,
83 std::auto_ptr<ConfigRom>( configRom ))
84 : FFADODevice( d, configRom )
85 , m_rme_model( RME_MODEL_NONE )
86 , settings( NULL )
87 , tco_settings( NULL )
88 , dev_config ( NULL )
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 )
99 debugOutput( DEBUG_LEVEL_VERBOSE, "Created Rme::Device (NodeID %d)\n",
100 getConfigRom().getNodeId() );
103 Device::~Device()
105 delete m_receiveProcessor;
106 delete m_transmitProcessor;
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);
111 if (iso_rx_channel>=0 && m_rme_model==RME_MODEL_FIREFACE400 &&
112 !get1394Service().freeIsoChannel(iso_rx_channel)) {
113 // FF800 handles the rx channel itself
114 debugOutput(DEBUG_LEVEL_VERBOSE, "Could not free rx iso channel %d\n", iso_rx_channel);
117 destroyMixer();
119 if (dev_config != NULL) {
120 switch (rme_shm_close(dev_config)) {
121 case RSO_CLOSE:
122 debugOutput( DEBUG_LEVEL_VERBOSE, "Configuration shared data object closed\n");
123 break;
124 case RSO_CLOSE_DELETE:
125 debugOutput( DEBUG_LEVEL_VERBOSE, "Configuration shared data object closed and deleted (no other users)\n");
126 break;
131 bool
132 Device::buildMixer() {
133 signed int i;
134 bool result = true;
136 destroyMixer();
137 debugOutput(DEBUG_LEVEL_VERBOSE, "Building an RME mixer...\n");
140 // Non-mixer device controls
141 m_ControlContainer = new Control::Container(this, "Control");
142 if (!m_ControlContainer) {
143 debugError("Could not create control container\n");
144 destroyMixer();
145 return false;
148 result &= m_ControlContainer->addElement(
149 new RmeSettingsCtrl(*this, RME_CTRL_INFO_MODEL, 0,
150 "Model", "Model ID", ""));
151 result &= m_ControlContainer->addElement(
152 new RmeSettingsCtrl(*this, RME_CTRL_INFO_TCO_PRESENT, 0,
153 "TCO_present", "TCO is present", ""));
154 result &= m_ControlContainer->addElement(
155 new RmeSettingsCtrl(*this, RME_CTRL_INFO_SYSCLOCK_MODE, 0,
156 "sysclock_mode", "System clock mode", ""));
157 result &= m_ControlContainer->addElement(
158 new RmeSettingsCtrl(*this, RME_CTRL_INFO_SYSCLOCK_FREQ, 0,
159 "sysclock_freq", "System clock frequency", ""));
160 result &= m_ControlContainer->addElement(
161 new RmeSettingsCtrl(*this, RME_CTRL_INFO_AUTOSYNC_FREQ, 0,
162 "autosync_freq", "Autosync frequency", ""));
163 result &= m_ControlContainer->addElement(
164 new RmeSettingsCtrl(*this, RME_CTRL_INFO_AUTOSYNC_SRC, 0,
165 "autosync_src", "Autosync source", ""));
166 result &= m_ControlContainer->addElement(
167 new RmeSettingsCtrl(*this, RME_CTRL_INFO_SYNC_STATUS, 0,
168 "sync_status", "Sync status", ""));
169 result &= m_ControlContainer->addElement(
170 new RmeSettingsCtrl(*this, RME_CTRL_INFO_SPDIF_FREQ, 0,
171 "spdif_freq", "SPDIF frequency", ""));
173 result &= m_ControlContainer->addElement(
174 new RmeSettingsCtrl(*this, RME_CTRL_PHANTOM_SW, 0,
175 "Phantom", "Phantom switches", ""));
176 result &= m_ControlContainer->addElement(
177 new RmeSettingsCtrl(*this, RME_CTRL_INPUT_LEVEL, 0,
178 "Input_level", "Input level", ""));
179 result &= m_ControlContainer->addElement(
180 new RmeSettingsCtrl(*this, RME_CTRL_OUTPUT_LEVEL, 0,
181 "Output_level", "Output level", ""));
182 result &= m_ControlContainer->addElement(
183 new RmeSettingsCtrl(*this, RME_CTRL_SPDIF_INPUT_MODE, 0,
184 "SPDIF_input_mode", "SPDIF input mode", ""));
185 result &= m_ControlContainer->addElement(
186 new RmeSettingsCtrl(*this, RME_CTRL_SPDIF_OUTPUT_OPTICAL, 0,
187 "SPDIF_output_optical", "SPDIF output optical", ""));
188 result &= m_ControlContainer->addElement(
189 new RmeSettingsCtrl(*this, RME_CTRL_SPDIF_OUTPUT_EMPHASIS, 0,
190 "SPDIF_output_emphasis", "SPDIF output emphasis", ""));
191 result &= m_ControlContainer->addElement(
192 new RmeSettingsCtrl(*this, RME_CTRL_SPDIF_OUTPUT_PRO, 0,
193 "SPDIF_output_pro", "SPDIF output pro", ""));
194 result &= m_ControlContainer->addElement(
195 new RmeSettingsCtrl(*this, RME_CTRL_SPDIF_OUTPUT_NONAUDIO, 0,
196 "SPDIF_output_nonaudio", "SPDIF output non-audio", ""));
197 result &= m_ControlContainer->addElement(
198 new RmeSettingsCtrl(*this, RME_CTRL_PHONES_LEVEL, 0,
199 "Phones_level", "Phones level", ""));
201 result &= m_ControlContainer->addElement(
202 new RmeSettingsCtrl(*this, RME_CTRL_CLOCK_MODE, 0,
203 "Clock_mode", "Clock mode", ""));
204 result &= m_ControlContainer->addElement(
205 new RmeSettingsCtrl(*this, RME_CTRL_SYNC_REF, 0,
206 "Sync_ref", "Preferred sync ref", ""));
207 result &= m_ControlContainer->addElement(
208 new RmeSettingsCtrl(*this, RME_CTRL_LIMIT_BANDWIDTH, 0,
209 "Bandwidth_limit", "Bandwidth limit", ""));
211 result &= m_ControlContainer->addElement(
212 new RmeSettingsCtrl(*this, RME_CTRL_FLASH, 0,
213 "Flash_control", "Flash control", ""));
214 result &= m_ControlContainer->addElement(
215 new RmeSettingsCtrl(*this, RME_CTRL_MIXER_PRESET, 0,
216 "Mixer_preset", "Mixer preset", ""));
218 if (m_rme_model == RME_MODEL_FIREFACE800) {
219 result &= m_ControlContainer->addElement(
220 new RmeSettingsCtrl(*this, RME_CTRL_INPUT_SOURCE, 1,
221 "Chan1_source", "Channel 1 source", ""));
222 result &= m_ControlContainer->addElement(
223 new RmeSettingsCtrl(*this, RME_CTRL_INPUT_SOURCE, 7,
224 "Chan7_source", "Channel 7 source", ""));
225 result &= m_ControlContainer->addElement(
226 new RmeSettingsCtrl(*this, RME_CTRL_INPUT_SOURCE, 8,
227 "Chan8_source", "Channel 8 source", ""));
228 result &= m_ControlContainer->addElement(
229 new RmeSettingsCtrl(*this, RME_CTRL_INSTRUMENT_OPTIONS, 1,
230 "Chan1_instr_opts", "Input instrument options channel 1", ""));
233 if (m_rme_model == RME_MODEL_FIREFACE400) {
234 // Instrument input options
235 for (i=3; i<=4; i++) {
236 char path[32], desc[64];
237 snprintf(path, sizeof(path), "Chan%d_opt_instr", i);
238 snprintf(desc, sizeof(desc), "Chan%d instrument option", i);
239 result &= m_ControlContainer->addElement(
240 new RmeSettingsCtrl(*this, RME_CTRL_FF400_INSTR_SW, i,
241 path, desc, ""));
242 snprintf(path, sizeof(path), "Chan%d_opt_pad", i);
243 snprintf(desc, sizeof(desc), "Chan%d pad option", i);
244 result &= m_ControlContainer->addElement(
245 new RmeSettingsCtrl(*this, RME_CTRL_FF400_PAD_SW, i,
246 path, desc, ""));
249 // Input/output gains
250 result &= m_ControlContainer->addElement(
251 new RmeSettingsMatrixCtrl(*this, RME_MATRIXCTRL_GAINS, "Gains"));
254 /* Mixer controls */
255 m_MixerContainer = new Control::Container(this, "Mixer");
256 if (!m_MixerContainer) {
257 debugError("Could not create mixer container\n");
258 destroyMixer();
259 return false;
262 result &= m_MixerContainer->addElement(
263 new RmeSettingsMatrixCtrl(*this, RME_MATRIXCTRL_INPUT_FADER, "InputFaders"));
264 result &= m_MixerContainer->addElement(
265 new RmeSettingsMatrixCtrl(*this, RME_MATRIXCTRL_PLAYBACK_FADER, "PlaybackFaders"));
266 result &= m_MixerContainer->addElement(
267 new RmeSettingsMatrixCtrl(*this, RME_MATRIXCTRL_OUTPUT_FADER, "OutputFaders"));
268 result &= m_MixerContainer->addElement(
269 new RmeSettingsMatrixCtrl(*this, RME_MATRIXCTRL_INPUT_MUTE, "InputMutes"));
270 result &= m_MixerContainer->addElement(
271 new RmeSettingsMatrixCtrl(*this, RME_MATRIXCTRL_PLAYBACK_MUTE, "PlaybackMutes"));
272 result &= m_MixerContainer->addElement(
273 new RmeSettingsMatrixCtrl(*this, RME_MATRIXCTRL_OUTPUT_MUTE, "OutputMutes"));
274 result &= m_MixerContainer->addElement(
275 new RmeSettingsMatrixCtrl(*this, RME_MATRIXCTRL_INPUT_INVERT, "InputInverts"));
276 result &= m_MixerContainer->addElement(
277 new RmeSettingsMatrixCtrl(*this, RME_MATRIXCTRL_PLAYBACK_INVERT, "PlaybackInverts"));
279 if (!result) {
280 debugWarning("One or more device control/mixer elements could not be created\n");
281 destroyMixer();
282 return false;
285 if (!addElement(m_ControlContainer) || !addElement(m_MixerContainer)) {
286 debugWarning("Could not register controls/mixer to device\n");
287 // clean up
288 destroyMixer();
289 return false;
292 return true;
295 bool
296 Device::destroyMixer() {
297 bool ret = true;
298 debugOutput(DEBUG_LEVEL_VERBOSE, "destroy mixer...\n");
300 if (m_MixerContainer == NULL) {
301 debugOutput(DEBUG_LEVEL_VERBOSE, "no mixer to destroy...\n");
302 } else
303 if (!deleteElement(m_MixerContainer)) {
304 debugError("Mixer present but not registered to the avdevice\n");
305 ret = false;
306 } else {
307 // remove and delete (as in free) child control elements
308 m_MixerContainer->clearElements(true);
309 delete m_MixerContainer;
310 m_MixerContainer = NULL;
313 // remove control container
314 if (m_ControlContainer == NULL) {
315 debugOutput(DEBUG_LEVEL_VERBOSE, "no controls to destroy...\n");
316 } else
317 if (!deleteElement(m_ControlContainer)) {
318 debugError("Controls present but not registered to the avdevice\n");
319 ret = false;
320 } else {
321 // remove and delete (as in free) child control elements
322 m_ControlContainer->clearElements(true);
323 delete m_ControlContainer;
324 m_ControlContainer = NULL;
327 return ret;
330 bool
331 Device::probe( Util::Configuration& c, ConfigRom& configRom, bool generic )
333 if (generic) {
334 return false;
335 } else {
336 // check if device is in supported devices list. Note that the RME
337 // devices use the unit version to identify the individual devices.
338 // To avoid having to extend the configuration file syntax to
339 // include this at this point, we'll use the configuration file
340 // model ID to test against the device unit version. This can be
341 // tidied up if the configuration file is extended at some point to
342 // include the unit version.
343 unsigned int vendorId = configRom.getNodeVendorId();
344 unsigned int unitVersion = configRom.getUnitVersion();
346 Util::Configuration::VendorModelEntry vme = c.findDeviceVME( vendorId, unitVersion );
347 return c.isValid(vme) && vme.driver == Util::Configuration::eD_RME;
351 FFADODevice *
352 Device::createDevice(DeviceManager& d, std::auto_ptr<ConfigRom>( configRom ))
354 return new Device(d, configRom );
357 bool
358 Device::discover()
360 signed int i;
361 unsigned int vendorId = getConfigRom().getNodeVendorId();
362 // See note in Device::probe() about why we use the unit version here.
363 unsigned int unitVersion = getConfigRom().getUnitVersion();
365 Util::Configuration &c = getDeviceManager().getConfiguration();
366 Util::Configuration::VendorModelEntry vme = c.findDeviceVME( vendorId, unitVersion );
368 if (c.isValid(vme) && vme.driver == Util::Configuration::eD_RME) {
369 debugOutput( DEBUG_LEVEL_VERBOSE, "found %s %s\n",
370 vme.vendor_name.c_str(),
371 vme.model_name.c_str());
372 } else {
373 debugWarning("Device '%s %s' unsupported by RME driver (no generic RME support)\n",
374 getConfigRom().getVendorName().c_str(), getConfigRom().getModelName().c_str());
377 switch (unitVersion) {
378 case RME_UNITVERSION_FF800: m_rme_model = RME_MODEL_FIREFACE800; break;
379 case RME_UNITVERSION_FF400: m_rme_model = RME_MODEL_FIREFACE400; break;
380 case RME_UNITVERSION_UFX: m_rme_model = RME_MODEL_FIREFACE_UFX; break;
381 case RME_UNITVERSION_UCX: m_rme_model = RME_MODEL_FIREFACE_UCX; break;
382 default:
383 debugError("Unsupported model\n");
384 return false;
387 if (m_rme_model==RME_MODEL_FIREFACE_UFX || m_rme_model==RME_MODEL_FIREFACE_UCX) {
388 debugError("Fireface UFX/UCX are not currently supported\n");
389 return false;
392 // Set up the shared data object for configuration data
393 i = rme_shm_open(&dev_config);
394 if (i == RSO_OPEN_CREATED) {
395 debugOutput( DEBUG_LEVEL_VERBOSE, "New configuration shared data object created\n");
396 } else
397 if (i == RSO_OPEN_ATTACHED) {
398 debugOutput( DEBUG_LEVEL_VERBOSE, "Attached to existing configuration shared data object\n");
400 if (dev_config == NULL) {
401 debugOutput( DEBUG_LEVEL_WARNING, "Could not create/access shared configuration memory object, using process-local storage\n");
402 memset(&local_dev_config_obj, 0, sizeof(local_dev_config_obj));
403 dev_config = &local_dev_config_obj;
405 settings = &dev_config->settings;
406 tco_settings = &dev_config->tco_settings;
408 // If device is FF800, check to see if the TCO is fitted
409 if (m_rme_model == RME_MODEL_FIREFACE800) {
410 dev_config->tco_present = (read_tco(NULL, 0) == 0);
412 debugOutput(DEBUG_LEVEL_VERBOSE, "TCO present: %s\n",
413 dev_config->tco_present?"yes":"no");
415 init_hardware();
417 if (!buildMixer()) {
418 debugWarning("Could not build mixer\n");
421 return true;
425 Device::getSamplingFrequency( ) {
427 // Retrieve the current sample rate. For practical purposes this
428 // is the software rate currently in use if in master clock mode, or
429 // the external clock if in slave mode.
431 // If dds_freq functionality is pursued, some thinking will be required
432 // here because the streaming engine will take its timings from the
433 // value returned by this function. If the DDS is not running at
434 // software_freq, returning software_freq won't work for the streaming
435 // engine. User software, on the other hand, would require the
436 // software_freq value. Ultimately the streaming engine will probably
437 // have to be changed to obtain the "real" sample rate through other
438 // means.
440 // The kernel (as of 3.10 at least) seems to crash with an out-of-memory
441 // condition if this function calls get_hardware_state() too frequently
442 // (for example, several times per iso cycle). The code of the RME
443 // driver should be structured in such a way as to prevent such calls
444 // from the fast path, but it's always possible that other components
445 // will call into this function when streaming is active (ffado-mixer
446 // for instance. In such cases return the software frequency as a proxy
447 // for the true rate.
449 if (hardware_is_streaming()) {
450 return dev_config->software_freq;
453 FF_state_t state;
454 if (get_hardware_state(&state) != 0) {
455 debugOutput(DEBUG_LEVEL_ERROR, "failed to read device state\n");
456 return 0;
458 if (state.clock_mode == FF_STATE_CLOCKMODE_AUTOSYNC) {
459 // Note: this could return 0 if there is no valid external clock
460 return state.autosync_freq;
463 return dev_config->software_freq;
467 Device::getConfigurationId()
469 return 0;
472 bool
473 Device::setDDSFrequency( int dds_freq )
475 // Set a fixed DDS frequency. If the device is the clock master this
476 // will immediately be copied to the hardware DDS register. Otherwise
477 // it will take effect as required at the time the sampling rate is
478 // changed or streaming is started.
480 // If the device is streaming, the new DDS rate must have the same
481 // multiplier as the software sample rate.
483 // Since FFADO doesn't make use of the dds_freq functionality at present
484 // (there being no user access provided for this) the effect of changing
485 // the hardware DDS while streaming is active has not been tested. A
486 // new DDS value will change the timestamp intervals applicable to the
487 // streaming engine, so an alteration here without at least a restart of
488 // the streaming will almost certainly cause trouble. Initially it may
489 // be easiest to disallow such changes when streaming is active.
490 if (hardware_is_streaming()) {
491 if (multiplier_of_freq(dds_freq) != multiplier_of_freq(dev_config->software_freq))
492 return false;
495 dev_config->dds_freq = dds_freq;
496 if (settings->clock_mode == FF_STATE_CLOCKMODE_MASTER) {
497 if (set_hardware_dds_freq(dds_freq) != 0)
498 return false;
501 return true;
504 bool
505 Device::setSamplingFrequency( int samplingFrequency )
507 // Request a sampling rate on behalf of software. Software is limited
508 // to sample rates of 32k, 44.1k, 48k and the 2x/4x multiples of these.
509 // The user may lock the device to a much wider range of frequencies via
510 // the explicit DDS controls in the control panel. If the explicit DDS
511 // control is active the software is limited to the "standard" speeds
512 // corresponding to the multiplier in use by the DDS.
514 // Similarly, if the device is externally clocked the software is
515 // limited to the external clock frequency.
517 // Otherwise the software has free choice of the software speeds noted
518 // above.
520 bool ret = -1;
521 signed int i, j;
522 signed int mult[3] = {1, 2, 4};
523 unsigned int base_freq[3] = {32000, 44100, 48000};
524 unsigned int freq = samplingFrequency;
525 FF_state_t state;
526 signed int fixed_freq = 0;
528 if (get_hardware_state(&state) != 0) {
529 debugOutput(DEBUG_LEVEL_ERROR, "failed to read device state\n");
530 return false;
533 // If device is locked to a frequency via external clock, explicit
534 // setting of the DDS or by virtue of streaming being active, get that
535 // frequency.
536 if (state.clock_mode == FF_STATE_CLOCKMODE_AUTOSYNC) {
537 // The autosync frequency can be retrieved from state.autosync_freq.
538 // An autosync_freq value of 0 indicates the absence of a valid
539 // external clock. Allow sampling frequencies which match the
540 // sync rate and reject all others.
542 // A further note: if synced to TCO, is autosync_freq valid?
543 if (state.autosync_freq == 0) {
544 debugOutput(DEBUG_LEVEL_ERROR, "slave clock mode active but no valid external clock present\n");
546 if (state.autosync_freq==0 || (int)state.autosync_freq!=samplingFrequency)
547 return false;
548 dev_config->software_freq = samplingFrequency;
549 return true;
550 } else
551 if (dev_config->dds_freq > 0) {
552 fixed_freq = dev_config->dds_freq;
553 } else
554 if (hardware_is_streaming()) {
555 // See comments in getSamplingFrequency() as to why this may not
556 // be successful in the long run.
557 fixed_freq = dev_config->software_freq;
560 // If the device is running to a fixed frequency, software can only
561 // request frequencies with the same multiplier. Similarly, the
562 // multiplier is locked in "master" clock mode if the device is
563 // streaming.
564 if (fixed_freq > 0) {
565 unsigned int fixed_mult = multiplier_of_freq(fixed_freq);
566 if (multiplier_of_freq(freq) != fixed_mult) {
567 debugOutput(DEBUG_LEVEL_ERROR, "DDS currently set to %d Hz, new sampling rate %d does not have the same multiplier\n",
568 fixed_freq, freq);
569 return false;
571 for (j=0; j<3; j++) {
572 if (freq == base_freq[j]*fixed_mult) {
573 ret = 0;
574 break;
577 } else {
578 for (i=0; i<3; i++) {
579 for (j=0; j<3; j++) {
580 if (freq == base_freq[j]*mult[i]) {
581 ret = 0;
582 break;
587 // If requested frequency is unavailable, return false
588 if (ret == -1) {
589 debugOutput(DEBUG_LEVEL_ERROR, "requested sampling rate %d Hz not available\n", freq);
590 return false;
593 // If a DDS frequency has been explicitly requested this is always used
594 // to program the hardware DDS regardless of the rate requested by the
595 // software (such use of the DDS is only possible if the Fireface is
596 // operating in master clock mode). Otherwise we use the requested
597 // sampling rate.
598 if (dev_config->dds_freq>0 && state.clock_mode==FF_STATE_CLOCKMODE_MASTER)
599 freq = dev_config->dds_freq;
600 if (set_hardware_dds_freq(freq) != 0) {
601 debugOutput(DEBUG_LEVEL_ERROR, "failed to set hardware sample rate to %d Hz\n", freq);
602 return false;
605 debugOutput(DEBUG_LEVEL_VERBOSE, "hardware set to sampling frequency %d Hz\n", samplingFrequency);
606 dev_config->software_freq = samplingFrequency;
607 settings->sample_rate = samplingFrequency;
608 return true;
611 std::vector<int>
612 Device::getSupportedSamplingFrequencies()
614 std::vector<int> frequencies;
615 signed int i, j;
616 signed int mult[3] = {1, 2, 4};
617 signed int freq[3] = {32000, 44100, 48000};
618 FF_state_t state;
620 if (get_hardware_state(&state) != 0) {
621 debugOutput(DEBUG_LEVEL_ERROR, "failed to read device state\n");
622 return frequencies;
625 // Generate the list of supported frequencies. If the device is
626 // externally clocked the frequency is limited to the external clock
627 // frequency.
628 if (state.clock_mode == FF_STATE_CLOCKMODE_AUTOSYNC) {
629 // FIXME: if synced to TCO, is autosync_freq valid?
630 // The autosync frequency will be zero if no valid clock is available
631 frequencies.push_back(state.autosync_freq);
632 } else
633 // If the device is running the multiplier is fixed.
634 if (state.is_streaming) {
635 // It's not certain that permitting rate changes while streaming
636 // is active will work. See comments in setSamplingFrequency() and
637 // elsewhere.
638 unsigned int fixed_mult = multiplier_of_freq(dev_config->software_freq);
639 for (j=0; j<3; j++) {
640 frequencies.push_back(freq[j]*fixed_mult);
642 } else {
643 for (i=0; i<3; i++) {
644 for (j=0; j<3; j++) {
645 frequencies.push_back(freq[j]*mult[i]);
649 return frequencies;
652 // The RME clock source selection logic is a little more complex than a
653 // simple list can cater for. Therefore we just put in a placeholder and
654 // rely on the extended controls in ffado-mixer to deal with the details.
656 FFADODevice::ClockSource
657 Device::dummyClockSource(void) {
658 ClockSource s;
659 s.id = 0;
660 s.type = eCT_Internal;
661 s.description = "Selected via device controls";
662 s.valid = s.active = s.locked = true;
663 s.slipping = false;
664 return s;
666 FFADODevice::ClockSourceVector
667 Device::getSupportedClockSources() {
668 FFADODevice::ClockSourceVector r;
669 ClockSource s;
670 s = dummyClockSource();
671 r.push_back(s);
672 return r;
674 bool
675 Device::setActiveClockSource(ClockSource s) {
676 return true;
678 FFADODevice::ClockSource
679 Device::getActiveClockSource() {
680 return dummyClockSource();
683 bool
684 Device::lock() {
686 return true;
690 bool
691 Device::unlock() {
693 return true;
696 void
697 Device::showDevice()
699 unsigned int vendorId = getConfigRom().getNodeVendorId();
700 unsigned int modelId = getConfigRom().getModelId();
702 Util::Configuration &c = getDeviceManager().getConfiguration();
703 Util::Configuration::VendorModelEntry vme = c.findDeviceVME( vendorId, modelId );
705 debugOutput(DEBUG_LEVEL_VERBOSE,
706 "%s %s at node %d\n", vme.vendor_name.c_str(), vme.model_name.c_str(), getNodeId());
709 bool
710 Device::resetForStreaming() {
711 signed int err;
713 signed int iso_rx;
714 unsigned int stat[4];
715 signed int i;
717 // Ensure the transmit processor is ready to start streaming. When
718 // this function is called from prepare() the transmit processor
719 // won't be allocated.
720 if (m_transmitProcessor != NULL)
721 m_transmitProcessor->resetForStreaming();
723 // Whenever streaming is restarted hardware_init_streaming() needs to be
724 // called. Otherwise the device won't start sending data when data is
725 // sent to it and the rx stream will fail to start.
726 err = hardware_init_streaming(dev_config->hardware_freq, iso_tx_channel) != 0;
727 if (err) {
728 debugFatal("Could not intialise device streaming system\n");
729 return false;
732 i = 0;
733 while (i < 100) {
734 err = (get_hardware_streaming_status(stat, 4) != 0);
735 if (err) {
736 debugFatal("error reading status register\n");
737 break;
740 debugOutput(DEBUG_LEVEL_VERBOSE, "rme init stat: %08x %08x %08x %08x\n",
741 stat[0], stat[1], stat[2], stat[3]);
743 if (m_rme_model == RME_MODEL_FIREFACE400) {
744 break;
747 // The Fireface-800 chooses its tx channel (our rx channel). Wait
748 // for the device busy flag to clear, then confirm that the rx iso
749 // channel hasn't changed (it shouldn't across a restart).
750 if (stat[2] == 0xffffffff) {
751 // Device not ready; wait 5 ms and try again
752 usleep(5000);
753 i++;
754 } else {
755 iso_rx = stat[2] & 63;
756 if (iso_rx!=iso_rx_channel && iso_rx_channel!=-1)
757 debugOutput(DEBUG_LEVEL_WARNING, "rx iso: now %d, was %d\n",
758 iso_rx, iso_rx_channel);
759 iso_rx_channel = iso_rx;
761 // Even if the rx channel has changed, the device takes care of
762 // registering the channel itself, so we don't have to (neither
763 // do we have to release the old one). If we try to call
764 // raw1394_channel_modify() on the returned channel we'll get an
765 // error.
766 // iso_rx_channel = get1394Service().allocateFixedIsoChannelGeneric(iso_rx_channel, bandwidth);
767 break;
770 if (i==100 || err) {
771 if (i == 100)
772 debugFatal("timeout waiting for device not busy\n");
773 return false;
774 } else {
775 signed int init_samplerate;
776 if ((stat[1] & SR1_CLOCK_MODE_MASTER) ||
777 (stat[0] & SR0_AUTOSYNC_FREQ_MASK)==0 ||
778 (stat[0] & SR0_AUTOSYNC_SRC_MASK)==SR0_AUTOSYNC_SRC_NONE) {
779 init_samplerate = dev_config->hardware_freq;
780 } else {
781 init_samplerate = (stat[0] & SR0_STREAMING_FREQ_MASK) * 250;
783 debugOutput(DEBUG_LEVEL_VERBOSE, "sample rate on start: %d\n",
784 init_samplerate);
787 return FFADODevice::resetForStreaming();
790 bool
791 Device::prepare() {
793 signed int mult, bandwidth;
794 signed int freq;
795 signed int err = 0;
797 debugOutput(DEBUG_LEVEL_NORMAL, "Preparing Device...\n" );
799 // If there is no iso data to send in a given cycle the RMEs simply
800 // don't send anything. This is in contrast to most other interfaces
801 // which at least send an empty packet. As a result the IsoHandler
802 // contains code which detects missing packets as dropped packets.
803 // For RME devices we must turn this test off since missing packets
804 // are in fact to be expected.
805 get1394Service().getIsoHandlerManager().setMissedCyclesOK(true);
807 freq = getSamplingFrequency();
808 if (freq <= 0) {
809 debugOutput(DEBUG_LEVEL_ERROR, "Can't continue: sampling frequency not set\n");
810 return false;
812 mult = freq<68100?1:(freq<136200?2:4);
814 frames_per_packet = getFramesPerPacket();
816 // The number of active channels depends on sample rate and whether
817 // bandwidth limitation is active. First set up the number of analog
818 // channels (which differs between devices), then add SPDIF channels if
819 // relevant. Finally, the number of channels available from each ADAT
820 // interface depends on sample rate: 0 at 4x, 4 at 2x and 8 at 1x.
821 // Note that "analog only" bandwidth limit mode means analog 1-8
822 // regardless of the fireface model in use.
823 if (m_rme_model==RME_MODEL_FIREFACE800 && settings->limit_bandwidth!=FF_SWPARAM_BWLIMIT_ANALOG_ONLY)
824 num_channels = 10;
825 else
826 num_channels = 8;
827 if (settings->limit_bandwidth != FF_SWPARAM_BWLIMIT_ANALOG_ONLY)
828 num_channels += 2;
829 if (settings->limit_bandwidth==FF_SWPARAM_BWLIMIT_SEND_ALL_CHANNELS ||
830 settings->limit_bandwidth==FF_DEV_FLASH_BWLIMIT_NO_ADAT2)
831 num_channels += (mult==4?0:(mult==2?4:8));
832 if (m_rme_model==RME_MODEL_FIREFACE800 &&
833 settings->limit_bandwidth==FF_SWPARAM_BWLIMIT_SEND_ALL_CHANNELS)
834 num_channels += (mult==4?0:(mult==2?4:8));
836 // Bandwidth is calculated here. For the moment we assume the device
837 // is connected at S400, so 1 allocation unit is 1 transmitted byte.
838 // There is 25 allocation units of protocol overhead per packet. Each
839 // channel of audio data is sent/received as a 32 bit integer.
840 bandwidth = 25 + num_channels*4*frames_per_packet;
842 // Both the FF400 and FF800 require we allocate a tx iso channel and
843 // then initialise the device. Device status is then read at least once
844 // regardless of which interface is in use. The rx channel is then
845 // allocated for the FF400 or acquired from the device in the case of
846 // the FF800. Even though the FF800 chooses the rx channel it does not
847 // handle the bus-level channel/bandwidth allocation so we must do that
848 // here.
849 if (iso_tx_channel < 0) {
850 iso_tx_channel = get1394Service().allocateIsoChannelGeneric(bandwidth);
852 if (iso_tx_channel < 0) {
853 debugFatal("Could not allocate iso tx channel\n");
854 return false;
855 } else {
856 debugOutput(DEBUG_LEVEL_NORMAL, "iso tx channel: %d\n", iso_tx_channel);
859 // Call this to initialise the device's streaming system and, in the
860 // case of the FF800, obtain the rx iso channel to use. Having that
861 // functionality in resetForStreaming() means it's effectively done
862 // twice when FFADO is first started, but this does no harm.
863 if (resetForStreaming() == false)
864 return false;
866 if (err) {
867 if (iso_tx_channel >= 0)
868 get1394Service().freeIsoChannel(iso_tx_channel);
869 if (iso_rx_channel>=0 && m_rme_model==RME_MODEL_FIREFACE400)
870 // The FF800 manages this channel itself.
871 get1394Service().freeIsoChannel(iso_rx_channel);
872 return false;
875 /* We need to manage the FF400's iso rx channel */
876 if (m_rme_model == RME_MODEL_FIREFACE400) {
877 iso_rx_channel = get1394Service().allocateIsoChannelGeneric(bandwidth);
880 // get the device specific and/or global SP configuration
881 Util::Configuration &config = getDeviceManager().getConfiguration();
882 // base value is the config.h value
883 float recv_sp_dll_bw = STREAMPROCESSOR_DLL_BW_HZ;
884 float xmit_sp_dll_bw = STREAMPROCESSOR_DLL_BW_HZ;
886 // we can override that globally
887 config.getValueForSetting("streaming.spm.recv_sp_dll_bw", recv_sp_dll_bw);
888 config.getValueForSetting("streaming.spm.xmit_sp_dll_bw", xmit_sp_dll_bw);
890 // or override in the device section
891 config.getValueForDeviceSetting(getConfigRom().getNodeVendorId(), getConfigRom().getModelId(), "recv_sp_dll_bw", recv_sp_dll_bw);
892 config.getValueForDeviceSetting(getConfigRom().getNodeVendorId(), getConfigRom().getModelId(), "xmit_sp_dll_bw", xmit_sp_dll_bw);
894 // Calculate the event size. Each audio channel is allocated 4 bytes in
895 // the data stream.
896 /* FIXME: this will still require fine-tuning, but it's a start */
897 signed int event_size = num_channels * 4;
899 // Set up receive stream processor, initialise it and set DLL bw
900 m_receiveProcessor = new Streaming::RmeReceiveStreamProcessor(*this,
901 m_rme_model, event_size);
902 m_receiveProcessor->setVerboseLevel(getDebugLevel());
903 if (!m_receiveProcessor->init()) {
904 debugFatal("Could not initialize receive processor!\n");
905 return false;
907 if (!m_receiveProcessor->setDllBandwidth(recv_sp_dll_bw)) {
908 debugFatal("Could not set DLL bandwidth\n");
909 delete m_receiveProcessor;
910 m_receiveProcessor = NULL;
911 return false;
914 // Add ports to the processor - TODO
915 std::string id=std::string("dev?");
916 if (!getOption("id", id)) {
917 debugWarning("Could not retrieve id parameter, defaulting to 'dev?'\n");
919 addDirPorts(Streaming::Port::E_Capture);
921 /* Now set up the transmit stream processor */
922 m_transmitProcessor = new Streaming::RmeTransmitStreamProcessor(*this,
923 m_rme_model, event_size);
924 m_transmitProcessor->setVerboseLevel(getDebugLevel());
925 if (!m_transmitProcessor->init()) {
926 debugFatal("Could not initialise receive processor!\n");
927 return false;
929 if (!m_transmitProcessor->setDllBandwidth(xmit_sp_dll_bw)) {
930 debugFatal("Could not set DLL bandwidth\n");
931 delete m_transmitProcessor;
932 m_transmitProcessor = NULL;
933 return false;
936 // Other things to be done:
937 // * add ports to transmit stream processor
938 addDirPorts(Streaming::Port::E_Playback);
940 return true;
944 Device::getStreamCount() {
945 return 2; // one receive, one transmit
948 Streaming::StreamProcessor *
949 Device::getStreamProcessorByIndex(int i) {
950 switch (i) {
951 case 0:
952 return m_receiveProcessor;
953 case 1:
954 return m_transmitProcessor;
955 default:
956 debugWarning("Invalid stream index %d\n", i);
958 return NULL;
961 enum FFADODevice::eStreamingState
962 Device::getStreamingState() {
963 if (hardware_is_streaming())
964 return eSS_Both;
965 return eSS_Idle;
968 bool
969 Device::startStreamByIndex(int i) {
970 // The RME does not allow separate enabling of the transmit and receive
971 // streams. Therefore we start all streaming when index 0 is referenced
972 // and silently ignore the start requests for other streams
973 // (unconditionally flagging them as being successful).
974 if (i == 0) {
975 m_receiveProcessor->setChannel(iso_rx_channel);
976 m_transmitProcessor->setChannel(iso_tx_channel);
977 if (hardware_start_streaming(iso_rx_channel) != 0)
978 return false;
980 return true;
983 bool
984 Device::stopStreamByIndex(int i) {
985 // See comments in startStreamByIndex() as to why we act only when stream
986 // 0 is requested.
987 if (i == 0) {
988 if (hardware_stop_streaming() != 0)
989 return false;
991 return true;
994 signed int
995 Device::getFramesPerPacket(void) {
996 // The number of frames transmitted in a single packet is solely
997 // determined by the sample rate. This function is called several times
998 // per iso cycle by the tx stream processor, so use the software rate as
999 // a proxy for the hardware sample rate. Calling getSamplingFrequency()
1000 // is best avoided because otherwise the kernel tends to crash having
1001 // run out of memory (something about the timing of async commands in
1002 // getSamplingFrequency() and the iso tx handler seems to be tripping it
1003 // up).
1005 // If streaming is active the software sampling rate should be set up.
1006 // If the dds_freq functionality is implemented the software rate can
1007 // probably still be used because the hardware dictates that both
1008 // must share the same multiplier, and the only reason for obtaining
1009 // the sampling frequency is to determine the multiplier.
1010 signed int freq = dev_config->software_freq;
1011 signed int mult = multiplier_of_freq(freq);
1012 switch (mult) {
1013 case 2: return 15;
1014 case 4: return 25;
1015 default:
1016 return 7;
1018 return 7;
1021 bool
1022 Device::addPort(Streaming::StreamProcessor *s_processor,
1023 char *name, enum Streaming::Port::E_Direction direction,
1024 int position, int size) {
1026 Streaming::Port *p;
1027 p = new Streaming::RmeAudioPort(*s_processor, name, direction, position, size);
1028 if (p == NULL) {
1029 debugOutput(DEBUG_LEVEL_VERBOSE, "Skipped port %s\n",name);
1031 return true;
1034 bool
1035 Device::addDirPorts(enum Streaming::Port::E_Direction direction) {
1037 const char *mode_str = direction==Streaming::Port::E_Capture?"cap":"pbk";
1038 Streaming::StreamProcessor *s_processor;
1039 std::string id;
1040 char name[128];
1041 signed int i;
1042 signed int n_analog, n_phones, n_adat, n_spdif;
1043 signed int sample_rate = getSamplingFrequency();
1045 /* Apply bandwidth limit if selected. This effectively sets up the
1046 * number of adat and spdif channels assuming single-rate speed.
1047 * The total number of expected analog channels is also set here.
1049 n_spdif = 2;
1050 n_analog = (m_rme_model==RME_MODEL_FIREFACE800)?10:8;
1051 switch (dev_config->settings.limit_bandwidth) {
1052 case FF_SWPARAM_BWLIMIT_ANALOG_ONLY:
1053 n_adat = n_spdif = 0;
1054 // "Analog only" means "Analog 1-8" regardless of the interface model
1055 n_analog = 8;
1056 break;
1057 case FF_SWPARAM_BWLIMIT_ANALOG_SPDIF_ONLY:
1058 n_adat = 0;
1059 break;
1060 case FF_SWPARAM_BWLIMIT_NO_ADAT2:
1061 /* FF800 only */
1062 n_adat = 8;
1063 break;
1064 default:
1065 /* Send all channels */
1066 n_adat = (m_rme_model==RME_MODEL_FIREFACE800)?16:8;
1069 /* Adjust the spdif and ADAT channels according to the current sample
1070 * rate.
1072 if (sample_rate>=MIN_DOUBLE_SPEED && sample_rate<MIN_QUAD_SPEED) {
1073 n_adat /= 2;
1074 } else
1075 if (sample_rate >= MIN_QUAD_SPEED) {
1076 n_adat = 0;
1079 n_phones = 0;
1080 if (direction == Streaming::Port::E_Capture) {
1081 s_processor = m_receiveProcessor;
1082 } else {
1083 s_processor = m_transmitProcessor;
1084 /* Phones generally count as two of the analog outputs. For
1085 * the FF800 in "Analog 1-8" bandwidth limit mode this is
1086 * not the case and the phones are inactive.
1088 if (m_rme_model==RME_MODEL_FIREFACE400 || dev_config->settings.limit_bandwidth!=FF_SWPARAM_BWLIMIT_ANALOG_ONLY) {
1089 n_analog -= 2;
1090 n_phones = 2;
1094 id = std::string("dev?");
1095 if (!getOption("id", id)) {
1096 debugWarning("Could not retrieve id parameter, defaulting to 'dev?'\n");
1099 for (i=0; i<n_analog; i++) {
1100 snprintf(name, sizeof(name), "%s_%s_analog-%d", id.c_str(), mode_str, i+1);
1101 addPort(s_processor, name, direction, i*4, 0);
1103 for (i=0; i<n_phones; i++) {
1104 snprintf(name, sizeof(name), "%s_%s_phones-%c", id.c_str(), mode_str,
1105 i==0?'L':'R');
1106 /* The headphone channels follow the straight analog lines */
1107 addPort(s_processor, name, direction, n_analog*4+i*4, 0);
1109 for (i=0; i<n_spdif; i++) {
1110 snprintf(name, sizeof(name), "%s_%s_SPDIF-%d", id.c_str(), mode_str, i+1);
1111 /* The SPDIF channels start after all analog lines */
1112 addPort(s_processor, name, direction, (n_analog+n_phones)*4+i*4, 0);
1114 for (i=0; i<n_adat; i++) {
1115 snprintf(name, sizeof(name), "%s_%s_adat-%d", id.c_str(), mode_str, i+1);
1116 /* ADAT ports follow all other ports */
1117 addPort(s_processor, name, direction, (n_analog+n_phones+n_spdif)*4+i*4, 0);
1120 return true;
1123 unsigned int
1124 Device::readRegister(fb_nodeaddr_t reg) {
1126 quadlet_t quadlet;
1128 quadlet = 0;
1129 if (get1394Service().read(0xffc0 | getNodeId(), reg, 1, &quadlet) <= 0) {
1130 debugError("Error doing RME read from register 0x%06llx\n",reg);
1132 return ByteSwapFromDevice32(quadlet);
1135 signed int
1136 Device::readBlock(fb_nodeaddr_t reg, quadlet_t *buf, unsigned int n_quads) {
1138 unsigned int i;
1140 if (get1394Service().read(0xffc0 | getNodeId(), reg, n_quads, buf) <= 0) {
1141 debugError("Error doing RME block read of %d quadlets from register 0x%06llx\n",
1142 n_quads, reg);
1143 return -1;
1145 for (i=0; i<n_quads; i++) {
1146 buf[i] = ByteSwapFromDevice32(buf[i]);
1149 return 0;
1152 signed int
1153 Device::writeRegister(fb_nodeaddr_t reg, quadlet_t data) {
1155 unsigned int err = 0;
1156 data = ByteSwapToDevice32(data);
1157 if (get1394Service().write(0xffc0 | getNodeId(), reg, 1, &data) <= 0) {
1158 err = 1;
1159 debugError("Error doing RME write to register 0x%06llx\n",reg);
1162 return (err==0)?0:-1;
1165 signed int
1166 Device::writeBlock(fb_nodeaddr_t reg, quadlet_t *data, unsigned int n_quads) {
1168 // Write a block of data to the device starting at address "reg". Note that
1169 // the conditional byteswap is done "in place" on data, so the contents of
1170 // data may be modified by calling this function.
1172 unsigned int err = 0;
1173 unsigned int i;
1175 for (i=0; i<n_quads; i++) {
1176 data[i] = ByteSwapToDevice32(data[i]);
1178 if (get1394Service().write(0xffc0 | getNodeId(), reg, n_quads, data) <= 0) {
1179 err = 1;
1180 debugError("Error doing RME block write of %d quadlets to register 0x%06llx\n",
1181 n_quads, reg);
1184 return (err==0)?0:-1;