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

Revision 2691, 44.7 kB (checked in by jwoithe, 7 years ago)

Initial attempt to address deprecation of auto_ptr.

C++11 deprecates auto_ptr, and gcc6 (and later versions) print compile time
warnings to this effect whenever it is encountered in the source. The
replacement type is either shared_ptr or unique_ptr depending on the usage.
For almost all usages within FFADO it seems unique_ptr could be the
appropriate choice, but the symantics are a little different to auto_ptr.
Shared_ptr on the other hand can be a drop-in replacement, although it comes
with considerable overheads which unique_ptr avoids. In the context of the
current usage, the extra overhead incurred is not critical.

The code-base cannot at this time change unconditionally to shared_ptr and
unique_ptr because these are not available in gcc4 unless "--std=c++11" is
given. When gcc4 is used certain older versions of dependent libraries must
be used and these in turn will cause compile failures in their header files
if "--std=c++11" is used (libxml++ being an example). At present there are
sufficient users of FFADO still on gcc4 to justify maintaining compatibility
with that gcc version.

The approach adopted at present is to define ffado_smartptr to be either
auto_ptr (if c++11 is not in use) or shared_ptr if it is. All auto_ptr
instances are then changed to ffado_smartptr. This should allow FFADO to be
compiled without errors or warnings on systems using gcc4 and above. Gcc6
defaults to the c++14 standard, so ffado_smartptr will be shared_ptr in that
case; thus the warnings will be avoided.

In time, once gcc4 drops out of common use, the ffado_smartptr instances can
be progressively migrated to unique_ptr or shared_ptr as is appropriate. It
has been pointed out in the ffado-devel mailing list by Jano Svitok (2 May
2017, subject "smart pointers Was: [FFADO-devel] Liquid Saffire 56") that
bebob_dl_mgr.cpp could use unique_ptr. shared_ptr should be ok in other
auto_ptr sites, but futher analysis may show that at least some of them can
use unique_ptr.

The addressing of the auto_ptr issue was prompted by Xavier Forestier's
patch set submitted to ffado-devel in November 2016.

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