]> git.mxchange.org Git - flightgear.git/blob - src/ATCDCL/ATCVoice.cxx
toggle fullscreen: also adapt GUI plane when resizing
[flightgear.git] / src / ATCDCL / ATCVoice.cxx
1 // FGATCVoice.cxx - a class to encapsulate an ATC voice
2 //
3 // Written by David Luff, started November 2002.
4 //
5 // Copyright (C) 2002  David C Luff - david.luff@nottingham.ac.uk
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20
21
22 #ifdef HAVE_CONFIG_H
23 #  include <config.h>
24 #endif
25
26 #include "ATCVoice.hxx"
27
28 #include <stdlib.h>
29 #include <string.h>
30 #include <ctype.h>
31 #include <fstream>
32 #include <vector>
33 #include <algorithm>
34
35 #include <simgear/sound/soundmgr_openal.hxx>
36 #include <simgear/sound/sample_openal.hxx>
37 #include <simgear/misc/sg_dir.hxx>
38
39 #include <simgear/misc/sg_path.hxx>
40 #include <simgear/debug/logstream.hxx>
41 #include <simgear/misc/sgstream.hxx>
42 #include <simgear/math/sg_random.h>
43
44 #include <Main/globals.hxx>
45
46 using namespace std;
47
48 FGATCVoice::FGATCVoice() :
49     rawSoundData(0),
50     rawDataSize(0),
51     SoundData(0)
52 {
53 }
54
55 FGATCVoice::~FGATCVoice() {
56     if (rawSoundData)
57         free( rawSoundData );
58     delete SoundData;
59 }
60
61 // Load all data for the requested voice.
62 // Return true if successful.
63 bool FGATCVoice::LoadVoice(const string& voicename)
64 {
65     rawDataSize = 0;
66     if (rawSoundData)
67         free(rawSoundData);
68     rawSoundData = NULL;
69
70     // determine voice directory
71     SGPath voicepath = globals->get_fg_root();
72     voicepath.append( "ATC" );
73     voicepath.append( "voices" );
74     voicepath.append( voicename );
75
76     simgear::Dir d(voicepath);
77     if (!d.exists())
78     {
79         SG_LOG(SG_ATC, SG_ALERT, "Unable to load ATIS voice. No such directory: " << voicepath.str());
80         return false;
81     }
82
83     // load all files from the voice's directory
84     simgear::PathList paths = d.children(simgear::Dir::TYPE_FILE);
85     bool Ok = false;
86     for (unsigned int i=0; i<paths.size(); ++i)
87     {
88         if (paths[i].lower_extension() == "vce")
89             Ok |= AppendVoiceFile(voicepath, paths[i].file_base());
90     }
91
92     if (!Ok)
93     {
94         SG_LOG(SG_ATC, SG_ALERT, "Unable to load ATIS voice. Files are invalid or no files in directory: " << voicepath.str());
95     }
96
97     // ok when at least some files loaded fine
98     return Ok;
99 }
100
101 // load a voice file and append it to the current word database
102 bool FGATCVoice::AppendVoiceFile(const SGPath& basepath, const string& file)
103 {
104     size_t offset = 0;
105
106     SG_LOG(SG_ATC, SG_INFO, "Loading ATIS voice file: " << file);
107
108     // path to compressed voice file
109     SGPath path(basepath);
110     path.append(file + ".wav.gz");
111
112     // load wave data
113     SGSoundMgr *smgr = globals->get_soundmgr();
114     int format, freq;
115     void *data;
116     size_t size;
117     if (!smgr->load(path.str(), &data, &format, &size, &freq))
118         return false;
119
120     // append to existing data
121     if (!rawSoundData)
122         rawSoundData = (char*)data;
123     else
124     {
125         rawSoundData = (char*) realloc(rawSoundData, rawDataSize + size);
126         // new data starts behind existing sound data
127         offset = rawDataSize;
128         if (!rawSoundData)
129         {
130             SG_LOG(SG_ATC, SG_ALERT, "Out of memory. Cannot load file " << path.str());
131             rawDataSize = 0;
132             return false;
133         }
134         // append to existing sound data
135         memcpy(rawSoundData+offset, data, size);
136         free(data);
137         data = NULL;
138     }
139     rawDataSize += size;
140
141 #ifdef VOICE_TEST
142         cout << "ATCVoice:  format: " << format
143                         << "  size: " << rawDataSize << endl;
144 #endif
145
146         // load and parse index file (.vce)
147         return ParseVoiceIndex(basepath, file, offset);
148 }
149
150 // Load and parse a voice index file (.vce)
151 bool FGATCVoice::ParseVoiceIndex(const SGPath& basepath, const string& file, size_t globaloffset)
152 {
153         // path to voice index file
154         SGPath path(basepath);
155         path.append(file + ".vce");
156         
157         // Now load the word data
158         std::ifstream fin;
159         fin.open(path.c_str(), ios::in);
160         if(!fin) {
161                 SG_LOG(SG_ATC, SG_ALERT, "Unable to open input file " << path.c_str());
162                 return(false);
163         }
164         SG_LOG(SG_ATC, SG_INFO, "Opened word data file " << path.c_str() << " OK...");
165
166         char numwds[10];
167         char wrd[100];
168         string wrdstr;
169         char wrdOffsetStr[20];
170         char wrdLengthStr[20];
171         unsigned int wrdOffset;         // Offset into the raw sound data that the word sample begins
172         unsigned int wrdLength;         // Length of the word sample in bytes
173         WordData wd;
174
175         // first entry: number of words in the index
176         fin >> numwds;
177         unsigned int numwords = atoi(numwds);
178         //cout << numwords << '\n';
179
180         // now load each word, its file offset and length
181         for(unsigned int i=0; i < numwords; ++i) {
182             // read data
183                 fin >> wrd;
184                 fin >> wrdOffsetStr;
185                 fin >> wrdLengthStr;
186
187                 wrdstr    = wrd;
188                 wrdOffset = atoi(wrdOffsetStr);
189                 wrdLength = atoi(wrdLengthStr);
190
191                 // store word in map
192                 wd.offset = wrdOffset + globaloffset;
193                 wd.length = wrdLength;
194                 wordMap[wrdstr] = wd;
195
196                 // post-process words
197                 string ws2 = wrdstr;
198                 for(string::iterator p = ws2.begin(); p != ws2.end(); p++){
199                     *p = tolower(*p);
200                     if (*p == '-')
201                         *p = '_';
202                 }
203
204                 // store alternative version of word (lowercase/no hyphen)
205                 if (wrdstr != ws2)
206                     wordMap[ws2] = wd;
207
208                 //cout << wrd << "\t\t" << wrdOffset << "\t\t" << wrdLength << '\n';
209                 //cout << i << '\n';
210         }
211
212         fin.close();
213         return(true);
214 }
215
216
217 // Given a desired message, return a string containing the
218 // sound-sample data
219 void* FGATCVoice::WriteMessage(const string& message, size_t* len) {
220         
221         // What should we do here?
222         // First - parse the message into a list of tokens.
223         // Sort the tokens into those we understand and those we don't.
224         // Add all the raw lengths of the token sound data, allocate enough space, and fill it with the rqd data.
225
226         vector<char> sound;
227         const char delimiters[] = " \t.,;:\"\n";
228         string::size_type token_start = message.find_first_not_of(delimiters);
229         while(token_start != string::npos) {
230                 string::size_type token_end = message.find_first_of(delimiters, token_start);
231                 string token;
232                 if (token_end == string::npos) {
233                         token = message.substr(token_start);
234                         token_start = string::npos;
235                 } else {
236                         token = message.substr(token_start, token_end - token_start);
237                         token_start = message.find_first_not_of(delimiters, token_end);
238                 }
239
240                 if (token == "/_") continue;
241
242                 for(string::iterator t = token.begin(); t != token.end(); t++) {
243                         // canonicalize the token, to match what's in the index
244                         *t = (*t == '-') ? '_' : tolower(*t);
245                 }
246                 SG_LOG(SG_ATC, SG_DEBUG, "voice synth: token: '"
247                     << token << "'");
248
249                 atc_word_map_const_iterator wordIt = wordMap.find(token);
250                 if(wordIt == wordMap.end()) {
251                         // Oh dear - the token isn't in the sound file
252                         SG_LOG(SG_ATC, SG_ALERT, "voice synth: word '"
253                                 << token << "' not found");
254                 } else {
255                         const WordData& word = wordIt->second;
256                         /*
257                         *  Sanity check for corrupt/mismatched sound data input - avoids a seg fault
258                         *  (As long as the calling function checks the return value!!)
259                         *  This check should be left in even when the default Flightgear files are known
260                         *  to be OK since it checks for mis-indexing of voice files by 3rd party developers.
261                         */
262                         if((word.offset + word.length) > rawDataSize) {
263                                 SG_LOG(SG_ATC, SG_ALERT, "ERROR - mismatch between ATC .wav and .vce file in ATCVoice.cxx\n");
264                                 SG_LOG(SG_ATC, SG_ALERT, "Offset + length: " << word.offset + word.length
265                                         << " exceeds rawdata size: " << rawDataSize << endl);
266
267                                 *len = 0;
268                                 return 0;
269                         }
270                         sound.insert(sound.end(), rawSoundData + word.offset, rawSoundData + word.offset + word.length);
271                 }
272         }
273
274         // Check for no tokens found else slScheduler can be crashed
275         *len = sound.size();
276         if (*len == 0) {
277                 return 0;
278         }
279
280         char* data = (char*)malloc(*len);
281         if (data == 0) {
282                 SG_LOG(SG_ATC, SG_ALERT, "ERROR - could not allocate " << *len << " bytes of memory for ATIS sound\n");
283                 *len = 0;
284                 return 0;
285         }
286
287         // randomize start position
288         unsigned int offsetIn = (unsigned int)(*len * sg_random());
289         if (offsetIn > 0 && offsetIn < *len) {
290                 copy(sound.begin() + offsetIn, sound.end(), data);
291                 copy(sound.begin(), sound.begin() + offsetIn, data + *len - offsetIn);
292         } else {
293                 copy(sound.begin(), sound.end(), data);
294         }
295
296         return data;
297 }