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

Revision 2169, 36.4 kB (checked in by adi, 12 years ago)

Use ByteSwap?32 from libutil/ByteSwap.h

Closes #357

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         } else {
664             iso_rx = stat[2] & 63;
665             if (iso_rx!=iso_rx_channel && iso_rx_channel!=-1)
666                 debugOutput(DEBUG_LEVEL_WARNING, "rx iso: now %d, was %d\n",
667                     iso_rx, iso_rx_channel);
668             iso_rx_channel = iso_rx;
669
670             // Even if the rx channel has changed, the device takes care of
671             // registering the channel itself, so we don't have to (neither
672             // do we have to release the old one).  If we try to call
673             // raw1394_channel_modify() on the returned channel we'll get an
674             // error.
675             //   iso_rx_channel = get1394Service().allocateFixedIsoChannelGeneric(iso_rx_channel, bandwidth);
676             break;
677         }
678     }
679     if (i==100 || err)
680         return false;
681
682     return FFADODevice::resetForStreaming();
683 }
684
685 bool
686 Device::prepare() {
687
688     signed int mult, bandwidth;
689     signed int freq, init_samplerate;
690     signed int err = 0;
691     unsigned int stat[4];
692
693     debugOutput(DEBUG_LEVEL_NORMAL, "Preparing Device...\n" );
694
695     // If there is no iso data to send in a given cycle the RMEs simply
696     // don't send anything.  This is in contrast to most other interfaces
697     // which at least send an empty packet.  As a result the IsoHandler
698     // contains code which detects missing packets as dropped packets.
699     // For RME devices we must turn this test off since missing packets
700     // are in fact to be expected.
701     get1394Service().getIsoHandlerManager().setMissedCyclesOK(true);
702
703     freq = getSamplingFrequency();
704     if (freq <= 0) {
705         debugOutput(DEBUG_LEVEL_ERROR, "Can't continue: sampling frequency not set\n");
706         return false;
707     }
708     mult = freq<68100?1:(freq<136200?2:4);
709
710     frames_per_packet = getFramesPerPacket();
711
712     // The number of active channels depends on sample rate and whether
713     // bandwidth limitation is active.  First set up the number of analog
714     // channels (which differs between devices), then add SPDIF channels if
715     // relevant.  Finally, the number of channels available from each ADAT
716     // interface depends on sample rate: 0 at 4x, 4 at 2x and 8 at 1x.
717     if (m_rme_model == RME_MODEL_FIREFACE800)
718         num_channels = 10;
719     else
720         num_channels = 8;
721     if (settings->limit_bandwidth != FF_SWPARAM_BWLIMIT_ANALOG_ONLY)
722         num_channels += 2;
723     if (settings->limit_bandwidth==FF_SWPARAM_BWLIMIT_SEND_ALL_CHANNELS)
724         num_channels += (mult==4?0:(mult==2?4:8));
725     if (m_rme_model==RME_MODEL_FIREFACE800 &&
726         settings->limit_bandwidth==FF_SWPARAM_BWLIMIT_SEND_ALL_CHANNELS)
727         num_channels += (mult==4?0:(mult==2?4:8));
728
729     // Bandwidth is calculated here.  For the moment we assume the device
730     // is connected at S400, so 1 allocation unit is 1 transmitted byte.
731     // There is 25 allocation units of protocol overhead per packet.  Each
732     // channel of audio data is sent/received as a 32 bit integer.
733     bandwidth = 25 + num_channels*4*frames_per_packet;
734
735     // Both the FF400 and FF800 require we allocate a tx iso channel and
736     // then initialise the device.  Device status is then read at least once
737     // regardless of which interface is in use.  The rx channel is then
738     // allocated for the FF400 or acquired from the device in the case of
739     // the FF800.  Even though the FF800 chooses the rx channel it does not
740     // handle the bus-level channel/bandwidth allocation so we must do that
741     // here.
742     if (iso_tx_channel < 0) {
743         iso_tx_channel = get1394Service().allocateIsoChannelGeneric(bandwidth);
744     }
745     if (iso_tx_channel < 0) {
746         debugFatal("Could not allocate iso tx channel\n");
747         return false;
748     } else {
749       debugOutput(DEBUG_LEVEL_NORMAL, "iso tx channel: %d\n", iso_tx_channel);
750     }
751
752     // Call this to initialise the device's streaming system and, in the
753     // case of the FF800, obtain the rx iso channel to use.  Having that
754     // functionality in resetForStreaming() means it's effectively done
755     // twice when FFADO is first started, but this does no harm.
756     resetForStreaming();
757  
758     if (err) {
759         if (iso_tx_channel >= 0)
760             get1394Service().freeIsoChannel(iso_tx_channel);
761         if (iso_rx_channel>=0 && m_rme_model==RME_MODEL_FIREFACE400)
762             // The FF800 manages this channel itself.
763             get1394Service().freeIsoChannel(iso_rx_channel);
764         return false;
765     }
766
767     /* We need to manage the FF400's iso rx channel */
768     if (m_rme_model == RME_MODEL_FIREFACE400) {
769         iso_rx_channel = get1394Service().allocateIsoChannelGeneric(bandwidth);
770     }
771
772     if ((stat[1] & SR1_CLOCK_MODE_MASTER) ||
773         (stat[0] & SR0_AUTOSYNC_FREQ_MASK)==0 ||
774         (stat[0] & SR0_AUTOSYNC_SRC_MASK)==SR0_AUTOSYNC_SRC_NONE) {
775         init_samplerate = dev_config->hardware_freq;
776     } else {
777         init_samplerate = (stat[0] & SR0_STREAMING_FREQ_MASK) * 250;
778     }
779
780     debugOutput(DEBUG_LEVEL_VERBOSE, "sample rate on start: %d\n",
781         init_samplerate);
782
783     // get the device specific and/or global SP configuration
784     Util::Configuration &config = getDeviceManager().getConfiguration();
785     // base value is the config.h value
786     float recv_sp_dll_bw = STREAMPROCESSOR_DLL_BW_HZ;
787     float xmit_sp_dll_bw = STREAMPROCESSOR_DLL_BW_HZ;
788
789     // we can override that globally
790     config.getValueForSetting("streaming.spm.recv_sp_dll_bw", recv_sp_dll_bw);
791     config.getValueForSetting("streaming.spm.xmit_sp_dll_bw", xmit_sp_dll_bw);
792
793     // or override in the device section
794     config.getValueForDeviceSetting(getConfigRom().getNodeVendorId(), getConfigRom().getModelId(), "recv_sp_dll_bw", recv_sp_dll_bw);
795     config.getValueForDeviceSetting(getConfigRom().getNodeVendorId(), getConfigRom().getModelId(), "xmit_sp_dll_bw", xmit_sp_dll_bw);
796
797     // Calculate the event size.  Each audio channel is allocated 4 bytes in
798     // the data stream.
799     /* FIXME: this will still require fine-tuning, but it's a start */
800     signed int event_size = num_channels * 4;
801
802     // Set up receive stream processor, initialise it and set DLL bw
803     m_receiveProcessor = new Streaming::RmeReceiveStreamProcessor(*this,
804       m_rme_model, event_size);
805     m_receiveProcessor->setVerboseLevel(getDebugLevel());
806     if (!m_receiveProcessor->init()) {
807         debugFatal("Could not initialize receive processor!\n");
808         return false;
809     }
810     if (!m_receiveProcessor->setDllBandwidth(recv_sp_dll_bw)) {
811         debugFatal("Could not set DLL bandwidth\n");
812         delete m_receiveProcessor;
813         m_receiveProcessor = NULL;
814         return false;
815     }
816
817     // Add ports to the processor - TODO
818     std::string id=std::string("dev?");
819     if (!getOption("id", id)) {
820         debugWarning("Could not retrieve id parameter, defaulting to 'dev?'\n");
821     }
822     addDirPorts(Streaming::Port::E_Capture);
823
824     /* Now set up the transmit stream processor */
825     m_transmitProcessor = new Streaming::RmeTransmitStreamProcessor(*this,
826       m_rme_model, event_size);
827     m_transmitProcessor->setVerboseLevel(getDebugLevel());
828     if (!m_transmitProcessor->init()) {
829         debugFatal("Could not initialise receive processor!\n");
830         return false;
831     }
832     if (!m_transmitProcessor->setDllBandwidth(xmit_sp_dll_bw)) {
833         debugFatal("Could not set DLL bandwidth\n");
834         delete m_transmitProcessor;
835         m_transmitProcessor = NULL;
836         return false;
837     }
838
839     // Other things to be done:
840     //  * add ports to transmit stream processor
841     addDirPorts(Streaming::Port::E_Playback);
842
843     return true;
844 }
845
846 int
847 Device::getStreamCount() {
848     return 2; // one receive, one transmit
849 }
850
851 Streaming::StreamProcessor *
852 Device::getStreamProcessorByIndex(int i) {
853     switch (i) {
854         case 0:
855             return m_receiveProcessor;
856         case 1:
857             return m_transmitProcessor;
858         default:
859             debugWarning("Invalid stream index %d\n", i);
860     }
861     return NULL;
862 }
863
864 enum FFADODevice::eStreamingState
865 Device::getStreamingState() {
866   if (hardware_is_streaming())
867     return eSS_Both;
868   return eSS_Idle;
869 }
870
871 bool
872 Device::startStreamByIndex(int i) {
873     // The RME does not allow separate enabling of the transmit and receive
874     // streams.  Therefore we start all streaming when index 0 is referenced
875     // and silently ignore the start requests for other streams
876     // (unconditionally flagging them as being successful).
877     if (i == 0) {
878         m_receiveProcessor->setChannel(iso_rx_channel);
879         m_transmitProcessor->setChannel(iso_tx_channel);
880         if (hardware_start_streaming(iso_rx_channel) != 0)
881             return false;
882     }
883     return true;
884 }
885
886 bool
887 Device::stopStreamByIndex(int i) {
888     // See comments in startStreamByIndex() as to why we act only when stream
889     // 0 is requested.
890     if (i == 0) {
891         if (hardware_stop_streaming() != 0)
892             return false;
893     }
894     return true;
895 }
896
897 signed int
898 Device::getFramesPerPacket(void) {
899     // The number of frames transmitted in a single packet is solely
900     // determined by the sample rate.
901     signed int freq = getSamplingFrequency();
902     signed int mult = multiplier_of_freq(freq);
903     switch (mult) {
904         case 2: return 15;
905         case 4: return 25;
906     default:
907         return 7;
908     }
909     return 7;
910 }
911
912 bool
913 Device::addPort(Streaming::StreamProcessor *s_processor,
914     char *name, enum Streaming::Port::E_Direction direction,
915     int position, int size) {
916
917     Streaming::Port *p;
918     p = new Streaming::RmeAudioPort(*s_processor, name, direction, position, size);
919     if (p == NULL) {
920         debugOutput(DEBUG_LEVEL_VERBOSE, "Skipped port %s\n",name);
921     }
922     return true;
923 }
924
925 bool
926 Device::addDirPorts(enum Streaming::Port::E_Direction direction) {
927
928     const char *mode_str = direction==Streaming::Port::E_Capture?"cap":"pbk";
929     Streaming::StreamProcessor *s_processor;
930     std::string id;
931     char name[128];
932     signed int i;
933     signed int n_analog, n_phones, n_adat, n_spdif;
934     signed int sample_rate = getSamplingFrequency();
935
936     /* Apply bandwidth limit if selected.  This effectively sets up the
937      * number of adat and spdif channels assuming single-rate speed.
938      */
939     n_spdif = 2;
940     switch (dev_config->settings.limit_bandwidth) {
941       case FF_SWPARAM_BWLIMIT_ANALOG_ONLY:
942         n_adat = n_spdif = 0;
943         break;
944       case FF_SWPARAM_BWLIMIT_ANALOG_SPDIF_ONLY:
945         n_adat = 0;
946         break;
947       case FF_SWPARAM_BWLIMIT_NO_ADAT2:
948         /* FF800 only */
949         n_adat = 8;
950         break;
951       default:
952         /* Send all channels */
953         n_adat = (m_rme_model==RME_MODEL_FIREFACE800)?16:8;
954     }
955
956     /* Work out the number of analog channels based on the device model and
957      * adjust the spdif and ADAT channels according to the current sample
958      * rate.
959      */
960     n_analog = (m_rme_model==RME_MODEL_FIREFACE800)?10:8;
961     n_phones = 0;
962     if (sample_rate>=MIN_DOUBLE_SPEED && sample_rate<MIN_QUAD_SPEED) {
963       n_adat /= 2;
964     } else
965     if (sample_rate >= MIN_QUAD_SPEED) {
966       n_adat = 0;
967       n_spdif = 0;
968     }
969
970     if (direction == Streaming::Port::E_Capture) {
971         s_processor = m_receiveProcessor;
972     } else {
973         s_processor = m_transmitProcessor;
974         /* Phones count as two of the analog outputs */
975         n_analog -= 2;
976         n_phones = 2;
977     }
978
979     id = std::string("dev?");
980     if (!getOption("id", id)) {
981         debugWarning("Could not retrieve id parameter, defaulting to 'dev?'\n");
982     }
983
984     for (i=0; i<n_analog; i++) {
985       snprintf(name, sizeof(name), "%s_%s_analog-%d", id.c_str(), mode_str, i+1);
986       addPort(s_processor, name, direction, i*4, 0);
987     }
988     for (i=0; i<n_phones; i++) {
989       snprintf(name, sizeof(name), "%s_%s_phones-%c", id.c_str(), mode_str,
990         i==0?'L':'R');
991       /* The headphone channels follow the straight analog lines */
992       addPort(s_processor, name, direction, n_analog*4+i*4, 0);
993     }
994     for (i=0; i<n_spdif; i++) {
995       snprintf(name, sizeof(name), "%s_%s_SPDIF-%d", id.c_str(), mode_str, i+1);
996       /* The SPDIF channels start after all analog lines */
997       addPort(s_processor, name, direction, (n_analog+n_phones)*4+i*4, 0);
998     }
999     for (i=0; i<n_adat; i++) {
1000       snprintf(name, sizeof(name), "%s_%s_adat-%d", id.c_str(), mode_str, i+1);
1001       /* ADAT ports follow all other ports */
1002       addPort(s_processor, name, direction, (n_analog+n_phones+n_spdif)*4+i*4, 0);
1003     }
1004
1005     return true;
1006 }
1007
1008 unsigned int
1009 Device::readRegister(fb_nodeaddr_t reg) {
1010
1011     quadlet_t quadlet;
1012    
1013     quadlet = 0;
1014     if (get1394Service().read(0xffc0 | getNodeId(), reg, 1, &quadlet) <= 0) {
1015         debugError("Error doing RME read from register 0x%06llx\n",reg);
1016     }
1017     return ByteSwapFromDevice32(quadlet);
1018 }
1019
1020 signed int
1021 Device::readBlock(fb_nodeaddr_t reg, quadlet_t *buf, unsigned int n_quads) {
1022
1023     unsigned int i;
1024
1025     if (get1394Service().read(0xffc0 | getNodeId(), reg, n_quads, buf) <= 0) {
1026         debugError("Error doing RME block read of %d quadlets from register 0x%06llx\n",
1027             n_quads, reg);
1028         return -1;
1029     }
1030     for (i=0; i<n_quads; i++) {
1031        buf[i] = ByteSwapFromDevice32(buf[i]);
1032     }
1033
1034     return 0;
1035 }
1036
1037 signed int
1038 Device::writeRegister(fb_nodeaddr_t reg, quadlet_t data) {
1039
1040     unsigned int err = 0;
1041     data = ByteSwapToDevice32(data);
1042     if (get1394Service().write(0xffc0 | getNodeId(), reg, 1, &data) <= 0) {
1043         err = 1;
1044         debugError("Error doing RME write to register 0x%06llx\n",reg);
1045     }
1046
1047     return (err==0)?0:-1;
1048 }
1049
1050 signed int
1051 Device::writeBlock(fb_nodeaddr_t reg, quadlet_t *data, unsigned int n_quads) {
1052 //
1053 // Write a block of data to the device starting at address "reg".  Note that
1054 // the conditional byteswap is done "in place" on data, so the contents of
1055 // data may be modified by calling this function.
1056 //
1057     unsigned int err = 0;
1058     unsigned int i;
1059
1060     for (i=0; i<n_quads; i++) {
1061       data[i] = ByteSwapToDevice32(data[i]);
1062     }
1063     if (get1394Service().write(0xffc0 | getNodeId(), reg, n_quads, data) <= 0) {
1064         err = 1;
1065         debugError("Error doing RME block write of %d quadlets to register 0x%06llx\n",
1066           n_quads, reg);
1067     }
1068
1069     return (err==0)?0:-1;
1070 }
1071                  
1072 }
Note: See TracBrowser for help on using the browser.