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

Revision 2033, 31.6 kB (checked in by jwoithe, 9 years ago)

rme: implement SPDIF output option control via ffado-mixer. Again, I haven't the means to confirm whether these settings have the desired effect on the SPDIF bitstream yet.

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