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

Revision 2032, 30.9 kB (checked in by jwoithe, 9 years ago)

rme: implement SPDIF input mode selection via ffado-mixer. Whether this has the desired effect on the device remains to be seen - I do not have anything to test the mode of the optical port right now.

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