--- linuxsampler/trunk/src/linuxsampler.cpp 2004/02/16 19:30:42 33 +++ linuxsampler/trunk/src/linuxsampler.cpp 2007/04/16 15:51:18 1161 @@ -2,7 +2,8 @@ * * * LinuxSampler - modular, streaming capable sampler * * * - * Copyright (C) 2003 by Benno Senoner and Christian Schoenebeck * + * Copyright (C) 2003-2004 by Benno Senoner and Christian Schoenebeck * + * Copyright (C) 2005-2007 Christian Schoenebeck * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * @@ -20,175 +21,211 @@ * MA 02111-1307 USA * ***************************************************************************/ -#include -#include -#include #include #include -#include -#include "global.h" -#include "diskthread.h" -#include "audiothread.h" -#include "alsaio.h" -#include "jackio.h" -#include "midiin.h" -#include "stream.h" -#include "RIFF.h" -#include "gig.h" - -#define AUDIO_CHANNELS 2 // stereo -#define AUDIO_FRAGMENTS 3 // 3 fragments, if it does not work set it to 2 -#define AUDIO_FRAGMENTSIZE 512 // each fragment has 512 frames -#define AUDIO_SAMPLERATE 44100 // Hz - -enum patch_format_t { - patch_format_unknown, - patch_format_gig, - patch_format_dls -} patch_format; - -AudioIO* pAudioIO; -DiskThread* pDiskThread; -AudioThread* pAudioThread; -MidiIn* pMidiInThread; -RIFF::File* pRIFF; -gig::File* pGig; -gig::Instrument* pInstrument; -uint instrument_index; -double volume; -int num_fragments; -int fragmentsize; -String input_client; -String alsaout; -String jack_playback[2]; -bool use_jack; -pthread_t signalhandlerthread; -uint samplerate; +#include "Sampler.h" +#include "engines/EngineFactory.h" +#include "drivers/midi/MidiInputDeviceFactory.h" +#include "drivers/audio/AudioOutputDeviceFactory.h" +#include "engines/gig/Profiler.h" +#include "network/lscpserver.h" +#include "common/stacktrace.h" +#include "common/Features.h" + +using namespace LinuxSampler; + +Sampler* pSampler = NULL; +LSCPServer* pLSCPServer = NULL; +pthread_t main_thread; +pid_t main_pid; +bool bPrintStatistics = false; +bool profile = false; +bool tune = true; +unsigned long int lscp_addr; +unsigned short int lscp_port; void parse_options(int argc, char **argv); void signal_handler(int signal); +void kill_app(); int main(int argc, char **argv) { - pAudioIO = NULL; - pRIFF = NULL; - pGig = NULL; + + // initialize the stack trace mechanism with our binary file + StackTraceInit(argv[0], -1); + + main_pid = getpid(); + main_thread = pthread_self(); // setting signal handler for catching SIGINT (thus e.g. ) - signalhandlerthread = pthread_self(); signal(SIGINT, signal_handler); - patch_format = patch_format_unknown; - instrument_index = 0; - num_fragments = AUDIO_FRAGMENTS; - fragmentsize = AUDIO_FRAGMENTSIZE; - volume = 0.25; // default volume - alsaout = "0,0"; // default card - jack_playback[0] = ""; - jack_playback[1] = ""; - samplerate = AUDIO_SAMPLERATE; - use_jack = true; + // register signal handler for all unusual signals + // (we will print the stack trace and exit) + struct sigaction sact; + sigemptyset(&sact.sa_mask); + sact.sa_flags = 0; + sact.sa_handler = signal_handler; + sigaction(SIGSEGV, &sact, NULL); + sigaction(SIGBUS, &sact, NULL); + sigaction(SIGILL, &sact, NULL); + sigaction(SIGFPE, &sact, NULL); + sigaction(SIGUSR1, &sact, NULL); + sigaction(SIGUSR2, &sact, NULL); + + lscp_addr = htonl(LSCP_ADDR); + lscp_port = htons(LSCP_PORT); // parse and assign command line options parse_options(argc, argv); - if (patch_format != patch_format_gig) { - printf("Sorry only Gigasampler loading migrated in LinuxSampler so far, use --gig to load a .gig file!\n"); - printf("Use 'linuxsampler --help' to see all available options.\n"); - return EXIT_FAILURE; + dmsg(1,("LinuxSampler %s\n", VERSION)); + dmsg(1,("Copyright (C) 2003,2004 by Benno Senoner and Christian Schoenebeck\n")); + dmsg(1,("Copyright (C) 2005-2007 Christian Schoenebeck\n")); + + if (tune) { + // detect and print system / CPU specific features + Features::detect(); + dmsg(1,("Detected features: %s\n", Features::featuresAsString().c_str())); + // prevent slow denormal FPU modes + Features::enableDenormalsAreZeroMode(); } - int error = 1; -#if HAVE_JACK - if (use_jack) { - dmsg(1,("Initializing audio output (Jack)...")); - pAudioIO = new JackIO(); - error = ((JackIO*)pAudioIO)->Initialize(AUDIO_CHANNELS, jack_playback); - if (error) dmsg(1,("Trying Alsa output instead.\n")); - } -#endif // HAVE_JACK - if (error) { - dmsg(1,("Initializing audio output (Alsa)...")); - pAudioIO = new AlsaIO(); - int error = ((AlsaIO*)pAudioIO)->Initialize(AUDIO_CHANNELS, samplerate, num_fragments, fragmentsize, alsaout); - if (error) return EXIT_FAILURE; - } + // create LinuxSampler instance + dmsg(1,("Creating Sampler...")); + pSampler = new Sampler; dmsg(1,("OK\n")); - // Loading gig file - try { - printf("Loading gig file..."); - fflush(stdout); - pRIFF = new RIFF::File(argv[argc - 1]); - pGig = new gig::File(pRIFF); - pInstrument = pGig->GetInstrument(instrument_index); - if (!pInstrument) { - printf("there's no instrument with index %d.\n", instrument_index); - exit(EXIT_FAILURE); - } - pGig->GetFirstSample(); // just to complete instrument loading before we enter the realtime part - printf("OK\n"); - fflush(stdout); - } - catch (RIFF::Exception e) { - e.PrintMessage(); - return EXIT_FAILURE; - } - catch (...) { - printf("Unknown exception while trying to parse gig file.\n"); - return EXIT_FAILURE; + dmsg(1,("Registered sampler engines: %s\n", EngineFactory::AvailableEngineTypesAsString().c_str())); + dmsg(1,("Registered MIDI input drivers: %s\n", MidiInputDeviceFactory::AvailableDriversAsString().c_str())); + dmsg(1,("Registered audio output drivers: %s\n", AudioOutputDeviceFactory::AvailableDriversAsString().c_str())); + + // start LSCP network server + struct in_addr addr; + addr.s_addr = lscp_addr; + dmsg(1,("Starting LSCP network server (%s:%d)...", inet_ntoa(addr), ntohs(lscp_port))); + pLSCPServer = new LSCPServer(pSampler, lscp_addr, lscp_port); + pLSCPServer->StartThread(); + pLSCPServer->WaitUntilInitialized(); + dmsg(1,("OK\n")); + + if (profile) + { + dmsg(1,("Calibrating profiler...")); + LinuxSampler::gig::Profiler::Calibrate(); + LinuxSampler::gig::Profiler::Reset(); + LinuxSampler::gig::Profiler::enable(); + dmsg(1,("OK\n")); } - DiskThread* pDiskThread = new DiskThread(((pAudioIO->MaxSamplesPerCycle() << MAX_PITCH) << 1) + 6); //FIXME: assuming stereo - AudioThread* pAudioThread = new AudioThread(pAudioIO, pDiskThread, pInstrument); - MidiIn* pMidiInThread = new MidiIn(pAudioThread); + printf("LinuxSampler initialization completed. :-)\n\n"); - dmsg(1,("Starting disk thread...")); - pDiskThread->StartThread(); - dmsg(1,("OK\n")); - dmsg(1,("Starting MIDI in thread...")); - if (input_client.size() > 0) pMidiInThread->SubscribeToClient(input_client.c_str()); - pMidiInThread->StartThread(); - dmsg(1,("OK\n")); + std::list rtEvents; + rtEvents.push_back(LSCPEvent::event_voice_count); + rtEvents.push_back(LSCPEvent::event_stream_count); + rtEvents.push_back(LSCPEvent::event_buffer_fill); + rtEvents.push_back(LSCPEvent::event_total_voice_count); - sleep(1); - dmsg(1,("Starting audio thread...")); - pAudioThread->Volume = volume; - pAudioIO->AssignEngine(pAudioThread); - pAudioIO->Activate(); - dmsg(1,("OK\n")); + while (true) { + if (bPrintStatistics) { + const std::set& engines = EngineFactory::EngineInstances(); + std::set::iterator itEngine = engines.begin(); + for (int i = 0; itEngine != engines.end(); itEngine++, i++) { + Engine* pEngine = *itEngine; + printf("Engine %d) Voices: %3.3d (Max: %3.3d) Streams: %3.3d (Max: %3.3d)\n", i, + pEngine->VoiceCount(), pEngine->VoiceCountMax(), + pEngine->DiskStreamCount(), pEngine->DiskStreamCountMax() + ); + fflush(stdout); + } + } - printf("LinuxSampler initialization completed.\n"); + sleep(1); + if (profile) + { + unsigned int samplingFreq = 48000; //FIXME: hardcoded for now + unsigned int bv = LinuxSampler::gig::Profiler::GetBogoVoices(samplingFreq); + if (bv != 0) + { + printf(" BogoVoices: %i \r", bv); + fflush(stdout); + } + } + + if (LSCPServer::EventSubscribers(rtEvents)) + { + LSCPServer::LockRTNotify(); + std::map channels = pSampler->GetSamplerChannels(); + std::map::iterator iter = channels.begin(); + for (; iter != channels.end(); iter++) { + SamplerChannel* pSamplerChannel = iter->second; + EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel(); + if (!pEngineChannel) continue; + Engine* pEngine = pEngineChannel->GetEngine(); + if (!pEngine) continue; + pSampler->fireVoiceCountChanged(iter->first, pEngine->VoiceCount()); + pSampler->fireStreamCountChanged(iter->first, pEngine->DiskStreamCount()); + pSampler->fireBufferFillChanged(iter->first, pEngine->DiskStreamBufferFillPercentage()); + pSampler->fireTotalVoiceCountChanged(pSampler->GetVoiceCount()); + } + LSCPServer::UnlockRTNotify(); + } - while(true) { - printf("Voices: %3.3d (Max: %3.3d) Streams: %3.3d (Max: %3.3d, Unused: %3.3d)\r", - pAudioThread->ActiveVoiceCount, pAudioThread->ActiveVoiceCountMax, - pDiskThread->ActiveStreamCount, pDiskThread->ActiveStreamCountMax, Stream::GetUnusedStreams()); - fflush(stdout); - usleep(500000); } return EXIT_SUCCESS; } -void signal_handler(int signal) { - if (pthread_equal(pthread_self(), signalhandlerthread) && signal == SIGINT) { - // stop all threads - if (pAudioIO) pAudioIO->Close(); - if (pMidiInThread) pMidiInThread->StopThread(); - if (pDiskThread) pDiskThread->StopThread(); - - // free all resources - if (pMidiInThread) delete pMidiInThread; - if (pAudioThread) delete pAudioThread; - if (pDiskThread) delete pDiskThread; - if (pGig) delete pGig; - if (pRIFF) delete pRIFF; - if (pAudioIO) delete pAudioIO; - - printf("LinuxSampler stopped due to SIGINT\n"); - exit(EXIT_SUCCESS); +void signal_handler(int iSignal) { + switch (iSignal) { + case SIGINT: { + if (pthread_equal(pthread_self(), main_thread)) { + if (pLSCPServer) { + pLSCPServer->StopThread(); + delete pLSCPServer; + } + if (pSampler) delete pSampler; +#if HAVE_SQLITE3 + InstrumentsDb::Destroy(); +#endif + printf("LinuxSampler stopped due to SIGINT.\n"); + exit(EXIT_SUCCESS); + } + return; + } + case SIGSEGV: + std::cerr << ">>> FATAL ERROR: Segmentation fault (SIGSEGV) occured! <<<\n" << std::flush; + break; + case SIGBUS: + std::cerr << ">>> FATAL ERROR: Access to undefined portion of a memory object (SIGBUS) occured! <<<\n" << std::flush; + break; + case SIGILL: + std::cerr << ">>> FATAL ERROR: Illegal instruction (SIGILL) occured! <<<\n" << std::flush; + break; + case SIGFPE: + std::cerr << ">>> FATAL ERROR: Erroneous arithmetic operation (SIGFPE) occured! <<<\n" << std::flush; + break; + case SIGUSR1: + std::cerr << ">>> User defined signal 1 (SIGUSR1) received <<<\n" << std::flush; + break; + case SIGUSR2: + std::cerr << ">>> User defined signal 2 (SIGUSR2) received <<<\n" << std::flush; + break; + default: { // this should never happen, as we register for the signals we want + std::cerr << ">>> FATAL ERROR: Unknown signal received! <<<\n" << std::flush; + break; + } } + signal(iSignal, SIG_DFL); // Reinstall default handler to prevent race conditions + std::cerr << "Showing stack trace...\n" << std::flush; + StackTrace(); + sleep(2); + std::cerr << "Killing LinuxSampler...\n" << std::flush; + kill_app(); // Use abort() if we want to generate a core dump. +} + +void kill_app() { + kill(main_pid, SIGKILL); } void parse_options(int argc, char **argv) { @@ -196,94 +233,62 @@ int option_index = 0; static struct option long_options[] = { - {"numfragments",1,0,0}, - {"fragmentsize",1,0,0}, - {"volume",1,0,0}, - {"dls",0,0,0}, - {"gig",0,0,0}, - {"instrument",1,0,0}, - {"inputclient",1,0,0}, - {"alsaout",1,0,0}, - {"jackout",1,0,0}, - {"samplerate",1,0,0}, {"help",0,0,0}, + {"version",0,0,0}, + {"profile",0,0,0}, + {"no-tune",0,0,0}, + {"statistics",0,0,0}, + {"lscp-addr",1,0,0}, + {"lscp-port",1,0,0}, {0,0,0,0} }; while (true) { - res = getopt_long_only(argc, argv, "", long_options, &option_index); + /* + Stephane Letz : letz@grame.fr + getopt_long_only does not exist on OSX : replaced by getopt_long for now. + */ + res = getopt_long(argc, argv, "", long_options, &option_index); if(res == -1) break; if (res == 0) { switch(option_index) { - case 0: // --numfragments - num_fragments = atoi(optarg); - break; - case 1: // --fragmentsize - fragmentsize = atoi(optarg); - break; - case 2: // --volume - volume = atof(optarg); - break; - case 3: // --dls - patch_format = patch_format_dls; - break; - case 4: // --gig - patch_format = patch_format_gig; - break; - case 5: // --instrument - instrument_index = atoi(optarg); + case 0: // --help + printf("usage: linuxsampler [OPTIONS]\n\n"); + printf("--help prints this message\n"); + printf("--version prints version information\n"); + printf("--profile profile synthesis algorithms\n"); + printf("--no-tune disable assembly optimization\n"); + printf("--statistics periodically prints statistics\n"); + printf("--lscp-addr set LSCP address (default: any)\n"); + printf("--lscp-port set LSCP port (default: 8888)\n"); + exit(EXIT_SUCCESS); break; - case 6: // --inputclient - input_client = optarg; + case 1: // --version + printf("LinuxSampler %s\n", VERSION); + exit(EXIT_SUCCESS); break; - case 7: // --alsaout - alsaout = optarg; - use_jack = false; // If this option is specified do not connect to jack + case 2: // --profile + profile = true; break; - case 8: { // --jackout - try { - String arg(optarg); - // remove outer apostrophes - arg = arg.substr(arg.find('\'') + 1, arg.rfind('\'') - (arg.find('\'') + 1)); - // split in two arguments - jack_playback[0] = arg.substr(0, arg.find("\' ")); - jack_playback[1] = arg.substr(arg.find("\' ") + 2, arg.size() - (arg.find("\' ") + 2)); - // remove inner apostrophes - jack_playback[0] = jack_playback[0].substr(0, jack_playback[0].find('\'')); - jack_playback[1] = jack_playback[1].substr(jack_playback[1].find('\'') + 1, jack_playback[1].size() - jack_playback[1].find('\'')); - // this is the default but set it up anyway in case alsa_card was also used. - use_jack = true; - } - catch (...) { - fprintf(stderr, "Invalid argument '%s' for parameter --jackout\n", optarg); - exit(EXIT_FAILURE); - } + case 3: // --no-tune + tune = false; break; - } - case 9: // --samplerate - samplerate = atoi(optarg); + case 4: // --statistics + bPrintStatistics = true; break; - case 10: // --help - printf("usage: linuxsampler [OPTIONS] \n\n"); - printf("--gig loads a Gigasampler instrument\n"); - printf("--dls loads a DLS instrument\n"); - printf("--instrument index of the instrument in the instrument file if it\n"); - printf(" contains more than one (default: 0)\n"); - printf("--numfragments sets the number of audio fragments\n"); - printf("--fragmentsize sets the fragment size\n"); - printf("--volume sets global volume gain factor (a value > 1.0 means\n"); - printf(" amplification, a value < 1.0 means attenuation,\n"); - printf(" default: 0.25)\n"); - printf("--inputclient connects to an Alsa sequencer input client on startup\n"); - printf(" (e.g. 64:0 to connect to a client with ID 64 and port 0)\n"); - printf("--alsaout connects to the given Alsa sound device on startup\n"); - printf(" (e.g. 0,0 to connect to hw:0,0 or plughw:0,0)\n"); - printf("--jackout connects to the given Jack playback ports on startup\n"); - printf(" (e.g. \"\'alsa_pcm:playback_1\' \'alsa_pcm:playback_2\'\"\n"); - printf(" in case of stereo output)\n"); - printf("--samplerate sets sample rate if supported by audio output system\n"); - printf(" (e.g. 44100)\n"); - exit(EXIT_SUCCESS); + case 5: // --lscp-addr + struct in_addr addr; + if (inet_aton(optarg, &addr) == 0) + printf("WARNING: Failed to parse lscp-addr argument, ignoring!\n"); + else + lscp_addr = addr.s_addr; + break; + case 6: // --lscp-port + long unsigned int port = 0; + if ((sscanf(optarg, "%u", &port) != 1) || (port == 0) || (port > 65535)) + printf("WARNING: Failed to parse lscp-port argument, ignoring!\n"); + else + lscp_port = htons(port); break; } }