Exemplo n.º 1
0
/*----------------------------------------------------------------------------*/
bool Analyzer::addPlugin( const QString& file )
{
	if ( file.isEmpty() ) //nothing to load
		return false;

	PRINT_DEBUG ("Loading plugin: " << file);

	PluginLoader * loader = new PluginLoader( file );
	Q_ASSERT (loader);
	if (loader->isLoaded())
	{
		error( "Plugin already loaded!" );
		loader->unload();
		delete loader;
		return false;
	}
	
	const bool success = loader->init();
	
	if (!success)
	{
		error( "Plugin initialization failed!" );
		loader->unload();
		delete loader;
		return false;
	}

	mPlugins.append( loader );
	connect( loader, SIGNAL(destroyed( QObject* )),
		this, SLOT(removePlugin( QObject* )) );

	emit newPlugin( loader );

	return true;
}
Exemplo n.º 2
0
/// Indexes all plugins found in /Plugins
void GameCore::loadPlugins()
{
	typedef PluginSDK::Types(*getPluginTypeFunc)();
	typedef ExtensionScripting*(*createScriptEnvironmentFunc)(GameCore*);
	typedef ExtensionAudio*(*createAudioEnvironmentFunc)(GameCore*);

	StringList dll_list = FileSystem::scanDirectory("Plugins", "dll", false);
	for (auto& dll_name : dll_list)
	{
		// Let's check what the plugin is and load immediately
		PluginLoader* plugin = new PluginLoader(dll_name);
		if (plugin)
		{
			Log("Plugin loaded: %s", dll_name.c_str());

			getPluginTypeFunc funptr = (getPluginTypeFunc)plugin->getFunctionAddress("getPluginType");
			if (funptr)
			{
				PluginSDK::Types pluginType = funptr();

				switch (pluginType)
				{
				case PluginSDK::Scripting:
					{
						 Log("THIS IS A SCRIPTING PLUGIN");
						 createScriptEnvironmentFunc funptr = (createScriptEnvironmentFunc)plugin->getFunctionAddress("createScriptingEnvironment");
						 if (funptr)
						 {
							 ExtensionScripting* scriptingEnvironment = funptr(this);
							 if (scriptingEnvironment)
							 {
								 Log("Got the scripting environment, Registered.");
								 scriptingEnvironments.push_back(scriptingEnvironment);
							 }
						 }
					}
					break;
				case PluginSDK::Audio:
					{
						 Log("THIS IS A AUDIO PLUGIN");
						 createAudioEnvironmentFunc funptr = (createAudioEnvironmentFunc)plugin->getFunctionAddress("createAudioEnvironment");
						 if (funptr)
						 {
							 ExtensionAudio* audioEnvironment = funptr(this);
							 if (audioEnvironment)
							 {
								 Log("Got the audio environment, Registered.");
								 gameAudio.audioEnvironments.push_back(audioEnvironment);
							 }
						 }
					}
					break;


				}
			}
		}
	}
}
Exemplo n.º 3
0
void Device::reloadPlugins()
{
    QHash<QString, KdeConnectPlugin*> newPluginMap;
    QMultiMap<QString, KdeConnectPlugin*> newPluginsByIncomingInterface;
    QMultiMap<QString, KdeConnectPlugin*> newPluginsByOutgoingInterface;
    QSet<QString> supportedIncomingInterfaces;
    QSet<QString> supportedOutgoingInterfaces;
    QStringList unsupportedPlugins;

    if (isPaired() && isReachable()) { //Do not load any plugin for unpaired devices, nor useless loading them for unreachable devices

        KConfigGroup pluginStates = KSharedConfig::openConfig(pluginsConfigFile())->group("Plugins");

        PluginLoader* loader = PluginLoader::instance();
        const bool deviceSupportsCapabilities = !m_incomingCapabilities.isEmpty() || !m_outgoingCapabilities.isEmpty();

        foreach (const QString& pluginName, loader->getPluginList()) {
            const KPluginMetaData service = loader->getPluginInfo(pluginName);
            const QSet<QString> incomingInterfaces = KPluginMetaData::readStringList(service.rawData(), "X-KdeConnect-SupportedPackageType").toSet();
            const QSet<QString> outgoingInterfaces = KPluginMetaData::readStringList(service.rawData(), "X-KdeConnect-OutgoingPackageType").toSet();

            const bool pluginEnabled = isPluginEnabled(pluginName);

            if (pluginEnabled) {
                supportedIncomingInterfaces += incomingInterfaces;
                supportedOutgoingInterfaces += outgoingInterfaces;
            }

            //If we don't find intersection with the received on one end and the sent on the other, we don't
            //let the plugin stay
            //Also, if no capabilities are specified on the other end, we don't apply this optimizaton, as
            //we assume that the other client doesn't know about capabilities.
            const bool capabilitiesSupported = deviceSupportsCapabilities && (!incomingInterfaces.isEmpty() || !outgoingInterfaces.isEmpty());
            if (capabilitiesSupported
                && (m_incomingCapabilities & outgoingInterfaces).isEmpty()
                && (m_outgoingCapabilities & incomingInterfaces).isEmpty()
            ) {
                qCWarning(KDECONNECT_CORE) << "not loading " << pluginName << "because of unmatched capabilities";
                unsupportedPlugins.append(pluginName);
                continue;
            }

            if (pluginEnabled) {
                KdeConnectPlugin* plugin = m_plugins.take(pluginName);

                if (!plugin) {
                    plugin = loader->instantiatePluginForDevice(pluginName, this);
                }

                foreach(const QString& interface, incomingInterfaces) {
                    newPluginsByIncomingInterface.insert(interface, plugin);
                }
                foreach(const QString& interface, outgoingInterfaces) {
                    newPluginsByOutgoingInterface.insert(interface, plugin);
                }

                newPluginMap[pluginName] = plugin;
            }
Exemplo n.º 4
0
void Device::reloadPlugins()
{
    QHash<QString, KdeConnectPlugin*> newPluginMap;
    QMultiMap<QString, KdeConnectPlugin*> newPluginsByIncomingInterface;
    QMultiMap<QString, KdeConnectPlugin*> newPluginsByOutgoingInterface;

    if (isPaired() && isReachable()) { //Do not load any plugin for unpaired devices, nor useless loading them for unreachable devices

        KConfigGroup pluginStates = KSharedConfig::openConfig(pluginsConfigFile())->group("Plugins");

        PluginLoader* loader = PluginLoader::instance();

        //Code borrowed from KWin
        foreach (const QString& pluginName, loader->getPluginList()) {
            QString enabledKey = pluginName + QString::fromLatin1("Enabled");

            bool isPluginEnabled = (pluginStates.hasKey(enabledKey) ? pluginStates.readEntry(enabledKey, false)
                                                            : loader->getPluginInfo(pluginName).isEnabledByDefault());

            if (isPluginEnabled) {
                KdeConnectPlugin* plugin = m_plugins.take(pluginName);
                QStringList incomingInterfaces, outgoingInterfaces;
                if (plugin) {
                    incomingInterfaces = m_pluginsByIncomingInterface.keys(plugin);
                    outgoingInterfaces = m_pluginsByOutgoingInterface.keys(plugin);
                } else {
                    const KPluginMetaData service = loader->getPluginInfo(pluginName);
                    incomingInterfaces = KPluginMetaData::readStringList(service.rawData(), "X-KdeConnect-SupportedPackageType");
                    outgoingInterfaces = KPluginMetaData::readStringList(service.rawData(), "X-KdeConnect-OutgoingPackageType");
                }

                //If we don't find intersection with the received on one end and the sent on the other, we don't
                //let the plugin stay
                //Also, if no capabilities are specified on the other end, we don't apply this optimizaton, as
                //we assume that the other client doesn't know about capabilities.
                if (!m_incomingCapabilities.isEmpty() && !m_outgoingCapabilities.isEmpty()
                    && (m_incomingCapabilities & outgoingInterfaces.toSet()).isEmpty()
                    && (m_outgoingCapabilities & incomingInterfaces.toSet()).isEmpty()
                ) {
                    delete plugin;
                    continue;
                }

                if (!plugin) {
                    plugin = loader->instantiatePluginForDevice(pluginName, this);
                }

                foreach(const QString& interface, incomingInterfaces) {
                    newPluginsByIncomingInterface.insert(interface, plugin);
                }
                foreach(const QString& interface, outgoingInterfaces) {
                    newPluginsByOutgoingInterface.insert(interface, plugin);
                }
                newPluginMap[pluginName] = plugin;
            }
Exemplo n.º 5
0
//-------------------------------------------------------------------------------------------------------
int main (int argc, char* argv[])
{
	if (!checkPlatform ())
	{
		printf ("Platform verification failed! Please check your Compiler Settings!\n");
		return -1;
	}

	const char* fileName = "again.dll";
	//const char* fileName = "adelay.dll";
	//const char* fileName = "surrounddelay.dll";
	//const char* fileName = "vstxsynth.dll";
	//const char* fileName = "drawtest.dll";

	if (argc > 1)
		fileName = argv[1];

	printf ("HOST> Load library...\n");
	PluginLoader loader;
	if (!loader.loadLibrary (fileName))
	{
		printf ("Failed to load VST Plugin library!\n");
		return -1;
	}

	PluginEntryProc mainEntry = loader.getMainEntry ();
	if (!mainEntry)
	{
		printf ("VST Plugin main entry not found!\n");
		return -1;
	}

	printf ("HOST> Create effect...\n");
	AEffect* effect = mainEntry (HostCallback);
	if (!effect)
	{
		printf ("Failed to create effect instance!\n");
		return -1;
	}

	printf ("HOST> Init sequence...\n");
	effect->dispatcher (effect, effOpen, 0, 0, 0, 0);
	effect->dispatcher (effect, effSetSampleRate, 0, 0, 0, kSampleRate);
	effect->dispatcher (effect, effSetBlockSize, 0, kBlockSize, 0, 0);

	checkEffectProperties (effect);
	checkEffectProcessing (effect);
	checkEffectEditor (effect);

	printf ("HOST> Close effect...\n");
	effect->dispatcher (effect, effClose, 0, 0, 0, 0);
	return 0;
}
Exemplo n.º 6
0
int main(int argc, char **argv) {
	int c;
	std::string fname("");
	while ((c = getopt(argc, argv, "hf:")) != -1) {
		switch (c) {
		default:
		case 'h':	usage(); return 0; break;
		case 'f':	fname = optarg;	break;
		}
	}
	if (optind != argc) return (usage());

	Project project;
	
	// Setup the plugins
	PluginLoader *loader = PluginLoader::s_getSystemLoader();
	log4cxx::PropertyConfigurator::configure("logger.conf");
	
	try {
		loader->loadDir("./plugins");
	} catch (IOException e) {
		std::cerr << "Error loading plugins: " << e.what() << std::endl;
		return 1;
	}
	
	// Load a file if it's been passed in
	if (fname.length() > 0) {
		try {
			project.load(fname);
		} catch (const std::exception &e) {
			std::cerr << "error opening file: " << fname << std::endl;
			std::cerr << e.what() << std::endl;
		}
	}

	std::cout << "Press the 'X' key to exit the application" << std::endl;

	char ch;
	while ((ch = std::cin.get()) != 'x' && ch != 'X') {}
	
	try {
		loader->unloadAll();
	} catch (IOException e) {
		std::cerr << "Error unloading plugins: " << e.what() << std::endl;
		return 1;
	}
	return 0;
}
Exemplo n.º 7
0
void Plugins::enumerate() {
  PluginParser.AddChild(&PluginMMLParser);
  PluginRootParser.AddChild(&PluginParser);

  logContext("parsing plugins");
  PluginLoader loader;
  loader.CurrentElement = &PluginRootParser;

  for (std::vector<DirectorySpecifier>::const_iterator it =
         data_search_path.begin();
       it != data_search_path.end(); ++it) {
    DirectorySpecifier path = *it + "Plugins";
    loader.ParseDirectory(path);
  }
  std::sort(m_plugins.begin(), m_plugins.end());
  clear_game_error();
}
Exemplo n.º 8
0
int main(int argc, char **argv) 
{
    PluginLoader factory;

    if(factory.OpenModule(gFilename, "CxUtils"))
    {
        // Every plugin library must have an initializer method to create
        // an instance of a plugin-based class.  CxUtils includes one example
        // method to do so, see plugin.h for how to declare and implement.
        Plugin* plugin = factory.CreatePlugin("CxUtils", "CreateCxUtilsPluginExample");

        if(plugin)
        {
            std::cout << plugin->GetPluginDescription() << std::endl;
            delete plugin;
        }
    }
    return 0;
}
Exemplo n.º 9
0
int main(int argc, char **argv)
{
    QtSingleApplication *app = new QtSingleApplication(argc, argv);
    PluginLoader pluginLoader;
    QObject *plugin = pluginLoader.loadLauncher("badi");
    if(plugin)
    {
        ApplicationPlugin *appPlugin = dynamic_cast<ApplicationPlugin *>(plugin);
        app->closeAllWindows();
        delete app;
        app = appPlugin->createApplication(argc, argv);
        if(app)
        {
            if (app->sendMessage("Wake up!"))
                return 0;
            return app->exec();
        }
    }
}
Exemplo n.º 10
0
void KRenameWindow::setupPlugins()
{
    PluginLoader *loader = PluginLoader::Instance();

    const QList<Plugin *> &list = loader->plugins();
    QList<Plugin *>::const_iterator it = list.begin();

    m_pluginsWidgetHash.reserve(list.count());
    m_pluginsHash.reserve(list.count());

    m_pagePlugins->searchPlugins->searchLine()->setTreeWidget(m_pagePlugins->listPlugins);

    while (it != list.end()) {
        // create plugin gui
        QWidget *widget = new QWidget(m_pagePlugins->stackPlugins);
        (*it)->createUI(widget);
        int idx = m_pagePlugins->stackPlugins->addWidget(widget);
        m_pagePlugins->stackPlugins->setCurrentIndex(idx);

        m_pluginsHash[(*it)->name()] = (*it);
        m_pluginsWidgetHash[(*it)->name()] = widget;

        // add to list of all plugins
        QTreeWidgetItem *item = new QTreeWidgetItem(m_pagePlugins->listPlugins);
        item->setText(0, (*it)->name());
        item->setIcon(0, (*it)->icon());

        slotPluginChanged(item);

        ++it;
    }

    m_pagePlugins->splitter->setStretchFactor(0, 0);
    m_pagePlugins->splitter->setStretchFactor(1, 8);
    m_pagePlugins->listPlugins->sortColumn();
}
Exemplo n.º 11
0
int main() {
    PluginLoader*   pluginTest  = new PluginLoader;
    TrinitasPlugin* tmpPlugin   = NULL;
    /*load all Plugins in the directory where
     *where this programm is located
     */
    pluginTest->Load("Plugins");
    // this dont work for now dont know why
    cout << "GetPluginByName:\n";

    tmpPlugin = pluginTest->GetByName("Client");
    if (tmpPlugin) {
        cout << "GetPluginByName: ";
        tmpPlugin->Do();
    }
    cout << "GetPluginByID:\n ";

    tmpPlugin = pluginTest->GetAt(1);
    if (tmpPlugin) {
        cout << "GetPluginByID: ";
        tmpPlugin->Do();
    }
	return 0;
}
Exemplo n.º 12
0
void
printPluginCategoryList()
{
    PluginLoader *loader = PluginLoader::getInstance();

    vector<PluginLoader::PluginKey> plugins = loader->listPlugins();

    set<string> printedcats;

    for (size_t i = 0; i < plugins.size(); ++i) {

        PluginLoader::PluginKey key = plugins[i];
        
        PluginLoader::PluginCategoryHierarchy category =
            loader->getPluginCategory(key);

        Plugin *plugin = loader->loadPlugin(key, 48000);
        if (!plugin) continue;

        string catstr = "";

        if (category.empty()) catstr = '|';
        else {
            for (size_t j = 0; j < category.size(); ++j) {
                catstr += category[j];
                catstr += '|';
                if (printedcats.find(catstr) == printedcats.end()) {
                    std::cout << catstr << std::endl;
                    printedcats.insert(catstr);
                }
            }
        }

        std::cout << catstr << key << ":::" << plugin->getName() << ":::" << plugin->getMaker() << ":::" << plugin->getDescription() << std::endl;
    }
}
Exemplo n.º 13
0
int main(int argc, char* argv[]) {
	if (argc < 4) {
		cerr << "Invalid number of arguments." << endl;
		cout << "Usage: " << argv[0] << " <input_video_file_path> <analytic_plugin_dir_path> <analytic_plugin_filename>" << endl;
		cout << "Example: " << argv[0] << "input.mp4 ~/analytic/ analytic_plugin.so" << endl;
		return -1;
	}
	string input_video_file_path = argv[1];
	string analytic_plugin_dir_path = argv[2];
	string analytic_plugin_filename = argv[3];

	ConcurrentQueue<api::Image_t>* pImageInputQueue = new ConcurrentQueue<api::Image_t>(10);
	ConcurrentQueue<api::Image_t>* pResultsOutputQueue = new ConcurrentQueue<api::Image_t>(10);

	// Load Analytic
	api::Analytic* pAnalytic = NULL;
	PluginLoader<api::Analytic> loader;
	string sPathToAnalyticPlugin = analytic_plugin_dir_path;
	if(*sPathToAnalyticPlugin.rbegin() != '/') // last char
	{
		sPathToAnalyticPlugin.append("/");
	}
	sPathToAnalyticPlugin.append(analytic_plugin_filename);
	try
	{
		loader.loadPlugin(sPathToAnalyticPlugin);
		pAnalytic = loader.createPluginInstance();
	}
	catch(opencctv::Exception &e)
	{
		cerr << "Failed to load the Analytic plugin: " << sPathToAnalyticPlugin << endl;
		return -1;
	}

	// Create Consumer thread to write results into a txt file
	string sOutputFilename = analytic_plugin_dir_path;
	if(*sOutputFilename.rbegin() != '/') // last char
	{
		sOutputFilename.append("/");
	}
	sOutputFilename.append(currentDateTime());
	sOutputFilename.append(".txt");
	ConsumerThread resultsConsumer(sOutputFilename, pResultsOutputQueue);
	boost::thread* pConsumerThread = new boost::thread(resultsConsumer);

	// Create Producer thread to read frames from input video files
	ProducerThread imageProducer(input_video_file_path, pImageInputQueue);
	boost::thread* pProducerThread = new boost::thread(imageProducer);

	// Run analytic
	try
	{
		if(pAnalytic->init(analytic_plugin_dir_path))
		{
			pAnalytic->process(pImageInputQueue, pResultsOutputQueue);
		}
		else
		{
			cerr << "Failed to initialize the Analytic. init() failed.";
		}
	}
	catch(exception &e)
	{
		cerr << "Exception in Analytic: " << e.what() << endl;
	}

	return 0;
}
Exemplo n.º 14
0
int runPlugin(string myname, string soname, string id,
              string output, int outputNo, bool useFrames, PaStreamParameters inputParameters)
{
    float				*recordedSamples;
    float				*fifo;
    PaStream*           stream;
    PaError             err = paNoError;
    int					elapsed = 0;
    int					returnValue = 1;
    RealTime			rt;
    PluginWrapper		*wrapper = 0;
    RealTime			adjustment = RealTime::zeroTime;
    PluginLoader		*loader = PluginLoader::getInstance();
    PluginLoader::PluginKey key = loader->composePluginKey(soname, id);

    // load plugin
    Plugin *plugin = loader->loadPlugin(key, SAMPLE_RATE, PluginLoader::ADAPT_ALL_SAFE);
    if (!plugin) {
        cerr << myname << ": ERROR: Failed to load plugin \"" << id
             << "\" from library \"" << soname << "\"" << endl;
        return 1;
    }

    // Find block/step size
    int blockSize = plugin->getPreferredBlockSize();
    int stepSize = plugin->getPreferredStepSize();

    if (blockSize == 0) {
        blockSize = 1024;
    }
    if (stepSize == 0) {
        if (plugin->getInputDomain() == Plugin::FrequencyDomain) {
            stepSize = blockSize/2;
        } else {
            stepSize = blockSize;
        }
    } else if (stepSize > blockSize) {
        cerr << "WARNING: stepSize " << stepSize << " > blockSize " << blockSize << ", resetting blockSize to ";
        if (plugin->getInputDomain() == Plugin::FrequencyDomain) {
            blockSize = stepSize * 2;
        } else {
            blockSize = stepSize;
        }
        cerr << blockSize << endl;
    }

    // set up port audio
    fifo = new float[blockSize]();
    recordedSamples = new float[stepSize]();

    ofstream *out = 0;
    cerr << "Running plugin: \"" << plugin->getIdentifier() << "\"..." << endl;
    cerr << "Using block size = " << blockSize << ", step size = " << stepSize << endl;

    // display output name
    Plugin::OutputList outputs = plugin->getOutputDescriptors();
    Plugin::OutputDescriptor od;

    if (outputs.empty()) {
    	cerr << "ERROR: Plugin has no outputs!" << endl;
    	goto done;
    }

    if (outputNo < 0) {

        for (size_t oi = 0; oi < outputs.size(); ++oi) {
            if (outputs[oi].identifier == output) {
                outputNo = oi;
                break;
            }
        }

        if (outputNo < 0) {
            cerr << "ERROR: Non-existent output \"" << output << "\" requested" << endl;
            goto done;
        }

    } else {

        if (int(outputs.size()) <= outputNo) {
            cerr << "ERROR: Output " << outputNo << " requested, but plugin has only " << outputs.size() << " output(s)" << endl;
            goto done;
        }
    }

    od = outputs[outputNo];
    cerr << "Output is: \"" << od.identifier << "\"" << endl;

    // Initialise plugin
    if (!plugin->initialise(1, stepSize, blockSize)) {
        cerr << "ERROR: Plugin initialise (stepSize = " << stepSize << ", blockSize = "
             << blockSize << ") failed." << endl;
        goto done;
    }

    // Compensate timestamp if in freq domain
    wrapper = dynamic_cast<PluginWrapper *>(plugin);
    if (wrapper) {
        PluginInputDomainAdapter *ida =  wrapper->getWrapper<PluginInputDomainAdapter>();
        if (ida) adjustment = ida->getTimestampAdjustment();
    }

    // Open portaudio stream
    err = Pa_OpenStream(
    		&stream,
    		&inputParameters,
    		NULL,
    		SAMPLE_RATE,
    		stepSize,
    		paClipOff,
    		NULL,
    		NULL );
    if( err != paNoError ) throwError(err);

    // Start the audio stream
    err = Pa_StartStream( stream );
    if( err != paNoError ) throwError(err);
//    printf("Now recording!!\n"); fflush(stdout);

    // do until interruptFlag is true
    while (1)
    {
    	// read step of audio data
    	err = Pa_ReadStream( stream, recordedSamples, stepSize );
    	if( err != paNoError ) throwError(err);

    	// shift buffer along a step size
    	for (int i=stepSize; i<blockSize; i++) fifo[i-stepSize] = fifo[i];

    	// add new step onto end
    	for (int i=0; i<stepSize; i++) fifo[blockSize-stepSize+i] = recordedSamples[i];

    	// process and print features
    	rt = RealTime::frame2RealTime(elapsed*stepSize, SAMPLE_RATE);
    	printFeatures(RealTime::realTime2Frame(rt + adjustment, SAMPLE_RATE), SAMPLE_RATE, outputNo, plugin->process(&fifo, rt), out, useFrames);

    	// note number of blocks processed
    	elapsed++;

    	// break out of loop
    	if (interruptFlag) break;
    }

    // stop the audio stream
    err = Pa_CloseStream( stream );
    if( err != paNoError ) throwError(err);

    // clean up variables
    delete [] recordedSamples;
    delete [] fifo;

    returnValue = 0;

done:
    delete plugin;
    return returnValue;
}
Exemplo n.º 15
0
void
enumeratePlugins(Verbosity verbosity)
{
    PluginLoader *loader = PluginLoader::getInstance();

    if (verbosity == PluginInformation) {
        cout << "\nVamp plugin libraries found in search path:" << endl;
    }

    vector<PluginLoader::PluginKey> plugins = loader->listPlugins();
    typedef multimap<string, PluginLoader::PluginKey>
        LibraryMap;
    LibraryMap libraryMap;

    for (size_t i = 0; i < plugins.size(); ++i) {
        string path = loader->getLibraryPathForPlugin(plugins[i]);
        libraryMap.insert(LibraryMap::value_type(path, plugins[i]));
    }

    string prevPath = "";
    int index = 0;

    for (LibraryMap::iterator i = libraryMap.begin();
         i != libraryMap.end(); ++i) {
        
        string path = i->first;
        PluginLoader::PluginKey key = i->second;

        if (path != prevPath) {
            prevPath = path;
            index = 0;
            if (verbosity == PluginInformation) {
                cout << "\n  " << path << ":" << endl;
            } else if (verbosity == PluginInformationDetailed) {
                string::size_type ki = i->second.find(':');
                string text = "Library \"" + i->second.substr(0, ki) + "\"";
                cout << "\n" << header(text, 1);
            }
        }

        Plugin *plugin = loader->loadPlugin(key, 48000);
        if (plugin) {

            char c = char('A' + index);
            if (c > 'Z') c = char('a' + (index - 26));

            PluginLoader::PluginCategoryHierarchy category =
                loader->getPluginCategory(key);
            string catstr;
            if (!category.empty()) {
                for (size_t ci = 0; ci < category.size(); ++ci) {
                    if (ci > 0) catstr += " > ";
                        catstr += category[ci];
                }
            }

            if (verbosity == PluginInformation) {

                cout << "    [" << c << "] [v"
                     << plugin->getVampApiVersion() << "] "
                     << plugin->getName() << ", \""
                     << plugin->getIdentifier() << "\"" << " ["
                     << plugin->getMaker() << "]" << endl;
                
                if (catstr != "") {
                    cout << "       > " << catstr << endl;
                }

                if (plugin->getDescription() != "") {
                    cout << "        - " << plugin->getDescription() << endl;
                }

            } else if (verbosity == PluginInformationDetailed) {

                cout << header(plugin->getName(), 2);
                cout << " - Identifier:         "
                     << key << endl;
                cout << " - Plugin Version:     " 
                     << plugin->getPluginVersion() << endl;
                cout << " - Vamp API Version:   "
                     << plugin->getVampApiVersion() << endl;
                cout << " - Maker:              \""
                     << plugin->getMaker() << "\"" << endl;
                cout << " - Copyright:          \""
                     << plugin->getCopyright() << "\"" << endl;
                cout << " - Description:        \""
                     << plugin->getDescription() << "\"" << endl;
                cout << " - Input Domain:       "
                     << (plugin->getInputDomain() == Vamp::Plugin::TimeDomain ?
                         "Time Domain" : "Frequency Domain") << endl;
                cout << " - Default Step Size:  " 
                     << plugin->getPreferredStepSize() << endl;
                cout << " - Default Block Size: " 
                     << plugin->getPreferredBlockSize() << endl;
                cout << " - Minimum Channels:   " 
                     << plugin->getMinChannelCount() << endl;
                cout << " - Maximum Channels:   " 
                     << plugin->getMaxChannelCount() << endl;

            } else if (verbosity == PluginIds) {
                cout << "vamp:" << key << endl;
            }
            
            Plugin::OutputList outputs =
                plugin->getOutputDescriptors();

            if (verbosity == PluginInformationDetailed) {

                Plugin::ParameterList params = plugin->getParameterDescriptors();
                for (size_t j = 0; j < params.size(); ++j) {
                    Plugin::ParameterDescriptor &pd(params[j]);
                    cout << "\nParameter " << j+1 << ": \"" << pd.name << "\"" << endl;
                    cout << " - Identifier:         " << pd.identifier << endl;
                    cout << " - Description:        \"" << pd.description << "\"" << endl;
                    if (pd.unit != "") {
                        cout << " - Unit:               " << pd.unit << endl;
                    }
                    cout << " - Range:              ";
                    cout << pd.minValue << " -> " << pd.maxValue << endl;
                    cout << " - Default:            ";
                    cout << pd.defaultValue << endl;
                    if (pd.isQuantized) {
                        cout << " - Quantize Step:      "
                             << pd.quantizeStep << endl;
                    }
                    if (!pd.valueNames.empty()) {
                        cout << " - Value Names:        ";
                        for (size_t k = 0; k < pd.valueNames.size(); ++k) {
                            if (k > 0) cout << ", ";
                            cout << "\"" << pd.valueNames[k] << "\"";
                        }
                        cout << endl;
                    }
                }

                if (outputs.empty()) {
                    cout << "\n** Note: This plugin reports no outputs!" << endl;
                }
                for (size_t j = 0; j < outputs.size(); ++j) {
                    Plugin::OutputDescriptor &od(outputs[j]);
                    cout << "\nOutput " << j+1 << ": \"" << od.name << "\"" << endl;
                    cout << " - Identifier:         " << od.identifier << endl;
                    cout << " - Description:        \"" << od.description << "\"" << endl;
                    if (od.unit != "") {
                        cout << " - Unit:               " << od.unit << endl;
                    }
                    if (od.hasFixedBinCount) {
                        cout << " - Default Bin Count:  " << od.binCount << endl;
                    }
                    if (!od.binNames.empty()) {
                        bool have = false;
                        for (size_t k = 0; k < od.binNames.size(); ++k) {
                            if (od.binNames[k] != "") {
                                have = true; break;
                            }
                        }
                        if (have) {
                            cout << " - Bin Names:          ";
                            for (size_t k = 0; k < od.binNames.size(); ++k) {
                                if (k > 0) cout << ", ";
                                cout << "\"" << od.binNames[k] << "\"";
                            }
                            cout << endl;
                        }
                    }
                    if (od.hasKnownExtents) {
                        cout << " - Default Extents:    ";
                        cout << od.minValue << " -> " << od.maxValue << endl;
                    }
                    if (od.isQuantized) {
                        cout << " - Quantize Step:      "
                             << od.quantizeStep << endl;
                    }
                    cout << " - Sample Type:        "
                         << (od.sampleType ==
                             Plugin::OutputDescriptor::OneSamplePerStep ?
                             "One Sample Per Step" :
                             od.sampleType ==
                             Plugin::OutputDescriptor::FixedSampleRate ?
                             "Fixed Sample Rate" :
                             "Variable Sample Rate") << endl;
                    if (od.sampleType !=
                        Plugin::OutputDescriptor::OneSamplePerStep) {
                        cout << " - Default Rate:       "
                             << od.sampleRate << endl;
                    }
                    cout << " - Has Duration:       "
                         << (od.hasDuration ? "Yes" : "No") << endl;
                }
            }

            if (outputs.size() > 1 || verbosity == PluginOutputIds) {
                for (size_t j = 0; j < outputs.size(); ++j) {
                    if (verbosity == PluginInformation) {
                        cout << "         (" << j << ") "
                             << outputs[j].name << ", \""
                             << outputs[j].identifier << "\"" << endl;
                        if (outputs[j].description != "") {
                            cout << "             - " 
                                 << outputs[j].description << endl;
                        }
                    } else if (verbosity == PluginOutputIds) {
                        cout << "vamp:" << key << ":" << outputs[j].identifier << endl;
                    }
                }
            }

            ++index;

            delete plugin;
        }
    }

    if (verbosity == PluginInformation ||
        verbosity == PluginInformationDetailed) {
        cout << endl;
    }
}
Exemplo n.º 16
0
wxArrayString VampEffectsModule::FindPlugins(PluginManagerInterface & WXUNUSED(pm))
{
   wxArrayString names;

   PluginLoader *loader = PluginLoader::getInstance();

   PluginLoader::PluginKeyList keys = loader->listPlugins();

   for (PluginLoader::PluginKeyList::iterator i = keys.begin(); i != keys.end(); ++i)
   {
      Plugin *vp = PluginLoader::getInstance()->loadPlugin(*i, 48000); // rate doesn't matter here
      if (!vp)
      {
         continue;
      }

      // We limit the listed plugin outputs to those whose results can
      // readily be displayed in an Audacity label track.
      //
      // - Any output whose features have no values (time instants only),
      //   with or without duration, is fine
      //
      // - Any output whose features have more than one value, or an
      //   unknown or variable number of values, is right out
      //
      // - Any output whose features have exactly one value, with
      //   variable sample rate or with duration, should be OK --
      //   this implies a sparse feature, of which the time and/or
      //   duration are significant aspects worth displaying
      //
      // - An output whose features have exactly one value, with
      //   fixed sample rate and no duration, cannot be usefully
      //   displayed -- the value is the only significant piece of
      //   data there and we have no good value plot

      Plugin::OutputList outputs = vp->getOutputDescriptors();

      int output = 0;

      for (Plugin::OutputList::iterator j = outputs.begin(); j != outputs.end(); ++j)
      {
         if (j->sampleType == Plugin::OutputDescriptor::FixedSampleRate ||
               j->sampleType == Plugin::OutputDescriptor::OneSamplePerStep ||
               !j->hasFixedBinCount ||
               (j->hasFixedBinCount && j->binCount > 1))
         {
            // All of these qualities disqualify (see notes above)

            ++output;
            continue;
         }

         wxString name = wxString::FromUTF8(vp->getName().c_str());

         if (outputs.size() > 1)
         {
            // This is not the plugin's only output.
            // Use "plugin name: output name" as the effect name,
            // unless the output name is the same as the plugin name
            wxString outputName = wxString::FromUTF8(j->name.c_str());
            if (outputName != name)
            {
               name = wxString::Format(wxT("%s: %s"),
                                       name.c_str(), outputName.c_str());
            }
         }

         wxString path = wxString::FromUTF8(i->c_str()) + wxT("/") + name;
         names.Add(path);

         ++output;
      }

      delete vp;
   }

   return names;
}
Exemplo n.º 17
0
/** The main test program.
 * @param argc the number of arguments
 * @param argv the arguments
 * @return 0 on success
 */
int
main(int argc, char **argv)
{
  // Load just the test module

  bool success = true;

  cout << "Running plain module tests" << endl;
  ModuleDL *m = new ModuleDL(PLUGINDIR"/test_splugin.so");
  try {
    m->open();
  } catch (Exception &e) {
    e.print_trace();
    throw;
  }
  success = test_module(m);
  m->close();
  delete m;
  if ( success ) {
    cout << "SUCCESSFULLY tested plain module" << endl;
  } else {
    cout << "FAILED plain module tests, aborting further tests" << endl;
    return -1;
  }

  success = true;
  cout << endl << endl << "Running ModuleManagerTemplate tests" << endl;
  ModuleManagerTemplate<ModuleDL> mm(PLUGINDIR);
  Module *mod = mm.open_module("test_plugin.so");
  if ( mod == NULL ) {
    cout << "Failed to retrieve module from manager" << endl;
    success = false;
  } else {
    cout << "Retrieved module from module manager" << endl;
  }

  success = test_module(mod);

  cout << "Testing ref count" << endl;
  cout << "RefCount (should be 1): " << mod->get_ref_count() << endl;
  cout << "Retrieving module twice, again" << endl;
  mm.open_module("test_plugin.so");
  mm.open_module("test_plugin.so");
  cout << "RefCount (should be 3): " << mod->get_ref_count() << endl;
  cout << "Closing module twice" << endl;
  mm.close_module(mod);
  mm.close_module(mod);
  cout << "RefCount (should be 1): " << mod->get_ref_count() << endl;
  cout << "Finally closing module" << endl;
  mm.close_module(mod);
  if ( mm.module_opened("test_plugin.so") ) {
    cout << "Plugin still opened, bug!" << endl;
    success = false;
  } else {
    cout << "Plugin has been unloaded from module manager" << endl;
  }


  if ( success ) {
    cout << "SUCCESSFULLY tested module manager" << endl;
  } else {
    cout << "FAILED module manager tests, aborting further tests" << endl;
    return 2;
  }


  success = true;
  cout << endl << endl << "Running PluginLoader tests" << endl;
  PluginLoader *pl = new PluginLoader(PLUGINDIR, NULL);

  Plugin *p;
  try {
    p = pl->load("test_plugin");
    success = test_plugin(p);
    pl->unload(p);
    success = true;
  } catch (PluginLoadException &e) {
    cout << "Could not load plugin" << endl;
    e.print_trace();
    success = false;
  }

  delete pl;
  if ( success ) {
    cout << "SUCCESSFULLY tested PluginLoader" << endl;
  } else {
    cout << "FAILED module manager tests, aborting further tests" << endl;
    return 3;
  }

  return 0;
}
Exemplo n.º 18
0
bool VampEffectsModule::AutoRegisterPlugins(PluginManagerInterface & pm)
{
#ifdef EFFECT_CATEGORIES
   InitCategoryMap();
#endif

   PluginLoader *loader = PluginLoader::getInstance();

   EffectManager& em = EffectManager::Get();

   PluginLoader::PluginKeyList keys = loader->listPlugins();

   for (PluginLoader::PluginKeyList::iterator i = keys.begin();
        i != keys.end(); ++i) {

      Plugin *vp = loader->loadPlugin(*i, 48000); // rate doesn't matter here
      if (!vp) continue;

#ifdef EFFECT_CATEGORIES

      PluginLoader::PluginCategoryHierarchy category =
         loader->getPluginCategory(*i);
      wxString vampCategory = VampHierarchyToUri(category);

#endif

      // We limit the listed plugin outputs to those whose results can
      // readily be displayed in an Audacity label track.
      //
      // - Any output whose features have no values (time instants only),
      //   with or without duration, is fine
      //
      // - Any output whose features have more than one value, or an
      //   unknown or variable number of values, is right out
      //
      // - Any output whose features have exactly one value, with
      //   variable sample rate or with duration, should be OK --
      //   this implies a sparse feature, of which the time and/or
      //   duration are significant aspects worth displaying
      //
      // - An output whose features have exactly one value, with
      //   fixed sample rate and no duration, cannot be usefully
      //   displayed -- the value is the only significant piece of
      //   data there and we have no good value plot

      Plugin::OutputList outputs = vp->getOutputDescriptors();

      int n = 0;

      bool hasParameters = !vp->getParameterDescriptors().empty();

      for (Plugin::OutputList::iterator j = outputs.begin();
           j != outputs.end(); ++j) {

         if (j->sampleType == Plugin::OutputDescriptor::FixedSampleRate ||
             j->sampleType == Plugin::OutputDescriptor::OneSamplePerStep ||
             !j->hasFixedBinCount ||
             (j->hasFixedBinCount && j->binCount > 1)) {

            // All of these qualities disqualify (see notes above)

            ++n;
            continue;
         }

         wxString name = LAT1CTOWX(vp->getName().c_str());

         if (outputs.size() > 1) {
            // This is not the plugin's only output.
            // Use "plugin name: output name" as the effect name,
            // unless the output name is the same as the plugin name
            wxString outputName = LAT1CTOWX(j->name.c_str());
            if (outputName != name) {
               name = wxString::Format(wxT("%s: %s"),
                                       name.c_str(), outputName.c_str());
            }
         }

#ifdef EFFECT_CATEGORIES
         VampEffect *effect = new VampEffect(*i, n, hasParameters, name,
                                                vampCategory);
#else
         VampEffect *effect = new VampEffect(*i, n, hasParameters, name);
#endif
         em.RegisterEffect(this, effect);

         ++n;
      }

      delete vp;
   }

   return true;
}
Exemplo n.º 19
0
int runPlugin(string myname, string soname, string id,
              string output, int outputNo, string wavname,
              string outfilename, bool useFrames,
              map<string,float> parameters)
{
    PluginLoader *loader = PluginLoader::getInstance();

    PluginLoader::PluginKey key = loader->composePluginKey(soname, id);
    
    SNDFILE *sndfile;
    SF_INFO sfinfo;
    memset(&sfinfo, 0, sizeof(SF_INFO));

    if (wavname == "") 
        sndfile = sf_open_fd(0, SFM_READ, &sfinfo, true);
    else
        sndfile = sf_open(wavname.c_str(), SFM_READ, &sfinfo);
    if (!sndfile) {
        cerr << myname << ": ERROR: Failed to open input file \""
             << wavname << "\": " << sf_strerror(sndfile) << endl;
        return 1;
    }

    ofstream *out = 0;
    if (outfilename != "") {
        out = new ofstream(outfilename.c_str(), ios::out);
        if (!*out) {
            cerr << myname << ": ERROR: Failed to open output file \""
                 << outfilename << "\" for writing" << endl;
            delete out;
            return 1;
        }
    }

    Plugin *plugin = loader->loadPlugin
        (key, sfinfo.samplerate, PluginLoader::ADAPT_ALL_SAFE);
    if (!plugin) {
        cerr << myname << ": ERROR: Failed to load plugin \"" << id
             << "\" from library \"" << soname << "\"" << endl;
        sf_close(sndfile);
        if (out) {
            out->close();
            delete out;
        }
        return 1;
    }

    cerr << "Running plugin: \"" << plugin->getIdentifier() << "\"..." << endl;

    // parameters
    for (map<string,float>::iterator iter = parameters.begin(); iter!=parameters.end(); iter++) {
        plugin->setParameter(iter->first, iter->second);
        cerr << "Set parameter " << iter->first << " = " << iter->second << endl;
    }
  
    // Note that the following would be much simpler if we used a
    // PluginBufferingAdapter as well -- i.e. if we had passed
    // PluginLoader::ADAPT_ALL to loader->loadPlugin() above, instead
    // of ADAPT_ALL_SAFE.  Then we could simply specify our own block
    // size, keep the step size equal to the block size, and ignore
    // the plugin's bleatings.  However, there are some issues with
    // using a PluginBufferingAdapter that make the results sometimes
    // technically different from (if effectively the same as) the
    // un-adapted plugin, so we aren't doing that here.  See the
    // PluginBufferingAdapter documentation for details.

    int blockSize = plugin->getPreferredBlockSize();
    int stepSize = plugin->getPreferredStepSize();

    if (blockSize == 0) {
        blockSize = 1024;
    }
    if (stepSize == 0) {
        if (plugin->getInputDomain() == Plugin::FrequencyDomain) {
            stepSize = blockSize/2;
        } else {
            stepSize = blockSize;
        }
    } else if (stepSize > blockSize) {
        cerr << "WARNING: stepSize " << stepSize << " > blockSize " << blockSize << ", resetting blockSize to ";
        if (plugin->getInputDomain() == Plugin::FrequencyDomain) {
            blockSize = stepSize * 2;
        } else {
            blockSize = stepSize;
        }
        cerr << blockSize << endl;
    }
    int overlapSize = blockSize - stepSize;
    sf_count_t currentStep = 0;
    int finalStepsRemaining = max(1, (blockSize / stepSize) - 1); // at end of file, this many part-silent frames needed after we hit EOF

    int channels = sfinfo.channels;

    float *filebuf = new float[blockSize * channels];
    float **plugbuf = new float*[channels];
    for (int c = 0; c < channels; ++c) plugbuf[c] = new float[blockSize + 2];

    cerr << "Using block size = " << blockSize << ", step size = "
              << stepSize << endl;

    // The channel queries here are for informational purposes only --
    // a PluginChannelAdapter is being used automatically behind the
    // scenes, and it will take case of any channel mismatch

    int minch = plugin->getMinChannelCount();
    int maxch = plugin->getMaxChannelCount();
    cerr << "Plugin accepts " << minch << " -> " << maxch << " channel(s)" << endl;
    cerr << "Sound file has " << channels << " (will mix/augment if necessary)" << endl;

    Plugin::OutputList outputs = plugin->getOutputDescriptors();
    Plugin::OutputDescriptor od;

    int returnValue = 1;
    int progress = 0;

    RealTime rt;
    PluginWrapper *wrapper = 0;
    RealTime adjustment = RealTime::zeroTime;

    if (outputs.empty()) {
        cerr << "ERROR: Plugin has no outputs!" << endl;
        goto done;
    }

    if (outputNo < 0) {

        for (size_t oi = 0; oi < outputs.size(); ++oi) {
            if (outputs[oi].identifier == output) {
                outputNo = oi;
                break;
            }
        }

        if (outputNo < 0) {
            cerr << "ERROR: Non-existent output \"" << output << "\" requested" << endl;
            goto done;
        }

    } else {

        if (int(outputs.size()) <= outputNo) {
            cerr << "ERROR: Output " << outputNo << " requested, but plugin has only " << outputs.size() << " output(s)" << endl;
            goto done;
        }        
    }

    od = outputs[outputNo];
    cerr << "Output is: \"" << od.identifier << "\"" << endl;

    if (!plugin->initialise(channels, stepSize, blockSize)) {
        cerr << "ERROR: Plugin initialise (channels = " << channels
             << ", stepSize = " << stepSize << ", blockSize = "
             << blockSize << ") failed." << endl;
        goto done;
    }

    wrapper = dynamic_cast<PluginWrapper *>(plugin);
    if (wrapper) {
        // See documentation for
        // PluginInputDomainAdapter::getTimestampAdjustment
        PluginInputDomainAdapter *ida =
            wrapper->getWrapper<PluginInputDomainAdapter>();
        if (ida) adjustment = ida->getTimestampAdjustment();
    }
    
    // Here we iterate over the frames, avoiding asking the numframes in case it's streaming input.
    do {

        int count;

        if ((blockSize==stepSize) || (currentStep==0)) {
            // read a full fresh block
            if ((count = sf_readf_float(sndfile, filebuf, blockSize)) < 0) {
                cerr << "ERROR: sf_readf_float failed: " << sf_strerror(sndfile) << endl;
                break;
            }
            if (count != blockSize) --finalStepsRemaining;
        } else {
            //  otherwise shunt the existing data down and read the remainder.
            memmove(filebuf, filebuf + (stepSize * channels), overlapSize * channels * sizeof(float));
            if ((count = sf_readf_float(sndfile, filebuf + (overlapSize * channels), stepSize)) < 0) {
                cerr << "ERROR: sf_readf_float failed: " << sf_strerror(sndfile) << endl;
                break;
            }
            if (count != stepSize) --finalStepsRemaining;
            count += overlapSize;
        }

        for (int c = 0; c < channels; ++c) {
            int j = 0;
            while (j < count) {
                plugbuf[c][j] = filebuf[j * sfinfo.channels + c];
                ++j;
            }
            while (j < blockSize) {
                plugbuf[c][j] = 0.0f;
                ++j;
            }
        }

        rt = RealTime::frame2RealTime(currentStep * stepSize, sfinfo.samplerate);

        printFeatures
            (RealTime::realTime2Frame(rt + adjustment, sfinfo.samplerate),
             sfinfo.samplerate, outputNo, plugin->process(plugbuf, rt),
             out, useFrames);

        if (sfinfo.frames > 0){
            int pp = progress;
            progress = (int)((float(currentStep * stepSize) / sfinfo.frames) * 100.f + 0.5f);
            if (progress != pp && out) {
                cerr << "\r" << progress << "%";
            }
        }

        ++currentStep;

    } while (finalStepsRemaining > 0);

    if (out) cerr << "\rDone" << endl;

    rt = RealTime::frame2RealTime(currentStep * stepSize, sfinfo.samplerate);

    printFeatures(RealTime::realTime2Frame(rt + adjustment, sfinfo.samplerate),
                  sfinfo.samplerate, outputNo,
                  plugin->getRemainingFeatures(), out, useFrames);

    returnValue = 0;

done:
    delete plugin;
    if (out) {
        out->close();
        delete out;
    }
    sf_close(sndfile);
    return returnValue;
}
Exemplo n.º 20
0
//**********MAIN**************************************************************************
int main(int argc, char* argv[])
{
    if(argc < 2)
    {
        cout << argv[0] << " cfg file " << "[run]" << endl; 
        return -1;
    }

    //---memory consumption tracking---
    float cpu[2]{0}, mem[2]={0}, vsz[2]={0}, rss[2]={0};

    //---load options---    
    CfgManager opts;
    opts.ParseConfigFile(argv[1]);

    //-----input setup-----    
    if(argc > 2)
    {
        vector<string> run(1, argv[2]);
        opts.SetOpt("h4reco.run", run);
    }
    string outSuffix = opts.GetOpt<string>("h4reco.outNameSuffix");
    string run = opts.GetOpt<string>("h4reco.run");
    TChain* inTree = new TChain("H4tree");
    ReadInputFiles(opts, inTree);
    H4Tree h4Tree(inTree);

    //-----output setup-----
    uint64 index=stoul(run)*1e9;
    TFile* outROOT = new TFile("ntuples/"+outSuffix+TString(run)+".root", "RECREATE");
    outROOT->cd();
    RecoTree mainTree(&index);

    //---Get plugin sequence---
    PluginLoader<PluginBase>* loader;
    vector<PluginLoader<PluginBase>* > pluginLoaders;    
    map<string, PluginBase*> pluginMap;
    vector<PluginBase*> pluginSequence;
    vector<string> pluginList = opts.GetOpt<vector<string> >("h4reco.pluginList");    
    //---plugin creation
    pluginLoaders.reserve(pluginList.size());
    for(auto& plugin : pluginList)
    {
        cout << ">>> Loading plugin <" << plugin << ">" << endl;
        //---create loader 
        loader = new PluginLoader<PluginBase>(opts.GetOpt<string>(plugin+".pluginType"));
        pluginLoaders.push_back(loader);
        pluginLoaders.back()->Create();
        //---get instance and put it in the plugin sequence   
        PluginBase* newPlugin = pluginLoaders.back()->CreateInstance();
        if(newPlugin)
        {
            pluginSequence.push_back(newPlugin);
            pluginSequence.back()->SetInstanceName(plugin);
            pluginMap[plugin] = pluginSequence.back();
        }
        else
        {
            cout << ">>> ERROR: plugin type " << opts.GetOpt<string>(plugin+".pluginType") << " is not defined." << endl;
            return 0;
        }
    }

    //---begin
    for(auto& plugin : pluginSequence)
    {
        plugin->Begin(opts, &index);
        for(auto& shared : plugin->GetSharedData("", "TTree", true))
        {
            TTree* tree = (TTree*)shared.obj;
            tree->SetMaxVirtualSize(10000);
            tree->SetDirectory(outROOT);
        }
    }
            
    //---events loop
    int maxEvents=opts.GetOpt<int>("h4reco.maxEvents");
    cout << ">>> Processing H4DAQ run #" << run << " <<<" << endl;
    while(h4Tree.NextEntry() && (index-stoul(run)*1e9<maxEvents || maxEvents==-1))
    {
        if(index % 1000 == 0)
        {
            cout << ">>>Processed events: " << index-stoul(run)*1e9 << "/"
                 << (maxEvents<0 ? h4Tree.GetEntries() : min((int)h4Tree.GetEntries(), maxEvents))
                 << endl;
            TrackProcess(cpu, mem, vsz, rss);
        }

        //---call ProcessEvent for each plugin
        for(auto& plugin : pluginSequence)
            plugin->ProcessEvent(h4Tree, pluginMap, opts);

        //---fill the main tree with info variables and increase event counter
        mainTree.time_stamp = h4Tree.evtTimeStart;
        mainTree.run = h4Tree.runNumber;
        mainTree.spill = h4Tree.spillNumber;
        mainTree.event = h4Tree.evtNumber;
        mainTree.Fill();
        ++index;
    }

    //---end
    for(auto& plugin : pluginSequence)
    {
        //---call endjob for each plugin
        plugin->End(opts);
        //---get permanent data from each plugin and store them in the out file
        for(auto& shared : plugin->GetSharedData())
        {
            if(shared.obj->IsA()->GetName() == string("TTree"))
            {
                TTree* currentTree = (TTree*)shared.obj;
                outROOT->cd();
                currentTree->BuildIndex("index");
                currentTree->Write(currentTree->GetName(), TObject::kOverwrite);
                mainTree.AddFriend(currentTree->GetName());
            }
            else
            {
                outROOT->cd();
                shared.obj->Write(shared.tag.c_str(), TObject::kOverwrite);
            }
        }
    }
    
    //---close
    mainTree.Write();
    opts.Write("cfg");
    outROOT->Close();
    for(auto& loader : pluginLoaders)
        loader->Destroy();

    //---info
    TrackProcess(cpu, mem, vsz, rss);

    exit(0);
}