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

Revision 2037, 32.3 kB (checked in by jwoithe, 9 years ago)

rme: make clock mode control active. Note that this isn't overly useful without the other clock-related controls and indicators being active. They will follow soon.

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