/[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 20 by schoenebeck, Thu Dec 25 00:02:45 2003 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 <string>  #include "Sampler.h"
28    #include "drivers/midi/MidiInputDeviceFactory.h"
29  #include "global.h"  #include "drivers/audio/AudioOutputDeviceFactory.h"
30  #include "audioio.h"  #include "engines/gig/Profiler.h"
31  #include "diskthread.h"  #include "network/lscpserver.h"
32  #include "audiothread.h"  #include "common/stacktrace.h"
33  #include "midiin.h"  #include "common/Features.h"
34  #include "stream.h"  
35  #include "RIFF.h"  using namespace LinuxSampler;
36  #include "gig.h"  
37    Sampler*    pSampler    = NULL;
38  #define AUDIO_CHANNELS          2     // stereo  LSCPServer* pLSCPServer = NULL;
39  #define AUDIO_FRAGMENTS         3     // 3 fragments, if it does not work set it to 2  pthread_t   main_thread;
40  #define AUDIO_FRAGMENTSIZE      512   // each fragment has 512 frames  bool profile = false;
41  #define AUDIO_SAMPLERATE        44100 // Hz  bool tune = true;
   
 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;  
 std::string      input_client;  
 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      pAudioIO = NULL;  
49      pRIFF    = NULL;      // initialize the stack trace mechanism with our binary file
50      pGig     = NULL;      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      patch_format      = patch_format_unknown;      // register signal handler for all unusual signals
58      instrument_index  = 0;      // (we will print the stack trace and exit)
59      num_fragments     = AUDIO_FRAGMENTS;      struct sigaction sact;
60      fragmentsize      = AUDIO_FRAGMENTSIZE;      sigemptyset(&sact.sa_mask);
61      volume            = 0.25; // default volume      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      dmsg(1,("Initializing audio output..."));              // detect and print system / CPU specific features
80      pAudioIO = new AudioIO();              String sFeatures;
81      int error = pAudioIO->Initialize(AUDIO_CHANNELS, AUDIO_SAMPLERATE, num_fragments, fragmentsize);              Features::detect();
82      if (error) return EXIT_FAILURE;  #if ARCH_X86
83                if (Features::supportsMMX()) sFeatures += " MMX";
84                if (Features::supportsSSE()) sFeatures += " SSE";
85    #endif // ARCH_X86
86                if (!sFeatures.size()) sFeatures = " None";
87                dmsg(1,("Detected features:%s\n",sFeatures.c_str()));
88        }
89    
90        // create LinuxSampler instance
91        dmsg(1,("Creating Sampler..."));
92        pSampler = new Sampler;
93      dmsg(1,("OK\n"));      dmsg(1,("OK\n"));
94    
95      // Loading gig file      dmsg(1,("Registered MIDI input drivers: %s\n", MidiInputDeviceFactory::AvailableDriversAsString().c_str()));
96      try {      dmsg(1,("Registered audio output drivers: %s\n", AudioOutputDeviceFactory::AvailableDriversAsString().c_str()));
         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;  
     }  
   
     DiskThread*  pDiskThread   = new DiskThread(((pAudioIO->FragmentSize << MAX_PITCH) << 1) + 6); //FIXME: assuming stereo  
     AudioThread* pAudioThread  = new AudioThread(pAudioIO, pDiskThread, pInstrument);  
     MidiIn*      pMidiInThread = new MidiIn(pAudioThread);  
97    
98      dmsg(1,("Starting disk thread..."));      // start LSCP network server
99      pDiskThread->StartThread();      dmsg(1,("Starting LSCP network server (on TCP port %d)...", LSCP_PORT));
100      dmsg(1,("OK\n"));      pLSCPServer = new LSCPServer(pSampler);
101      dmsg(1,("Starting MIDI in thread..."));      pLSCPServer->StartThread();
102      if (input_client.size() > 0) pMidiInThread->SubscribeToClient(input_client.c_str());      pLSCPServer->WaitUntilInitialized();
     pMidiInThread->StartThread();  
103      dmsg(1,("OK\n"));      dmsg(1,("OK\n"));
104    
105      sleep(1);      if (profile)
106      dmsg(1,("Starting audio thread..."));      {
107      pAudioThread->Volume = volume;              dmsg(1,("Calibrating profiler..."));
108      pAudioThread->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              pAudioThread->ActiveVoiceCount, pAudioThread->ActiveVoiceCountMax,      rtEvents.push_back(LSCPEvent::event_stream_count);
118              pDiskThread->ActiveStreamCount, pDiskThread->ActiveStreamCountMax, Stream::GetUnusedStreams());      rtEvents.push_back(LSCPEvent::event_buffer_fill);
119        fflush(stdout);  
120        usleep(500000);      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,
124                pEngine->pDiskThread->ActiveStreamCount, pEngine->pDiskThread->ActiveStreamCountMax, Stream::GetUnusedStreams());
125          fflush(stdout);*/
126          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 (pMidiInThread) pMidiInThread->StopThread();              if (pthread_equal(pthread_self(), main_thread)) {
165          if (pAudioThread)  pAudioThread->StopThread();                  if (pLSCPServer) {
166          if (pDiskThread)   pDiskThread->StopThread();                      pLSCPServer->StopThread();
167                        delete pLSCPServer;
168          // free all resources                  }
169          if (pMidiInThread) delete pMidiInThread;                  if (pSampler) delete pSampler;
170          if (pAudioThread)  delete pAudioThread;                  printf("LinuxSampler stopped due to SIGINT.\n");
171          if (pDiskThread)   delete pDiskThread;                  exit(EXIT_SUCCESS);
172          if (pGig)          delete pGig;              }
173          if (pRIFF)         delete pRIFF;              return;
174          if (pAudioIO)      delete pAudioIO;          }
175            case SIGSEGV:
176          printf("LinuxSampler stopped due to SIGINT\n");              std::cerr << ">>> FATAL ERROR: Segmentation fault (SIGSEGV) occured! <<<\n" << std::flush;
177          exit(EXIT_SUCCESS);              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 176  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},  
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:                  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:                      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:                      exit(EXIT_SUCCESS);
238                      volume = atof(optarg);                      break;
239                      break;                  case 1: // --version
240                  case 3:                      printf("LinuxSampler %s\n", VERSION);
241                      patch_format = patch_format_dls;                      exit(EXIT_SUCCESS);
                     break;  
                 case 4:  
                     patch_format = patch_format_gig;  
                     break;  
                 case 5:  
                     instrument_index = atoi(optarg);  
242                      break;                      break;
243                  case 6:                  case 2: // --profile
244                      input_client = optarg;                      profile = true;
245                      break;                      break;
246                  case 7:                  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");  
                     exit(0);  
248                      break;                      break;
249              }              }
250          }          }

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

  ViewVC Help
Powered by ViewVC