Debian Codegraph @

sfont.cpp

raw symbols SCIP
1 //=============================================================================
2 // MuseScore sftools
3 //
4 // Copyright (C) 2010 Werner Schweer and others
5 //
6 // This work is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Library General Public
8 // License as published by the Free Software Foundation; either
9 // version 2 of the License, or (at your option) any later version.
10 //
11 // In addition, as a special exception, licensor gives permission to
12 // link the code of this work with the OpenSSL Library (or with modified
13 // versions of OpenSSL that use the same license as OpenSSL), and
14 // distribute linked combinations including the two. You must obey the
15 // GNU General Public License in all respects for all of the code used
16 // other than OpenSSL. If you modify this file, you may extend this
17 // exception to your version of the file, but you are not obligated to
18 // do so. If you do not wish to do so, delete this exception statement
19 // from your version. (This exception is necessary should this work be
20 // included in a GPL-licenced work.)
21 //
22 // See COPYING.LIB for the licence text and disclaimer of warranty.
23 //=============================================================================
24
25 #include <stdio.h>
26 #include <unistd.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <math.h>
30 #include <sndfile.h>
31 #include <vorbis/vorbisenc.h>
32
33 #include "sfont.h"
34 #include "xml.h"
35 #include "time.h"
36
37 #include <QtCore/QFile>
38
39 extern bool smallSf; // create small sf
40
41 // #define DEBUG
42
43 #define BE_SHORT(x) ((((x)&0xFF)<<8) | (((x)>>8)&0xFF))
44 #ifdef __i486__
45 #define BE_LONG(x) \
46 ({ int __value; \
47 asm ("bswap %1; movl %1,%0" : "=g" (__value) : "r" (x)); \
48 __value; })
49 #else
50 #define BE_LONG(x) ((((x)&0xFF)<<24) | \
51 (((x)&0xFF00)<<8) | \
52 (((x)&0xFF0000)>>8) | \
53 (((x)>>24)&0xFF))
54 #endif
55
56 #define FOURCC(a, b, c, d) a << 24 | b << 16 | c << 8 | d
57
58 #define BLOCK_SIZE 1024
59
60 static const bool writeCompressed = true;
61
62 //---------------------------------------------------------
63 // Sample
64 //---------------------------------------------------------
65
66 Sample::Sample()
67 {
68 name = 0;
69 }
70
71 Sample::~Sample()
72 {
73 free(name);
74 }
75
76 //---------------------------------------------------------
77 // Instrument
78 //---------------------------------------------------------
79
80 Instrument::Instrument()
81 {
82 name = 0;
83 }
84
85 Instrument::~Instrument()
86 {
87 free(name);
88 }
89
90 //---------------------------------------------------------
91 // SoundFont
92 //---------------------------------------------------------
93
94 SoundFont::SoundFont(const QString& s)
95 {
96 path = s;
97 engine = 0;
98 name = 0;
99 date = 0;
100 comment = 0;
101 tools = 0;
102 creator = 0;
103 product = 0;
104 copyright = 0;
105 }
106
107 SoundFont::~SoundFont()
108 {
109 free(engine);
110 free(name);
111 free(date);
112 free(comment);
113 free(tools);
114 free(creator);
115 free(product);
116 free(copyright);
117 }
118
119 //---------------------------------------------------------
120 // read
121 //---------------------------------------------------------
122
123 bool SoundFont::read()
124 {
125 file = new QFile(path);
126 if (!file->open(QIODevice::ReadOnly)) {
127 fprintf(stderr, "cannot open <%s>\n", qPrintable(path));
128 delete file;
129 return false;
130 }
131 try {
132 int len = readFourcc("RIFF");
133 readSignature("sfbk");
134 len -= 4;
135 while (len) {
136 int len2 = readFourcc("LIST");
137 len -= (len2 + 8);
138 char fourcc[5];
139 fourcc[0] = 0;
140 readSignature(fourcc);
141 fourcc[4] = 0;
142 len2 -= 4;
143 while (len2) {
144 fourcc[0] = 0;
145 int len3 = readFourcc(fourcc);
146 fourcc[4] = 0;
147 len2 -= (len3 + 8);
148 readSection(fourcc, len3);
149 }
150 }
151 }
152 catch (QString s) {
153 printf("read sf file failed: %s\n", qPrintable(s));
154 delete file;
155 return false;
156 }
157 delete file;
158 return true;
159 }
160
161 //---------------------------------------------------------
162 // skip
163 //---------------------------------------------------------
164
165 void SoundFont::skip(int n)
166 {
167 qint64 pos = file->pos();
168 if (!file->seek(pos + n))
169 throw(QString("unexpected end of file\n"));
170 }
171
172 //---------------------------------------------------------
173 // readFourcc
174 //---------------------------------------------------------
175
176 int SoundFont::readFourcc(char* signature)
177 {
178 readSignature(signature);
179 return readDword();
180 }
181
182 int SoundFont::readFourcc(const char* signature)
183 {
184 readSignature(signature);
185 return readDword();
186 }
187
188 //---------------------------------------------------------
189 // readSignature
190 //---------------------------------------------------------
191
192 void SoundFont::readSignature(const char* signature)
193 {
194 char fourcc[4];
195 readSignature(fourcc);
196 if (memcmp(fourcc, signature, 4) != 0)
197 throw(QString("fourcc <%1> expected").arg(signature));
198 }
199
200 void SoundFont::readSignature(char* signature)
201 {
202 if (file->read(signature, 4) != 4)
203 throw(QString("unexpected end of file\n"));
204 }
205
206 //---------------------------------------------------------
207 // readDword
208 //---------------------------------------------------------
209
210 unsigned SoundFont::readDword()
211 {
212 unsigned format;
213 if (file->read((char*)&format, 4) != 4)
214 throw(QString("unexpected end of file\n"));
215 if (QSysInfo::ByteOrder == QSysInfo::BigEndian)
216 return BE_LONG(format);
217 else
218 return format;
219 }
220
221 //---------------------------------------------------------
222 // writeDword
223 //---------------------------------------------------------
224
225 void SoundFont::writeDword(int val)
226 {
227 if (QSysInfo::ByteOrder == QSysInfo::BigEndian)
228 val = BE_LONG(val);
229 write((char*)&val, 4);
230 }
231
232 //---------------------------------------------------------
233 // writeWord
234 //---------------------------------------------------------
235
236 void SoundFont::writeWord(unsigned short int val)
237 {
238 if (QSysInfo::ByteOrder == QSysInfo::BigEndian)
239 val = BE_SHORT(val);
240 write((char*)&val, 2);
241 }
242
243 //---------------------------------------------------------
244 // writeByte
245 //---------------------------------------------------------
246
247 void SoundFont::writeByte(unsigned char val)
248 {
249 write((char*)&val, 1);
250 }
251
252 //---------------------------------------------------------
253 // writeChar
254 //---------------------------------------------------------
255
256 void SoundFont::writeChar(char val)
257 {
258 write((char*)&val, 1);
259 }
260
261 //---------------------------------------------------------
262 // writeShort
263 //---------------------------------------------------------
264
265 void SoundFont::writeShort(short val)
266 {
267 if (QSysInfo::ByteOrder == QSysInfo::BigEndian)
268 val = BE_SHORT(val);
269 write((char*)&val, 2);
270 }
271
272 //---------------------------------------------------------
273 // readWord
274 //---------------------------------------------------------
275
276 int SoundFont::readWord()
277 {
278 unsigned short format;
279 if (file->read((char*)&format, 2) != 2)
280 throw(QString("unexpected end of file\n"));
281 if (QSysInfo::ByteOrder == QSysInfo::BigEndian)
282 return BE_SHORT(format);
283 else
284 return format;
285 }
286
287 //---------------------------------------------------------
288 // readShort
289 //---------------------------------------------------------
290
291 int SoundFont::readShort()
292 {
293 short format;
294 if (file->read((char*)&format, 2) != 2)
295 throw(QString("unexpected end of file\n"));
296 if (QSysInfo::ByteOrder == QSysInfo::BigEndian)
297 return BE_SHORT(format);
298 else
299 return format;
300 }
301
302 //---------------------------------------------------------
303 // readByte
304 //---------------------------------------------------------
305
306 int SoundFont::readByte()
307 {
308 uchar val;
309 if (file->read((char*)&val, 1) != 1)
310 throw(QString("unexpected end of file\n"));
311 return val;
312 }
313
314 //---------------------------------------------------------
315 // readChar
316 //---------------------------------------------------------
317
318 int SoundFont::readChar()
319 {
320 char val;
321 if (file->read(&val, 1) != 1)
322 throw(QString("unexpected end of file\n"));
323 return val;
324 }
325
326 //---------------------------------------------------------
327 // readVersion
328 //---------------------------------------------------------
329
330 void SoundFont::readVersion()
331 {
332 unsigned char data[4];
333 if (file->read((char*)data, 4) != 4)
334 throw(QString("unexpected end of file\n"));
335 version.major = data[0] + (data[1] << 8);
336 version.minor = data[2] + (data[3] << 8);
337 }
338
339 //---------------------------------------------------------
340 // readString
341 //---------------------------------------------------------
342
343 char* SoundFont::readString(int n)
344 {
345 char data[2500];
346 if (file->read((char*)data, n) != n)
347 throw(QString("unexpected end of file\n"));
348 if (data[n-1] != 0)
349 data[n] = 0;
350 return strdup(data);
351 }
352
353 //---------------------------------------------------------
354 // readSection
355 //---------------------------------------------------------
356
357 void SoundFont::readSection(const char* fourcc, int len)
358 {
359 printf("readSection <%s> len %d\n", fourcc, len);
360
361 switch(FOURCC(fourcc[0], fourcc[1], fourcc[2], fourcc[3])) {
362 case FOURCC('i', 'f', 'i', 'l'): // version
363 readVersion();
364 break;
365 case FOURCC('I','N','A','M'): // sound font name
366 name = readString(len);
367 break;
368 case FOURCC('i','s','n','g'): // target render engine
369 engine = readString(len);
370 break;
371 case FOURCC('I','P','R','D'): // product for which the bank was intended
372 product = readString(len);
373 break;
374 case FOURCC('I','E','N','G'): // sound designers and engineers for the bank
375 creator = readString(len);
376 break;
377 case FOURCC('I','S','F','T'): // SoundFont tools used to create and alter the bank
378 tools = readString(len);
379 break;
380 case FOURCC('I','C','R','D'): // date of creation of the bank
381 date = readString(len);
382 break;
383 case FOURCC('I','C','M','T'): // comments on the bank
384 comment = readString(len);
385 break;
386 case FOURCC('I','C','O','P'): // copyright message
387 copyright = readString(len);
388 break;
389 case FOURCC('s','m','p','l'): // the digital audio samples
390 samplePos = file->pos();
391 sampleLen = len;
392 skip(len);
393 break;
394 case FOURCC('p','h','d','r'): // preset headers
395 readPhdr(len);
396 break;
397 case FOURCC('p','b','a','g'): // preset index list
398 readBag(len, &pZones);
399 break;
400 case FOURCC('p','m','o','d'): // preset modulator list
401 readMod(len, &pZones);
402 break;
403 case FOURCC('p','g','e','n'): // preset generator list
404 readGen(len, &pZones);
405 break;
406 case FOURCC('i','n','s','t'): // instrument names and indices
407 readInst(len);
408 break;
409 case FOURCC('i','b','a','g'): // instrument index list
410 readBag(len, &iZones);
411 break;
412 case FOURCC('i','m','o','d'): // instrument modulator list
413 readMod(len, &iZones);
414 break;
415 case FOURCC('i','g','e','n'): // instrument generator list
416 readGen(len, &iZones);
417 break;
418 case FOURCC('s','h','d','r'): // sample headers
419 readShdr(len);
420 break;
421 case FOURCC('i', 'r', 'o', 'm'): // sample rom
422 case FOURCC('i', 'v', 'e', 'r'): // sample rom version
423 default:
424 skip(len);
425 throw(QString("unknown fourcc <%1>").arg(fourcc));
426 break;
427 }
428 }
429
430 //---------------------------------------------------------
431 // readPhdr
432 //---------------------------------------------------------
433
434 void SoundFont::readPhdr(int len)
435 {
436 if (len < (38 * 2))
437 throw(QString("phdr too short"));
438 if (len % 38)
439 throw(QString("phdr not a multiple of 38"));
440 int n = len / 38;
441 if (n <= 1) {
442 printf("no presets\n");
443 skip(len);
444 return;
445 }
446 int index1 = 0, index2;
447 for (int i = 0; i < n; ++i) {
448 Preset* preset = new Preset;
449 preset->name = readString(20);
450 preset->preset = readWord();
451 preset->bank = readWord();
452 index2 = readWord();
453 preset->library = readDword();
454 preset->genre = readDword();
455 preset->morphology = readDword();
456 if (index2 < index1)
457 throw("preset header indices not monotonic");
458 if (i > 0) {
459 int n = index2 - index1;
460 while (n--) {
461 Zone* z = new Zone;
462 presets.back()->zones.append(z);
463 pZones.append(z);
464 }
465 }
466 index1 = index2;
467 presets.append(preset);
468 }
469 presets.takeLast();
470 }
471
472 //---------------------------------------------------------
473 // readBag
474 //---------------------------------------------------------
475
476 void SoundFont::readBag(int len, QList<Zone*>* zones)
477 {
478 if (len % 4)
479 throw(QString("bag size not a multiple of 4"));
480 int gIndex2, mIndex2;
481 int gIndex1 = readWord();
482 int mIndex1 = readWord();
483 len -= 4;
484 foreach(Zone* zone, *zones) {
485 gIndex2 = readWord();
486 mIndex2 = readWord();
487 len -= 4;
488 if (len < 0)
489 throw(QString("bag size too small"));
490 if (gIndex2 < gIndex1)
491 throw("generator indices not monotonic");
492 if (mIndex2 < mIndex1)
493 throw("modulator indices not monotonic");
494 int n = mIndex2 - mIndex1;
495 while (n--)
496 zone->modulators.append(new ModulatorList);
497 n = gIndex2 - gIndex1;
498 while (n--)
499 zone->generators.append(new GeneratorList);
500 gIndex1 = gIndex2;
501 mIndex1 = mIndex2;
502 }
503 }
504
505 //---------------------------------------------------------
506 // readMod
507 //---------------------------------------------------------
508
509 void SoundFont::readMod(int size, QList<Zone*>* zones)
510 {
511 foreach(Zone* zone, *zones) {
512 foreach(ModulatorList* m, zone->modulators) {
513 size -= 10;
514 if (size < 0)
515 throw(QString("pmod size mismatch"));
516 m->src = static_cast<Modulator>(readWord());
517 m->dst = static_cast<Generator>(readWord());
518 m->amount = readShort();
519 m->amtSrc = static_cast<Modulator>(readWord());
520 m->transform = static_cast<Transform>(readWord());
521 }
522 }
523 if (size != 10)
524 throw(QString("modulator list size mismatch"));
525 skip(10);
526 }
527
528 //---------------------------------------------------------
529 // readGen
530 //---------------------------------------------------------
531
532 void SoundFont::readGen(int size, QList<Zone*>* zones)
533 {
534 if (size % 4)
535 throw(QString("bad generator list size"));
536 foreach (Zone* zone, *zones) {
537 size -= (zone->generators.size() * 4);
538 if (size < 0)
539 break;
540
541 foreach (GeneratorList* gen, zone->generators) {
542 gen->gen = static_cast<Generator>(readWord());
543 if (gen->gen == Gen_KeyRange || gen->gen == Gen_VelRange) {
544 gen->amount.lo = readByte();
545 gen->amount.hi = readByte();
546 }
547 else if (gen->gen == Gen_Instrument)
548 gen->amount.uword = readWord();
549 else
550 gen->amount.sword = readWord();
551 }
552 }
553 if (size != 4)
554 throw(QString("generator list size mismatch %1 != 4").arg(size));
555 skip(size);
556 }
557
558 //---------------------------------------------------------
559 // readInst
560 //---------------------------------------------------------
561
562 void SoundFont::readInst(int size)
563 {
564 int n = size / 22;
565 int index1 = 0, index2;
566 for (int i = 0; i < n; ++i) {
567 Instrument* instrument = new Instrument;
568 instrument->name = readString(20);
569 index2 = readWord();
570 if (index2 < index1)
571 throw("instrument header indices not monotonic");
572 if (i > 0) {
573 int n = index2 - index1;
574 while (n--) {
575 Zone* z = new Zone;
576 instruments.back()->zones.append(z);
577 iZones.append(z);
578 }
579 }
580 index1 = index2;
581 instruments.append(instrument);
582 }
583 instruments.takeLast();
584 }
585
586 //---------------------------------------------------------
587 // readShdr
588 //---------------------------------------------------------
589
590 void SoundFont::readShdr(int size)
591 {
592 int n = size / 46;
593 for (int i = 0; i < n-1; ++i) {
594 Sample* s = new Sample;
595 s->name = readString(20);
596 s->start = readDword();
597 s->end = readDword();
598 s->loopstart = readDword();
599 s->loopend = readDword();
600 s->samplerate = readDword();
601 s->origpitch = readByte();
602 s->pitchadj = readChar();
603 readWord(); // sampleLink
604 s->sampletype = readWord();
605
606 s->loopstart -= s->start;
607 s->loopend -= s->start;
608 // printf("readFontHeader %d %d %d %d\n", s->start, s->end, s->loopstart, s->loopend);
609 samples.append(s);
610 }
611 skip(46); // trailing record
612 }
613
614 //---------------------------------------------------------
615 // writeXml
616 //---------------------------------------------------------
617
618 bool SoundFont::writeXml(QFile* f)
619 {
620 Xml xml(f);
621
622 xml.header();
623 xml.stag("Sfont");
624 xml.tag("version", QString("%1.%2").arg(version.major).arg(version.minor));
625 if (name)
626 xml.tag("name", Xml::xmlString(name));
627 if (engine)
628 xml.tag("engine", Xml::xmlString(engine));
629 if (date)
630 xml.tag("date", Xml::xmlString(date));
631 if (comment)
632 xml.tag("comment", Xml::xmlString(comment));
633 if (tools)
634 xml.tag("tools", Xml::xmlString(tools));
635 if (creator)
636 xml.tag("creator", Xml::xmlString(creator));
637 if (product)
638 xml.tag("product", Xml::xmlString(product));
639 if (copyright)
640 xml.tag("copyright", Xml::xmlString(copyright));
641
642 foreach(Preset* p, presets) {
643 xml.stag(QString("Preset name=\"%1\" preset=\"%2\" bank=\"%3\"")
644 .arg(p->name).arg(p->preset).arg(p->bank));
645 foreach(Zone* z, p->zones)
646 write(xml, z);
647 xml.etag();
648 }
649 foreach(Instrument* instrument, instruments) {
650 xml.stag(QString("Instrument name=\"%1\"").arg(instrument->name));
651 foreach(Zone* z, instrument->zones)
652 write(xml, z);
653 xml.etag();
654 }
655 int idx = 0;
656 foreach(Sample* s, samples) {
657 xml.stag(QString("Sample name=\"%1\"").arg(s->name));
658 xml.tag("start", s->start);
659 xml.tag("end", s->end);
660 xml.tag("loopstart", s->loopstart);
661 xml.tag("loopend", s->loopend);
662 xml.tag("samplerate", s->samplerate);
663 xml.tag("origpitch", s->origpitch);
664 if (s->pitchadj)
665 xml.tag("pitchadj", s->pitchadj);
666 xml.tag("sampletype", s->sampletype);
667 xml.etag();
668 writeSampleFile(s, QString("%1").arg(idx));
669 ++idx;
670 }
671 xml.etag();
672 return true;
673 }
674
675 static const char* generatorNames[] = {
676 "StartAddrOfs", "EndAddrOfs", "StartLoopAddrOfs",
677 "EndLoopAddrOfs", "StartAddrCoarseOfs", "ModLFO2Pitch",
678 "VibLFO2Pitch", "ModEnv2Pitch", "FilterFc", "FilterQ",
679 "ModLFO2FilterFc", "ModEnv2FilterFc", "EndAddrCoarseOfs",
680 "ModLFO2Vol", "Unused1", "ChorusSend", "ReverbSend", "Pan",
681 "Unused2", "Unused3", "Unused4",
682 "ModLFODelay", "ModLFOFreq", "VibLFODelay", "VibLFOFreq",
683 "ModEnvDelay", "ModEnvAttack", "ModEnvHold", "ModEnvDecay",
684 "ModEnvSustain", "ModEnvRelease", "Key2ModEnvHold",
685 "Key2ModEnvDecay", "VolEnvDelay", "VolEnvAttack",
686 "VolEnvHold", "VolEnvDecay", "VolEnvSustain", "VolEnvRelease",
687 "Key2VolEnvHold", "Key2VolEnvDecay", "Instrument",
688 "Reserved1", "KeyRange", "VelRange",
689 "StartLoopAddrCoarseOfs", "Keynum", "Velocity",
690 "Attenuation", "Reserved2", "EndLoopAddrCoarseOfs",
691 "CoarseTune", "FineTune", "SampleId", "SampleModes",
692 "Reserved3", "ScaleTune", "ExclusiveClass", "OverrideRootKey",
693 "Dummy"
694 };
695
696 //---------------------------------------------------------
697 // write
698 //---------------------------------------------------------
699
700 void SoundFont::write(Xml& xml, Zone* z)
701 {
702 xml.stag("Zone");
703 foreach(GeneratorList* g, z->generators) {
704 const char* name = generatorNames[g->gen];
705 if (g->gen == Gen_KeyRange || g->gen == Gen_VelRange)
706 xml.tagE(QString("Generator name=\"%1\" lo=\"%2\" hi=\"%3\"")
707 .arg(name).arg(g->amount.lo).arg(g->amount.hi));
708 else if (g->gen == Gen_Instrument) {
709 int idx = g->amount.uword;
710 xml.tag("Instrument", instruments[idx]->name);
711 }
712 else if (g->gen == Gen_SampleId) {
713 int idx = g->amount.uword;
714 xml.tag("SampleId", samples[idx]->name);
715 }
716 else
717 xml.tagE(QString("Generator name=\"%1\" val=\"%2\"")
718 .arg(name).arg(g->amount.sword));
719 }
720 foreach(ModulatorList* m, z->modulators) {
721 xml.stag("Modulator");
722 xml.tag("src", m->src);
723 xml.tag("dst", m->dst);
724 xml.tag("amount", m->amount);
725 xml.tag("amtSrc", m->amtSrc);
726 xml.tag("transform", m->transform);
727 xml.etag();
728 }
729 xml.etag();
730 }
731
732 //---------------------------------------------------------
733 // write
734 //---------------------------------------------------------
735
736 bool SoundFont::write(QFile* f, double oggQuality, double oggAmp, qint64 oggSerial)
737 {
738 file = f;
739 _oggQuality = oggQuality;
740 _oggAmp = oggAmp;
741 _oggSerial = oggSerial;
742 qint64 riffLenPos;
743 qint64 listLenPos;
744 try {
745 file->write("RIFF", 4);
746 riffLenPos = file->pos();
747 writeDword(0);
748 file->write("sfbk", 4);
749
750 file->write("LIST", 4);
751 listLenPos = file->pos();
752 writeDword(0);
753 file->write("INFO", 4);
754
755 writeIfil();
756 if (name)
757 writeStringSection("INAM", name);
758 if (engine)
759 writeStringSection("isng", engine);
760 if (product)
761 writeStringSection("IPRD", product);
762 if (creator)
763 writeStringSection("IENG", creator);
764 if (tools)
765 writeStringSection("ISFT", tools);
766 if (date)
767 writeStringSection("ICRD", date);
768 if (comment)
769 writeStringSection("ICMT", comment);
770 if (copyright)
771 writeStringSection("ICOP", copyright);
772
773 qint64 pos = file->pos();
774 file->seek(listLenPos);
775 writeDword(pos - listLenPos - 4);
776 file->seek(pos);
777
778 file->write("LIST", 4);
779 listLenPos = file->pos();
780 writeDword(0);
781 file->write("sdta", 4);
782 writeSmpl();
783 pos = file->pos();
784 file->seek(listLenPos);
785 writeDword(pos - listLenPos - 4);
786 file->seek(pos);
787
788 file->write("LIST", 4);
789 listLenPos = file->pos();
790 writeDword(0);
791 file->write("pdta", 4);
792
793 writePhdr();
794 writeBag("pbag", &pZones);
795 writeMod("pmod", &pZones);
796 writeGen("pgen", &pZones);
797 writeInst();
798 writeBag("ibag", &iZones);
799 writeMod("imod", &iZones);
800 writeGen("igen", &iZones);
801 writeShdr();
802
803 pos = file->pos();
804 file->seek(listLenPos);
805 writeDword(pos - listLenPos - 4);
806 file->seek(pos);
807
808 qint64 endPos = file->pos();
809 file->seek(riffLenPos);
810 writeDword(endPos - riffLenPos - 4);
811 }
812 catch (QString s) {
813 printf("write sf file failed: %s\n", qPrintable(s));
814 return false;
815 }
816 return true;
817 }
818
819 //---------------------------------------------------------
820 // readXml
821 //---------------------------------------------------------
822
823 bool SoundFont::readXml(QFile* f)
824 {
825 QDomDocument doc;
826 int line, column;
827 QString err;
828 if (!doc.setContent(f, false, &err, &line, &column)) {
829 QString s;
830 printf("error reading file %s at line %d column %d: %s\n",
831 qPrintable(f->fileName()), line, column, qPrintable(err));
832 return false;
833 }
834 return true;
835 }
836
837 //---------------------------------------------------------
838 // write
839 //---------------------------------------------------------
840
841 void SoundFont::write(const char* p, int n)
842 {
843 if (file->write(p, n) != n)
844 throw(QString("write error"));
845 }
846
847 //---------------------------------------------------------
848 // writeStringSection
849 //---------------------------------------------------------
850
851 void SoundFont::writeStringSection(const char* fourcc, char* s)
852 {
853 write(fourcc, 4);
854 int nn = strlen(s) + 1;
855 int n = ((nn + 1) / 2) * 2;
856 writeDword(n);
857 write(s, nn);
858 if (n - nn) {
859 char c = 0;
860 write(&c, 1);
861 }
862 }
863
864 //---------------------------------------------------------
865 // writeIfil
866 //---------------------------------------------------------
867
868 void SoundFont::writeIfil()
869 {
870 write("ifil", 4);
871 writeDword(4);
872 unsigned char data[4];
873 if (writeCompressed)
874 version.major = 3;
875 data[0] = version.major;
876 data[1] = version.major >> 8;
877 data[2] = version.minor;
878 data[3] = version.minor >> 8;
879 write((char*)data, 4);
880 }
881
882 //---------------------------------------------------------
883 // writeSmpl
884 //---------------------------------------------------------
885
886 void SoundFont::writeSmpl()
887 {
888 write("smpl", 4);
889
890 qint64 pos = file->pos();
891 writeDword(0);
892 int sampleLen = 0;
893 if (writeCompressed) {
894 foreach(Sample* s, samples) {
895 s->sampletype |= 0x10;
896 int len = writeCompressedSample(s);
897 s->start = sampleLen;
898 sampleLen += len;
899 s->end = sampleLen;
900 }
901 }
902 else {
903 char* buffer = new char[sampleLen];
904 QFile f(path);
905 if (!f.open(QIODevice::ReadOnly))
906 throw(QString("cannot open <%1>").arg(f.fileName()));
907 foreach(Sample* s, samples) {
908 f.seek(samplePos + s->start * sizeof(short));
909
910 int len = (s->end - s->start) * sizeof(short);
911 f.read(buffer, len);
912 write(buffer, len);
913 s->start = sampleLen / sizeof(short);
914 sampleLen += len;
915 s->end = sampleLen / sizeof(short);
916 s->loopstart += s->start;
917 s->loopend += s->start;
918 }
919 f.close();
920 delete[] buffer;
921 }
922 qint64 npos = file->pos();
923 file->seek(pos);
924 writeDword(npos - pos - 4);
925 file->seek(npos);
926 }
927
928 //---------------------------------------------------------
929 // writePhdr
930 //---------------------------------------------------------
931
932 void SoundFont::writePhdr()
933 {
934 write("phdr", 4);
935 int n = presets.size();
936 writeDword((n + 1) * 38);
937 int zoneIdx = 0;
938 foreach(const Preset* p, presets) {
939 writePreset(zoneIdx, p);
940 zoneIdx += p->zones.size();
941 }
942 Preset p;
943 memset(&p, sizeof(p), 0);
944 writePreset(zoneIdx, &p);
945 }
946
947 //---------------------------------------------------------
948 // writePreset
949 //---------------------------------------------------------
950
951 void SoundFont::writePreset(int zoneIdx, const Preset* preset)
952 {
953 char name[20];
954 memset(name, 0, 20);
955 if (preset->name)
956 memcpy(name, preset->name, strlen(preset->name));
957 write(name, 20);
958 writeWord(preset->preset);
959 writeWord(preset->bank);
960 writeWord(zoneIdx);
961 writeDword(preset->library);
962 writeDword(preset->genre);
963 writeDword(preset->morphology);
964 }
965
966 //---------------------------------------------------------
967 // writeBag
968 //---------------------------------------------------------
969
970 void SoundFont::writeBag(const char* fourcc, QList<Zone*>* zones)
971 {
972 write(fourcc, 4);
973 int n = zones->size();
974 writeDword((n + 1) * 4);
975 int gIndex = 0;
976 int pIndex = 0;
977 foreach(const Zone* z, *zones) {
978 writeWord(gIndex);
979 writeWord(pIndex);
980 gIndex += z->generators.size();
981 pIndex += z->modulators.size();
982 }
983 writeWord(gIndex);
984 writeWord(pIndex);
985 }
986
987 //---------------------------------------------------------
988 // writeMod
989 //---------------------------------------------------------
990
991 void SoundFont::writeMod(const char* fourcc, const QList<Zone*>* zones)
992 {
993 write(fourcc, 4);
994 int n = 0;
995 foreach(const Zone* z, *zones)
996 n += z->modulators.size();
997 writeDword((n + 1) * 10);
998
999 foreach(const Zone* zone, *zones) {
1000 foreach(const ModulatorList* m, zone->modulators)
1001 writeModulator(m);
1002 }
1003 ModulatorList mod;
1004 memset(&mod, 0, sizeof(mod));
1005 writeModulator(&mod);
1006 }
1007
1008 //---------------------------------------------------------
1009 // writeModulator
1010 //---------------------------------------------------------
1011
1012 void SoundFont::writeModulator(const ModulatorList* m)
1013 {
1014 writeWord(m->src);
1015 writeWord(m->dst);
1016 writeShort(m->amount);
1017 writeWord(m->amtSrc);
1018 writeWord(m->transform);
1019 }
1020
1021 //---------------------------------------------------------
1022 // writeGen
1023 //---------------------------------------------------------
1024
1025 void SoundFont::writeGen(const char* fourcc, QList<Zone*>* zones)
1026 {
1027 write(fourcc, 4);
1028 int n = 0;
1029 foreach(const Zone* z, *zones)
1030 n += z->generators.size();
1031 writeDword((n + 1) * 4);
1032
1033 foreach(const Zone* zone, *zones) {
1034 foreach(const GeneratorList* g, zone->generators)
1035 writeGenerator(g);
1036 }
1037 GeneratorList gen;
1038 memset(&gen, 0, sizeof(gen));
1039 writeGenerator(&gen);
1040 }
1041
1042 //---------------------------------------------------------
1043 // writeGenerator
1044 //---------------------------------------------------------
1045
1046 void SoundFont::writeGenerator(const GeneratorList* g)
1047 {
1048 writeWord(g->gen);
1049 if (g->gen == Gen_KeyRange || g->gen == Gen_VelRange) {
1050 writeByte(g->amount.lo);
1051 writeByte(g->amount.hi);
1052 }
1053 else if (g->gen == Gen_Instrument)
1054 writeWord(g->amount.uword);
1055 else
1056 writeWord(g->amount.sword);
1057 }
1058
1059 //---------------------------------------------------------
1060 // writeInst
1061 //---------------------------------------------------------
1062
1063 void SoundFont::writeInst()
1064 {
1065 write("inst", 4);
1066 int n = instruments.size();
1067 writeDword((n + 1) * 22);
1068 int zoneIdx = 0;
1069 foreach(const Instrument* p, instruments) {
1070 writeInstrument(zoneIdx, p);
1071 zoneIdx += p->zones.size();
1072 }
1073 Instrument p;
1074 memset(&p, sizeof(p), 0);
1075 writeInstrument(zoneIdx, &p);
1076 }
1077
1078 //---------------------------------------------------------
1079 // writeInstrument
1080 //---------------------------------------------------------
1081
1082 void SoundFont::writeInstrument(int zoneIdx, const Instrument* instrument)
1083 {
1084 char name[20];
1085 memset(name, 0, 20);
1086 if (instrument->name)
1087 memcpy(name, instrument->name, strlen(instrument->name));
1088 write(name, 20);
1089 writeWord(zoneIdx);
1090 }
1091
1092 //---------------------------------------------------------
1093 // writeShdr
1094 //---------------------------------------------------------
1095
1096 void SoundFont::writeShdr()
1097 {
1098 write("shdr", 4);
1099 writeDword(46 * (samples.size() + 1));
1100 foreach(const Sample* s, samples)
1101 writeSample(s);
1102 Sample s;
1103 memset(&s, 0, sizeof(s));
1104 writeSample(&s);
1105 }
1106
1107 //---------------------------------------------------------
1108 // writeSample
1109 //---------------------------------------------------------
1110
1111 void SoundFont::writeSample(const Sample* s)
1112 {
1113 char name[20];
1114 memset(name, 0, 20);
1115 if (s->name)
1116 memcpy(name, s->name, strlen(s->name));
1117 write(name, 20);
1118 writeDword(s->start);
1119 writeDword(s->end);
1120 writeDword(s->loopstart);
1121 writeDword(s->loopend);
1122 writeDword(s->samplerate);
1123 writeByte(s->origpitch);
1124 writeChar(s->pitchadj);
1125 writeWord(0);
1126 writeWord(s->sampletype);
1127 }
1128
1129 //---------------------------------------------------------
1130 // writeSampleFile
1131 //---------------------------------------------------------
1132
1133 bool SoundFont::writeSampleFile(Sample* s, QString name)
1134 {
1135 QString path = "waves/" + name + ".ogg";
1136
1137 QFile f(path);
1138 if (!f.open(QIODevice::ReadOnly)) {
1139 fprintf(stderr, "cannot open <%s>\n", qPrintable(f.fileName()));
1140 return false;
1141 }
1142 f.seek(samplePos + s->start * sizeof(short));
1143 int len = s->end - s->start;
1144 short buffer[len];
1145 f.read((char*)buffer, len * sizeof(short));
1146 f.close();
1147
1148 // int format = SF_FORMAT_WAV | SF_FORMAT_PCM_16;
1149 int format = SF_FORMAT_OGG | SF_FORMAT_VORBIS;
1150
1151 SF_INFO info;
1152 memset(&info, 0, sizeof(info));
1153 info.channels = 1;
1154 info.samplerate = s->samplerate;
1155 info.format = format;
1156
1157 SNDFILE* sf = sf_open(qPrintable(path), SFM_WRITE, &info);
1158 if (sf == 0) {
1159 fprintf(stderr, "open soundfile <%s> failed: %s\n",
1160 qPrintable(path), sf_strerror(sf));
1161 return false;
1162 }
1163
1164 sf_write_short(sf, buffer, len);
1165
1166 if (sf_close(sf)) {
1167 fprintf(stderr, "close soundfile failed\n");
1168 return false;
1169 }
1170 return true;
1171 }
1172
1173 //---------------------------------------------------------
1174 // writeCompressedSample
1175 //---------------------------------------------------------
1176
1177 int SoundFont::writeCompressedSample(Sample* s)
1178 {
1179 QFile f(path);
1180 if (!f.open(QIODevice::ReadOnly)) {
1181 fprintf(stderr, "cannot open <%s>\n", qPrintable(f.fileName()));
1182 return 0;
1183 }
1184 f.seek(samplePos + s->start * sizeof(short));
1185 int samples = s->end - s->start;
1186 short ibuffer[samples];
1187 f.read((char*)ibuffer, samples * sizeof(short));
1188 f.close();
1189
1190 ogg_stream_state os;
1191 ogg_page og;
1192 ogg_packet op;
1193 vorbis_info vi;
1194 vorbis_dsp_state vd;
1195 vorbis_block vb;
1196 vorbis_comment vc;
1197
1198 vorbis_info_init(&vi);
1199 int ret = vorbis_encode_init_vbr(&vi, 1, s->samplerate, _oggQuality);
1200 if (ret) {
1201 printf("vorbis init failed\n");
1202 return false;
1203 }
1204 vorbis_comment_init(&vc);
1205 vorbis_analysis_init(&vd, &vi);
1206 vorbis_block_init(&vd, &vb);
1207 srand(time(NULL));
1208 ogg_stream_init(&os, _oggSerial == std::numeric_limits<qint64>::max() ? rand() : (int)_oggSerial);
1209
1210 ogg_packet header;
1211 ogg_packet header_comm;
1212 ogg_packet header_code;
1213
1214 vorbis_analysis_headerout(&vd, &vc, &header, &header_comm, &header_code);
1215 ogg_stream_packetin(&os, &header);
1216 ogg_stream_packetin(&os, &header_comm);
1217 ogg_stream_packetin(&os, &header_code);
1218
1219 char obuf[1024 * 1024];
1220 char* p = obuf;
1221
1222 for (;;) {
1223 int result = ogg_stream_flush(&os, &og);
1224 if (result == 0)
1225 break;
1226 memcpy(p, og.header, og.header_len);
1227 p += og.header_len;
1228 memcpy(p, og.body, og.body_len);
1229 p += og.body_len;
1230 }
1231
1232 long i;
1233 int page = 0;
1234 double linearAmp = pow(10.0, _oggAmp / 20.0);
1235 for(;;) {
1236 int bufflength = qMin(BLOCK_SIZE, samples-page*BLOCK_SIZE);
1237 float **buffer = vorbis_analysis_buffer(&vd, bufflength);
1238 int j = 0;
1239 int max = qMin((page+1)*BLOCK_SIZE, samples);
1240 for (i = page * BLOCK_SIZE; i < max ; i++) {
1241 buffer[0][j] = (ibuffer[i] / 32768.f) * linearAmp;
1242 j++;
1243 }
1244
1245 vorbis_analysis_wrote(&vd, bufflength);
1246
1247 while (vorbis_analysis_blockout(&vd, &vb) == 1) {
1248 vorbis_analysis(&vb, 0);
1249 vorbis_bitrate_addblock(&vb);
1250
1251 while (vorbis_bitrate_flushpacket(&vd, &op)) {
1252 ogg_stream_packetin(&os, &op);
1253
1254 for(;;) {
1255 int result = ogg_stream_pageout(&os, &og);
1256 if (result == 0)
1257 break;
1258 memcpy(p, og.header, og.header_len);
1259 p += og.header_len;
1260 memcpy(p, og.body, og.body_len);
1261 p += og.body_len;
1262 }
1263 }
1264 }
1265 page++;
1266 if ((max == samples) || !((samples-page*BLOCK_SIZE)>0))
1267 break;
1268 }
1269
1270 vorbis_analysis_wrote(&vd, 0);
1271
1272 while (vorbis_analysis_blockout(&vd, &vb) == 1) {
1273 vorbis_analysis(&vb, 0);
1274 vorbis_bitrate_addblock(&vb);
1275
1276 while (vorbis_bitrate_flushpacket(&vd, &op)) {
1277 ogg_stream_packetin(&os, &op);
1278
1279 for(;;) {
1280 int result = ogg_stream_pageout(&os, &og);
1281 if (result == 0)
1282 break;
1283 memcpy(p, og.header, og.header_len);
1284 p += og.header_len;
1285 memcpy(p, og.body, og.body_len);
1286 p += og.body_len;
1287 }
1288 }
1289 }
1290
1291 ogg_stream_clear(&os);
1292 vorbis_block_clear(&vb);
1293 vorbis_dsp_clear(&vd);
1294 vorbis_comment_clear(&vc);
1295 vorbis_info_clear(&vi);
1296
1297 int n = p - obuf;
1298 write(obuf, n);
1299
1300 return n;
1301 }
1302
1303 //---------------------------------------------------------
1304 // readCompressedSample
1305 //---------------------------------------------------------
1306
1307 char* SoundFont::readCompressedSample(Sample* s)
1308 {
1309 return 0;
1310 }
1311
1312 //---------------------------------------------------------
1313 // writeCSample
1314 //---------------------------------------------------------
1315
1316 bool SoundFont::writeCSample(Sample* s, int idx)
1317 {
1318 QFile fi(path);
1319 if (!fi.open(QIODevice::ReadOnly)) {
1320 fprintf(stderr, "cannot open <%s>\n", qPrintable(fi.fileName()));
1321 return false;
1322 }
1323 fi.seek(samplePos + s->start * sizeof(short));
1324 int samples = s->end - s->start;
1325 short ibuffer[samples];
1326 fi.read((char*)ibuffer, samples * sizeof(short));
1327 fi.close();
1328
1329 fprintf(f, "static const short wave%d[] = {\n ", idx);
1330 int n = 0;
1331 for (int row = 0;; ++row) {
1332 for (int col = 0; col < 16; ++col) {
1333 if (n >= samples)
1334 break;
1335 if (col != 0)
1336 fprintf(f, ", ");
1337 fprintf(f, "%d", ibuffer[n]);
1338 ++n;
1339 }
1340 if (n >= samples)
1341 break;
1342 fprintf(f, ",\n ");
1343 }
1344 fprintf(f, "\n };\n");
1345 return true;
1346 }
1347
1348 //---------------------------------------------------------
1349 // checkInstrument
1350 //---------------------------------------------------------
1351
1352 static bool checkInstrument(QList<int> pnums, QList<Preset*> presets, int instrIdx)
1353 {
1354 foreach(int idx, pnums) {
1355 Preset* p = presets[idx];
1356 foreach(Zone* z, p->zones) {
1357 foreach(GeneratorList* g, z->generators) {
1358 if (g->gen == Gen_Instrument) {
1359 if (instrIdx == g->amount.uword)
1360 return true;
1361 }
1362 }
1363 }
1364 }
1365 return false;
1366 }
1367
1368 static bool checkInstrument(QList<Preset*> presets, int instrIdx) {
1369 bool result = false;
1370 for(int i = 0; i < presets.size(); i++) {
1371 Preset* p = presets[i];
1372 Zone* z = p->zones[0];
1373 foreach(GeneratorList* g, z->generators) {
1374 if (g->gen == Gen_Instrument) {
1375 if (instrIdx == g->amount.uword)
1376 return true;
1377 }
1378 }
1379 }
1380 return false;
1381 }
1382
1383 //---------------------------------------------------------
1384 // checkSample
1385 //---------------------------------------------------------
1386
1387 static bool checkSample(QList<int> pnums, QList<Preset*> presets, QList<Instrument*> instruments,
1388 int sampleIdx)
1389 {
1390 int idx = 0;
1391 foreach(Instrument* instrument, instruments) {
1392 if (!checkInstrument(pnums, presets, idx)) {
1393 ++idx;
1394 continue;
1395 }
1396 int zones = instrument->zones.size();
1397 foreach(Zone* z, instrument->zones) {
1398 QList<GeneratorList*> gl;
1399 foreach(GeneratorList* g, z->generators) {
1400 if (g->gen == Gen_SampleId) {
1401 if (sampleIdx == g->amount.uword)
1402 return true;
1403 }
1404 }
1405 }
1406 ++idx;
1407 }
1408 return false;
1409 }
1410
1411 //---------------------------------------------------------
1412 // checkSample
1413 //---------------------------------------------------------
1414
1415 static bool checkSample(QList<Preset*> presets, QList<Instrument*> instruments,
1416 int sampleIdx)
1417 {
1418 int idx = 0;
1419 foreach(Instrument* instrument, instruments) {
1420 if (!checkInstrument(presets, idx)) {
1421 ++idx;
1422 continue;
1423 }
1424 int zones = instrument->zones.size();
1425 foreach(Zone* z, instrument->zones) {
1426 QList<GeneratorList*> gl;
1427 foreach(GeneratorList* g, z->generators) {
1428 if (g->gen == Gen_SampleId) {
1429 if (sampleIdx == g->amount.uword)
1430 return true;
1431 }
1432 }
1433 }
1434 ++idx;
1435 }
1436 return false;
1437 }
1438
1439 //---------------------------------------------------------
1440 // writeCode
1441 //---------------------------------------------------------
1442
1443 bool SoundFont::writeCode()
1444 {
1445 int segments = 8;
1446 int n = samples.size() / segments;
1447 for (int i = 0; i < segments; ++i) {
1448 char buffer[16];
1449 sprintf(buffer, "sf%d.cpp", i + 1);
1450 f = fopen(buffer, "w+");
1451 fprintf(f, "//\n// this is generated code, do not change\n//\n");
1452 fprintf(f, "#include \"sfont.h\"\n\n");
1453 fprintf(f, "namespace FluidS {\n\n");
1454
1455 //
1456 // dump wave samples
1457 //
1458 int end;
1459 if (i+1 == segments)
1460 end = samples.size();
1461 else
1462 end = (i+1) * n;
1463 QList<int> sampleIdx;
1464 for (int idx = i * n; idx < end; ++idx) {
1465 if (smallSf && !checkSample(presets, instruments, idx))
1466 continue;
1467 Sample* s = samples[idx];
1468 writeCSample(s, idx);
1469 sampleIdx.append(idx);
1470 }
1471
1472 //
1473 // dump Sample[]
1474 //
1475 foreach(int idx, sampleIdx) {
1476 Sample* s = samples[idx];
1477 fprintf(f, "Sample sample%d(%d, %d, %d, %d, %d, %d, %d, %d, wave%d);\n",
1478 idx,
1479 0,
1480 s->end - (s->start + 1),
1481 s->loopstart, // - s->start,
1482 s->loopend, // - s->start,
1483 s->samplerate, s->origpitch, s->pitchadj, s->sampletype,
1484 idx);
1485 }
1486 fprintf(f, "} // end namespace\n");
1487 fclose(f);
1488 }
1489
1490 f = fopen("sf.cpp", "w+");
1491 fprintf(f, "//\n// this is generated code, do not change\n//\n");
1492 fprintf(f, "#include \"sfont.h\"\n\n");
1493 fprintf(f, "namespace FluidS {\n\n");
1494
1495 fprintf(f, "extern Sample ");
1496 for (int i = 0; i < samples.size(); ++i) {
1497 if (i) {
1498 if ((i % 8) == 0)
1499 fprintf(f, ";\nextern Sample ");
1500 else
1501 fprintf(f, ", ");
1502 }
1503 fprintf(f, "sample%d", i);
1504 }
1505 fprintf(f, ";\n");
1506
1507 //
1508 // dump Instrument[]
1509 //
1510 int idx2;
1511 int idx = 0;
1512 foreach(Instrument* instrument, instruments) {
1513 if (smallSf && !checkInstrument(presets, idx)) {
1514 ++idx;
1515 continue;
1516 }
1517 int zones = instrument->zones.size();
1518 idx2 = 0;
1519 foreach(Zone* z, instrument->zones) {
1520 int keyLo = 0;
1521 int keyHi = 127;
1522 int veloLo = 0;
1523 int veloHi = 127;
1524 int sampleIdx = -1;
1525
1526 QList<GeneratorList*> gl;
1527 foreach(GeneratorList* g, z->generators) {
1528 const char* name = generatorNames[g->gen];
1529 if (g->gen == Gen_KeyRange) {
1530 keyLo = g->amount.lo;
1531 keyHi = g->amount.hi;
1532 }
1533 else if (g->gen == Gen_VelRange) {
1534 veloLo = g->amount.lo;
1535 veloHi = g->amount.hi;
1536 }
1537 else if (g->gen == Gen_SampleId)
1538 sampleIdx = g->amount.uword;
1539 else
1540 gl.append(g);
1541 if (smallSf && g->gen == Gen_Pan)
1542 g->amount.uword = 0;
1543 }
1544 int idx3 = 0;
1545 foreach(GeneratorList* g, gl) {
1546 if ((idx3 % 8) == 0) {
1547 if (idx3)
1548 fprintf(f, ";\n");
1549 fprintf(f, "static Generator ");
1550 }
1551 else
1552 fprintf(f, ", ");
1553 fprintf(f, "ge_%d_%d_%d(%d, %d)",
1554 idx, idx2, idx3, int(g->gen), g->amount.sword);
1555 ++idx3;
1556 }
1557 fprintf(f, ";\n");
1558 int n = gl.size();
1559 if (n) {
1560 fprintf(f, "static Generator* geList_%d_%d[%d] = {\n ", idx, idx2, n);
1561 for (int i = 0; i < n; ++i) {
1562 if (i) {
1563 fprintf(f, ", ");
1564 if ((i % 8) == 0)
1565 fprintf(f, "\n ");
1566 }
1567 fprintf(f, "&ge_%d_%d_%d", idx, idx2, i);
1568 }
1569 fprintf(f, "\n };\n");
1570 }
1571 if (sampleIdx == -1)
1572 fprintf(f, "static IZone iz%d_%d(%d, %d, %d, %d, 0, 0, 0);\n", idx, idx2, keyLo, keyHi, veloLo, veloHi);
1573 else if (n)
1574 fprintf(f, "static IZone iz%d_%d(%d, %d, %d, %d, &sample%d, %d, geList_%d_%d); // %s\n",
1575 idx, idx2, keyLo, keyHi, veloLo, veloHi, sampleIdx, n, idx, idx2,
1576 samples[sampleIdx]->name);
1577 else
1578 fprintf(f, "static IZone iz%d_%d(%d, %d, %d, %d, &sample%d, %d, 0); // %s\n",
1579 idx, idx2, keyLo, keyHi, veloLo, veloHi, sampleIdx, n,
1580 samples[sampleIdx]->name);
1581
1582 ++idx2;
1583 }
1584
1585 fprintf(f, "static IZone* izones%d[%d] = {\n", idx, zones);
1586 idx2 = 0;
1587 for (int i = 0; i < zones; ++i)
1588 fprintf(f, " &iz%d_%d,\n", idx, idx2++);
1589 fprintf(f, " };\n");
1590 fprintf(f, "static Instrument instr%d(0, %d, izones%d);\n\n", idx, zones, idx);
1591 ++idx;
1592 }
1593 //
1594 // dump Preset[]
1595 //
1596 idx = 0;
1597 foreach(Preset* p, presets) {
1598 idx2 = 0;
1599 int zones = p->zones.size();
1600 if (smallSf)
1601 zones = 1;
1602
1603 foreach(Zone* z, p->zones) {
1604 int keyLo = 0;
1605 int keyHi = 127;
1606 int veloLo = 0;
1607 int veloHi = 127;
1608 int instrIdx = -1;
1609
1610 foreach(GeneratorList* g, z->generators) {
1611 const char* name = generatorNames[g->gen];
1612 if (g->gen == Gen_KeyRange) {
1613 keyLo = g->amount.lo;
1614 keyHi = g->amount.hi;
1615 }
1616 else if (g->gen == Gen_VelRange) {
1617 veloLo = g->amount.lo;
1618 veloHi = g->amount.hi;
1619 }
1620 else if (g->gen == Gen_Instrument)
1621 instrIdx = g->amount.uword;
1622 }
1623 if (keyLo == 0
1624 && keyHi == 127
1625 && veloLo == 0
1626 && veloHi == 127) {
1627 if (instrIdx == -1)
1628 fprintf(f, "static PZone pz%d_%d(0);\n", idx, idx2);
1629 else
1630 fprintf(f, "static PZone pz%d_%d(&instr%d);\n", idx, idx2, instrIdx);
1631 }
1632 else {
1633 //abort();
1634
1635 if (instrIdx == -1)
1636 fprintf(f, "static PZone pz%d_%d(%d, %d, %d, %d, 0);\n", idx, idx2, keyLo, keyHi, veloLo, veloHi);
1637 else
1638 fprintf(f, "static PZone pz%d_%d(%d, %d, %d, %d, &instr%d);\n", idx, idx2, keyLo, keyHi, veloLo, veloHi, instrIdx);
1639 }
1640 if (smallSf)
1641 break;
1642 ++idx2;
1643 }
1644 fprintf(f, "static PZone* pzones%d[%d] = {\n", idx, zones);
1645 idx2 = 0;
1646 for (int i = 0; i < zones; ++i) {
1647 fprintf(f, " &pz%d_%d,\n", idx, idx2);
1648 ++idx2;
1649 }
1650 fprintf(f, " };\n");
1651
1652 fprintf(f, "static Preset preset%d(%d, %d, 0, %d, pzones%d); // %s\n\n",
1653 idx, p->preset, p->bank, zones, idx, p->name);
1654 ++idx;
1655 }
1656
1657 fprintf(f, "static Preset* sfPresets[%d] = {\n", presets.size());
1658 for(int idx = 0; idx < presets.size(); ++idx)
1659 fprintf(f, " &preset%d, // %s\n", idx, presets[idx]->name);
1660 fprintf(f, " };\n");
1661
1662 fprintf(f, "static SFont _buildinSf(%d, sfPresets);\n", presets.size());
1663 fprintf(f, "SFont* createSf() { return &_buildinSf; }\n");
1664 fprintf(f, "} // end namespace\n");
1665 fclose(f);
1666 return true;
1667 }
1668
1669 //---------------------------------------------------------
1670 // writeCode
1671 //---------------------------------------------------------
1672
1673 bool SoundFont::writeCode(QList<int> pnums)
1674 {
1675 printf("write code\n");
1676
1677 int n = samples.size();
1678 f = fopen("sf.cpp", "w+");
1679 fprintf(f, "//\n// this is generated code, do not change\n//\n");
1680 fprintf(f, "#include \"sfont.h\"\n\n");
1681 fprintf(f, "namespace FluidS {\n\n");
1682
1683 //
1684 // dump wave samples
1685 //
1686 QList<int> sampleIdx;
1687 for (int idx = 0; idx < n; ++idx) {
1688 if (!checkSample(pnums, presets, instruments, idx))
1689 continue;
1690 Sample* s = samples[idx];
1691 writeCSample(s, idx);
1692 sampleIdx.append(idx);
1693 }
1694
1695 //
1696 // dump Sample[]
1697 //
1698 foreach(int idx, sampleIdx) {
1699 Sample* s = samples[idx];
1700 fprintf(f, "Sample sample%d(%d, %d, %d, %d, %d, %d, %d, %d, wave%d);\n",
1701 idx,
1702 0, // sample start
1703 s->end - s->start, // samples
1704 s->loopstart - s->start,
1705 s->loopend - s->start,
1706 s->samplerate,
1707 s->origpitch, s->pitchadj, s->sampletype,
1708 idx);
1709 }
1710
1711 //
1712 // dump Instrument[]
1713 //
1714 int idx2;
1715 int idx = 0;
1716 foreach(Instrument* instrument, instruments) {
1717 if (!checkInstrument(pnums, presets, idx)) {
1718 ++idx;
1719 continue;
1720 }
1721 int zones = instrument->zones.size();
1722 idx2 = 0;
1723 foreach(Zone* z, instrument->zones) {
1724 int keyLo = 0;
1725 int keyHi = 127;
1726 int veloLo = 0;
1727 int veloHi = 127;
1728 int sampleIdx = -1;
1729
1730 QList<GeneratorList*> gl;
1731
1732 foreach(GeneratorList* g, z->generators) {
1733 const char* name = generatorNames[g->gen];
1734 if (g->gen == Gen_KeyRange) {
1735 keyLo = g->amount.lo;
1736 keyHi = g->amount.hi;
1737 }
1738 else if (g->gen == Gen_VelRange) {
1739 veloLo = g->amount.lo;
1740 veloHi = g->amount.hi;
1741 }
1742 else if (g->gen == Gen_SampleId)
1743 sampleIdx = g->amount.uword;
1744 else
1745 gl.append(g);
1746 }
1747 int idx3 = 0;
1748 foreach(GeneratorList* g, gl) {
1749 if ((idx3 % 8) == 0) {
1750 if (idx3)
1751 fprintf(f, ";\n");
1752 fprintf(f, "static Generator ");
1753 }
1754 else
1755 fprintf(f, ", ");
1756 fprintf(f, "ge_%d_%d_%d(%d, %d)",
1757 idx, idx2, idx3, int(g->gen), g->amount.sword);
1758 ++idx3;
1759 }
1760 fprintf(f, ";\n");
1761 int n = gl.size();
1762 if (n) {
1763 fprintf(f, "static Generator* geList_%d_%d[%d] = {\n ", idx, idx2, n);
1764 for (int i = 0; i < n; ++i) {
1765 if (i) {
1766 fprintf(f, ", ");
1767 if ((i % 8) == 0)
1768 fprintf(f, "\n ");
1769 }
1770 fprintf(f, "&ge_%d_%d_%d", idx, idx2, i);
1771 }
1772 fprintf(f, "\n };\n");
1773 }
1774 if (sampleIdx == -1)
1775 fprintf(f, "static IZone iz%d_%d(%d, %d, %d, %d, 0, 0, 0);\n", idx, idx2, keyLo, keyHi, veloLo, veloHi);
1776 else
1777 fprintf(f, "static IZone iz%d_%d(%d, %d, %d, %d, &sample%d, %d, geList_%d_%d);\n",
1778 idx, idx2, keyLo, keyHi, veloLo, veloHi, sampleIdx, n, idx, idx2);
1779 ++idx2;
1780 }
1781
1782 fprintf(f, "static IZone* izones%d[%d] = {\n", idx, zones);
1783 idx2 = 0;
1784 for (int i = 0; i < zones; ++i)
1785 fprintf(f, " &iz%d_%d,\n", idx, idx2++);
1786 fprintf(f, " };\n");
1787 fprintf(f, "static Instrument instr%d(0, %d, izones%d);\n\n", idx, zones, idx);
1788 ++idx;
1789 }
1790 //
1791 // dump Preset[]
1792 //
1793
1794 foreach(int idx, pnums) {
1795 Preset* p = presets[idx];
1796 idx2 = 0;
1797 int zones = p->zones.size();
1798 foreach(Zone* z, p->zones) {
1799 int keyLo = 0;
1800 int keyHi = 127;
1801 int veloLo = 0;
1802 int veloHi = 127;
1803 int instrIdx = -1;
1804 foreach(GeneratorList* g, z->generators) {
1805 const char* name = generatorNames[g->gen];
1806 if (g->gen == Gen_KeyRange) {
1807 keyLo = g->amount.lo;
1808 keyHi = g->amount.hi;
1809 }
1810 else if (g->gen == Gen_VelRange) {
1811 veloLo = g->amount.lo;
1812 veloHi = g->amount.hi;
1813 }
1814 else if (g->gen == Gen_Instrument)
1815 instrIdx = g->amount.uword;
1816 }
1817 if (keyLo == 0
1818 && keyHi == 127
1819 && veloLo == 0
1820 && veloHi == 127) {
1821 if (instrIdx == -1)
1822 fprintf(f, "static PZone pz%d_%d(0);\n", idx, idx2);
1823 else
1824 fprintf(f, "static PZone pz%d_%d(&instr%d);\n", idx, idx2, instrIdx);
1825 }
1826 else {
1827 if (instrIdx == -1)
1828 fprintf(f, "static PZone pz%d_%d(%d, %d, %d, %d, 0);\n", idx, idx2, keyLo, keyHi, veloLo, veloHi);
1829 else
1830 fprintf(f, "static PZone pz%d_%d(%d, %d, %d, %d, &instr%d);\n", idx, idx2, keyLo, keyHi, veloLo, veloHi, instrIdx);
1831 }
1832 ++idx2;
1833 }
1834 fprintf(f, "static PZone* pzones%d[%d] = {\n", idx, zones);
1835 idx2 = 0;
1836 for (int i = 0; i < zones; ++i) {
1837 fprintf(f, " &pz%d_%d,\n", idx, idx2);
1838 ++idx2;
1839 }
1840 fprintf(f, " };\n");
1841
1842 fprintf(f, "static Preset preset%d(%d, %d, 0, %d, pzones%d); // %s\n\n",
1843 idx, p->preset, p->bank, p->zones.size(), idx, p->name);
1844 ++idx;
1845 }
1846
1847 fprintf(f, "static Preset* sfPresets[%d] = {\n", pnums.size());
1848 foreach(int idx, pnums)
1849 fprintf(f, " &preset%d, // %s\n", idx, presets[idx]->name);
1850 fprintf(f, " };\n");
1851
1852 fprintf(f, "static SFont _buildinSf(%d, sfPresets);\n", pnums.size());
1853 fprintf(f, "SFont* createSf() { return &_buildinSf; }\n");
1854 fprintf(f, "} // end namespace\n");
1855 fclose(f);
1856 return true;
1857 }
1858
1859 //---------------------------------------------------------
1860 // dumpPresets
1861 //---------------------------------------------------------
1862
1863 void SoundFont::dumpPresets()
1864 {
1865 int idx = 0;
1866 foreach(const Preset* p, presets) {
1867 printf("%03d %04x-%02x %s\n", idx, p->bank, p->preset, p->name);
1868 ++idx;
1869 }
1870 }