root/branches/libffado-2.0/src/devicemanager.cpp

Revision 1545, 38.6 kB (checked in by ppalmers, 12 years ago)

fixes #201

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1 /*
2  * Copyright (C) 2005-2008 by Daniel Wagner
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 #include "fbtypes.h"
26
27 #include "devicemanager.h"
28 #include "ffadodevice.h"
29 #include "DeviceStringParser.h"
30
31 #include "libieee1394/configrom.h"
32 #include "libieee1394/ieee1394service.h"
33 #include "libieee1394/IsoHandlerManager.h"
34
35 #include "libstreaming/generic/StreamProcessor.h"
36 #include "libstreaming/StreamProcessorManager.h"
37
38 #include "debugmodule/debugmodule.h"
39
40 #include "libutil/PosixMutex.h"
41
42 #ifdef ENABLE_BEBOB
43 #include "bebob/bebob_avdevice.h"
44 #endif
45
46 #ifdef ENABLE_GENERICAVC
47     #include "genericavc/avc_avdevice.h"
48 #endif
49
50 #ifdef ENABLE_FIREWORKS
51     #include "fireworks/fireworks_device.h"
52 #endif
53
54 #ifdef ENABLE_MOTU
55 #include "motu/motu_avdevice.h"
56 #endif
57
58 #include <iostream>
59 #include <sstream>
60
61 #include <algorithm>
62
63 using namespace std;
64
65 IMPL_DEBUG_MODULE( DeviceManager, DeviceManager, DEBUG_LEVEL_NORMAL );
66
67 DeviceManager::DeviceManager()
68     : Control::Container(NULL, "devicemanager") // this is the control root node
69     , m_DeviceListLock( new Util::PosixMutex("DEVLST") )
70     , m_BusResetLock( new Util::PosixMutex("DEVBR") )
71     , m_processorManager( new Streaming::StreamProcessorManager( *this ) )
72     , m_deviceStringParser( new DeviceStringParser() )
73     , m_configuration ( new Util::Configuration() )
74     , m_used_cache_last_time( false )
75     , m_thread_realtime( false )
76     , m_thread_priority( 0 )
77 {
78     addOption(Util::OptionContainer::Option("slaveMode",false));
79     addOption(Util::OptionContainer::Option("snoopMode",false));
80 }
81
82 DeviceManager::~DeviceManager()
83 {
84     // save configuration
85     if(!m_configuration->save()) {
86         debugWarning("could not save configuration\n");
87     }
88
89     m_BusResetLock->Lock(); // make sure we are not handling a busreset.
90     m_DeviceListLock->Lock(); // make sure nobody is using this
91     for ( FFADODeviceVectorIterator it = m_avDevices.begin();
92           it != m_avDevices.end();
93           ++it )
94     {
95         if (!deleteElement(*it)) {
96             debugWarning("failed to remove AvDevice from Control::Container\n");
97         }
98         delete *it;
99     }
100     m_DeviceListLock->Unlock();
101
102     // the SP's are automatically unregistered from the SPM
103     delete m_processorManager;
104
105     // the device list is empty, so wake up any waiting
106     // reset handlers
107     m_BusResetLock->Unlock();
108
109     // remove the bus-reset handlers
110     for ( FunctorVectorIterator it = m_busreset_functors.begin();
111           it != m_busreset_functors.end();
112           ++it )
113     {
114         delete *it;
115     }
116
117     for ( Ieee1394ServiceVectorIterator it = m_1394Services.begin();
118           it != m_1394Services.end();
119           ++it )
120     {
121         delete *it;
122     }
123
124     delete m_DeviceListLock;
125     delete m_BusResetLock;
126     delete m_deviceStringParser;
127 }
128
129 bool
130 DeviceManager::setThreadParameters(bool rt, int priority) {
131     if (!m_processorManager->setThreadParameters(rt, priority)) {
132         debugError("Could not set processor manager thread parameters\n");
133         return false;
134     }
135     for ( Ieee1394ServiceVectorIterator it = m_1394Services.begin();
136           it != m_1394Services.end();
137           ++it )
138     {
139         if (!(*it)->setThreadParameters(rt, priority)) {
140             debugError("Could not set 1394 service thread parameters\n");
141             return false;
142         }
143     }
144     m_thread_realtime = rt;
145     m_thread_priority = priority;
146     return true;
147 }
148
149 bool
150 DeviceManager::initialize()
151 {
152     assert(m_1394Services.size() == 0);
153     assert(m_busreset_functors.size() == 0);
154
155     m_configuration->openFile( "temporary", Util::Configuration::eFM_Temporary );
156     m_configuration->openFile( USER_CONFIG_FILE, Util::Configuration::eFM_ReadWrite );
157     m_configuration->openFile( SYSTEM_CONFIG_FILE, Util::Configuration::eFM_ReadOnly );
158
159     int nb_detected_ports = Ieee1394Service::detectNbPorts();
160     if (nb_detected_ports < 0) {
161         debugFatal("Failed to detect the number of 1394 adapters. Is the IEEE1394 stack loaded (raw1394)?\n");
162         return false;
163     }
164     if (nb_detected_ports == 0) {
165         debugFatal("No firewire adapters (ports) found.\n");
166         return false;
167     }
168     debugOutput( DEBUG_LEVEL_VERBOSE, "Found %d firewire adapters (ports)\n", nb_detected_ports);
169     for (unsigned int port = 0; port < (unsigned int)nb_detected_ports; port++) {
170         Ieee1394Service* tmp1394Service = new Ieee1394Service();
171         if ( !tmp1394Service ) {
172             debugFatal( "Could not create Ieee1349Service object for port %d\n", port );
173             return false;
174         }
175         tmp1394Service->setVerboseLevel( getDebugLevel() );
176         m_1394Services.push_back(tmp1394Service);
177
178         if(!tmp1394Service->useConfiguration(m_configuration)) {
179             debugWarning("Could not load config to 1394service\n");
180         }
181
182         tmp1394Service->setThreadParameters(m_thread_realtime, m_thread_priority);
183         if ( !tmp1394Service->initialize( port ) ) {
184             debugFatal( "Could not initialize Ieee1349Service object for port %d\n", port );
185             return false;
186         }
187         // add the bus reset handler
188         Util::Functor* tmp_busreset_functor = new Util::MemberFunctor1< DeviceManager*,
189                     void (DeviceManager::*)(Ieee1394Service &), Ieee1394Service & >
190                     ( this, &DeviceManager::busresetHandler, *tmp1394Service, false );
191         if ( !tmp_busreset_functor ) {
192             debugFatal( "Could not create busreset handler for port %d\n", port );
193             return false;
194         }
195         m_busreset_functors.push_back(tmp_busreset_functor);
196
197         tmp1394Service->addBusResetHandler( tmp_busreset_functor );
198     }
199
200     return true;
201 }
202
203 bool
204 DeviceManager::addSpecString(char *s) {
205     std::string spec = s;
206     if(isSpecStringValid(spec)) {
207         debugOutput(DEBUG_LEVEL_VERBOSE, "Adding spec string %s\n", spec.c_str());
208         assert(m_deviceStringParser);
209         m_deviceStringParser->parseString(spec);
210         return true;
211     } else {
212         debugError("Invalid spec string: %s\n", spec.c_str());
213         return false;
214     }
215 }
216
217 bool
218 DeviceManager::isSpecStringValid(std::string s) {
219     assert(m_deviceStringParser);
220     return m_deviceStringParser->isValidString(s);
221 }
222
223 void
224 DeviceManager::busresetHandler(Ieee1394Service &service)
225 {
226     // serialize bus reset handling since it can be that a new one occurs while we're
227     // doing stuff.
228     debugOutput( DEBUG_LEVEL_NORMAL, "Bus reset detected on service %p...\n", &service );
229     Util::MutexLockHelper lock(*m_BusResetLock);
230     debugOutput( DEBUG_LEVEL_NORMAL, " handling busreset...\n" );
231
232     // FIXME: what if the devices are gone? (device should detect this!)
233     // propagate the bus reset to all avDevices
234     m_DeviceListLock->Lock(); // make sure nobody is using this
235     for ( FFADODeviceVectorIterator it = m_avDevices.begin();
236           it != m_avDevices.end();
237           ++it )
238     {
239         if(&service == &((*it)->get1394Service())) {
240             debugOutput(DEBUG_LEVEL_NORMAL,
241                         "issue busreset on device GUID %s\n",
242                         (*it)->getConfigRom().getGuidString().c_str());
243             (*it)->handleBusReset();
244         } else {
245             debugOutput(DEBUG_LEVEL_NORMAL,
246                         "skipping device GUID %s since not on service %p\n",
247                         (*it)->getConfigRom().getGuidString().c_str(), &service);
248         }
249     }
250     m_DeviceListLock->Unlock();
251
252     // now that the devices have been updates, we can request to update the iso streams
253     if(!service.getIsoHandlerManager().handleBusReset()) {
254         debugError("IsoHandlerManager failed to handle busreset\n");
255     }
256
257     // notify the streamprocessormanager of the busreset
258 //     if(m_processorManager) {
259 //         m_processorManager->handleBusReset(service);
260 //     } else {
261 //         debugWarning("No valid SPM\n");
262 //     }
263
264     // rediscover to find new devices
265     // (only for the control server ATM, streaming can't dynamically add/remove devices)
266     if(!discover(m_used_cache_last_time, true)) {
267         debugError("Could not rediscover devices\n");
268     }
269
270     // notify any clients
271     signalNotifiers(m_busResetNotifiers);
272
273     // display the new state
274     if(getDebugLevel() >= DEBUG_LEVEL_VERBOSE) {
275         showDeviceInfo();
276     }
277 }
278
279 void
280 DeviceManager::signalNotifiers(notif_vec_t& list)
281 {
282     for ( notif_vec_t::iterator it = list.begin();
283           it != list.end();
284           ++it )
285     {
286         Util::Functor* func = *it;
287         debugOutput( DEBUG_LEVEL_VERBOSE, " running notifier %p...\n", func );
288         ( *func )();
289     }
290 }
291
292 bool
293 DeviceManager::registerNotification(notif_vec_t& list, Util::Functor *handler)
294 {
295     debugOutput( DEBUG_LEVEL_VERBOSE, "register %p...\n", handler);
296     assert(handler);
297     for ( notif_vec_t::iterator it = list.begin();
298       it != list.end();
299       ++it )
300     {
301         if ( *it == handler ) {
302             debugOutput(DEBUG_LEVEL_VERBOSE, "already registered\n");
303             return false;
304         }
305     }
306     list.push_back(handler);
307     return true;
308 }
309
310 bool
311 DeviceManager::unregisterNotification(notif_vec_t& list, Util::Functor *handler)
312 {
313     debugOutput( DEBUG_LEVEL_VERBOSE, "unregister %p...\n", handler);
314     assert(handler);
315
316     for ( notif_vec_t::iterator it = list.begin();
317       it != list.end();
318       ++it )
319     {
320         if ( *it == handler ) {
321             list.erase(it);
322             return true;
323         }
324     }
325     debugError("Could not find handler (%p)\n", handler);
326     return false; //not found
327 }
328
329 bool
330 DeviceManager::discover( bool useCache, bool rediscover )
331 {
332     debugOutput( DEBUG_LEVEL_NORMAL, "Starting discovery...\n" );
333     useCache = useCache && ENABLE_DISCOVERY_CACHE;
334     m_used_cache_last_time = useCache;
335     bool slaveMode=false;
336     if(!getOption("slaveMode", slaveMode)) {
337         debugWarning("Could not retrieve slaveMode parameter, defauling to false\n");
338     }
339     bool snoopMode=false;
340     if(!getOption("snoopMode", snoopMode)) {
341         debugWarning("Could not retrieve snoopMode parameter, defauling to false\n");
342     }
343
344     setVerboseLevel(getDebugLevel());
345
346     // FIXME: it could be that a 1394service has disappeared (cardbus)
347
348     ConfigRomVector configRoms;
349     // build a list of configroms on the bus.
350     for ( Ieee1394ServiceVectorIterator it = m_1394Services.begin();
351         it != m_1394Services.end();
352         ++it )
353     {
354         Ieee1394Service *portService = *it;
355         for ( fb_nodeid_t nodeId = 0;
356             nodeId < portService->getNodeCount();
357             ++nodeId )
358         {
359             debugOutput( DEBUG_LEVEL_VERBOSE, "Probing node %d...\n", nodeId );
360
361             if (nodeId == portService->getLocalNodeId()) {
362                 debugOutput( DEBUG_LEVEL_VERBOSE, "Skipping local node (%d)...\n", nodeId );
363                 continue;
364             }
365
366             ConfigRom * configRom = new ConfigRom( *portService, nodeId );
367             if ( !configRom->initialize() ) {
368                 // \todo If a PHY on the bus is in power safe mode then
369                 // the config rom is missing. So this might be just
370                 // such this case and we can safely skip it. But it might
371                 // be there is a real software problem on our side.
372                 // This should be handlede more carefuly.
373                 debugOutput( DEBUG_LEVEL_NORMAL,
374                             "Could not read config rom from device (node id %d). "
375                             "Skip device discovering for this node\n",
376                             nodeId );
377                 continue;
378             }
379             configRoms.push_back(configRom);
380         }
381     }
382
383
384     // notify that we are going to manipulate the list
385     signalNotifiers(m_preUpdateNotifiers);
386     m_DeviceListLock->Lock(); // make sure nobody starts using the list
387     if(rediscover) {
388
389         FFADODeviceVector discovered_devices_on_bus;
390         for ( FFADODeviceVectorIterator it = m_avDevices.begin();
391             it != m_avDevices.end();
392             ++it )
393         {
394             bool seen_device = false;
395             for ( ConfigRomVectorIterator it2 = configRoms.begin();
396                 it2 != configRoms.end();
397                 ++it2 )
398             {
399                 seen_device |= ((*it)->getConfigRom().getGuid() == (*it2)->getGuid());
400             }
401
402             if(seen_device) {
403                 debugOutput( DEBUG_LEVEL_VERBOSE,
404                             "Already discovered device with GUID: %s\n",
405                             (*it)->getConfigRom().getGuidString().c_str() );
406                 // we already discovered this device, and it is still here. keep it
407                 discovered_devices_on_bus.push_back(*it);
408             } else {
409                 debugOutput( DEBUG_LEVEL_VERBOSE,
410                             "Device with GUID: %s disappeared from bus, removing...\n",
411                             (*it)->getConfigRom().getGuidString().c_str() );
412
413                 // the device has disappeared, remove it from the control tree
414                 if (!deleteElement(*it)) {
415                     debugWarning("failed to remove AvDevice from Control::Container\n");
416                 }
417                 // delete the device
418                 // FIXME: this will mess up the any code that waits for bus resets to
419                 //        occur
420                 delete *it;
421             }
422         }
423         // prune the devices that disappeared
424         m_avDevices = discovered_devices_on_bus;
425     } else { // remove everything since we are not rediscovering
426         for ( FFADODeviceVectorIterator it = m_avDevices.begin();
427             it != m_avDevices.end();
428             ++it )
429         {
430             if (!deleteElement(*it)) {
431                 debugWarning("failed to remove AvDevice from Control::Container\n");
432             }
433             delete *it;
434         }
435
436         m_avDevices.clear();
437     }
438
439     // delete the config rom list entries
440     // FIXME: we should reuse it
441     for ( ConfigRomVectorIterator it = configRoms.begin();
442         it != configRoms.end();
443         ++it )
444     {
445         delete *it;
446     }
447
448     assert(m_deviceStringParser);
449     // show the spec strings we're going to use
450     if(getDebugLevel() >= DEBUG_LEVEL_VERBOSE) {
451         m_deviceStringParser->show();
452     }
453
454     if (!slaveMode) {
455         // for the devices that are still in the list check if they require re-discovery
456         FFADODeviceVector failed_to_rediscover;
457         for ( FFADODeviceVectorIterator it_dev = m_avDevices.begin();
458             it_dev != m_avDevices.end();
459             ++it_dev )
460         {
461             FFADODevice* avDevice = *it_dev;
462             if(avDevice->needsRediscovery()) {
463                 debugOutput( DEBUG_LEVEL_NORMAL,
464                              "Device with GUID %s requires rediscovery (state changed)...\n",
465                              avDevice->getConfigRom().getGuidString().c_str());
466
467                 bool isFromCache = false;
468                 if ( useCache && avDevice->loadFromCache() ) {
469                     debugOutput( DEBUG_LEVEL_VERBOSE, "could load from cache\n" );
470                     isFromCache = true;
471                     // restore the debug level for everything that was loaded
472                     avDevice->setVerboseLevel( getDebugLevel() );
473                 } else if ( avDevice->discover() ) {
474                     debugOutput( DEBUG_LEVEL_VERBOSE, "discovery successful\n" );
475                 } else {
476                     debugError( "could not discover device\n" );
477                     failed_to_rediscover.push_back(avDevice);
478                     continue;
479                 }
480                 if ( !isFromCache && !avDevice->saveCache() ) {
481                     debugOutput( DEBUG_LEVEL_VERBOSE, "No cached version of AVC model created\n" );
482                 }
483             } else {
484                 debugOutput( DEBUG_LEVEL_NORMAL,
485                              "Device with GUID %s does not require rediscovery...\n",
486                              avDevice->getConfigRom().getGuidString().c_str());
487             }
488         }
489         // remove devices that failed to rediscover
490         // FIXME: surely there has to be a better way to do this
491         FFADODeviceVector to_keep;
492         for ( FFADODeviceVectorIterator it = m_avDevices.begin();
493             it != m_avDevices.end();
494             ++it )
495         {
496             bool keep_this_device = true;
497             for ( FFADODeviceVectorIterator it2 = failed_to_rediscover.begin();
498                 it2 != failed_to_rediscover.end();
499                 ++it2 )
500             {
501                 if(*it == *it2) {
502                     debugOutput( DEBUG_LEVEL_NORMAL,
503                                 "Removing device with GUID %s due to failed discovery...\n",
504                                 (*it)->getConfigRom().getGuidString().c_str());
505                     keep_this_device = false;
506                     break;
507                 }
508             }
509             if(keep_this_device) {
510                 to_keep.push_back(*it);
511             }
512         }
513         for ( FFADODeviceVectorIterator it2 = failed_to_rediscover.begin();
514             it2 != failed_to_rediscover.end();
515             ++it2 )
516         {
517             if (!deleteElement(*it2)) {
518                 debugWarning("failed to remove AvDevice from Control::Container\n");
519             }
520             delete *it2;
521         }
522         m_avDevices = to_keep;
523
524         // pick up new devices
525         for ( Ieee1394ServiceVectorIterator it = m_1394Services.begin();
526             it != m_1394Services.end();
527             ++it )
528         {
529             Ieee1394Service *portService = *it;
530             for ( fb_nodeid_t nodeId = 0;
531                 nodeId < portService->getNodeCount();
532                 ++nodeId )
533             {
534                 debugOutput( DEBUG_LEVEL_VERBOSE, "Probing node %d...\n", nodeId );
535    
536                 if (nodeId == portService->getLocalNodeId()) {
537                     debugOutput( DEBUG_LEVEL_VERBOSE, "Skipping local node (%d)...\n", nodeId );
538                     continue;
539                 }
540    
541                 ConfigRom *configRom = new ConfigRom( *portService, nodeId );
542                 if ( !configRom->initialize() ) {
543                     // \todo If a PHY on the bus is in power safe mode then
544                     // the config rom is missing. So this might be just
545                     // such this case and we can safely skip it. But it might
546                     // be there is a real software problem on our side.
547                     // This should be handlede more carefuly.
548                     debugOutput( DEBUG_LEVEL_NORMAL,
549                                 "Could not read config rom from device (node id %d). "
550                                 "Skip device discovering for this node\n",
551                                 nodeId );
552                     continue;
553                 }
554
555                 bool already_in_vector = false;
556                 for ( FFADODeviceVectorIterator it_dev = m_avDevices.begin();
557                     it_dev != m_avDevices.end();
558                     ++it_dev )
559                 {
560                     if ((*it_dev)->getConfigRom().getGuid() == configRom->getGuid()) {
561                         already_in_vector = true;
562                         break;
563                     }
564                 }
565                 if(already_in_vector) {
566                     if(!rediscover) {
567                         debugWarning("Device with GUID %s already discovered on other port, skipping device...\n",
568                                     configRom->getGuidString().c_str());
569                     }
570                     continue;
571                 }
572
573                 if(getDebugLevel() >= DEBUG_LEVEL_VERBOSE) {
574                     configRom->printConfigRomDebug();
575                 }
576
577                 // if spec strings are given, only add those devices
578                 // that match the spec string(s).
579                 // if no (valid) spec strings are present, grab all
580                 // supported devices.
581                 if(m_deviceStringParser->countDeviceStrings() &&
582                   !m_deviceStringParser->match(*configRom)) {
583                     debugOutput(DEBUG_LEVEL_VERBOSE, "Device doesn't match any of the spec strings. skipping...\n");
584                     continue;
585                 }
586
587                 // find a driver
588                 FFADODevice* avDevice = getDriverForDevice( configRom,
589                                                             nodeId );
590
591                 if ( avDevice ) {
592                     debugOutput( DEBUG_LEVEL_NORMAL,
593                                 "driver found for device %d\n",
594                                 nodeId );
595
596                     avDevice->setVerboseLevel( getDebugLevel() );
597                     bool isFromCache = false;
598                     if ( useCache && avDevice->loadFromCache() ) {
599                         debugOutput( DEBUG_LEVEL_VERBOSE, "could load from cache\n" );
600                         isFromCache = true;
601                         // restore the debug level for everything that was loaded
602                         avDevice->setVerboseLevel( getDebugLevel() );
603                     } else if ( avDevice->discover() ) {
604                         debugOutput( DEBUG_LEVEL_VERBOSE, "discovery successful\n" );
605                     } else {
606                         debugError( "could not discover device\n" );
607                         delete avDevice;
608                         continue;
609                     }
610
611                     if (snoopMode) {
612                         debugOutput( DEBUG_LEVEL_VERBOSE,
613                                     "Enabling snoop mode on node %d...\n", nodeId );
614
615                         if(!avDevice->setOption("snoopMode", snoopMode)) {
616                             debugWarning("Could not set snoop mode for device on node %d\n", nodeId);
617                             delete avDevice;
618                             continue;
619                         }
620                     }
621
622                     if ( !isFromCache && !avDevice->saveCache() ) {
623                         debugOutput( DEBUG_LEVEL_VERBOSE, "No cached version of AVC model created\n" );
624                     }
625                     m_avDevices.push_back( avDevice );
626
627                     if (!addElement(avDevice)) {
628                         debugWarning("failed to add AvDevice to Control::Container\n");
629                     }
630
631                     debugOutput( DEBUG_LEVEL_NORMAL, "discovery of node %d on port %d done...\n", nodeId, portService->getPort() );
632                 } else {
633                     // we didn't get a device, hence we have to delete the configrom ptr manually
634                     delete configRom;
635                 }
636             }
637         }
638
639         debugOutput( DEBUG_LEVEL_NORMAL, "Discovery finished...\n" );
640         // FIXME: do better sorting
641         // sort the m_avDevices vector on their GUID
642         // then assign reassign the id's to the devices
643         // the side effect of this is that for the same set of attached devices,
644         // a device id always corresponds to the same device
645         sort(m_avDevices.begin(), m_avDevices.end(), FFADODevice::compareGUID);
646
647         // first map the devices to a position using the device spec strings
648         std::map<fb_octlet_t, int> positionMap;
649         for ( FFADODeviceVectorIterator it = m_avDevices.begin();
650             it != m_avDevices.end();
651             ++it )
652         {
653             int pos = m_deviceStringParser->matchPosition((*it)->getConfigRom());
654             fb_octlet_t guid = (*it)->getConfigRom().getGuid();
655             positionMap[guid] = pos;
656             debugOutput( DEBUG_LEVEL_VERBOSE, "Mapping %s to position %d...\n", (*it)->getConfigRom().getGuidString().c_str(), pos );
657         }
658
659         // now run over all positions, and add the devices that belong to it
660         FFADODeviceVector sorted;
661         int nbPositions = m_deviceStringParser->countDeviceStrings();
662         int i=0;
663         for (i=0; i < nbPositions; i++) {
664             for ( FFADODeviceVectorIterator it = m_avDevices.begin();
665                 it != m_avDevices.end();
666                 ++it )
667             {
668                 fb_octlet_t guid = (*it)->getConfigRom().getGuid();
669                 if(positionMap[guid] == i) {
670                     sorted.push_back(*it);
671                 }
672             }
673         }
674
675         // assign the new vector
676         assert(sorted.size() == m_avDevices.size());
677         m_avDevices = sorted;
678
679         // set device id's
680         i = 0;
681         for ( FFADODeviceVectorIterator it = m_avDevices.begin();
682             it != m_avDevices.end();
683             ++it )
684         {
685             if ( !(*it)->setId( i++ ) ) {
686                 debugError( "setting Id failed\n" );
687             }
688         }
689         showDeviceInfo();
690
691     } else { // slave mode
692         // notify any clients
693         signalNotifiers(m_preUpdateNotifiers);
694         Ieee1394Service *portService = m_1394Services.at(0);
695         fb_nodeid_t nodeId = portService->getLocalNodeId();
696         debugOutput( DEBUG_LEVEL_VERBOSE, "Starting in slave mode on node %d...\n", nodeId );
697
698         std::auto_ptr<ConfigRom> configRom =
699             std::auto_ptr<ConfigRom>( new ConfigRom( *portService,
700                                                      nodeId ) );
701         if ( !configRom->initialize() ) {
702             // \todo If a PHY on the bus is in power safe mode then
703             // the config rom is missing. So this might be just
704             // such this case and we can safely skip it. But it might
705             // be there is a real software problem on our side.
706             // This should be handled more carefuly.
707             debugOutput( DEBUG_LEVEL_NORMAL,
708                          "Could not read config rom from device (node id %d). "
709                          "Skip device discovering for this node\n",
710                          nodeId );
711             return false;
712         }
713
714         // remove any already present devices
715         for ( FFADODeviceVectorIterator it = m_avDevices.begin();
716             it != m_avDevices.end();
717             ++it )
718         {
719             if (!deleteElement(*it)) {
720                 debugWarning("failed to remove AvDevice from Control::Container\n");
721             }
722             delete *it;
723         }
724
725         m_avDevices.clear();
726
727         // get the slave driver
728         FFADODevice* avDevice = getSlaveDriver( configRom );
729         if ( avDevice ) {
730             debugOutput( DEBUG_LEVEL_NORMAL,
731                          "driver found for device %d\n",
732                          nodeId );
733
734             avDevice->setVerboseLevel( getDebugLevel() );
735
736             if ( !avDevice->discover() ) {
737                 debugError( "could not discover device\n" );
738                 delete avDevice;
739                 return false;
740             }
741
742             if ( !avDevice->setId( m_avDevices.size() ) ) {
743                 debugError( "setting Id failed\n" );
744             }
745             if ( getDebugLevel() >= DEBUG_LEVEL_VERBOSE ) {
746                 avDevice->showDevice();
747             }
748             m_avDevices.push_back( avDevice );
749             debugOutput( DEBUG_LEVEL_NORMAL, "discovery of node %d on port %d done...\n", nodeId, portService->getPort() );
750         }
751
752         debugOutput( DEBUG_LEVEL_NORMAL, "discovery finished...\n" );
753     }
754
755     m_DeviceListLock->Unlock();
756     // notify any clients
757     signalNotifiers(m_postUpdateNotifiers);
758     return true;
759 }
760
761 bool
762 DeviceManager::initStreaming()
763 {
764     // iterate over the found devices
765     // add the stream processors of the devices to the managers
766     for ( FFADODeviceVectorIterator it = m_avDevices.begin();
767         it != m_avDevices.end();
768         ++it )
769     {
770         FFADODevice *device = *it;
771         assert(device);
772
773         debugOutput(DEBUG_LEVEL_VERBOSE, "Locking device (%p)\n", device);
774
775         if (!device->lock()) {
776             debugWarning("Could not lock device, skipping device (%p)!\n", device);
777             continue;
778         }
779
780         debugOutput(DEBUG_LEVEL_VERBOSE, "Setting samplerate to %d for (%p)\n",
781                     m_processorManager->getNominalRate(), device);
782
783         // Set the device's sampling rate to that requested
784         // FIXME: does this really belong here?  If so we need to handle errors.
785         if (!device->setSamplingFrequency(m_processorManager->getNominalRate())) {
786             debugOutput(DEBUG_LEVEL_VERBOSE, " => Retry setting samplerate to %d for (%p)\n",
787                         m_processorManager->getNominalRate(), device);
788
789             // try again:
790             if (!device->setSamplingFrequency(m_processorManager->getNominalRate())) {
791                 debugFatal("Could not set sampling frequency to %d\n",m_processorManager->getNominalRate());
792                 return false;
793             }
794         }
795         // prepare the device
796         device->prepare();
797     }
798
799     // set the sync source
800     if (!m_processorManager->setSyncSource(getSyncSource())) {
801         debugWarning("Could not set processorManager sync source (%p)\n",
802             getSyncSource());
803     }
804
805     return true;
806 }
807
808 bool
809 DeviceManager::prepareStreaming()
810 {
811     if (!m_processorManager->prepare()) {
812         debugFatal("Could not prepare streaming...\n");
813         return false;
814     }
815     return true;
816 }
817
818 bool
819 DeviceManager::finishStreaming() {
820     bool result = true;
821     // iterate over the found devices
822     for ( FFADODeviceVectorIterator it = m_avDevices.begin();
823         it != m_avDevices.end();
824         ++it )
825     {
826         debugOutput(DEBUG_LEVEL_VERBOSE, "Unlocking device (%p)\n", *it);
827
828         if (!(*it)->unlock()) {
829             debugWarning("Could not unlock device (%p)!\n", *it);
830             result = false;
831         }
832     }
833     return result;
834 }
835
836 bool
837 DeviceManager::startStreaming() {
838     // create the connections for all devices
839     // iterate over the found devices
840     // add the stream processors of the devices to the managers
841     for ( FFADODeviceVectorIterator it = m_avDevices.begin();
842         it != m_avDevices.end();
843         ++it )
844     {
845         FFADODevice *device = *it;
846         assert(device);
847
848         int j=0;
849         for(j=0; j < device->getStreamCount(); j++) {
850         debugOutput(DEBUG_LEVEL_VERBOSE,"Starting stream %d of device %p\n", j, device);
851             // start the stream
852             if (!device->startStreamByIndex(j)) {
853                 debugWarning("Could not start stream %d of device %p\n", j, device);
854                 continue;
855             }
856         }
857
858         if (!device->enableStreaming()) {
859             debugWarning("Could not enable streaming on device %p!\n", device);
860         }
861     }
862
863     if(m_processorManager->start()) {
864         return true;
865     } else {
866         stopStreaming();
867         return false;
868     }
869 }
870
871 bool
872 DeviceManager::resetStreaming() {
873     return true;
874 }
875
876 bool
877 DeviceManager::stopStreaming()
878 {
879     bool result = true;
880     m_processorManager->stop();
881
882     // create the connections for all devices
883     // iterate over the found devices
884     // add the stream processors of the devices to the managers
885     for ( FFADODeviceVectorIterator it = m_avDevices.begin();
886         it != m_avDevices.end();
887         ++it )
888     {
889         FFADODevice *device = *it;
890         assert(device);
891
892         if (!device->disableStreaming()) {
893             debugWarning("Could not disable streaming on device %p!\n", device);
894         }
895
896         int j=0;
897         for(j=0; j < device->getStreamCount(); j++) {
898             debugOutput(DEBUG_LEVEL_VERBOSE,"Stopping stream %d of device %p\n", j, device);
899             // stop the stream
900             // start the stream
901             if (!device->stopStreamByIndex(j)) {
902                 debugWarning("Could not stop stream %d of device %p\n", j, device);
903                 result = false;
904                 continue;
905             }
906         }
907     }
908     return result;
909 }
910
911 enum DeviceManager::eWaitResult
912 DeviceManager::waitForPeriod() {
913     if(m_processorManager->waitForPeriod()) {
914         return eWR_OK;
915     } else {
916         if(m_processorManager->shutdownNeeded()) {
917             debugWarning("Shutdown requested\n");
918             return eWR_Shutdown;
919         } else {
920             debugWarning("XRUN detected\n");
921             // do xrun recovery
922             if(m_processorManager->handleXrun()) {
923                 return eWR_Xrun;
924             } else {
925                 debugError("Could not handle XRUN\n");
926                 return eWR_Error;
927             }
928         }
929     }
930 }
931
932 bool
933 DeviceManager::setStreamingParams(unsigned int period, unsigned int rate, unsigned int nb_buffers) {
934     m_processorManager->setPeriodSize(period);
935     m_processorManager->setNominalRate(rate);
936     m_processorManager->setNbBuffers(nb_buffers);
937     return true;
938 }
939
940 FFADODevice*
941 DeviceManager::getDriverForDeviceDo( ConfigRom *configRom,
942                                    int id, bool generic )
943 {
944 #ifdef ENABLE_BEBOB
945     debugOutput( DEBUG_LEVEL_VERBOSE, "Trying BeBoB...\n" );
946     if ( BeBoB::AvDevice::probe( getConfiguration(), *configRom, generic ) ) {
947         return BeBoB::AvDevice::createDevice( *this, std::auto_ptr<ConfigRom>( configRom ) );
948     }
949 #endif
950
951 #ifdef ENABLE_FIREWORKS
952     debugOutput( DEBUG_LEVEL_VERBOSE, "Trying ECHO Audio FireWorks...\n" );
953     if ( FireWorks::Device::probe( getConfiguration(), *configRom, generic ) ) {
954         return FireWorks::Device::createDevice( *this, std::auto_ptr<ConfigRom>( configRom ) );
955     }
956 #endif
957
958 // we want to try the non-generic AV/C platforms before trying the generic ones
959 #ifdef ENABLE_GENERICAVC
960     debugOutput( DEBUG_LEVEL_VERBOSE, "Trying Generic AV/C...\n" );
961     if ( GenericAVC::AvDevice::probe( getConfiguration(), *configRom, generic ) ) {
962         return GenericAVC::AvDevice::createDevice( *this, std::auto_ptr<ConfigRom>( configRom ) );
963     }
964 #endif
965
966 #ifdef ENABLE_MOTU
967     debugOutput( DEBUG_LEVEL_VERBOSE, "Trying Motu...\n" );
968     if ( Motu::MotuDevice::probe( getConfiguration(), *configRom, generic ) ) {
969         return Motu::MotuDevice::createDevice( *this, std::auto_ptr<ConfigRom>( configRom ) );
970     }
971 #endif
972
973     return NULL;
974 }
975
976 FFADODevice*
977 DeviceManager::getDriverForDevice( ConfigRom *configRom,
978                                    int id )
979 {
980     debugOutput( DEBUG_LEVEL_VERBOSE, "Probing for supported device...\n" );
981     FFADODevice* dev = getDriverForDeviceDo(configRom, id, false);
982     if(dev) {
983         debugOutput( DEBUG_LEVEL_VERBOSE, " found supported device...\n" );
984         dev->setVerboseLevel(getDebugLevel());
985         return dev;
986     }
987
988     debugOutput( DEBUG_LEVEL_VERBOSE, " no supported device found, trying generic support...\n" );
989     dev = getDriverForDeviceDo(configRom, id, true);
990     if(dev) {
991         debugOutput( DEBUG_LEVEL_VERBOSE, " found generic support for device...\n" );
992         dev->setVerboseLevel(getDebugLevel());
993         return dev;
994     }
995     debugOutput( DEBUG_LEVEL_VERBOSE, " device not supported...\n" );
996     return NULL;
997 }
998
999 FFADODevice*
1000 DeviceManager::getSlaveDriver( std::auto_ptr<ConfigRom>( configRom ) )
1001 {
1002     return NULL;
1003 }
1004
1005 bool
1006 DeviceManager::isValidNode(int node)
1007 {
1008     for ( FFADODeviceVectorIterator it = m_avDevices.begin();
1009           it != m_avDevices.end();
1010           ++it )
1011     {
1012         FFADODevice* avDevice = *it;
1013
1014         if (avDevice->getConfigRom().getNodeId() == node) {
1015             return true;
1016     }
1017     }
1018     return false;
1019 }
1020
1021 int
1022 DeviceManager::getNbDevices()
1023 {
1024     return m_avDevices.size();
1025 }
1026
1027 int
1028 DeviceManager::getDeviceNodeId( int deviceNr )
1029 {
1030     if ( ! ( deviceNr < getNbDevices() ) ) {
1031         debugError( "Device number out of range (%d)\n", deviceNr );
1032         return -1;
1033     }
1034
1035     FFADODevice* avDevice = m_avDevices.at( deviceNr );
1036
1037     if ( !avDevice ) {
1038         debugError( "Could not get device at position (%d)\n",  deviceNr );
1039     }
1040
1041     return avDevice->getConfigRom().getNodeId();
1042 }
1043
1044 FFADODevice*
1045 DeviceManager::getAvDevice( int nodeId )
1046 {
1047     for ( FFADODeviceVectorIterator it = m_avDevices.begin();
1048           it != m_avDevices.end();
1049           ++it )
1050     {
1051         FFADODevice* avDevice = *it;
1052         if ( avDevice->getConfigRom().getNodeId() == nodeId ) {
1053             return avDevice;
1054         }
1055     }
1056
1057     return 0;
1058 }
1059
1060 FFADODevice*
1061 DeviceManager::getAvDeviceByIndex( int idx )
1062 {
1063     return m_avDevices.at(idx);
1064 }
1065
1066 unsigned int
1067 DeviceManager::getAvDeviceCount( )
1068 {
1069     return m_avDevices.size();
1070 }
1071
1072 /**
1073  * Return the streamprocessor that is to be used as
1074  * the sync source.
1075  *
1076  * Algorithm still to be determined
1077  *
1078  * @return StreamProcessor that is sync source
1079  */
1080 Streaming::StreamProcessor *
1081 DeviceManager::getSyncSource() {
1082     FFADODevice* device = getAvDeviceByIndex(0);
1083
1084     bool slaveMode=false;
1085     if(!getOption("slaveMode", slaveMode)) {
1086         debugOutput(DEBUG_LEVEL_NORMAL,
1087                     "Could not retrieve slaveMode parameter, defauling to false\n");
1088     }
1089     return device->getStreamProcessorByIndex(0);
1090 }
1091
1092 bool
1093 DeviceManager::deinitialize()
1094 {
1095     return true;
1096 }
1097
1098 void
1099 DeviceManager::setVerboseLevel(int l)
1100 {
1101     setDebugLevel(l);
1102     Control::Element::setVerboseLevel(l);
1103     m_processorManager->setVerboseLevel(l);
1104     m_deviceStringParser->setVerboseLevel(l);
1105     m_configuration->setVerboseLevel(l);
1106     for ( FFADODeviceVectorIterator it = m_avDevices.begin();
1107           it != m_avDevices.end();
1108           ++it )
1109     {
1110         (*it)->setVerboseLevel(l);
1111     }
1112     for ( Ieee1394ServiceVectorIterator it = m_1394Services.begin();
1113           it != m_1394Services.end();
1114           ++it )
1115     {
1116         (*it)->setVerboseLevel(l);
1117     }
1118     debugOutput( DEBUG_LEVEL_VERBOSE, "Setting verbose level to %d...\n", l );
1119 }
1120
1121 void
1122 DeviceManager::showDeviceInfo() {
1123     debugOutput(DEBUG_LEVEL_NORMAL, "===== Device Manager =====\n");
1124     Control::Element::show();
1125
1126     int i=0;
1127     for ( Ieee1394ServiceVectorIterator it = m_1394Services.begin();
1128           it != m_1394Services.end();
1129           ++it )
1130     {
1131         debugOutput(DEBUG_LEVEL_NORMAL, "--- IEEE1394 Service %2d ---\n", i++);
1132         (*it)->show();
1133     }
1134
1135     i=0;
1136     for ( FFADODeviceVectorIterator it = m_avDevices.begin();
1137         it != m_avDevices.end();
1138         ++it )
1139     {
1140         FFADODevice* avDevice = *it;
1141         debugOutput(DEBUG_LEVEL_NORMAL, "--- Device %2d ---\n", i++);
1142         avDevice->showDevice();
1143
1144         debugOutput(DEBUG_LEVEL_NORMAL, "Clock sync sources:\n");
1145         FFADODevice::ClockSourceVector sources=avDevice->getSupportedClockSources();
1146         for ( FFADODevice::ClockSourceVector::const_iterator it
1147                 = sources.begin();
1148             it != sources.end();
1149             ++it )
1150         {
1151             FFADODevice::ClockSource c=*it;
1152             debugOutput(DEBUG_LEVEL_NORMAL, " Type: %s, Id: %2d, Valid: %1d, Active: %1d, Locked %1d, Slipping: %1d, Description: %s\n",
1153                 FFADODevice::ClockSourceTypeToString(c.type), c.id, c.valid, c.active, c.locked, c.slipping, c.description.c_str());
1154         }
1155     }
1156 }
1157 void
1158 DeviceManager::showStreamingInfo() {
1159     m_processorManager->dumpInfo();
1160 }
Note: See TracBrowser for help on using the browser.