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

Revision 2038, 33.3 kB (checked in by jwoithe, 12 years ago)

rme: various information panes are now active in ffado-mixer: sync check, autosync reference, spdif freqency and system clock. The function of these in the presence of actual external sync sources is yet to be confirmed. The system clock information has been confirmed to update when the clock mode and/or sample rate controls are altered.

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