/[svn]/linuxsampler/trunk/src/linuxsampler.cpp
ViewVC logotype

Diff of /linuxsampler/trunk/src/linuxsampler.cpp

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 35 by schoenebeck, Fri Mar 5 13:46:15 2004 UTC revision 411 by schoenebeck, Sat Feb 26 02:01:14 2005 UTC
# Line 2  Line 2 
2   *                                                                         *   *                                                                         *
3   *   LinuxSampler - modular, streaming capable sampler                     *   *   LinuxSampler - modular, streaming capable sampler                     *
4   *                                                                         *   *                                                                         *
5   *   Copyright (C) 2003 by Benno Senoner and Christian Schoenebeck         *   *   Copyright (C) 2003, 2004 by Benno Senoner and Christian Schoenebeck   *
6     *   Copyright (C) 2005 Christian Schoenebeck                              *
7   *                                                                         *   *                                                                         *
8   *   This program is free software; you can redistribute it and/or modify  *   *   This program is free software; you can redistribute it and/or modify  *
9   *   it under the terms of the GNU General Public License as published by  *   *   it under the terms of the GNU General Public License as published by  *
# Line 20  Line 21 
21   *   MA  02111-1307  USA                                                   *   *   MA  02111-1307  USA                                                   *
22   ***************************************************************************/   ***************************************************************************/
23    
 #include <stdio.h>  
 #include <stdlib.h>  
 #include <unistd.h>  
24  #include <getopt.h>  #include <getopt.h>
25  #include <signal.h>  #include <signal.h>
 #include <pthread.h>  
26    
27  #include "global.h"  #include "Sampler.h"
28  #include "diskthread.h"  #include "drivers/midi/MidiInputDeviceFactory.h"
29  #include "audiothread.h"  #include "drivers/audio/AudioOutputDeviceFactory.h"
30  #include "alsaio.h"  #include "engines/gig/Profiler.h"
 #include "jackio.h"  
 #include "midiin.h"  
 #include "stream.h"  
 #include "RIFF.h"  
 #include "gig.h"  
31  #include "network/lscpserver.h"  #include "network/lscpserver.h"
32    #include "common/stacktrace.h"
33    #include "common/Features.h"
34    
35  #define AUDIO_CHANNELS          2     // stereo  using namespace LinuxSampler;
36  #define AUDIO_FRAGMENTS         3     // 3 fragments, if it does not work set it to 2  
37  #define AUDIO_FRAGMENTSIZE      512   // each fragment has 512 frames  Sampler*    pSampler    = NULL;
38  #define AUDIO_SAMPLERATE        44100 // Hz  LSCPServer* pLSCPServer = NULL;
39    pthread_t   main_thread;
40  enum patch_format_t {  bool profile = false;
41      patch_format_unknown,  bool tune = true;
     patch_format_gig,  
     patch_format_dls  
 } patch_format = patch_format_unknown;  
   
 AudioIO*     pAudioIO         = NULL;  
 MidiIn*      pMidiInThread    = NULL;  
 LSCPServer*  pLSCPServer      = NULL;  
 AudioThread* pEngine          = NULL;  
 uint         instrument_index = 0;  
 double       volume           = 0.25;  
 int          num_fragments    = AUDIO_FRAGMENTS;  
 int          fragmentsize     = AUDIO_FRAGMENTSIZE;  
 uint         samplerate       = AUDIO_SAMPLERATE;  
 String       input_client;  
 String       alsaout          = "0,0"; // default card  
 String       jack_playback[2] = { "", "" };  
 bool         use_jack         = true;  
 bool         run_server       = false;  
 pthread_t    signalhandlerthread;  
42    
43  void parse_options(int argc, char **argv);  void parse_options(int argc, char **argv);
44  void signal_handler(int signal);  void signal_handler(int signal);
45    void kill_app();
46    
47  int main(int argc, char **argv) {  int main(int argc, char **argv) {
48    
49        // initialize the stack trace mechanism with our binary file
50        StackTraceInit(argv[0], -1);
51    
52        main_thread = pthread_self();
53    
54      // setting signal handler for catching SIGINT (thus e.g. <CTRL><C>)      // setting signal handler for catching SIGINT (thus e.g. <CTRL><C>)
     signalhandlerthread = pthread_self();  
55      signal(SIGINT, signal_handler);      signal(SIGINT, signal_handler);
56    
57        // register signal handler for all unusual signals
58        // (we will print the stack trace and exit)
59        struct sigaction sact;
60        sigemptyset(&sact.sa_mask);
61        sact.sa_flags   = 0;
62        sact.sa_handler = signal_handler;
63        sigaction(SIGSEGV, &sact, NULL);
64        sigaction(SIGBUS,  &sact, NULL);
65        sigaction(SIGILL,  &sact, NULL);
66        sigaction(SIGFPE,  &sact, NULL);
67        sigaction(SIGUSR1, &sact, NULL);
68        sigaction(SIGUSR2, &sact, NULL);
69    
70      // parse and assign command line options      // parse and assign command line options
71      parse_options(argc, argv);      parse_options(argc, argv);
72    
73      if (patch_format != patch_format_gig) {      dmsg(1,("LinuxSampler %s\n", VERSION));
74          printf("Sorry only Gigasampler loading migrated in LinuxSampler so far, use --gig to load a .gig file!\n");      dmsg(1,("Copyright (C) 2003, 2004 by Benno Senoner and Christian Schoenebeck\n"));
75          printf("Use 'linuxsampler --help' to see all available options.\n");      dmsg(1,("Copyright (C) 2005 Christian Schoenebeck\n"));
76          return EXIT_FAILURE;  
77      }      if (tune)
78        {
79      int error = 1;              // detect and print system / CPU specific features
80  #if HAVE_JACK              String sFeatures;
81      if (use_jack) {              Features::detect();
82          dmsg(1,("Initializing audio output (Jack)..."));  #if ARCH_X86
83          pAudioIO = new JackIO();              if (Features::supportsMMX()) sFeatures += " MMX";
84          error = ((JackIO*)pAudioIO)->Initialize(AUDIO_CHANNELS, jack_playback);              if (Features::supportsSSE()) sFeatures += " SSE";
85          if (error) dmsg(1,("Trying Alsa output instead.\n"));  #endif // ARCH_X86
86      }              if (!sFeatures.size()) sFeatures = " None";
87  #endif // HAVE_JACK              dmsg(1,("Detected features:%s\n",sFeatures.c_str()));
88      if (error) {      }
89          dmsg(1,("Initializing audio output (Alsa)..."));  
90          pAudioIO = new AlsaIO();      // create LinuxSampler instance
91          int error = ((AlsaIO*)pAudioIO)->Initialize(AUDIO_CHANNELS, samplerate, num_fragments, fragmentsize, alsaout);      dmsg(1,("Creating Sampler..."));
92          if (error) return EXIT_FAILURE;      pSampler = new Sampler;
     }  
     dmsg(1,("OK\n"));  
   
     AudioThread* pEngine       = new AudioThread(pAudioIO);  
     MidiIn*      pMidiInThread = new MidiIn(pEngine);  
   
     // Loading gig file  
     result_t result = pEngine->LoadInstrument(argv[argc - 1], instrument_index);  
     if (result.type == result_type_error) return EXIT_FAILURE;  
     pEngine->Volume = volume;  
   
     dmsg(1,("Starting MIDI in thread..."));  
     if (input_client.size() > 0) pMidiInThread->SubscribeToClient(input_client.c_str());  
     pMidiInThread->StartThread();  
93      dmsg(1,("OK\n"));      dmsg(1,("OK\n"));
94    
95      sleep(1);      dmsg(1,("Registered MIDI input drivers: %s\n", MidiInputDeviceFactory::AvailableDriversAsString().c_str()));
96        dmsg(1,("Registered audio output drivers: %s\n", AudioOutputDeviceFactory::AvailableDriversAsString().c_str()));
97    
98      dmsg(1,("Starting audio thread..."));      // start LSCP network server
99      pAudioIO->AssignEngine(pEngine);      dmsg(1,("Starting LSCP network server (on TCP port %d)...", LSCP_PORT));
100      pAudioIO->Activate();      pLSCPServer = new LSCPServer(pSampler);
101        pLSCPServer->StartThread();
102        pLSCPServer->WaitUntilInitialized();
103      dmsg(1,("OK\n"));      dmsg(1,("OK\n"));
104    
105      if (run_server) {      if (profile)
106          dmsg(1,("Starting network server..."));      {
107          pLSCPServer = new LSCPServer(pEngine);              dmsg(1,("Calibrating profiler..."));
108          pLSCPServer->StartThread();              gig::Profiler::Calibrate();
109          dmsg(1,("OK\n"));              gig::Profiler::Reset();
110                dmsg(1,("OK\n"));
111      }      }
112    
113      printf("LinuxSampler initialization completed.\n");      printf("LinuxSampler initialization completed.\n");
114    
115      while(true)  {      std::list<LSCPEvent::event_t> rtEvents;
116        printf("Voices: %3.3d (Max: %3.3d) Streams: %3.3d (Max: %3.3d, Unused: %3.3d)\r",      rtEvents.push_back(LSCPEvent::event_voice_count);
117        rtEvents.push_back(LSCPEvent::event_stream_count);
118        rtEvents.push_back(LSCPEvent::event_buffer_fill);
119    
120        while(true)
121        {
122          /*printf("Voices: %3.3d (Max: %3.3d) Streams: %3.3d (Max: %3.3d, Unused: %3.3d)\r",
123              pEngine->ActiveVoiceCount, pEngine->ActiveVoiceCountMax,              pEngine->ActiveVoiceCount, pEngine->ActiveVoiceCountMax,
124              pEngine->pDiskThread->ActiveStreamCount, pEngine->pDiskThread->ActiveStreamCountMax, Stream::GetUnusedStreams());              pEngine->pDiskThread->ActiveStreamCount, pEngine->pDiskThread->ActiveStreamCountMax, Stream::GetUnusedStreams());
125        fflush(stdout);        fflush(stdout);*/
126        usleep(500000);        sleep(1);
127          if (profile)
128          {
129                  unsigned int samplingFreq = 48000; //FIXME: hardcoded for now
130                  unsigned int bv = gig::Profiler::GetBogoVoices(samplingFreq);
131                  if (bv != 0)
132                  {
133                          printf("       BogoVoices: %i         \r", bv);
134                          fflush(stdout);
135                  }
136          }
137          
138          if (LSCPServer::EventSubscribers(rtEvents))
139          {
140                  LSCPServer::LockRTNotify();
141                  std::map<uint,SamplerChannel*> channels = pSampler->GetSamplerChannels();
142                  std::map<uint,SamplerChannel*>::iterator iter = channels.begin();
143                  for (; iter != channels.end(); iter++) {
144                          SamplerChannel* pSamplerChannel = iter->second;
145                          EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
146                          if (!pEngineChannel) continue;
147                          Engine* pEngine = pEngineChannel->GetEngine();
148                          if (!pEngine) continue;
149                          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_voice_count, iter->first, pEngine->VoiceCount()));
150                          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_stream_count, iter->first, pEngine->DiskStreamCount()));
151                          LSCPServer::SendLSCPNotify(LSCPEvent(LSCPEvent::event_buffer_fill, iter->first, pEngine->DiskStreamBufferFillPercentage()));
152                  }
153                  LSCPServer::UnlockRTNotify();
154          }
155    
156      }      }
157    
158      return EXIT_SUCCESS;      return EXIT_SUCCESS;
159  }  }
160    
161  void signal_handler(int signal) {  void signal_handler(int iSignal) {
162      if (pthread_equal(pthread_self(), signalhandlerthread) && signal == SIGINT) {      switch (iSignal) {
163          // stop all threads          case SIGINT: {
164          if (pAudioIO)      pAudioIO->Close();              if (pthread_equal(pthread_self(), main_thread)) {
165          if (pMidiInThread) pMidiInThread->StopThread();                  if (pLSCPServer) {
166                        pLSCPServer->StopThread();
167          // free all resources                      delete pLSCPServer;
168          if (pMidiInThread) delete pMidiInThread;                  }
169          if (pEngine)       delete pEngine;                  if (pSampler) delete pSampler;
170          if (pAudioIO)      delete pAudioIO;                  printf("LinuxSampler stopped due to SIGINT.\n");
171                    exit(EXIT_SUCCESS);
172          printf("LinuxSampler stopped due to SIGINT\n");              }
173          exit(EXIT_SUCCESS);              return;
174            }
175            case SIGSEGV:
176                std::cerr << ">>> FATAL ERROR: Segmentation fault (SIGSEGV) occured! <<<\n" << std::flush;
177                break;
178            case SIGBUS:
179                std::cerr << ">>> FATAL ERROR: Access to undefined portion of a memory object (SIGBUS) occured! <<<\n" << std::flush;
180                break;
181            case SIGILL:
182                std::cerr << ">>> FATAL ERROR: Illegal instruction (SIGILL) occured! <<<\n" << std::flush;
183                break;
184            case SIGFPE:
185                std::cerr << ">>> FATAL ERROR: Erroneous arithmetic operation (SIGFPE) occured! <<<\n" << std::flush;
186                break;
187            case SIGUSR1:
188                std::cerr << ">>> User defined signal 1 (SIGUSR1) received <<<\n" << std::flush;
189                break;
190            case SIGUSR2:
191                std::cerr << ">>> User defined signal 2 (SIGUSR2) received <<<\n" << std::flush;
192                break;
193            default: { // this should never happen, as we register for the signals we want
194                std::cerr << ">>> FATAL ERROR: Unknown signal received! <<<\n" << std::flush;
195                break;
196            }
197      }      }
198        signal(iSignal, SIG_DFL); // Reinstall default handler to prevent race conditions
199        std::cerr << "Showing stack trace...\n" << std::flush;
200        StackTrace();
201        sleep(2);
202        std::cerr << "Killing LinuxSampler...\n" << std::flush;
203        kill_app(); // Use abort() if we want to generate a core dump.
204    }
205    
206    void kill_app() {
207        kill(main_thread, SIGKILL);
208  }  }
209    
210  void parse_options(int argc, char **argv) {  void parse_options(int argc, char **argv) {
# Line 161  void parse_options(int argc, char **argv Line 212  void parse_options(int argc, char **argv
212      int option_index = 0;      int option_index = 0;
213      static struct option long_options[] =      static struct option long_options[] =
214          {          {
             {"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},  
             {"server",0,0,0},  
215              {"help",0,0,0},              {"help",0,0,0},
216                {"version",0,0,0},
217                {"profile",0,0,0},
218                {"no-tune",0,0,0},
219              {0,0,0,0}              {0,0,0,0}
220          };          };
221    
222      while (true) {      while (true) {
223          res = getopt_long_only(argc, argv, "", long_options, &option_index);          /*
224              Stephane Letz : letz@grame.fr
225              getopt_long_only does not exist on OSX : replaced by getopt_long for now.
226            */
227            res = getopt_long(argc, argv, "", long_options, &option_index);
228          if(res == -1) break;          if(res == -1) break;
229          if (res == 0) {          if (res == 0) {
230              switch(option_index) {              switch(option_index) {
231                  case 0: // --numfragments                  case 0: // --help
232                      num_fragments = atoi(optarg);                      printf("usage: linuxsampler [OPTIONS]\n\n");
233                      break;                      printf("--help             prints this message\n");
234                  case 1: // --fragmentsize                      printf("--version          prints version information\n");
235                      fragmentsize = atoi(optarg);                      printf("--profile          profile synthesis algorithms\n");
236                      break;                      printf("--no-tune          disable assembly optimization\n");
237                  case 2: // --volume                      exit(EXIT_SUCCESS);
                     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);  
                     break;  
                 case 6: // --inputclient  
                     input_client = optarg;  
                     break;  
                 case 7: // --alsaout  
                     alsaout = optarg;  
                     use_jack = false; // If this option is specified do not connect to jack  
                     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);  
                     }  
238                      break;                      break;
239                  }                  case 1: // --version
240                  case 9: // --samplerate                      printf("LinuxSampler %s\n", VERSION);
241                      samplerate = atoi(optarg);                      exit(EXIT_SUCCESS);
242                      break;                      break;
243                  case 10: // --server                  case 2: // --profile
244                      run_server = true;                      profile = true;
245                      break;                      break;
246                  case 11: // --help                  case 3: // --no-tune
247                      printf("usage: linuxsampler [OPTIONS] <INSTRUMENTFILE>\n\n");                      tune = false;
                     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");  
                     printf("--server           launch network server for remote control\n");  
                     exit(EXIT_SUCCESS);  
248                      break;                      break;
249              }              }
250          }          }

Legend:
Removed from v.35  
changed lines
  Added in v.411

  ViewVC Help
Powered by ViewVC