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

Revision 2021, 30.8 kB (checked in by jwoithe, 12 years ago)

matrixmixer: complete initial implementation of optional mute functionality. A graphical indication of mute state (beyond the toggled menu item) is still needed.
matrixmixer: implement optional phase inversion interface. Again, a graphical indication of this state is still required.
rme: make use of the mute/invert functionality of the matrix mixer. Currently this is only connected for the input faders.

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