/[svn]/libgig/trunk/src/gigextract.cpp
ViewVC logotype

Annotation of /libgig/trunk/src/gigextract.cpp

Parent Directory Parent Directory | Revision Log Revision Log


Revision 2465 - (hide annotations) (download)
Thu Sep 5 03:01:51 2013 UTC (10 years, 5 months ago) by schoenebeck
File size: 18594 byte(s)
* src/gigextract.cpp: export sample loop, unity note and fine tune
  with libsndfile

1 schoenebeck 2 /***************************************************************************
2     * *
3 schoenebeck 933 * libgig - C++ cross-platform Gigasampler format file access library *
4 schoenebeck 2 * *
5 schoenebeck 2465 * Copyright (C) 2003-2013 by Christian Schoenebeck *
6 schoenebeck 518 * <cuse@users.sourceforge.net> *
7 schoenebeck 2 * *
8 schoenebeck 933 * This program is part of libgig. *
9     * *
10 schoenebeck 2 * This program is free software; you can redistribute it and/or modify *
11     * it under the terms of the GNU General Public License as published by *
12     * the Free Software Foundation; either version 2 of the License, or *
13     * (at your option) any later version. *
14     * *
15     * This program is distributed in the hope that it will be useful, *
16     * but WITHOUT ANY WARRANTY; without even the implied warranty of *
17     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
18     * GNU General Public License for more details. *
19     * *
20     * You should have received a copy of the GNU General Public License *
21     * along with this program; if not, write to the Free Software *
22     * Foundation, Inc., 59 Temple Place, Suite 330, Boston, *
23     * MA 02111-1307 USA *
24     ***************************************************************************/
25    
26     #ifdef HAVE_CONFIG_H
27     #include <config.h>
28     #endif
29    
30     // just for testing the disk streaming capability of libgig;
31     // you will also need to set this to 1 at the moment if you want to
32     // extract compressed samples, as I haven't implemented the
33     // decompression algorithm in gig::Sample::LoadSampleData() yet
34     #define USE_DISK_STREAMING 1
35    
36     // only when USE_DISK_STREAMING is set to 1:
37     // just for testing the disk stream capability; with this option set
38     // gigextract will read the samples in smaller pieces, just to stress
39     // gig::Sample::Read() method a bit
40     #define HASHED_READS_TEST 1
41    
42     #include <iostream>
43     #include <cstdlib>
44 schoenebeck 220 #include <string.h>
45 schoenebeck 518 #include <string>
46 schoenebeck 2 #include <stdlib.h>
47     #include <sys/types.h>
48     #include <sys/stat.h>
49     #include <errno.h>
50 schoenebeck 220
51 schoenebeck 1063 #include "gig.h"
52    
53 persson 1869 #ifdef _MSC_VER
54     #define S_ISDIR(x) (S_IFDIR & (x))
55     #define S_IWUSR S_IWRITE
56     #define S_IXUSR S_IEXEC
57     #endif
58    
59 schoenebeck 1063 #if POSIX
60     # include <dlfcn.h>
61     #endif
62    
63 schoenebeck 220 // only libsndfile is available for Windows, so we use that for writing the sound files
64     #ifdef WIN32
65     # define HAVE_SNDFILE 1
66     #endif // WIN32
67    
68 schoenebeck 608 // abort compilation here if neither libsndfile nor libaudiofile are available
69     #if !HAVE_SNDFILE && !HAVE_AUDIOFILE
70     # error "Neither libsndfile nor libaudiofile seem to be available!"
71     # error "(HAVE_SNDFILE and HAVE_AUDIOFILE are both false)"
72     #endif
73    
74 schoenebeck 220 // we prefer libsndfile before libaudiofile
75     #if HAVE_SNDFILE
76     # include <sndfile.h>
77     #else
78     # include <audiofile.h>
79     #endif // HAVE_SNDFILE
80    
81 schoenebeck 2 using namespace std;
82    
83     typedef map<unsigned int, bool> OrderMap;
84     OrderMap* pOrderedSamples = NULL;
85    
86 schoenebeck 518 string Revision();
87     void PrintVersion();
88 schoenebeck 2 void PrintUsage();
89     void ExtractSamples(gig::File* gig, char* destdir, OrderMap* ordered);
90 schoenebeck 2465 int writeWav(gig::Sample* sample, const char* filename, void* samples, long samplecount, int channels, int bitdepth, long rate);
91 schoenebeck 220 string ToString(int i);
92    
93 schoenebeck 608 #if !HAVE_SNDFILE // use libaudiofile
94 schoenebeck 2 void* hAFlib; // handle to libaudiofile
95     void openAFlib(void);
96     void closeAFlib(void);
97     // pointers to libaudiofile functions
98     AFfilesetup(*_afNewFileSetup)(void);
99     void(*_afFreeFileSetup)(AFfilesetup);
100     void(*_afInitChannels)(AFfilesetup,int,int);
101     void(*_afInitSampleFormat)(AFfilesetup,int,int,int);
102     void(*_afInitFileFormat)(AFfilesetup,int);
103     void(*_afInitRate)(AFfilesetup,int,double);
104     int(*_afWriteFrames)(AFfilehandle,int,const void*,int);
105     AFfilehandle(*_afOpenFile)(const char*,const char*,AFfilesetup);
106     int(*_afCloseFile)(AFfilehandle file);
107 schoenebeck 220 #endif // !HAVE_SNDFILE
108 schoenebeck 2
109     int main(int argc, char *argv[]) {
110 schoenebeck 518 if (argc >= 2) {
111     if (argv[1][0] == '-') {
112     switch (argv[1][1]) {
113     case 'v':
114     PrintVersion();
115     return EXIT_SUCCESS;
116     }
117     }
118     }
119 schoenebeck 2 if (argc < 3) {
120     PrintUsage();
121     return EXIT_FAILURE;
122     }
123     if (argc > 3) { // extracting specific samples
124     pOrderedSamples = new OrderMap;
125     for (int i = 3; i < argc; i++) {
126     unsigned int index = atoi(argv[i]);
127     (*pOrderedSamples)[index] = true;
128     }
129     }
130     FILE* hFile = fopen(argv[1], "r");
131     if (!hFile) {
132     cout << "Invalid input file argument!" << endl;
133     return EXIT_FAILURE;
134     }
135     fclose(hFile);
136 persson 1869 struct stat buf;
137     if (stat(argv[2], &buf) == -1) {
138 schoenebeck 2 cout << "Unable to open DESTDIR: ";
139     switch (errno) {
140     case EACCES: cout << "Permission denied." << endl;
141     break;
142     case ENOENT: cout << "Directory does not exist, or name is an empty string." << endl;
143     break;
144     case ENOMEM: cout << "Insufficient memory to complete the operation." << endl;
145     break;
146     case ENOTDIR: cout << "Is not a directory." << endl;
147     break;
148     default: cout << "Unknown error" << endl;
149     }
150     return EXIT_FAILURE;
151 persson 1869 } else if (!S_ISDIR(buf.st_mode)) {
152     cout << "Unable to open DESTDIR: Is not a directory." << endl;
153     return EXIT_FAILURE;
154     } else if (!(S_IWUSR & buf.st_mode) || !(S_IXUSR & buf.st_mode)) {
155     cout << "Unable to open DESTDIR: Permission denied." << endl;
156     return EXIT_FAILURE;
157 schoenebeck 2 }
158     try {
159     RIFF::File* riff = new RIFF::File(argv[1]);
160     gig::File* gig = new gig::File(riff);
161     cout << "Extracting samples from \"" << argv[1] << "\" to directory \"" << argv[2] << "\"." << endl << flush;
162     ExtractSamples(gig, argv[2], pOrderedSamples);
163     cout << "Extraction finished." << endl << flush;
164     delete gig;
165     delete riff;
166     if (pOrderedSamples) delete pOrderedSamples;
167     }
168     catch (RIFF::Exception e) {
169     e.PrintMessage();
170     return EXIT_FAILURE;
171     }
172     catch (...) {
173     cout << "Unknown exception while trying to parse file." << endl;
174     return EXIT_FAILURE;
175     }
176    
177     return EXIT_SUCCESS;
178     }
179    
180 schoenebeck 2465 static std::string getLoopTypeText(gig::loop_type_t type) {
181     switch (type) {
182     case gig::loop_type_normal:
183     return "normal";
184     case gig::loop_type_bidirectional:
185     return "pingpong";
186     case gig::loop_type_backward:
187     return "backward";
188     default:
189     return "INVALID";
190     }
191     }
192    
193 schoenebeck 2 void ExtractSamples(gig::File* gig, char* destdir, OrderMap* ordered) {
194 schoenebeck 608 #if !HAVE_SNDFILE // use libaudiofile
195 schoenebeck 2 hAFlib = NULL;
196     openAFlib();
197 schoenebeck 220 #endif // !HAVE_SNDFILE
198 schoenebeck 2 uint8_t* pWave = NULL;
199 persson 902 int* pIntWave = NULL;
200 schoenebeck 2 long BufferSize = 0;
201     int samples = 0;
202 persson 902 gig::buffer_t decompressionBuffer;
203     decompressionBuffer.Size = 0;
204 schoenebeck 2 cout << "Seeking for available samples..." << flush;
205     gig::Sample* pSample = gig->GetFirstSample();
206     cout << "OK" << endl << flush;
207     while (pSample) {
208     samples++;
209     if (ordered) {
210     if ((*ordered)[samples] == false) {
211     pSample = gig->GetNextSample();
212     continue;
213     }
214     }
215     string name = pSample->pInfo->Name;
216     string filename = destdir;
217     if (filename[filename.size() - 1] != '/') filename += "/";
218     filename += ToString(samples);
219     filename += "_";
220     if (name == "") {
221     name = "(NO NAME)";
222     filename += "NONAME";
223     }
224     else {
225     filename += name;
226     name.insert(0, "\"");
227     name += "\"";
228     }
229     filename += ".wav";
230     if (pSample->Compressed) cout << "Decompressing ";
231     else cout << "Extracting ";
232 schoenebeck 2465 cout << "Sample " << samples << ") " << name << " (" << pSample->BitDepth <<"Bits, " << pSample->SamplesPerSecond << "Hz, " << pSample->Channels << " Channels, " << pSample->SamplesTotal << " Samples";
233     if (pSample->Loops > 0) {
234     cout << ", LoopType " << getLoopTypeText(pSample->LoopType)
235     << ", LoopStart " << pSample->LoopStart
236     << ", LoopEnd " << pSample->LoopEnd;
237     }
238     cout << ")..." << flush;
239 schoenebeck 2
240    
241     #if USE_DISK_STREAMING
242 persson 902 long neededsize = pSample->BitDepth == 24 ?
243     pSample->SamplesTotal * pSample->Channels * sizeof(int) :
244     pSample->SamplesTotal * pSample->FrameSize;
245 schoenebeck 2 if (BufferSize < neededsize) {
246     if (pWave) delete[] pWave;
247     pWave = new uint8_t[neededsize];
248     BufferSize = neededsize;
249     }
250 persson 902 pIntWave = (int*)pWave;
251 schoenebeck 2 # if HASHED_READS_TEST
252 persson 902 unsigned long readinthisrun = 0,
253 schoenebeck 2 samplepiecesize = 2000;
254     uint8_t* pSamplePiece = pWave;
255     do { // we read the sample in small pieces and increment the size with each run just to test streaming capability
256     readinthisrun = pSample->Read(pSamplePiece, ++samplepiecesize);
257 persson 902 pSamplePiece += readinthisrun * pSample->FrameSize;
258 schoenebeck 2 } while (readinthisrun == samplepiecesize);
259    
260     # else // read in one piece
261     if (pSample->Compressed) {
262 persson 902 if (decompressionBufferSize < pSample->SamplesTotal) {
263     gig::Sample::DestroyDecompressionBuffer(decompressionBuffer);
264     decompressionBuffer = gig::Sample::CreateDecompressionBuffer(pSample->SamplesTotal);
265     decompressionBufferSize = pSample->SamplesTotal;
266     }
267     pSample->Read(pWave, pSample->SamplesTotal, &decompressionBuffer);
268     } else {
269 schoenebeck 2 pSample->Read(pWave, pSample->SamplesTotal);
270     }
271     # endif // HASHED_READS_TEST
272     #else // no disk streaming
273     if (pSample->Compressed) {
274 persson 902 cout << "Sorry, sample is compressed and Sample::LoadSampleData() only decompresses the beginning of the sample - Solution: set USE_DISK_STREAMING in gigextract.cpp (line 32) to 1 and recompile!" << endl;
275     } else {
276     gig::buffer_t buffer = pSample->LoadSampleData(); // load wave into RAM
277     pWave = static_cast<uint8_t*>(buffer.pStart);
278     if (pSample->BitDepth == 24) {
279     long neededsize = pSample->SamplesTotal * pSample->Channels;
280     if (BufferSize < neededsize) {
281     if (pIntWave) delete[] pIntWave;
282     pIntWave = new int[neededsize];
283     BufferSize = neededsize;
284     }
285     }
286 schoenebeck 2 }
287     #endif // USE_DISK_STREAMING
288     if (pWave) {
289 persson 902
290     // Both libsndfile and libaudiofile uses int for 24 bit
291     // samples. libgig however returns 3 bytes per sample, so
292     // we have to convert the wave data before writing.
293     if (pSample->BitDepth == 24) {
294     int n = pSample->SamplesTotal * pSample->Channels;
295     for (int i = n - 1 ; i >= 0 ; i--) {
296     #if HAVE_SNDFILE
297     pIntWave[i] = pWave[i * 3] << 8 | pWave[i * 3 + 1] << 16 | pWave[i * 3 + 2] << 24;
298     #else
299     pIntWave[i] = pWave[i * 3] | pWave[i * 3 + 1] << 8 | pWave[i * 3 + 2] << 16;
300     #endif
301     }
302     }
303    
304 schoenebeck 2465 int res = writeWav(pSample,
305     filename.c_str(),
306 persson 902 pSample->BitDepth == 24 ? static_cast<void*>(pIntWave) : pWave,
307 schoenebeck 2 pSample->SamplesTotal,
308     pSample->Channels,
309     pSample->BitDepth,
310     pSample->SamplesPerSecond);
311     if (res < 0) cout << "Couldn't write sample data." << endl;
312     else cout << "ok" << endl;
313     pSample->ReleaseSampleData(); // free wave from RAM
314     }
315     else cout << "Failed to load sample data." << endl;
316    
317     pSample = gig->GetNextSample();
318     }
319 persson 902 gig::Sample::DestroyDecompressionBuffer(decompressionBuffer);
320     #if USE_DISK_STREAMING
321     if (pWave) delete[] pWave;
322     #else
323     if (pIntWave) delete[] pIntWave;
324     #endif
325 schoenebeck 608 #if !HAVE_SNDFILE // use libaudiofile
326 schoenebeck 2 closeAFlib();
327 schoenebeck 220 #endif // !HAVE_SNDFILE
328 schoenebeck 2 }
329    
330 schoenebeck 2465 int writeWav(gig::Sample* sample, const char* filename, void* samples, long samplecount, int channels, int bitdepth, long rate) {
331 schoenebeck 220 #if HAVE_SNDFILE
332     SNDFILE* hfile;
333     SF_INFO sfinfo;
334 schoenebeck 2465 SF_INSTRUMENT instr;
335 schoenebeck 220 int format = SF_FORMAT_WAV;
336     switch (bitdepth) {
337     case 8:
338     format |= SF_FORMAT_PCM_S8;
339     break;
340     case 16:
341     format |= SF_FORMAT_PCM_16;
342     break;
343     case 24:
344     format |= SF_FORMAT_PCM_24;
345     break;
346     case 32:
347     format |= SF_FORMAT_PCM_32;
348     break;
349     default:
350     cerr << "Error: Bithdepth " << ToString(bitdepth) << " not supported by libsndfile, ignoring sample!\n" << flush;
351     return -1;
352     }
353     memset(&sfinfo, 0, sizeof (sfinfo));
354 schoenebeck 2465 memset(&instr, 0, sizeof (instr));
355 schoenebeck 220 sfinfo.samplerate = rate;
356     sfinfo.frames = samplecount;
357     sfinfo.channels = channels;
358     sfinfo.format = format;
359     if (!(hfile = sf_open(filename, SFM_WRITE, &sfinfo))) {
360     cerr << "Error: Unable to open output file \'" << filename << "\'.\n" << flush;
361     return -1;
362     }
363 schoenebeck 2465 instr.basenote = sample->MIDIUnityNote;
364     instr.detune = sample->FineTune;
365     if (sample->Loops > 0) {
366     instr.loop_count = 1;
367     switch (sample->LoopType) {
368     case gig::loop_type_normal:
369     instr.loops[0].mode = SF_LOOP_FORWARD;
370     break;
371     case gig::loop_type_bidirectional:
372     instr.loops[0].mode = SF_LOOP_ALTERNATING;
373     break;
374     case gig::loop_type_backward:
375     instr.loops[0].mode = SF_LOOP_BACKWARD;
376     break;
377     default:
378     instr.loops[0].mode = SF_LOOP_NONE;
379     break;
380     }
381     instr.loops[0].start = sample->LoopStart;
382     instr.loops[0].end = sample->LoopEnd;
383     instr.loops[0].count = sample->LoopPlayCount;
384     }
385     sf_command(hfile, SFC_SET_INSTRUMENT, &instr, sizeof(instr));
386 persson 902 sf_count_t res = bitdepth == 24 ?
387     sf_write_int(hfile, static_cast<int*>(samples), channels * samplecount) :
388     sf_write_short(hfile, static_cast<short*>(samples), channels * samplecount);
389     if (res != channels * samplecount) {
390 schoenebeck 220 cerr << sf_strerror(hfile) << endl << flush;
391     sf_close(hfile);
392     return -1;
393     }
394     sf_close(hfile);
395 schoenebeck 608 #else // use libaudiofile
396 schoenebeck 2 AFfilesetup setup = _afNewFileSetup();
397     _afInitFileFormat(setup, AF_FILE_WAVE);
398     _afInitChannels(setup, AF_DEFAULT_TRACK, channels);
399     _afInitSampleFormat(setup, AF_DEFAULT_TRACK, AF_SAMPFMT_TWOSCOMP, bitdepth);
400     _afInitRate(setup, AF_DEFAULT_TRACK, rate);
401     if (setup == AF_NULL_FILESETUP) return -1;
402     AFfilehandle hFile = _afOpenFile(filename, "w", setup);
403     if (hFile == AF_NULL_FILEHANDLE) return -1;
404     if (_afWriteFrames(hFile, AF_DEFAULT_TRACK, samples, samplecount) < 0) return -1;
405     _afCloseFile(hFile);
406     _afFreeFileSetup(setup);
407 schoenebeck 220 #endif // HAVE_SNDFILE
408 schoenebeck 55
409 schoenebeck 220 return 0; // success
410 schoenebeck 2 }
411    
412 schoenebeck 608 #if !HAVE_SNDFILE // use libaudiofile
413 schoenebeck 2 void openAFlib() {
414     hAFlib = dlopen("libaudiofile.so", RTLD_NOW);
415     if (!hAFlib) {
416     cout << "Unable to load library libaudiofile.so: " << dlerror() << endl;
417     return;
418     }
419     _afNewFileSetup = (AFfilesetup(*)(void)) dlsym(hAFlib, "afNewFileSetup");
420     _afFreeFileSetup = (void(*)(AFfilesetup)) dlsym(hAFlib, "afFreeFileSetup");
421     _afInitChannels = (void(*)(AFfilesetup,int,int)) dlsym(hAFlib, "afInitChannels");
422     _afInitSampleFormat = (void(*)(AFfilesetup,int,int,int)) dlsym(hAFlib, "afInitSampleFormat");
423     _afInitFileFormat = (void(*)(AFfilesetup,int)) dlsym(hAFlib, "afInitFileFormat");
424     _afInitRate = (void(*)(AFfilesetup,int,double)) dlsym(hAFlib, "afInitRate");
425     _afWriteFrames = (int(*)(AFfilehandle,int,const void*,int)) dlsym(hAFlib, "afWriteFrames");
426     _afOpenFile = (AFfilehandle(*)(const char*,const char*,AFfilesetup)) dlsym(hAFlib, "afOpenFile");
427     _afCloseFile = (int(*)(AFfilehandle file)) dlsym(hAFlib, "afCloseFile");
428     if (dlerror()) cout << "Failed to load function from libaudiofile.so: " << dlerror() << endl;
429     }
430    
431     void closeAFlib() {
432     if (hAFlib) dlclose(hAFlib);
433     }
434 schoenebeck 220 #endif // !HAVE_SNDFILE
435 schoenebeck 2
436 schoenebeck 518 string Revision() {
437 schoenebeck 1953 string s = "$Revision: 1.12 $";
438 schoenebeck 518 return s.substr(11, s.size() - 13); // cut dollar signs, spaces and CVS macro keyword
439     }
440    
441     void PrintVersion() {
442     cout << "gigextract revision " << Revision() << endl;
443 schoenebeck 549 cout << "using " << gig::libraryName() << " " << gig::libraryVersion();
444     #if HAVE_SNDFILE
445     char versionBuffer[128];
446     sf_command(NULL, SFC_GET_LIB_VERSION, versionBuffer, 128);
447     cout << ", " << versionBuffer;
448 schoenebeck 608 #else // use libaudiofile
449     cout << "\nbuilt against libaudiofile "
450     << LIBAUDIOFILE_MAJOR_VERSION << "." << LIBAUDIOFILE_MINOR_VERSION;
451     # ifdef LIBAUDIOFILE_MICRO_VERSION
452     cout << "." << LIBAUDIOFILE_MICRO_VERSION;
453     # endif // LIBAUDIOFILE_MICRO_VERSION
454 schoenebeck 549 #endif // HAVE_SNDFILE
455     cout << endl;
456 schoenebeck 518 }
457    
458 schoenebeck 2 void PrintUsage() {
459     cout << "gigextract - extracts samples from a Gigasampler file." << endl;
460     cout << endl;
461 schoenebeck 518 cout << "Usage: gigextract [-v] GIGFILE DESTDIR [SAMPLENR] [ [SAMPLENR] ...]" << endl;
462 schoenebeck 2 cout << endl;
463     cout << " GIGFILE Input Gigasampler (.gig) file." << endl;
464     cout << endl;
465     cout << " DESTDIR Destination directory where all .wav files will be written to." << endl;
466     cout << endl;
467     cout << " SAMPLENR Index (/indices) of Sample(s) which should be extracted." << endl;
468     cout << " If no sample indices are given, all samples will be extracted" << endl;
469     cout << " (use gigdump to look for available samples)." << endl;
470     cout << endl;
471 schoenebeck 518 cout << " -v Print version and exit." << endl;
472     cout << endl;
473 schoenebeck 2 }
474    
475     string ToString(int i) {
476     static char strbuf[1024];
477     sprintf(strbuf,"%d",i);
478     string s = strbuf;
479     return s;
480     }

  ViewVC Help
Powered by ViewVC