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

Revision 1660, 20.6 kB (checked in by jwoithe, 14 years ago)

ieee1394Service: new method allocateFixedIsoChannelGeneric() to allocate a specific channel number instead of scanning for the next available channel number. This functionality is needed for the RME devices.
RME: assign/detect iso channels to use and allocate required bandwidth.

Line 
1 /*
2  * Copyright (C) 2005-2009 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 "rme/rme_avdevice.h"
28 #include "rme/fireface_def.h"
29 #include "rme/fireface_settings_ctrls.h"
30
31 #include "libieee1394/configrom.h"
32 #include "libieee1394/ieee1394service.h"
33
34 #include "debugmodule/debugmodule.h"
35
36 #include "devicemanager.h"
37
38 #include <string>
39 #include <stdint.h>
40 #include <assert.h>
41 #include "libutil/ByteSwap.h"
42
43 #include <iostream>
44 #include <sstream>
45
46 #include <libraw1394/csr.h>
47
48 // Known values for the unit version of RME devices
49 #define RME_UNITVERSION_FF800  0x0001
50 #define RME_UNITVERSION_FF400  0x0002
51
52 namespace Rme {
53
54 // The RME devices expect async packet data in little endian format (as
55 // opposed to bus order, which is big endian).  Therefore define our own
56 // 32-bit byteswap function to do this.
57 #if __BYTE_ORDER == __BIG_ENDIAN
58 static inline uint32_t
59 ByteSwapToDevice32(uint32_t d)
60 {
61     return byteswap_32(d);
62 }
63 ByteSwapFromDevice32(uint32_t d)
64 {
65     return byteswap_32(d);
66 }
67 #else
68 static inline uint32_t
69 ByteSwapToDevice32(uint32_t d)
70 {
71     return d;
72 }
73 static inline uint32_t
74 ByteSwapFromDevice32(uint32_t d)
75 {
76     return d;
77 }
78 #endif
79
80 Device::Device( DeviceManager& d,
81                       std::auto_ptr<ConfigRom>( configRom ))
82     : FFADODevice( d, configRom )
83     , m_rme_model( RME_MODEL_NONE )
84     , num_channels( 0 )
85     , frames_per_packet( 0 )
86     , speed800( 0 )
87     , iso_tx_channel( -1 )
88     , iso_rx_channel( -1 )
89     , m_MixerContainer( NULL )
90     , m_ControlContainer( NULL )
91 {
92     debugOutput( DEBUG_LEVEL_VERBOSE, "Created Rme::Device (NodeID %d)\n",
93                  getConfigRom().getNodeId() );
94 }
95
96 Device::~Device()
97 {
98     if (iso_tx_channel>=0 && !get1394Service().freeIsoChannel(iso_tx_channel)) {
99         debugOutput(DEBUG_LEVEL_VERBOSE, "Could not free tx iso channel %d\n", iso_tx_channel);
100     }
101     if (iso_rx_channel>=0 && !get1394Service().freeIsoChannel(iso_rx_channel)) {
102         debugOutput(DEBUG_LEVEL_VERBOSE, "Could not free rx iso channel %d\n", iso_rx_channel);
103     }
104
105     destroyMixer();
106
107     if (dev_config != NULL) {
108         switch (rme_shm_close(dev_config)) {
109             case RSO_CLOSE:
110                 debugOutput( DEBUG_LEVEL_VERBOSE, "Configuration shared data object closed\n");
111                 break;
112             case RSO_CLOSE_DELETE:
113                 debugOutput( DEBUG_LEVEL_VERBOSE, "Configuration shared data object closed and deleted (no other users)\n");
114                 break;
115         }
116     }
117 }
118
119 bool
120 Device::buildMixer() {
121     signed int i;
122     bool result = true;
123
124     destroyMixer();
125     debugOutput(DEBUG_LEVEL_VERBOSE, "Building an RME mixer...\n");
126
127
128     // Non-mixer device controls
129     m_ControlContainer = new Control::Container(this, "Control");
130     if (!m_ControlContainer) {
131         debugError("Could not create control container\n");
132         destroyMixer();
133         return false;
134     }
135
136     result &= m_ControlContainer->addElement(
137         new RmeSettingsCtrl(*this, RME_CTRL_INFO_MODEL, 0,
138             "Model", "Model ID", ""));
139     result &= m_ControlContainer->addElement(
140         new RmeSettingsCtrl(*this, RME_CTRL_INFO_TCO_PRESENT, 0,
141             "TCO_present", "TCO is present", ""));
142
143     result &= m_ControlContainer->addElement(
144         new RmeSettingsCtrl(*this, RME_CTRL_PHANTOM_SW, 0,
145             "Phantom", "Phantom switches", ""));
146     result &= m_ControlContainer->addElement(
147         new RmeSettingsCtrl(*this, RME_CTRL_INPUT_LEVEL, 0,
148             "Input_level", "Input level", ""));
149     result &= m_ControlContainer->addElement(
150         new RmeSettingsCtrl(*this, RME_CTRL_OUTPUT_LEVEL, 0,
151             "Output_level", "Output level", ""));
152     result &= m_ControlContainer->addElement(
153         new RmeSettingsCtrl(*this, RME_CTRL_PHONES_LEVEL, 0,
154             "Phones_level", "Phones level", ""));
155
156     if (m_rme_model == RME_MODEL_FIREFACE400) {
157         // Instrument input options
158         for (i=3; i<=4; i++) {
159             char path[32], desc[64];
160             snprintf(path, sizeof(path), "Chan%d_opt_instr", i);
161             snprintf(desc, sizeof(desc), "Chan%d instrument option", i);
162             result &= m_ControlContainer->addElement(
163                 new RmeSettingsCtrl(*this, RME_CTRL_FF400_INSTR_SW, i,
164                     path, desc, ""));
165             snprintf(path, sizeof(path), "Chan%d_opt_pad", i);
166             snprintf(desc, sizeof(desc), "Chan%d pad option", i);
167             result &= m_ControlContainer->addElement(
168                 new RmeSettingsCtrl(*this, RME_CTRL_FF400_PAD_SW, i,
169                     path, desc, ""));
170         }
171
172         // Input/output gains
173         result &= m_ControlContainer->addElement(
174             new RmeSettingsMatrixCtrl(*this, RME_MATRIXCTRL_GAINS, "Gains"));
175     }
176
177     if (!result) {
178         debugWarning("One or more device control elements could not be created\n");
179         destroyMixer();
180         return false;
181     }
182
183     if (!addElement(m_ControlContainer)) {
184         debugWarning("Could not register mixer to device\n");
185         // clean up
186         destroyMixer();
187         return false;
188     }
189
190     return true;
191 }
192
193 bool
194 Device::destroyMixer() {
195     bool ret = true;
196     debugOutput(DEBUG_LEVEL_VERBOSE, "destroy mixer...\n");
197
198     if (m_MixerContainer == NULL) {
199         debugOutput(DEBUG_LEVEL_VERBOSE, "no mixer to destroy...\n");
200     } else
201     if (!deleteElement(m_MixerContainer)) {
202         debugError("Mixer present but not registered to the avdevice\n");
203         ret = false;
204     } else {
205         // remove and delete (as in free) child control elements
206         m_MixerContainer->clearElements(true);
207         delete m_MixerContainer;
208         m_MixerContainer = NULL;
209     }
210
211     // remove control container
212     if (m_ControlContainer == NULL) {
213         debugOutput(DEBUG_LEVEL_VERBOSE, "no controls to destroy...\n");
214     } else
215     if (!deleteElement(m_ControlContainer)) {
216         debugError("Controls present but not registered to the avdevice\n");
217         ret = false;
218     } else {
219         // remove and delete (as in free) child control elements
220         m_ControlContainer->clearElements(true);
221         delete m_ControlContainer;
222         m_ControlContainer = NULL;
223     }
224
225     return false;
226 }
227
228 bool
229 Device::probe( Util::Configuration& c, ConfigRom& configRom, bool generic )
230 {
231     if (generic) {
232         return false;
233     } else {
234         // check if device is in supported devices list.  Note that the RME
235         // devices use the unit version to identify the individual devices.
236         // To avoid having to extend the configuration file syntax to
237         // include this at this point, we'll use the configuration file
238         // model ID to test against the device unit version.  This can be
239         // tidied up if the configuration file is extended at some point to
240         // include the unit version.
241         unsigned int vendorId = configRom.getNodeVendorId();
242         unsigned int unitVersion = configRom.getUnitVersion();
243
244         Util::Configuration::VendorModelEntry vme = c.findDeviceVME( vendorId, unitVersion );
245         return c.isValid(vme) && vme.driver == Util::Configuration::eD_RME;
246     }
247 }
248
249 FFADODevice *
250 Device::createDevice(DeviceManager& d, std::auto_ptr<ConfigRom>( configRom ))
251 {
252     return new Device(d, configRom );
253 }
254
255 bool
256 Device::discover()
257 {
258     signed int i;
259     unsigned int vendorId = getConfigRom().getNodeVendorId();
260     // See note in Device::probe() about why we use the unit version here.
261     unsigned int unitVersion = getConfigRom().getUnitVersion();
262
263     Util::Configuration &c = getDeviceManager().getConfiguration();
264     Util::Configuration::VendorModelEntry vme = c.findDeviceVME( vendorId, unitVersion );
265
266     if (c.isValid(vme) && vme.driver == Util::Configuration::eD_RME) {
267         debugOutput( DEBUG_LEVEL_VERBOSE, "found %s %s\n",
268                      vme.vendor_name.c_str(),
269                      vme.model_name.c_str());
270     } else {
271         debugWarning("Device '%s %s' unsupported by RME driver (no generic RME support)\n",
272                      getConfigRom().getVendorName().c_str(), getConfigRom().getModelName().c_str());
273     }
274
275     if (unitVersion == RME_UNITVERSION_FF800) {
276         m_rme_model = RME_MODEL_FIREFACE800;
277     } else
278     if (unitVersion == RME_MODEL_FIREFACE400) {
279         m_rme_model = RME_MODEL_FIREFACE400;
280     } else {
281         debugError("Unsupported model\n");
282         return false;
283     }
284
285     // Set up the shared data object for configuration data
286     i = rme_shm_open(&dev_config);
287     if (i == RSO_OPEN_CREATED) {
288         debugOutput( DEBUG_LEVEL_VERBOSE, "New configuration shared data object created\n");
289     } else
290     if (i == RSO_OPEN_ATTACHED) {
291         debugOutput( DEBUG_LEVEL_VERBOSE, "Attached to existing configuration shared data object\n");
292     }
293     if (dev_config == NULL) {
294         debugOutput( DEBUG_LEVEL_WARNING, "Could not create/access shared configuration memory object, using process-local storage\n");
295         memset(&local_dev_config_obj, 0, sizeof(local_dev_config_obj));
296         dev_config = &local_dev_config_obj;
297     }
298     settings = &dev_config->settings;
299     tco_settings = &dev_config->tco_settings;
300
301     // If device is FF800, check to see if the TCO is fitted
302     if (m_rme_model == RME_MODEL_FIREFACE800) {
303         dev_config->tco_present = (read_tco(NULL, 0) == 0);
304     }
305     debugOutput(DEBUG_LEVEL_VERBOSE, "TCO present: %s\n",
306       dev_config->tco_present?"yes":"no");
307
308     init_hardware();
309
310     if (!buildMixer()) {
311         debugWarning("Could not build mixer\n");
312     }
313
314     // This is just for testing
315     read_device_flash_settings(NULL);
316
317     return true;
318 }
319
320 int
321 Device::getSamplingFrequency( ) {
322
323     // Retrieve the current sample rate.  For practical purposes this
324     // is the software rate currently in use.
325     return dev_config->software_freq;
326 }
327
328 int
329 Device::getConfigurationId()
330 {
331     return 0;
332 }
333
334 bool
335 Device::setDDSFrequency( int dds_freq )
336 {
337     // Set a fixed DDS frequency.  If the device is the clock master this
338     // will immediately be copied to the hardware DDS register.  Otherwise
339     // it will take effect as required at the time the sampling rate is
340     // changed or streaming is started.
341
342     // If the device is streaming, the new DDS rate must have the same
343     // multiplier as the software sample rate
344     if (hardware_is_streaming()) {
345         if (multiplier_of_freq(dds_freq) != multiplier_of_freq(dev_config->software_freq))
346             return false;
347     }
348
349     dev_config->dds_freq = dds_freq;
350     if (settings->clock_mode == FF_STATE_CLOCKMODE_MASTER) {
351         if (set_hardware_dds_freq(dds_freq) != 0)
352             return false;
353     }
354
355     return true;
356 }
357
358 bool
359 Device::setSamplingFrequency( int samplingFrequency )
360 {
361     // Request a sampling rate on behalf of software.  Software is limited
362     // to sample rates of 32k, 44.1k, 48k and the 2x/4x multiples of these.
363     // The user may lock the device to a much wider range of frequencies via
364     // the explicit DDS controls in the control panel.  If the explicit DDS
365     // control is active the software is limited to the "standard" speeds
366     // corresponding to the multiplier in use by the DDS.
367     //
368     // Similarly, if the device is externally clocked the software is
369     // limited to the external clock frequency.
370     //
371     // Otherwise the software has free choice of the software speeds noted
372     // above.
373
374     bool ret = -1;
375     signed int i, j;
376     signed int mult[3] = {1, 2, 4};
377     signed int base_freq[3] = {32000, 44100, 48000};
378     signed int freq = samplingFrequency;
379     FF_state_t state;
380     signed int fixed_freq = 0;
381
382     get_hardware_state(&state);
383
384     // If device is locked to a frequency via external clock, explicit
385     // setting of the DDS or by virtue of streaming being active, get that
386     // frequency.
387     if (state.clock_mode == FF_STATE_CLOCKMODE_AUTOSYNC) {
388         // FIXME: if synced to TCO, is autosync_freq valid?
389         fixed_freq = state.autosync_freq;
390     } else
391     if (dev_config->dds_freq > 0) {
392         fixed_freq = dev_config->dds_freq;
393     } else
394     if (hardware_is_streaming()) {
395         fixed_freq = dev_config->software_freq;
396     }
397
398     // If the device is running to a fixed frequency, software can only
399     // request frequencies with the same multiplier.  Similarly, the
400     // multiplier is locked in "master" clock mode if the device is
401     // streaming.
402     if (fixed_freq > 0) {
403         signed int fixed_mult = multiplier_of_freq(fixed_freq);
404         if (multiplier_of_freq(freq) != multiplier_of_freq(fixed_freq))
405             return -1;
406         for (j=0; j<3; j++) {
407             if (freq == base_freq[j]*fixed_mult) {
408                 ret = 0;
409                 break;
410             }
411         }
412     } else {
413         for (i=0; i<3; i++) {
414             for (j=0; j<3; j++) {
415                 if (freq == base_freq[j]*mult[i]) {
416                     ret = 0;
417                     break;
418                 }
419             }
420         }
421     }
422     // If requested frequency is unavailable, return -1
423     if (ret == -1)
424         return false;
425
426     // If a DDS frequency has been explicitly requested this is always
427     // used to programm the hardware DDS regardless of the rate requested
428     // by the software.  Otherwise we use the requested sampling rate.
429     if (dev_config->dds_freq > 0)
430         freq = dev_config->dds_freq;
431     if (set_hardware_dds_freq(freq) != 0)
432         return false;
433
434     dev_config->software_freq = samplingFrequency;
435     return true;
436 }
437
438 std::vector<int>
439 Device::getSupportedSamplingFrequencies()
440 {
441     std::vector<int> frequencies;
442     signed int i, j;
443     signed int mult[3] = {1, 2, 4};
444     signed int freq[3] = {32000, 44100, 48000};
445     FF_state_t state;
446
447     get_hardware_state(&state);
448
449     // Generate the list of supported frequencies.  If the device is
450     // externally clocked the frequency is limited to the external clock
451     // frequency.  If the device is running the multiplier is fixed.
452     if (state.clock_mode == FF_STATE_CLOCKMODE_AUTOSYNC) {
453         // FIXME: if synced to TCO, is autosync_freq valid?
454         frequencies.push_back(state.autosync_freq);
455     } else
456     if (state.is_streaming) {
457         unsigned int fixed_mult = multiplier_of_freq(dev_config->software_freq);
458         for (j=0; j<3; j++) {
459             frequencies.push_back(freq[j]*fixed_mult);
460         }
461     } else {
462         for (i=0; i<3; i++) {
463             for (j=0; j<3; j++) {
464                 frequencies.push_back(freq[j]*mult[i]);
465             }
466         }
467     }
468     return frequencies;
469 }
470
471 FFADODevice::ClockSourceVector
472 Device::getSupportedClockSources() {
473     FFADODevice::ClockSourceVector r;
474     return r;
475 }
476
477 bool
478 Device::setActiveClockSource(ClockSource s) {
479     return false;
480 }
481
482 FFADODevice::ClockSource
483 Device::getActiveClockSource() {
484     ClockSource s;
485     return s;
486 }
487
488 bool
489 Device::lock() {
490
491     return true;
492 }
493
494
495 bool
496 Device::unlock() {
497
498     return true;
499 }
500
501 void
502 Device::showDevice()
503 {
504     unsigned int vendorId = getConfigRom().getNodeVendorId();
505     unsigned int modelId = getConfigRom().getModelId();
506
507     Util::Configuration &c = getDeviceManager().getConfiguration();
508     Util::Configuration::VendorModelEntry vme = c.findDeviceVME( vendorId, modelId );
509
510     debugOutput(DEBUG_LEVEL_VERBOSE,
511         "%s %s at node %d\n", vme.vendor_name.c_str(), vme.model_name.c_str(), getNodeId());
512 }
513
514 bool
515 Device::prepare() {
516
517     signed int mult, bandwidth;
518
519     debugOutput(DEBUG_LEVEL_NORMAL, "Preparing Device...\n" );
520
521     // The number of frames transmitted in a single packet is solely
522     // determined by the sample rate.
523     mult = multiplier_of_freq(getSamplingFrequency());
524     switch (mult) {
525         case 2: frames_per_packet = 15; break;
526         case 4: frames_per_packet = 25; break;
527     default:
528         frames_per_packet = 7;
529     }
530
531     // The number of active channels depends on sample rate and whether
532     // bandwidth limitation is active.  First set up the number of analog
533     // channels (which differs between devices), then add SPDIF channels if
534     // relevant.  Finally, the number of channels available from each ADAT
535     // interface depends on sample rate: 0 at 4x, 4 at 2x and 8 at 1x.
536     if (m_rme_model == RME_MODEL_FIREFACE800)
537         num_channels = 10;
538     else
539         num_channels = 8;
540     if (settings->limit_bandwidth != FF_SWPARAM_BWLIMIT_ANALOG_ONLY)
541         num_channels += 2;
542     if (settings->limit_bandwidth==FF_SWPARAM_BWLIMIT_NO_ADAT2 ||
543         settings->limit_bandwidth==FF_SWPARAM_BWLIMIT_SEND_ALL_CHANNELS)
544         num_channels += (mult==4?0:(mult==2?4:8));
545     if (settings->limit_bandwidth==FF_SWPARAM_BWLIMIT_SEND_ALL_CHANNELS)
546         num_channels += (mult==4?0:(mult==2?4:8));
547
548     // Bandwidth is calculated here.  For the moment we assume the device
549     // is connected at S400, so 1 allocation unit is 1 transmitted byte.
550     // There is 25 allocation units of protocol overhead per packet.  Each
551     // channel of audio data is sent/received as a 32 bit integer.
552     bandwidth = 25 + num_channels*4*frames_per_packet;
553
554     // Both the FF400 and FF800 require we allocate a tx iso channel.  The
555     // rx channel is also allocated for the FF400 while the FF800 handles
556     // the rx channel allocation for that device.
557     if (iso_tx_channel < 0) {
558         iso_tx_channel = get1394Service().allocateIsoChannelGeneric(bandwidth);
559     }
560
561     if (iso_rx_channel < 0) {
562         if (m_rme_model == RME_MODEL_FIREFACE800) {
563             unsigned int stat[4];
564             get_hardware_streaming_status(stat, 4);
565             // CHECKME: does this work before streaming has been initialised?
566             iso_rx_channel = stat[2] & 63;
567             iso_rx_channel = get1394Service().allocateFixedIsoChannelGeneric(iso_rx_channel, bandwidth);
568         } else {
569             iso_rx_channel = get1394Service().allocateIsoChannelGeneric(bandwidth);
570         }
571     }
572
573     if (iso_tx_channel<0 || iso_rx_channel<0) {
574         if (iso_tx_channel >= 0)
575             get1394Service().freeIsoChannel(iso_tx_channel);
576         if (iso_rx_channel >= 0)
577             get1394Service().freeIsoChannel(iso_rx_channel);
578         debugFatal("Could not allocate iso channels\n");
579         return false;
580     }
581
582
583     return true;
584 }
585
586 int
587 Device::getStreamCount() {
588         return 0; // one receive, one transmit
589 }
590
591 Streaming::StreamProcessor *
592 Device::getStreamProcessorByIndex(int i) {
593     return NULL;
594 }
595
596 bool
597 Device::startStreamByIndex(int i) {
598     return false;
599 }
600
601 bool
602 Device::stopStreamByIndex(int i) {
603     return false;
604
605 }
606
607 unsigned int
608 Device::readRegister(fb_nodeaddr_t reg) {
609
610     quadlet_t quadlet;
611    
612     quadlet = 0;
613     if (get1394Service().read(0xffc0 | getNodeId(), reg, 1, &quadlet) <= 0) {
614         debugError("Error doing RME read from register 0x%06x\n",reg);
615     }
616     return ByteSwapFromDevice32(quadlet);
617 }
618
619 signed int
620 Device::readBlock(fb_nodeaddr_t reg, quadlet_t *buf, unsigned int n_quads) {
621
622     unsigned int i;
623
624     if (get1394Service().read(0xffc0 | getNodeId(), reg, n_quads, buf) <= 0) {
625         debugError("Error doing RME block read of %d quadlets from register 0x%06x\n",
626             n_quads, reg);
627         return -1;
628     }
629     for (i=0; i<n_quads; i++) {
630        buf[i] = ByteSwapFromDevice32(buf[i]);
631     }
632
633     return 0;
634 }
635
636 signed int
637 Device::writeRegister(fb_nodeaddr_t reg, quadlet_t data) {
638
639     unsigned int err = 0;
640     data = ByteSwapToDevice32(data);
641     if (get1394Service().write(0xffc0 | getNodeId(), reg, 1, &data) <= 0) {
642         err = 1;
643         debugError("Error doing RME write to register 0x%06x\n",reg);
644     }
645     return (err==0)?0:-1;
646 }
647
648 signed int
649 Device::writeBlock(fb_nodeaddr_t reg, quadlet_t *data, unsigned int n_quads) {
650 //
651 // Write a block of data to the device starting at address "reg".  Note that
652 // the conditional byteswap is done "in place" on data, so the contents of
653 // data may be modified by calling this function.
654 //
655     unsigned int err = 0;
656     unsigned int i;
657
658     for (i=0; i<n_quads; i++) {
659       data[i] = ByteSwapToDevice32(data[i]);
660     }
661     if (get1394Service().write(0xffc0 | getNodeId(), reg, n_quads, data) <= 0) {
662         err = 1;
663         debugError("Error doing RME block write of %d quadlets to register 0x%06x\n",
664           n_quads, reg);
665     }
666     return (err==0)?0:-1;
667 }
668                  
669 }
Note: See TracBrowser for help on using the browser.