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 <DataExchange.h>
51#include <DormantNodeManager.h>
52#include <MediaDebug.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
66typedef std::vector<media_node> NodeVector;
67
68
69struct 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
81class MediaAddonServer : BApplication {
82public:
83								MediaAddonServer(const char* signature);
84	virtual						~MediaAddonServer();
85	virtual	void				ReadyToRun();
86	virtual bool				QuitRequested();
87	virtual void				MessageReceived(BMessage* message);
88
89private:
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
110private:
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
128class MediaAddonServer::MonitorHandler : public AddOnMonitorHandler {
129public:
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
135private:
136			MediaAddonServer*	fServer;
137};
138
139
140#if DEBUG >= 2
141static void
142DumpFlavorInfo(const flavor_info* info)
143{
144	printf("  name = %s\n", info->name);
145	printf("  info = %s\n", info->info);
146	printf("  internal_id = %" B_PRId32 "\n", info->internal_id);
147	printf("  possible_count = %" B_PRId32 "\n", info->possible_count);
148	printf("  flavor_flags = 0x%" B_PRIx32, 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%" B_PRIx64, 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 = %" B_PRId32 "\n", info->in_format_count);
164	printf("  out_format_count = %" B_PRId32 "\n", info->out_format_count);
165}
166#endif
167
168
169// #pragma mark -
170
171
172MediaAddonServer::MonitorHandler::MonitorHandler(MediaAddonServer* server)
173{
174	fServer = server;
175}
176
177
178void
179MediaAddonServer::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
194void
195MediaAddonServer::MonitorHandler::AddOnDisabled(const add_on_entry_info* info)
196{
197	fServer->_AddOnRemoved(info->nref.node);
198}
199
200
201// #pragma mark -
202
203
204MediaAddonServer::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
222MediaAddonServer::~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
239void
240MediaAddonServer::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
316bool
317MediaAddonServer::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	for (iterator = fInfoMap.begin(); iterator != fInfoMap.end(); iterator++)
339		_PutAddonIfPossible(iterator->second);
340
341	return true;
342}
343
344
345void
346MediaAddonServer::MessageReceived(BMessage* message)
347{
348	switch (message->what) {
349		case MEDIA_ADD_ON_SERVER_PLAY_MEDIA:
350		{
351			const char* name;
352			const char* type;
353			if (message->FindString(MEDIA_NAME_KEY, &name) != B_OK
354				|| message->FindString(MEDIA_TYPE_KEY, &type) != B_OK) {
355				message->SendReply(B_ERROR);
356				break;
357			}
358
359			PlayMediaFile(type, name);
360			message->SendReply((uint32)B_OK);
361			// TODO: don't know which reply is expected
362			return;
363		}
364
365		default:
366			BApplication::MessageReceived(message);
367			break;
368	}
369}
370
371
372void
373MediaAddonServer::_HandleMessage(int32 code, const void* data, size_t size)
374{
375	switch (code) {
376		case ADD_ON_SERVER_INSTANTIATE_DORMANT_NODE:
377		{
378			const add_on_server_instantiate_dormant_node_request* request
379				= static_cast<
380					const add_on_server_instantiate_dormant_node_request*>(
381						data);
382			add_on_server_instantiate_dormant_node_reply reply;
383
384			status_t status
385				= MediaRosterEx(fMediaRoster)->InstantiateDormantNode(
386					request->add_on_id, request->flavor_id,
387					request->creator_team, &reply.node);
388			request->SendReply(status, &reply, sizeof(reply));
389			break;
390		}
391
392		case ADD_ON_SERVER_RESCAN_ADD_ON_FLAVORS:
393		{
394			const add_on_server_rescan_flavors_command* command = static_cast<
395				const add_on_server_rescan_flavors_command*>(data);
396			BMediaAddOn* addOn
397				= gDormantNodeManager->GetAddOn(command->add_on_id);
398			if (addOn == NULL) {
399				ERROR("rescan flavors: Can't find a addon object for id %d\n",
400					(int)command->add_on_id);
401				break;
402			}
403			_ScanAddOnFlavors(addOn);
404			gDormantNodeManager->PutAddOn(command->add_on_id);
405			break;
406		}
407
408		case ADD_ON_SERVER_RESCAN_FINISHED_NOTIFY:
409			if (fStartupSound) {
410				system_beep(MEDIA_SOUNDS_STARTUP);
411				fStartupSound = false;
412			}
413			break;
414
415		default:
416			ERROR("media_addon_server: received unknown message code %#08"
417				B_PRIx32 "\n", code);
418			break;
419	}
420}
421
422
423status_t
424MediaAddonServer::_ControlThread(void* _server)
425{
426	MediaAddonServer* server = (MediaAddonServer*)_server;
427
428	char data[B_MEDIA_MESSAGE_SIZE];
429	ssize_t size;
430	int32 code;
431	while ((size = read_port_etc(server->_ControlPort(), &code, data,
432			sizeof(data), 0, 0)) > 0)
433		server->_HandleMessage(code, data, size);
434
435	return B_OK;
436}
437
438
439void
440MediaAddonServer::_ScanAddOnFlavors(BMediaAddOn* addon)
441{
442	ASSERT(addon->AddonID() > 0);
443
444	TRACE("MediaAddonServer::_ScanAddOnFlavors: id %" B_PRId32 "\n",
445		addon->AddonID());
446
447	// cache the media_addon_id in a local variable to avoid
448	// calling BMediaAddOn::AddonID() too often
449	media_addon_id addonID = addon->AddonID();
450
451	// update the cached flavor count, get oldflavorcount and newflavorcount
452
453	InfoMap::iterator found = fInfoMap.find(addonID);
454	ASSERT(found != fInfoMap.end());
455
456	AddOnInfo& info = found->second;
457	int32 oldFlavorCount = info.flavor_count;
458	int32 newFlavorCount = addon->CountFlavors();
459	info.flavor_count = newFlavorCount;
460
461	TRACE("%" B_PRId32 " old flavors, %" B_PRId32 " new flavors\n",
462		oldFlavorCount, newFlavorCount);
463
464	// during the first update (i == 0), the server removes old dormant_flavor_infos
465	for (int i = 0; i < newFlavorCount; i++) {
466		const flavor_info* flavorInfo;
467		TRACE("flavor %d:\n", i);
468		if (addon->GetFlavorAt(i, &flavorInfo) != B_OK) {
469			ERROR("MediaAddonServer::_ScanAddOnFlavors GetFlavorAt failed for "
470				"index %d!\n", i);
471			continue;
472		}
473
474#if DEBUG >= 2
475		DumpFlavorInfo(flavorInfo);
476#endif
477
478		dormant_flavor_info dormantFlavorInfo;
479		dormantFlavorInfo = *flavorInfo;
480		dormantFlavorInfo.node_info.addon = addonID;
481		dormantFlavorInfo.node_info.flavor_id = flavorInfo->internal_id;
482		strlcpy(dormantFlavorInfo.node_info.name, flavorInfo->name,
483			B_MEDIA_NAME_LENGTH);
484
485		size_t flattenedSize = dormantFlavorInfo.FlattenedSize();
486		size_t messageSize = flattenedSize
487			+ sizeof(server_register_dormant_node_command);
488		server_register_dormant_node_command* message
489			= (server_register_dormant_node_command*)malloc(messageSize);
490		if (message == NULL)
491			break;
492
493		// The server should remove previously registered "dormant_flavor_info"s
494		// during the first update, but after  the first iteration, we don't
495		// want the server to anymore remove old dormant_flavor_infos
496		message->purge_id = i == 0 ? addonID : 0;
497
498		message->type = dormantFlavorInfo.TypeCode();
499		message->flattened_size = flattenedSize;
500		dormantFlavorInfo.Flatten(message->flattened_data, flattenedSize);
501
502		status_t status = SendToServer(SERVER_REGISTER_DORMANT_NODE,
503			message, messageSize);
504		if (status != B_OK) {
505			ERROR("MediaAddonServer::_ScanAddOnFlavors: couldn't register "
506				"dormant node: %s\n", strerror(status));
507		}
508
509		free(message);
510	}
511
512	// TODO: we currently pretend that all old flavors have been removed, this
513	// could probably be done in a smarter way
514	BPrivate::media::notifications::FlavorsChanged(addonID, newFlavorCount,
515		oldFlavorCount);
516}
517
518
519void
520MediaAddonServer::_AddOnAdded(const char* path, ino_t fileNode)
521{
522	TRACE("\n\nMediaAddonServer::_AddOnAdded: path %s\n", path);
523
524	media_addon_id id = gDormantNodeManager->RegisterAddOn(path);
525	if (id <= 0) {
526		ERROR("MediaAddonServer::_AddOnAdded: failed to register add-on %s\n",
527			path);
528		return;
529	}
530
531	TRACE("MediaAddonServer::_AddOnAdded: loading addon %" B_PRId32 " now..."
532		"\n", id);
533
534	BMediaAddOn* addon = gDormantNodeManager->GetAddOn(id);
535	if (addon == NULL) {
536		ERROR("MediaAddonServer::_AddOnAdded: failed to get add-on %s\n",
537			path);
538		gDormantNodeManager->UnregisterAddOn(id);
539		return;
540	}
541
542	TRACE("MediaAddonServer::_AddOnAdded: loading finished, id %" B_PRId32
543		"\n", id);
544
545	try {
546		// put file's inode and addon's id into map
547		fFileMap.insert(std::make_pair(fileNode, id));
548
549		AddOnInfo info;
550		fInfoMap.insert(std::make_pair(id, info));
551	} catch (std::bad_alloc& exception) {
552		fFileMap.erase(fileNode);
553		return;
554	}
555
556	InfoMap::iterator found = fInfoMap.find(id);
557	AddOnInfo& info = found->second;
558
559	info.id = id;
560	// temporary default
561	info.wants_autostart = false;
562	info.flavor_count = 0;
563	info.addon = addon;
564
565	// scan the flavors
566	_ScanAddOnFlavors(addon);
567
568	// need to call BMediaNode::WantsAutoStart()
569	// after the flavors have been scanned
570	info.wants_autostart = addon->WantsAutoStart();
571
572	if (info.wants_autostart)
573		TRACE("add-on %" B_PRId32 " WantsAutoStart!\n", id);
574
575	// During startup, first all add-ons are loaded, then all
576	// nodes (flavors) representing physical inputs and outputs
577	// are instantiated. Next, all add-ons that need autostart
578	// will be autostarted. Finally, add-ons that don't have
579	// any active nodes (flavors) will be unloaded.
580
581	// After startup is done, we simply do it for each new
582	// loaded add-on, too.
583	if (!fStartup) {
584		_InstantiatePhysicalInputsAndOutputs(info);
585		_InstantiateAutostartFlavors(info);
586		_PutAddonIfPossible(info);
587
588		// since something might have changed
589		server_rescan_defaults_command cmd;
590		SendToServer(SERVER_RESCAN_DEFAULTS, &cmd, sizeof(cmd));
591	}
592
593	// we do not call gDormantNodeManager->PutAddOn(id)
594	// since it is done by _PutAddonIfPossible()
595}
596
597
598void
599MediaAddonServer::_DestroyInstantiatedFlavors(AddOnInfo& info)
600{
601	printf("MediaAddonServer::_DestroyInstantiatedFlavors addon %" B_PRId32
602		"\n", info.id);
603
604	NodeVector::iterator iterator = info.active_flavors.begin();
605	for (; iterator != info.active_flavors.end(); iterator++) {
606		media_node& node = *iterator;
607
608		printf("node %" B_PRId32 "\n", node.node);
609
610		if ((node.kind & B_TIME_SOURCE) != 0
611			&& (fMediaRoster->StopTimeSource(node, 0, true) != B_OK)) {
612			printf("MediaAddonServer::_DestroyInstantiatedFlavors couldn't stop "
613				"timesource\n");
614			continue;
615		}
616
617		if (fMediaRoster->StopNode(node, 0, true) != B_OK) {
618			printf("MediaAddonServer::_DestroyInstantiatedFlavors couldn't stop "
619				"node\n");
620			continue;
621		}
622
623		if ((node.kind & B_BUFFER_CONSUMER) != 0) {
624			media_input inputs[16];
625			int32 count = 0;
626			if (fMediaRoster->GetConnectedInputsFor(node, inputs, 16, &count)
627					!= B_OK) {
628				printf("MediaAddonServer::_DestroyInstantiatedFlavors couldn't "
629					"get connected inputs\n");
630				continue;
631			}
632
633			for (int32 i = 0; i < count; i++) {
634				media_node_id sourceNode;
635				if ((sourceNode = fMediaRoster->NodeIDFor(
636						inputs[i].source.port)) < 0) {
637					printf("MediaAddonServer::_DestroyInstantiatedFlavors "
638						"couldn't get source node id\n");
639					continue;
640				}
641
642				if (fMediaRoster->Disconnect(sourceNode, inputs[i].source,
643						node.node, inputs[i].destination) != B_OK) {
644					printf("MediaAddonServer::_DestroyInstantiatedFlavors "
645						"couldn't disconnect input\n");
646					continue;
647				}
648			}
649		}
650
651		if ((node.kind & B_BUFFER_PRODUCER) != 0) {
652			media_output outputs[16];
653			int32 count = 0;
654			if (fMediaRoster->GetConnectedOutputsFor(node, outputs, 16,
655					&count) != B_OK) {
656				printf("MediaAddonServer::_DestroyInstantiatedFlavors couldn't "
657					"get connected outputs\n");
658				continue;
659			}
660
661			for (int32 i = 0; i < count; i++) {
662				media_node_id destNode;
663				if ((destNode = fMediaRoster->NodeIDFor(
664						outputs[i].destination.port)) < 0) {
665					printf("MediaAddonServer::_DestroyInstantiatedFlavors "
666						"couldn't get destination node id\n");
667					continue;
668				}
669
670				if (fMediaRoster->Disconnect(node.node, outputs[i].source,
671						destNode, outputs[i].destination) != B_OK) {
672					printf("MediaAddonServer::_DestroyInstantiatedFlavors "
673						"couldn't disconnect output\n");
674					continue;
675				}
676			}
677		}
678
679		if (MediaRosterEx(fMediaRoster)->ReleaseNodeAll(node) != B_OK) {
680			printf("MediaAddonServer::_DestroyInstantiatedFlavors "
681						"couldn't release node\n");
682		}
683
684		// wait a bit to let the node clean up
685		snooze(50000);
686	}
687
688	info.active_flavors.clear();
689}
690
691
692void
693MediaAddonServer::_PutAddonIfPossible(AddOnInfo& info)
694{
695	if (info.addon && info.active_flavors.empty()) {
696		gDormantNodeManager->PutAddOn(info.id);
697		info.addon = NULL;
698	}
699}
700
701
702void
703MediaAddonServer::_InstantiatePhysicalInputsAndOutputs(AddOnInfo& info)
704{
705	CALLED();
706	int32 count = info.addon->CountFlavors();
707
708	for (int32 i = 0; i < count; i++) {
709		const flavor_info* flavorinfo;
710		if (info.addon->GetFlavorAt(i, &flavorinfo) != B_OK) {
711			ERROR("MediaAddonServer::InstantiatePhysialInputsAndOutputs "
712				"GetFlavorAt failed for index %" B_PRId32 "!\n", i);
713			continue;
714		}
715		if ((flavorinfo->kinds & (B_PHYSICAL_INPUT | B_PHYSICAL_OUTPUT)) != 0) {
716			media_node node;
717
718			dormant_node_info dormantNodeInfo;
719			dormantNodeInfo.addon = info.id;
720			dormantNodeInfo.flavor_id = flavorinfo->internal_id;
721			strcpy(dormantNodeInfo.name, flavorinfo->name);
722
723			TRACE("MediaAddonServer::InstantiatePhysialInputsAndOutputs: "
724				"\"%s\" is a physical input/output\n", flavorinfo->name);
725			status_t status = fMediaRoster->InstantiateDormantNode(
726				dormantNodeInfo, &node);
727			if (status != B_OK) {
728				ERROR("MediaAddonServer::InstantiatePhysialInputsAndOutputs "
729					"Couldn't instantiate node flavor, internal_id %" B_PRId32
730					", name %s\n", flavorinfo->internal_id, flavorinfo->name);
731			} else {
732				TRACE("Node created!\n");
733				info.active_flavors.push_back(node);
734			}
735		}
736	}
737}
738
739
740void
741MediaAddonServer::_InstantiateAutostartFlavors(AddOnInfo& info)
742{
743	if (!info.wants_autostart)
744		return;
745
746	for (int32 index = 0;; index++) {
747		TRACE("trying autostart of node %" B_PRId32 ", index %" B_PRId32 "\n",
748			info.id, index);
749
750		BMediaNode* node;
751		int32 internalID;
752		bool hasMore;
753		status_t status = info.addon->AutoStart(index, &node, &internalID,
754			&hasMore);
755		if (status == B_MEDIA_ADDON_FAILED && hasMore)
756			continue;
757		else if (status != B_OK)
758			break;
759
760		printf("started node %" B_PRId32 "\n", index);
761
762		status = MediaRosterEx(fMediaRoster)->RegisterNode(node, info.id,
763			internalID);
764		if (status != B_OK) {
765			ERROR("failed to register node %" B_PRId32 "\n", index);
766			node->Release();
767		} else {
768			MediaRosterEx(fMediaRoster)->IncrementAddonFlavorInstancesCount(
769				info.id, internalID);
770			info.active_flavors.push_back(node->Node());
771		}
772
773		if (!hasMore)
774			return;
775	}
776}
777
778
779void
780MediaAddonServer::_AddOnRemoved(ino_t fileNode)
781{
782	// TODO: locking?
783
784	FileMap::iterator foundFile = fFileMap.find(fileNode);
785	if (foundFile == fFileMap.end()) {
786		ERROR("MediaAddonServer::_AddOnRemoved: inode %" B_PRIdINO " removed, but no "
787			"media add-on found\n", fileNode);
788		return;
789	}
790
791	media_addon_id id = foundFile->second;
792	fFileMap.erase(foundFile);
793
794	int32 oldFlavorCount;
795	InfoMap::iterator foundInfo = fInfoMap.find(id);
796
797	if (foundInfo == fInfoMap.end()) {
798		ERROR("MediaAddonServer::_AddOnRemoved: couldn't get addon info for "
799			"add-on %" B_PRId32 "\n", id);
800		oldFlavorCount = 1000;
801	} else {
802		AddOnInfo& info = foundInfo->second;
803		oldFlavorCount = info.flavor_count;
804
805		_DestroyInstantiatedFlavors(info);
806		_PutAddonIfPossible(info);
807
808		if (info.addon) {
809			ERROR("MediaAddonServer::_AddOnRemoved: couldn't unload addon "
810				"%" B_PRId32 " since flavors are in use\n", id);
811		}
812
813		fInfoMap.erase(foundInfo);
814	}
815
816	gDormantNodeManager->UnregisterAddOn(id);
817
818	BPrivate::media::notifications::FlavorsChanged(id, 0, oldFlavorCount);
819}
820
821
822//	#pragma mark -
823
824
825int
826main()
827{
828	new MediaAddonServer(B_MEDIA_ADDON_SERVER_SIGNATURE);
829	be_app->Run();
830	delete be_app;
831	return 0;
832}
833