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

Revision 2732, 44.7 kB (checked in by jwoithe, 3 years ago)

Fix typos throughout the source tree.

Rectify some long-lived typos in strings throughout the source code. in the
FFADO desktop file. This benefits Debian and possibly others. Patch by
Nicolas Boulenguez for Debian and provided to FFADO by Benoit Delcour via
the ffado-user mailing list.

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