/[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 41 by schoenebeck, Wed Mar 31 10:28:42 2004 UTC revision 1364 by schoenebeck, Mon Oct 1 13:38:37 2007 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-2007 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 23  Line 24 
24  #include <getopt.h>  #include <getopt.h>
25  #include <signal.h>  #include <signal.h>
26    
27  #include "global.h"  #include "Sampler.h"
28  #include "diskthread.h"  #include "engines/EngineFactory.h"
29  #include "audiothread.h"  #include "engines/InstrumentEditorFactory.h"
30  #include "alsaio.h"  #include "drivers/midi/MidiInputDeviceFactory.h"
31  #include "jackio.h"  #include "drivers/audio/AudioOutputDeviceFactory.h"
32  #include "midiin.h"  #include "engines/gig/Profiler.h"
 #include "stream.h"  
 #include "RIFF.h"  
 #include "gig.h"  
33  #include "network/lscpserver.h"  #include "network/lscpserver.h"
34    #include "common/stacktrace.h"
35    #include "common/Features.h"
36    
37  #define AUDIO_CHANNELS          2     // stereo  using namespace LinuxSampler;
38  #define AUDIO_FRAGMENTS         3     // 3 fragments, if it does not work set it to 2  
39  #define AUDIO_FRAGMENTSIZE      512   // each fragment has 512 frames  Sampler*    pSampler    = NULL;
40  #define AUDIO_SAMPLERATE        44100 // Hz  LSCPServer* pLSCPServer = NULL;
41    pthread_t   main_thread;
42  enum patch_format_t {  pid_t       main_pid;
43      patch_format_unknown,  bool bPrintStatistics = false;
44      patch_format_gig,  bool profile = false;
45      patch_format_dls  bool tune = true;
46  } patch_format = patch_format_unknown;  unsigned long int lscp_addr;
47    unsigned short int lscp_port;
 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;  
48    
49  void parse_options(int argc, char **argv);  void parse_options(int argc, char **argv);
50  void signal_handler(int signal);  void signal_handler(int signal);
51    void kill_app();
52    
53  int main(int argc, char **argv) {  int main(int argc, char **argv) {
54    
55        // initialize the stack trace mechanism with our binary file
56        StackTraceInit(argv[0], -1);
57    
58        main_pid = getpid();
59        main_thread = pthread_self();
60    
61      // 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();  
62      signal(SIGINT, signal_handler);      signal(SIGINT, signal_handler);
63    
64        // register signal handler for all unusual signals
65        // (we will print the stack trace and exit)
66        struct sigaction sact;
67        sigemptyset(&sact.sa_mask);
68        sact.sa_flags   = 0;
69        sact.sa_handler = signal_handler;
70        sigaction(SIGSEGV, &sact, NULL);
71        sigaction(SIGBUS,  &sact, NULL);
72        sigaction(SIGILL,  &sact, NULL);
73        sigaction(SIGFPE,  &sact, NULL);
74        sigaction(SIGUSR1, &sact, NULL);
75        sigaction(SIGUSR2, &sact, NULL);
76    
77        lscp_addr = htonl(LSCP_ADDR);
78        lscp_port = htons(LSCP_PORT);
79    
80      // parse and assign command line options      // parse and assign command line options
81      parse_options(argc, argv);      parse_options(argc, argv);
82    
83      if (patch_format != patch_format_gig) {      dmsg(1,("LinuxSampler %s\n", VERSION));
84          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"));
85          printf("Use 'linuxsampler --help' to see all available options.\n");      dmsg(1,("Copyright (C) 2005-2007 Christian Schoenebeck\n"));
86          return EXIT_FAILURE;  
87        if (tune) {
88            // detect and print system / CPU specific features
89            Features::detect();
90            dmsg(1,("Detected features: %s\n", Features::featuresAsString().c_str()));
91            // prevent slow denormal FPU modes
92            Features::enableDenormalsAreZeroMode();
93      }      }
94    
95      int error = 1;      // create LinuxSampler instance
96  #if HAVE_JACK      dmsg(1,("Creating Sampler..."));
97      if (use_jack) {      pSampler = new Sampler;
         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;  
     }  
98      dmsg(1,("OK\n"));      dmsg(1,("OK\n"));
99    
100      AudioThread* pEngine       = new AudioThread(pAudioIO);      dmsg(1,("Registered sampler engines: %s\n", EngineFactory::AvailableEngineTypesAsString().c_str()));
101      MidiIn*      pMidiInThread = new MidiIn(pEngine);      dmsg(1,("Registered MIDI input drivers: %s\n", MidiInputDeviceFactory::AvailableDriversAsString().c_str()));
102        dmsg(1,("Registered audio output drivers: %s\n", AudioOutputDeviceFactory::AvailableDriversAsString().c_str()));
103      // Loading gig file      dmsg(1,("Registered instrument editors: %s\n", InstrumentEditorFactory::AvailableEditorsAsString().c_str()));
104      result_t result = pEngine->LoadInstrument(argv[argc - 1], instrument_index);  
105      if (result.type == result_type_error) return EXIT_FAILURE;      // start LSCP network server
106      pEngine->Volume = volume;      struct in_addr addr;
107        addr.s_addr = lscp_addr;
108      dmsg(1,("Starting MIDI in thread..."));      dmsg(1,("Starting LSCP network server (%s:%d)...", inet_ntoa(addr), ntohs(lscp_port)));
109      if (input_client.size() > 0) pMidiInThread->SubscribeToClient(input_client.c_str());      pLSCPServer = new LSCPServer(pSampler, lscp_addr, lscp_port);
110      pMidiInThread->StartThread();      pLSCPServer->StartThread();
111        pLSCPServer->WaitUntilInitialized();
112      dmsg(1,("OK\n"));      dmsg(1,("OK\n"));
113    
114      sleep(1);      if (profile)
115        {
116      dmsg(1,("Starting audio thread..."));          dmsg(1,("Calibrating profiler..."));
117      pAudioIO->AssignEngine(pEngine);          LinuxSampler::gig::Profiler::Calibrate();
118      pAudioIO->Activate();          LinuxSampler::gig::Profiler::Reset();
119      dmsg(1,("OK\n"));          LinuxSampler::gig::Profiler::enable();
   
     if (run_server) {  
         dmsg(1,("Starting network server..."));  
         pLSCPServer = new LSCPServer(pEngine);  
         pLSCPServer->StartThread();  
120          dmsg(1,("OK\n"));          dmsg(1,("OK\n"));
121      }      }
122    
123      printf("LinuxSampler initialization completed.\n");      printf("LinuxSampler initialization completed. :-)\n\n");
124    
125        std::list<LSCPEvent::event_t> rtEvents;
126        rtEvents.push_back(LSCPEvent::event_voice_count);
127        rtEvents.push_back(LSCPEvent::event_stream_count);
128        rtEvents.push_back(LSCPEvent::event_buffer_fill);
129        rtEvents.push_back(LSCPEvent::event_total_voice_count);
130    
131        while (true) {
132            if (bPrintStatistics) {
133                const std::set<Engine*>& engines = EngineFactory::EngineInstances();
134                std::set<Engine*>::iterator itEngine = engines.begin();
135                for (int i = 0; itEngine != engines.end(); itEngine++, i++) {
136                    Engine* pEngine = *itEngine;
137                    printf("Engine %d) Voices: %3.3d (Max: %3.3d) Streams: %3.3d (Max: %3.3d)\n", i,
138                        pEngine->VoiceCount(), pEngine->VoiceCountMax(),
139                        pEngine->DiskStreamCount(), pEngine->DiskStreamCountMax()
140                    );
141                    fflush(stdout);
142                }
143            }
144    
145          sleep(1);
146          if (profile)
147          {
148              unsigned int samplingFreq = 48000; //FIXME: hardcoded for now
149              unsigned int bv = LinuxSampler::gig::Profiler::GetBogoVoices(samplingFreq);
150              if (bv != 0)
151              {
152                  printf("       BogoVoices: %i         \r", bv);
153                  fflush(stdout);
154              }
155          }
156    
157          if (LSCPServer::EventSubscribers(rtEvents))
158          {
159              LSCPServer::LockRTNotify();
160              std::map<uint,SamplerChannel*> channels = pSampler->GetSamplerChannels();
161              std::map<uint,SamplerChannel*>::iterator iter = channels.begin();
162              for (; iter != channels.end(); iter++) {
163                  SamplerChannel* pSamplerChannel = iter->second;
164                  EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
165                  if (!pEngineChannel) continue;
166                  Engine* pEngine = pEngineChannel->GetEngine();
167                  if (!pEngine) continue;
168                  pSampler->fireVoiceCountChanged(iter->first, pEngineChannel->GetVoiceCount());
169                  pSampler->fireStreamCountChanged(iter->first, pEngineChannel->GetDiskStreamCount());
170                  pSampler->fireBufferFillChanged(iter->first, pEngine->DiskStreamBufferFillPercentage());
171                  pSampler->fireTotalVoiceCountChanged(pSampler->GetVoiceCount());
172              }
173              LSCPServer::UnlockRTNotify();
174          }
175    
     while(true)  {  
       printf("Voices: %3.3d (Max: %3.3d) Streams: %3.3d (Max: %3.3d, Unused: %3.3d)\r",  
             pEngine->ActiveVoiceCount, pEngine->ActiveVoiceCountMax,  
             pEngine->pDiskThread->ActiveStreamCount, pEngine->pDiskThread->ActiveStreamCountMax, Stream::GetUnusedStreams());  
       fflush(stdout);  
       usleep(500000);  
176      }      }
177    
178      return EXIT_SUCCESS;      return EXIT_SUCCESS;
179  }  }
180    
181  void signal_handler(int signal) {  void signal_handler(int iSignal) {
182      if (pthread_equal(pthread_self(), signalhandlerthread) && signal == SIGINT) {      switch (iSignal) {
183          // stop all threads          case SIGINT: {
184          if (pAudioIO)      pAudioIO->Close();              if (pthread_equal(pthread_self(), main_thread)) {
185          if (pMidiInThread) pMidiInThread->StopThread();                  if (pLSCPServer) pLSCPServer->StopThread();
186                    // the delete order here is important: the Sampler
187          // free all resources                  // destructor sends notifications to the lscpserver
188          if (pMidiInThread) delete pMidiInThread;                  if (pSampler) delete pSampler;
189          if (pEngine)       delete pEngine;                  if (pLSCPServer) delete pLSCPServer;
190          if (pAudioIO)      delete pAudioIO;  #if HAVE_SQLITE3
191                    InstrumentsDb::Destroy();
192          printf("LinuxSampler stopped due to SIGINT\n");  #endif
193          exit(EXIT_SUCCESS);                  printf("LinuxSampler stopped due to SIGINT.\n");
194                    exit(EXIT_SUCCESS);
195                }
196                return;
197            }
198            case SIGSEGV:
199                std::cerr << ">>> FATAL ERROR: Segmentation fault (SIGSEGV) occured! <<<\n" << std::flush;
200                break;
201            case SIGBUS:
202                std::cerr << ">>> FATAL ERROR: Access to undefined portion of a memory object (SIGBUS) occured! <<<\n" << std::flush;
203                break;
204            case SIGILL:
205                std::cerr << ">>> FATAL ERROR: Illegal instruction (SIGILL) occured! <<<\n" << std::flush;
206                break;
207            case SIGFPE:
208                std::cerr << ">>> FATAL ERROR: Erroneous arithmetic operation (SIGFPE) occured! <<<\n" << std::flush;
209                break;
210            case SIGUSR1:
211                std::cerr << ">>> User defined signal 1 (SIGUSR1) received <<<\n" << std::flush;
212                break;
213            case SIGUSR2:
214                std::cerr << ">>> User defined signal 2 (SIGUSR2) received <<<\n" << std::flush;
215                break;
216            default: { // this should never happen, as we register for the signals we want
217                std::cerr << ">>> FATAL ERROR: Unknown signal received! <<<\n" << std::flush;
218                break;
219            }
220      }      }
221        signal(iSignal, SIG_DFL); // Reinstall default handler to prevent race conditions
222        std::cerr << "Showing stack trace...\n" << std::flush;
223        StackTrace();
224        sleep(2);
225        std::cerr << "Killing LinuxSampler...\n" << std::flush;
226        kill_app(); // Use abort() if we want to generate a core dump.
227    }
228    
229    void kill_app() {
230        kill(main_pid, SIGKILL);
231  }  }
232    
233  void parse_options(int argc, char **argv) {  void parse_options(int argc, char **argv) {
# Line 157  void parse_options(int argc, char **argv Line 235  void parse_options(int argc, char **argv
235      int option_index = 0;      int option_index = 0;
236      static struct option long_options[] =      static struct option long_options[] =
237          {          {
             {"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},  
238              {"help",0,0,0},              {"help",0,0,0},
239                {"version",0,0,0},
240                {"profile",0,0,0},
241                {"no-tune",0,0,0},
242                {"statistics",0,0,0},
243                {"instruments-db-location",1,0,0},
244                {"create-instruments-db",1,0,0},
245                {"lscp-addr",1,0,0},
246                {"lscp-port",1,0,0},
247              {0,0,0,0}              {0,0,0,0}
248          };          };
249    
250      while (true) {      while (true) {
251          res = getopt_long_only(argc, argv, "", long_options, &option_index);          /*
252              Stephane Letz : letz@grame.fr
253              getopt_long_only does not exist on OSX : replaced by getopt_long for now.
254            */
255            res = getopt_long(argc, argv, "", long_options, &option_index);
256          if(res == -1) break;          if(res == -1) break;
257          if (res == 0) {          if (res == 0) {
258              switch(option_index) {              switch(option_index) {
259                  case 0: // --numfragments                  case 0: // --help
260                      num_fragments = atoi(optarg);                      printf("usage: linuxsampler [OPTIONS]\n\n");
261                      break;                      printf("--help                      prints this message\n");
262                  case 1: // --fragmentsize                      printf("--version                   prints version information\n");
263                      fragmentsize = atoi(optarg);                      printf("--profile                   profile synthesis algorithms\n");
264                      break;                      printf("--no-tune                   disable assembly optimization\n");
265                  case 2: // --volume                      printf("--statistics                periodically prints statistics\n");
266                      volume = atof(optarg);                      printf("--lscp-addr                 set LSCP address (default: any)\n");
267                      break;                      printf("--lscp-port                 set LSCP port (default: 8888)\n");
268                  case 3: // --dls                      printf("--create-instruments-db     creates an instruments DB\n");
269                      patch_format = patch_format_dls;                      printf("--instruments-db-location   specifies the instruments DB file\n");
270                        exit(EXIT_SUCCESS);
271                      break;                      break;
272                  case 4: // --gig                  case 1: // --version
273                      patch_format = patch_format_gig;                      printf("LinuxSampler %s\n", VERSION);
274                        exit(EXIT_SUCCESS);
275                      break;                      break;
276                  case 5: // --instrument                  case 2: // --profile
277                      instrument_index = atoi(optarg);                      profile = true;
278                      break;                      break;
279                  case 6: // --inputclient                  case 3: // --no-tune
280                      input_client = optarg;                      tune = false;
281                      break;                      break;
282                  case 7: // --alsaout                  case 4: // --statistics
283                      alsaout = optarg;                      bPrintStatistics = true;
                     use_jack = false; // If this option is specified do not connect to jack  
284                      break;                      break;
285                  case 8: { // --jackout                  case 5: // --instruments-db-location
286    #if HAVE_SQLITE3
287                      try {                      try {
288                          String arg(optarg);                          if (optarg) {
289                          // remove outer apostrophes                              struct stat statBuf;
290                          arg = arg.substr(arg.find('\'') + 1, arg.rfind('\'') - (arg.find('\'') + 1));                              int res = stat(optarg, &statBuf);
291                          // split in two arguments  
292                          jack_playback[0] = arg.substr(0, arg.find("\' "));                              if (res) {
293                          jack_playback[1] = arg.substr(arg.find("\' ") + 2, arg.size() - (arg.find("\' ") + 2));                                  std::stringstream ss;
294                          // remove inner apostrophes                                  ss << "Failed to stat `" << optarg << "`: " << strerror(errno);
295                          jack_playback[0] = jack_playback[0].substr(0, jack_playback[0].find('\''));                                  throw Exception(ss.str());
296                          jack_playback[1] = jack_playback[1].substr(jack_playback[1].find('\'') + 1, jack_playback[1].size() - jack_playback[1].find('\''));                              }
297                          // this is the default but set it up anyway in case alsa_card was also used.  
298                          use_jack = true;                              if (!S_ISREG(statBuf.st_mode)) {
299                      }                                  std::stringstream ss;
300                      catch (...) {                                  ss << "`" << optarg << "` is not a regular file";
301                          fprintf(stderr, "Invalid argument '%s' for parameter --jackout\n", optarg);                                  throw Exception(ss.str());
302                                }
303    
304                                InstrumentsDb::GetInstrumentsDb()->SetDbFile(String(optarg));
305                            }
306                        } catch(Exception e) {
307                            std::cerr << "Could not open instruments DB file: "
308                                      << e.Message() << std::endl;
309                          exit(EXIT_FAILURE);                          exit(EXIT_FAILURE);
310                      }                      }
311                      break;                      break;
312                  }  #else
313                  case 9: // --samplerate                      std::cerr << "LinuxSampler was not build with ";
314                      samplerate = atoi(optarg);                      std::cerr << "instruments database support!\n";
315                      break;                      exit(EXIT_FAILURE);
316                  case 10: // --server                      break;
317                      run_server = true;  #endif
318                      break;                  case 6: // --create-instruments-db
319                  case 11: // --help  #if HAVE_SQLITE3
320                      printf("usage: linuxsampler [OPTIONS] <INSTRUMENTFILE>\n\n");                      try {
321                      printf("--gig              loads a Gigasampler instrument\n");                          if (optarg) {
322                      printf("--dls              loads a DLS instrument\n");                              std::cout << "Creating instruments database..." << std::endl;
323                      printf("--instrument       index of the instrument in the instrument file if it\n");                              InstrumentsDb::CreateInstrumentsDb(String(optarg));
324                      printf("                   contains more than one (default: 0)\n");                              InstrumentsDb::Destroy();
325                      printf("--numfragments     sets the number of audio fragments\n");                              std::cout << "Done" << std::endl;
326                      printf("--fragmentsize     sets the fragment size\n");                          }
327                      printf("--volume           sets global volume gain factor (a value > 1.0 means\n");                      } catch(Exception e) {
328                      printf("                   amplification, a value < 1.0 means attenuation,\n");                          std::cerr << e.Message() << std::endl;
329                      printf("                   default: 0.25)\n");                          exit(EXIT_FAILURE);
330                      printf("--inputclient      connects to an Alsa sequencer input client on startup\n");                          return;
331                      printf("                   (e.g. 64:0 to connect to a client with ID 64 and port 0)\n");                      }
332                      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");  
333                      exit(EXIT_SUCCESS);                      exit(EXIT_SUCCESS);
334                        return;
335    #else
336                        std::cerr << "Failed to create the database. LinuxSampler was ";
337                        std::cerr << "not build with instruments database support!\n";
338                        exit(EXIT_FAILURE);
339                        return;
340    #endif
341                    case 7: // --lscp-addr
342                        struct in_addr addr;
343                        if (inet_aton(optarg, &addr) == 0)
344                            printf("WARNING: Failed to parse lscp-addr argument, ignoring!\n");
345                        else
346                            lscp_addr = addr.s_addr;
347                        break;
348                    case 8: // --lscp-port
349                        long unsigned int port = 0;
350                        if ((sscanf(optarg, "%u", &port) != 1) || (port == 0) || (port > 65535))
351                            printf("WARNING: Failed to parse lscp-port argument, ignoring!\n");
352                        else
353                            lscp_port = htons(port);
354                      break;                      break;
355              }              }
356          }          }

Legend:
Removed from v.41  
changed lines
  Added in v.1364

  ViewVC Help
Powered by ViewVC