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

Revision 2245, 36.5 kB (checked in by jwoithe, 10 years ago)

rme: gracefully handle the case where the device does not appear to come out of the busy state during initialisation.

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