xref: /haiku/src/servers/media_addon/MediaAddonServer.cpp (revision a2d9c45398ebcab924c89b2d4961bbebc2aeb3d6)
1 /*
2  * Copyright 2009, Axel Dörfler, axeld@pinc-software.de.
3  * Copyright 2013 Haiku, Inc. All rights reserved.
4  * Distributed under the terms of the MIT License.
5  */
6 
7 /*
8  * Copyright (c) 2002-2004, Marcus Overhagen <marcus@overhagen.de>
9  * All rights reserved.
10  *
11  * Redistribution and use in source and binary forms, with or without modification,
12  * are permitted provided that the following conditions are met:
13  *
14  *  * Redistributions of source code must retain the above copyright notice,
15  *    this list of conditions and the following disclaimer.
16  *  * Redistributions in binary form must reproduce the above copyright notice,
17  *    this list of conditions and the following disclaimer in the documentation
18  *    and/or other materials provided with the distribution.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
24  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
26  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
27  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
28  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30  */
31 
32 
33 #include <map>
34 #include <stdio.h>
35 #include <vector>
36 
37 #include <Alert.h>
38 #include <Application.h>
39 #include <Beep.h>
40 #include <Directory.h>
41 #include <Entry.h>
42 #include <MediaAddOn.h>
43 #include <MediaRoster.h>
44 #include <MessageRunner.h>
45 #include <Path.h>
46 #include <Roster.h>
47 #include <String.h>
48 
49 #include <AddOnMonitorHandler.h>
50 #include <debug.h>
51 #include <DataExchange.h>
52 #include <DormantNodeManager.h>
53 #include <MediaMisc.h>
54 #include <MediaRosterEx.h>
55 #include <MediaSounds.h>
56 #include <Notifications.h>
57 #include <ServerInterface.h>
58 
59 #include "MediaFilePlayer.h"
60 #include "SystemTimeSource.h"
61 
62 
63 //#define USER_ADDON_PATH "../add-ons/media"
64 
65 
66 typedef std::vector<media_node> NodeVector;
67 
68 
69 struct AddOnInfo {
70 			media_addon_id		id;
71 			bool				wants_autostart;
72 			int32				flavor_count;
73 
74 			NodeVector			active_flavors;
75 
76 			// if != NULL, need to call gDormantNodeManager->PutAddOn(id)
77 			BMediaAddOn*		addon;
78 };
79 
80 
81 class MediaAddonServer : BApplication {
82 public:
83 								MediaAddonServer(const char* signature);
84 	virtual						~MediaAddonServer();
85 	virtual	void				ReadyToRun();
86 	virtual bool				QuitRequested();
87 	virtual void				MessageReceived(BMessage* message);
88 
89 private:
90 	class MonitorHandler;
91 	friend class MonitorHandler;
92 
93 			void				_AddOnAdded(const char* path, ino_t fileNode);
94 			void				_AddOnRemoved(ino_t fileNode);
95 			void				_HandleMessage(int32 code, const void* data,
96 									size_t size);
97 
98 			void				_PutAddonIfPossible(AddOnInfo& info);
99 			void				_InstantiatePhysicalInputsAndOutputs(
100 									AddOnInfo& info);
101 			void				_InstantiateAutostartFlavors(AddOnInfo& info);
102 			void				_DestroyInstantiatedFlavors(AddOnInfo& info);
103 
104 			void				_ScanAddOnFlavors(BMediaAddOn* addOn);
105 
106 			port_id				_ControlPort() const { return fControlPort; }
107 
108 	static	status_t			_ControlThread(void* arg);
109 
110 private:
111 	typedef std::map<ino_t, media_addon_id> FileMap;
112 	typedef std::map<media_addon_id, AddOnInfo> InfoMap;
113 
114 			FileMap				fFileMap;
115 			InfoMap				fInfoMap;
116 
117 			BMediaRoster*		fMediaRoster;
118 			MonitorHandler*		fMonitorHandler;
119 			BMessageRunner*		fPulseRunner;
120 			port_id				fControlPort;
121 			thread_id			fControlThread;
122 			bool				fStartup;
123 			bool				fStartupSound;
124 			SystemTimeSource*	fSystemTimeSource;
125 };
126 
127 
128 class MediaAddonServer::MonitorHandler : public AddOnMonitorHandler {
129 public:
130 								MonitorHandler(MediaAddonServer* server);
131 
132 	virtual void				AddOnEnabled(const add_on_entry_info* info);
133 	virtual void				AddOnDisabled(const add_on_entry_info* info);
134 
135 private:
136 			MediaAddonServer*	fServer;
137 };
138 
139 
140 #if DEBUG >= 2
141 static void
142 DumpFlavorInfo(const flavor_info* info)
143 {
144 	printf("  name = %s\n", info->name);
145 	printf("  info = %s\n", info->info);
146 	printf("  internal_id = %ld\n", info->internal_id);
147 	printf("  possible_count = %ld\n", info->possible_count);
148 	printf("  flavor_flags = 0x%lx", info->flavor_flags);
149 	if (info->flavor_flags & B_FLAVOR_IS_GLOBAL) printf(" B_FLAVOR_IS_GLOBAL");
150 	if (info->flavor_flags & B_FLAVOR_IS_LOCAL) printf(" B_FLAVOR_IS_LOCAL");
151 	printf("\n");
152 	printf("  kinds = 0x%Lx", info->kinds);
153 	if (info->kinds & B_BUFFER_PRODUCER) printf(" B_BUFFER_PRODUCER");
154 	if (info->kinds & B_BUFFER_CONSUMER) printf(" B_BUFFER_CONSUMER");
155 	if (info->kinds & B_TIME_SOURCE) printf(" B_TIME_SOURCE");
156 	if (info->kinds & B_CONTROLLABLE) printf(" B_CONTROLLABLE");
157 	if (info->kinds & B_FILE_INTERFACE) printf(" B_FILE_INTERFACE");
158 	if (info->kinds & B_ENTITY_INTERFACE) printf(" B_ENTITY_INTERFACE");
159 	if (info->kinds & B_PHYSICAL_INPUT) printf(" B_PHYSICAL_INPUT");
160 	if (info->kinds & B_PHYSICAL_OUTPUT) printf(" B_PHYSICAL_OUTPUT");
161 	if (info->kinds & B_SYSTEM_MIXER) printf(" B_SYSTEM_MIXER");
162 	printf("\n");
163 	printf("  in_format_count = %ld\n", info->in_format_count);
164 	printf("  out_format_count = %ld\n", info->out_format_count);
165 }
166 #endif
167 
168 
169 // #pragma mark -
170 
171 
172 MediaAddonServer::MonitorHandler::MonitorHandler(MediaAddonServer* server)
173 {
174 	fServer = server;
175 }
176 
177 
178 void
179 MediaAddonServer::MonitorHandler::AddOnEnabled(const add_on_entry_info* info)
180 {
181 	entry_ref ref;
182 	make_entry_ref(info->dir_nref.device, info->dir_nref.node,
183 		info->name, &ref);
184 	BEntry entry(&ref, true);
185 	if (!entry.IsFile())
186 		return;
187 
188 	BPath path(&ref);
189 	if (path.InitCheck() == B_OK)
190 		fServer->_AddOnAdded(path.Path(), info->nref.node);
191 }
192 
193 
194 void
195 MediaAddonServer::MonitorHandler::AddOnDisabled(const add_on_entry_info* info)
196 {
197 	fServer->_AddOnRemoved(info->nref.node);
198 }
199 
200 
201 // #pragma mark -
202 
203 
204 MediaAddonServer::MediaAddonServer(const char* signature)
205 	:
206 	BApplication(signature),
207 	fMonitorHandler(NULL),
208 	fPulseRunner(NULL),
209 	fStartup(true),
210 	fStartupSound(true),
211 	fSystemTimeSource(NULL)
212 {
213 	CALLED();
214 	fMediaRoster = BMediaRoster::Roster();
215 	fControlPort = create_port(64, MEDIA_ADDON_SERVER_PORT_NAME);
216 	fControlThread = spawn_thread(_ControlThread, "media_addon_server control",
217 		B_NORMAL_PRIORITY + 2, this);
218 	resume_thread(fControlThread);
219 }
220 
221 
222 MediaAddonServer::~MediaAddonServer()
223 {
224 	CALLED();
225 
226 	delete_port(fControlPort);
227 	wait_for_thread(fControlThread, NULL);
228 
229 	// unregister all media add-ons
230 	FileMap::iterator iterator = fFileMap.begin();
231 	for (; iterator != fFileMap.end(); iterator++)
232 		gDormantNodeManager->UnregisterAddOn(iterator->second);
233 
234 	delete fMonitorHandler;
235 	delete fPulseRunner;
236 }
237 
238 
239 void
240 MediaAddonServer::ReadyToRun()
241 {
242 	if (!be_roster->IsRunning(B_MEDIA_SERVER_SIGNATURE)) {
243 		// the media server is not running, let's quit
244 		fprintf(stderr, "The media_server is not running!\n");
245 		Quit();
246 		return;
247 	}
248 
249 	// the control thread is already running at this point,
250 	// so we can talk to the media server and also receive
251 	// commands for instantiation
252 
253 	ASSERT(fStartup == true);
254 
255 	// The very first thing to do is to create the system time source,
256 	// register it with the server, and make it the default SYSTEM_TIME_SOURCE
257 	fSystemTimeSource = new SystemTimeSource();
258 	status_t result = fMediaRoster->RegisterNode(fSystemTimeSource);
259 	if (result != B_OK) {
260 		fprintf(stderr, "Can't register system time source : %s\n",
261 			strerror(result));
262 		ERROR("Can't register system time source");
263 	}
264 
265 	if (fSystemTimeSource->ID() != NODE_SYSTEM_TIMESOURCE_ID)
266 		ERROR("System time source got wrong node ID");
267 	media_node node = fSystemTimeSource->Node();
268 	result = MediaRosterEx(fMediaRoster)->SetNode(SYSTEM_TIME_SOURCE, &node);
269 	if (result != B_OK)
270 		ERROR("Can't setup system time source as default");
271 
272 	// During startup, first all add-ons are loaded, then all
273 	// nodes (flavors) representing physical inputs and outputs
274 	// are instantiated. Next, all add-ons that need autostart
275 	// will be autostarted. Finally, add-ons that don't have
276 	// any active nodes (flavors) will be unloaded.
277 
278 	fMonitorHandler = new MonitorHandler(this);
279 	AddHandler(fMonitorHandler);
280 
281 	BMessage pulse(B_PULSE);
282 	// the monitor handler needs a pulse to check if add-ons are ready
283 	fPulseRunner = new BMessageRunner(fMonitorHandler, &pulse, 1000000LL);
284 
285 	result = fPulseRunner->InitCheck();
286 	if (result != B_OK)
287 		ERROR("Can't create the pulse runner");
288 
289 	fMonitorHandler->AddAddOnDirectories("media");
290 
291 #ifdef USER_ADDON_PATH
292 	node_ref nodeRef;
293 	if (entry.SetTo(USER_ADDON_PATH) == B_OK
294 		&& entry.GetNodeRef(&nodeRef) == B_OK) {
295 		fMonitorHandler->AddDirectory(&nodeRef);
296 	}
297 #endif
298 
299 	fStartup = false;
300 
301 	InfoMap::iterator iterator = fInfoMap.begin();
302 	for (; iterator != fInfoMap.end(); iterator++)
303 		_InstantiatePhysicalInputsAndOutputs(iterator->second);
304 
305 	for (iterator = fInfoMap.begin(); iterator != fInfoMap.end(); iterator++)
306 		_InstantiateAutostartFlavors(iterator->second);
307 
308 	for (iterator = fInfoMap.begin(); iterator != fInfoMap.end(); iterator++)
309 		_PutAddonIfPossible(iterator->second);
310 
311 	server_rescan_defaults_command cmd;
312 	SendToServer(SERVER_RESCAN_DEFAULTS, &cmd, sizeof(cmd));
313 }
314 
315 
316 bool
317 MediaAddonServer::QuitRequested()
318 {
319 	CALLED();
320 
321 	InfoMap::iterator iterator = fInfoMap.begin();
322 	for (iterator = fInfoMap.begin(); iterator != fInfoMap.end(); iterator++)
323 		_DestroyInstantiatedFlavors(iterator->second);
324 
325 	// the System timesource should be removed before we quit the roster
326 	if (fSystemTimeSource != NULL &&
327 		be_roster->IsRunning(B_MEDIA_SERVER_SIGNATURE)) {
328 		status_t result = fMediaRoster->UnregisterNode(fSystemTimeSource);
329 		if (result != B_OK) {
330 			fprintf(stderr, "Error removing the system time source : %s\n",
331 				strerror(result));
332 			ERROR("Can't remove the system time source");
333 		}
334 		fSystemTimeSource->Release();
335 		fSystemTimeSource = NULL;
336 	}
337 
338 	BMediaRoster::CurrentRoster()->Lock();
339 	BMediaRoster::CurrentRoster()->Quit();
340 
341 	for (iterator = fInfoMap.begin(); iterator != fInfoMap.end(); iterator++)
342 		_PutAddonIfPossible(iterator->second);
343 
344 	return true;
345 }
346 
347 
348 void
349 MediaAddonServer::MessageReceived(BMessage* message)
350 {
351 	switch (message->what) {
352 		case MEDIA_ADD_ON_SERVER_PLAY_MEDIA:
353 		{
354 			const char* name;
355 			const char* type;
356 			if (message->FindString(MEDIA_NAME_KEY, &name) != B_OK
357 				|| message->FindString(MEDIA_TYPE_KEY, &type) != B_OK) {
358 				message->SendReply(B_ERROR);
359 				break;
360 			}
361 
362 			PlayMediaFile(type, name);
363 			message->SendReply((uint32)B_OK);
364 			// TODO: don't know which reply is expected
365 			return;
366 		}
367 
368 		default:
369 			BApplication::MessageReceived(message);
370 			break;
371 	}
372 }
373 
374 
375 void
376 MediaAddonServer::_HandleMessage(int32 code, const void* data, size_t size)
377 {
378 	switch (code) {
379 		case ADD_ON_SERVER_INSTANTIATE_DORMANT_NODE:
380 		{
381 			const add_on_server_instantiate_dormant_node_request* request
382 				= static_cast<
383 					const add_on_server_instantiate_dormant_node_request*>(
384 						data);
385 			add_on_server_instantiate_dormant_node_reply reply;
386 
387 			status_t status
388 				= MediaRosterEx(fMediaRoster)->InstantiateDormantNode(
389 					request->add_on_id, request->flavor_id,
390 					request->creator_team, &reply.node);
391 			request->SendReply(status, &reply, sizeof(reply));
392 			break;
393 		}
394 
395 		case ADD_ON_SERVER_RESCAN_ADD_ON_FLAVORS:
396 		{
397 			const add_on_server_rescan_flavors_command* command = static_cast<
398 				const add_on_server_rescan_flavors_command*>(data);
399 			BMediaAddOn* addOn
400 				= gDormantNodeManager->GetAddOn(command->add_on_id);
401 			if (addOn == NULL) {
402 				ERROR("rescan flavors: Can't find a addon object for id %d\n",
403 					(int)command->add_on_id);
404 				break;
405 			}
406 			_ScanAddOnFlavors(addOn);
407 			gDormantNodeManager->PutAddOn(command->add_on_id);
408 			break;
409 		}
410 
411 		case ADD_ON_SERVER_RESCAN_FINISHED_NOTIFY:
412 			if (fStartupSound) {
413 				system_beep(MEDIA_SOUNDS_STARTUP);
414 				fStartupSound = false;
415 			}
416 			break;
417 
418 		default:
419 			ERROR("media_addon_server: received unknown message code %#08"
420 				B_PRIx32 "\n", code);
421 			break;
422 	}
423 }
424 
425 
426 status_t
427 MediaAddonServer::_ControlThread(void* _server)
428 {
429 	MediaAddonServer* server = (MediaAddonServer*)_server;
430 
431 	char data[B_MEDIA_MESSAGE_SIZE];
432 	ssize_t size;
433 	int32 code;
434 	while ((size = read_port_etc(server->_ControlPort(), &code, data,
435 			sizeof(data), 0, 0)) > 0)
436 		server->_HandleMessage(code, data, size);
437 
438 	return B_OK;
439 }
440 
441 
442 void
443 MediaAddonServer::_ScanAddOnFlavors(BMediaAddOn* addon)
444 {
445 	ASSERT(addon->AddonID() > 0);
446 
447 	TRACE("MediaAddonServer::_ScanAddOnFlavors: id %ld\n", addon->AddonID());
448 
449 	// cache the media_addon_id in a local variable to avoid
450 	// calling BMediaAddOn::AddonID() too often
451 	media_addon_id addonID = addon->AddonID();
452 
453 	// update the cached flavor count, get oldflavorcount and newflavorcount
454 
455 	InfoMap::iterator found = fInfoMap.find(addonID);
456 	ASSERT(found != fInfoMap.end());
457 
458 	AddOnInfo& info = found->second;
459 	int32 oldFlavorCount = info.flavor_count;
460 	int32 newFlavorCount = addon->CountFlavors();
461 	info.flavor_count = newFlavorCount;
462 
463 	TRACE("%ld old flavors, %ld new flavors\n", oldFlavorCount, newFlavorCount);
464 
465 	// during the first update (i == 0), the server removes old dormant_flavor_infos
466 	for (int i = 0; i < newFlavorCount; i++) {
467 		const flavor_info* flavorInfo;
468 		TRACE("flavor %d:\n", i);
469 		if (addon->GetFlavorAt(i, &flavorInfo) != B_OK) {
470 			ERROR("MediaAddonServer::_ScanAddOnFlavors GetFlavorAt failed for "
471 				"index %d!\n", i);
472 			continue;
473 		}
474 
475 #if DEBUG >= 2
476 		DumpFlavorInfo(flavorInfo);
477 #endif
478 
479 		dormant_flavor_info dormantFlavorInfo;
480 		dormantFlavorInfo = *flavorInfo;
481 		dormantFlavorInfo.node_info.addon = addonID;
482 		dormantFlavorInfo.node_info.flavor_id = flavorInfo->internal_id;
483 		strlcpy(dormantFlavorInfo.node_info.name, flavorInfo->name,
484 			B_MEDIA_NAME_LENGTH);
485 
486 		size_t flattenedSize = dormantFlavorInfo.FlattenedSize();
487 		size_t messageSize = flattenedSize
488 			+ sizeof(server_register_dormant_node_command);
489 		server_register_dormant_node_command* message
490 			= (server_register_dormant_node_command*)malloc(messageSize);
491 		if (message == NULL)
492 			break;
493 
494 		// The server should remove previously registered "dormant_flavor_info"s
495 		// during the first update, but after  the first iteration, we don't
496 		// want the server to anymore remove old dormant_flavor_infos
497 		message->purge_id = i == 0 ? addonID : 0;
498 
499 		message->type = dormantFlavorInfo.TypeCode();
500 		message->flattened_size = flattenedSize;
501 		dormantFlavorInfo.Flatten(message->flattened_data, flattenedSize);
502 
503 		status_t status = SendToServer(SERVER_REGISTER_DORMANT_NODE,
504 			message, messageSize);
505 		if (status != B_OK) {
506 			ERROR("MediaAddonServer::_ScanAddOnFlavors: couldn't register "
507 				"dormant node: %s\n", strerror(status));
508 		}
509 
510 		free(message);
511 	}
512 
513 	// TODO: we currently pretend that all old flavors have been removed, this
514 	// could probably be done in a smarter way
515 	BPrivate::media::notifications::FlavorsChanged(addonID, newFlavorCount,
516 		oldFlavorCount);
517 }
518 
519 
520 void
521 MediaAddonServer::_AddOnAdded(const char* path, ino_t fileNode)
522 {
523 	TRACE("\n\nMediaAddonServer::_AddOnAdded: path %s\n", path);
524 
525 	media_addon_id id = gDormantNodeManager->RegisterAddOn(path);
526 	if (id <= 0) {
527 		ERROR("MediaAddonServer::_AddOnAdded: failed to register add-on %s\n",
528 			path);
529 		return;
530 	}
531 
532 	TRACE("MediaAddonServer::_AddOnAdded: loading addon %ld now...\n", id);
533 
534 	BMediaAddOn* addon = gDormantNodeManager->GetAddOn(id);
535 	if (addon == NULL) {
536 		ERROR("MediaAddonServer::_AddOnAdded: failed to get add-on %s\n", path);
537 		gDormantNodeManager->UnregisterAddOn(id);
538 		return;
539 	}
540 
541 	TRACE("MediaAddonServer::_AddOnAdded: loading finished, id %ld\n", id);
542 
543 	try {
544 		// put file's inode and addon's id into map
545 		fFileMap.insert(std::make_pair(fileNode, id));
546 
547 		AddOnInfo info;
548 		fInfoMap.insert(std::make_pair(id, info));
549 	} catch (std::bad_alloc& exception) {
550 		fFileMap.erase(fileNode);
551 		return;
552 	}
553 
554 	InfoMap::iterator found = fInfoMap.find(id);
555 	AddOnInfo& info = found->second;
556 
557 	info.id = id;
558 	// temporary default
559 	info.wants_autostart = false;
560 	info.flavor_count = 0;
561 	info.addon = addon;
562 
563 	// scan the flavors
564 	_ScanAddOnFlavors(addon);
565 
566 	// need to call BMediaNode::WantsAutoStart()
567 	// after the flavors have been scanned
568 	info.wants_autostart = addon->WantsAutoStart();
569 
570 	if (info.wants_autostart)
571 		TRACE("add-on %ld WantsAutoStart!\n", id);
572 
573 	// During startup, first all add-ons are loaded, then all
574 	// nodes (flavors) representing physical inputs and outputs
575 	// are instantiated. Next, all add-ons that need autostart
576 	// will be autostarted. Finally, add-ons that don't have
577 	// any active nodes (flavors) will be unloaded.
578 
579 	// After startup is done, we simply do it for each new
580 	// loaded add-on, too.
581 	if (!fStartup) {
582 		_InstantiatePhysicalInputsAndOutputs(info);
583 		_InstantiateAutostartFlavors(info);
584 		_PutAddonIfPossible(info);
585 
586 		// since something might have changed
587 		server_rescan_defaults_command cmd;
588 		SendToServer(SERVER_RESCAN_DEFAULTS, &cmd, sizeof(cmd));
589 	}
590 
591 	// we do not call gDormantNodeManager->PutAddOn(id)
592 	// since it is done by _PutAddonIfPossible()
593 }
594 
595 
596 void
597 MediaAddonServer::_DestroyInstantiatedFlavors(AddOnInfo& info)
598 {
599 	printf("MediaAddonServer::_DestroyInstantiatedFlavors addon %" B_PRId32
600 		"\n", info.id);
601 
602 	NodeVector::iterator iterator = info.active_flavors.begin();
603 	for (; iterator != info.active_flavors.end(); iterator++) {
604 		media_node& node = *iterator;
605 
606 		printf("node %" B_PRId32 "\n", node.node);
607 
608 		if ((node.kind & B_TIME_SOURCE) != 0
609 			&& (fMediaRoster->StopTimeSource(node, 0, true) != B_OK)) {
610 			printf("MediaAddonServer::_DestroyInstantiatedFlavors couldn't stop "
611 				"timesource\n");
612 			continue;
613 		}
614 
615 		if (fMediaRoster->StopNode(node, 0, true) != B_OK) {
616 			printf("MediaAddonServer::_DestroyInstantiatedFlavors couldn't stop "
617 				"node\n");
618 			continue;
619 		}
620 
621 		if ((node.kind & B_BUFFER_CONSUMER) != 0) {
622 			media_input inputs[16];
623 			int32 count = 0;
624 			if (fMediaRoster->GetConnectedInputsFor(node, inputs, 16, &count)
625 					!= B_OK) {
626 				printf("MediaAddonServer::_DestroyInstantiatedFlavors couldn't "
627 					"get connected inputs\n");
628 				continue;
629 			}
630 
631 			for (int32 i = 0; i < count; i++) {
632 				media_node_id sourceNode;
633 				if ((sourceNode = fMediaRoster->NodeIDFor(
634 						inputs[i].source.port)) < 0) {
635 					printf("MediaAddonServer::_DestroyInstantiatedFlavors "
636 						"couldn't get source node id\n");
637 					continue;
638 				}
639 
640 				if (fMediaRoster->Disconnect(sourceNode, inputs[i].source,
641 						node.node, inputs[i].destination) != B_OK) {
642 					printf("MediaAddonServer::_DestroyInstantiatedFlavors "
643 						"couldn't disconnect input\n");
644 					continue;
645 				}
646 			}
647 		}
648 
649 		if ((node.kind & B_BUFFER_PRODUCER) != 0) {
650 			media_output outputs[16];
651 			int32 count = 0;
652 			if (fMediaRoster->GetConnectedOutputsFor(node, outputs, 16,
653 					&count) != B_OK) {
654 				printf("MediaAddonServer::_DestroyInstantiatedFlavors couldn't "
655 					"get connected outputs\n");
656 				continue;
657 			}
658 
659 			for (int32 i = 0; i < count; i++) {
660 				media_node_id destNode;
661 				if ((destNode = fMediaRoster->NodeIDFor(
662 						outputs[i].destination.port)) < 0) {
663 					printf("MediaAddonServer::_DestroyInstantiatedFlavors "
664 						"couldn't get destination node id\n");
665 					continue;
666 				}
667 
668 				if (fMediaRoster->Disconnect(node.node, outputs[i].source,
669 						destNode, outputs[i].destination) != B_OK) {
670 					printf("MediaAddonServer::_DestroyInstantiatedFlavors "
671 						"couldn't disconnect output\n");
672 					continue;
673 				}
674 			}
675 		}
676 
677 		if (MediaRosterEx(fMediaRoster)->ReleaseNodeAll(node) != B_OK) {
678 			printf("MediaAddonServer::_DestroyInstantiatedFlavors "
679 						"couldn't release node\n");
680 		}
681 
682 		// wait a bit to let the node clean up
683 		snooze(50000);
684 	}
685 
686 	info.active_flavors.clear();
687 }
688 
689 
690 void
691 MediaAddonServer::_PutAddonIfPossible(AddOnInfo& info)
692 {
693 	if (info.addon && info.active_flavors.empty()) {
694 		gDormantNodeManager->PutAddOn(info.id);
695 		info.addon = NULL;
696 	}
697 }
698 
699 
700 void
701 MediaAddonServer::_InstantiatePhysicalInputsAndOutputs(AddOnInfo& info)
702 {
703 	CALLED();
704 	int32 count = info.addon->CountFlavors();
705 
706 	for (int32 i = 0; i < count; i++) {
707 		const flavor_info* flavorinfo;
708 		if (info.addon->GetFlavorAt(i, &flavorinfo) != B_OK) {
709 			ERROR("MediaAddonServer::InstantiatePhysialInputsAndOutputs "
710 				"GetFlavorAt failed for index %" B_PRId32 "!\n", i);
711 			continue;
712 		}
713 		if ((flavorinfo->kinds & (B_PHYSICAL_INPUT | B_PHYSICAL_OUTPUT)) != 0) {
714 			media_node node;
715 
716 			dormant_node_info dormantNodeInfo;
717 			dormantNodeInfo.addon = info.id;
718 			dormantNodeInfo.flavor_id = flavorinfo->internal_id;
719 			strcpy(dormantNodeInfo.name, flavorinfo->name);
720 
721 			TRACE("MediaAddonServer::InstantiatePhysialInputsAndOutputs: "
722 				"\"%s\" is a physical input/output\n", flavorinfo->name);
723 			status_t status = fMediaRoster->InstantiateDormantNode(
724 				dormantNodeInfo, &node);
725 			if (status != B_OK) {
726 				ERROR("MediaAddonServer::InstantiatePhysialInputsAndOutputs "
727 					"Couldn't instantiate node flavor, internal_id %" B_PRId32
728 					", name %s\n", flavorinfo->internal_id, flavorinfo->name);
729 			} else {
730 				TRACE("Node created!\n");
731 				info.active_flavors.push_back(node);
732 			}
733 		}
734 	}
735 }
736 
737 
738 void
739 MediaAddonServer::_InstantiateAutostartFlavors(AddOnInfo& info)
740 {
741 	if (!info.wants_autostart)
742 		return;
743 
744 	for (int32 index = 0;; index++) {
745 		TRACE("trying autostart of node %ld, index %ld\n", info.id, index);
746 
747 		BMediaNode* node;
748 		int32 internalID;
749 		bool hasMore;
750 		status_t status = info.addon->AutoStart(index, &node, &internalID,
751 			&hasMore);
752 		if (status == B_MEDIA_ADDON_FAILED && hasMore)
753 			continue;
754 		else if (status != B_OK)
755 			break;
756 
757 		printf("started node %" B_PRId32 "\n", index);
758 
759 		status = MediaRosterEx(fMediaRoster)->RegisterNode(node, info.id,
760 			internalID);
761 		if (status != B_OK) {
762 			ERROR("failed to register node %" B_PRId32 "\n", index);
763 			node->Release();
764 		} else {
765 			MediaRosterEx(fMediaRoster)->IncrementAddonFlavorInstancesCount(
766 				info.id, internalID);
767 			info.active_flavors.push_back(node->Node());
768 		}
769 
770 		if (!hasMore)
771 			return;
772 	}
773 }
774 
775 
776 void
777 MediaAddonServer::_AddOnRemoved(ino_t fileNode)
778 {
779 	// TODO: locking?
780 
781 	FileMap::iterator foundFile = fFileMap.find(fileNode);
782 	if (foundFile == fFileMap.end()) {
783 		ERROR("MediaAddonServer::_AddOnRemoved: inode %" B_PRIdINO " removed, but no "
784 			"media add-on found\n", fileNode);
785 		return;
786 	}
787 
788 	media_addon_id id = foundFile->second;
789 	fFileMap.erase(foundFile);
790 
791 	int32 oldFlavorCount;
792 	InfoMap::iterator foundInfo = fInfoMap.find(id);
793 
794 	if (foundInfo == fInfoMap.end()) {
795 		ERROR("MediaAddonServer::_AddOnRemoved: couldn't get addon info for "
796 			"add-on %" B_PRId32 "\n", id);
797 		oldFlavorCount = 1000;
798 	} else {
799 		AddOnInfo& info = foundInfo->second;
800 		oldFlavorCount = info.flavor_count;
801 
802 		_DestroyInstantiatedFlavors(info);
803 		_PutAddonIfPossible(info);
804 
805 		if (info.addon) {
806 			ERROR("MediaAddonServer::_AddOnRemoved: couldn't unload addon "
807 				"%" B_PRId32 " since flavors are in use\n", id);
808 		}
809 
810 		fInfoMap.erase(foundInfo);
811 	}
812 
813 	gDormantNodeManager->UnregisterAddOn(id);
814 
815 	BPrivate::media::notifications::FlavorsChanged(id, 0, oldFlavorCount);
816 }
817 
818 
819 //	#pragma mark -
820 
821 
822 int
823 main()
824 {
825 	new MediaAddonServer(B_MEDIA_ADDON_SERVER_SIGNATURE);
826 	be_app->Run();
827 	delete be_app;
828 	return 0;
829 }
830