Automated commit for upstream build of version 0.9.0
[wdq2wav.git] / wdq2wav.cpp
1 /*****************************************************************************
2 ** FILE IDENTIFICATION
3 **
4 **   Name:          wdq2wav.cpp
5 **   Purpose:       Converts a channel of WinDAQ file to .WAV format
6 **   Programmer:    Kevin Rosenberg <kevin@rosenberg.net>
7 **   Date Started:  Jan 2003
8 **
9 **  Copyright (c) 2003 Kevin Rosenberg
10 **
11 **  This program is free software; you can redistribute it and/or modify
12 **  it under the terms of the GNU General Public License (version 2) as
13 **  published by the Free Software Foundation.
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, MA  02111-1307  USA
23 ******************************************************************************/
24
25 #include <stdlib.h>
26 #include <wdq2wav.h>
27
28 const char* g_szIdStr = "$Id$";
29
30 bool g_quiet = false;
31 bool g_verbose = false;
32 bool g_debug = false;
33 bool g_ignore_zero = false;
34 bool g_dont_demean = false;
35
36
37 #ifdef WIN32
38 #define lseek _lseek
39 #define close _close
40 #define open _open
41 #define read _read
42 #define write _write
43 #define O_BINARY _O_BINARY
44 #define O_RDONLY _O_RDONLY
45 #define O_WRONLY _O_WRONLY
46 #define O_RDWR _O_RDRW
47 #define O_TRUNC _O_TRUNC
48 #define O_CREAT _O_CREAT
49 const int g_fileMode = _S_IWRITE | _S_IREAD;
50 struct fpos_t std::_Fpz = {0,0};
51 #else
52 const int g_fileMode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
53 // Define as NULL for non-Windows platforms
54 #ifndef O_BINARY
55 #define O_BINARY 0
56 #endif
57 #endif
58
59
60 void
61 error_msg (const char *msg)
62 {
63   std::cerr << msg << std::endl;
64 }
65
66 void
67 info_msg (const char* msg)
68 {
69   std::cout << msg << std::endl;
70 }
71
72 void
73 info_msg_sans_newline (const char* msg)
74 {
75   std::cout << msg;
76 }
77
78 const char*
79 fileBasename (const char* filename)
80 {
81   const char* pslash = strrchr (filename, '/');
82   const char* pbackslash = strrchr (filename, '\\');
83   const char* p = filename;
84   if (pbackslash && (! pslash || pbackslash >= pslash))
85         p = pbackslash+1;
86   else if (pslash && (! pbackslash || pslash >= pbackslash))
87     p = pslash+1;
88
89   return p;
90 }
91
92 char *
93 str_rm_tail (char *str, const char* const charlist)
94 {
95   size_t i;
96
97   for (i = strlen(str) - 1; i >= 0; i--)
98     if (strchr (charlist, str[i]) != NULL)
99       str[i] = 0;
100     else
101       break;            /* found non-specified char, all done */
102
103   return (str);
104 }
105
106 char *
107 str_wrm_tail (char *str)
108 {
109   return (str_rm_tail(str, "\b\t\n\r"));
110 }
111
112
113 void
114 usage (const char* progname)
115 {
116   std::cout << "usage: " << fileBasename (progname) << " [OPTIONS] <wdq-file> <channel-number> <wav-file>\n";
117   std::cout << "OPTIONS\n";
118   std::cout << "  -p   Play channel through audio system\n";
119   std::cout << "  -q   Supress all messages\n";
120   std::cout << "  -z   Scale output without preserving zero point\n";
121   std::cout << "  -m   Do not demean the data (don't subtract the mean value from each sample)\n";
122   std::cout << "  -v   Verbose mode\n";
123   std::cout << "  -d   Debug mode\n";
124   std::cout << "  -r   Print program version and exit\n";
125   std::cout << "  -h   Print this help message\n";
126 }
127
128
129 int
130 main (int argc, char *argv[])
131 {
132   int c;
133   bool play = false;
134
135   const char* progname = argv[0];
136
137   while ((c = getopt (argc, argv, "rqvzmdph")) != -1) {
138     switch (c) {
139     case 'r':
140         std::cout << "Version " << g_szIdStr << std::endl;
141                 exit(0);
142         break;
143     case 'q':
144       g_quiet = true;
145       break;
146     case 'm':
147       g_dont_demean = true;
148       break;
149     case 'z':
150       g_ignore_zero = true;
151       break;
152     case 'v':
153       g_verbose = true;
154       break;
155     case 'd':
156       g_debug = true;
157       break;
158     case 'p':
159       play = true;
160       break;
161     case 'h':
162       usage (progname);
163       return (0);
164     case '?':
165     default:
166         usage (progname);
167         return (1);
168       }
169     }
170
171   if (g_verbose || g_debug)
172           std::cout << "Version " << g_szIdStr << std::endl;
173
174   argc -= optind;
175   argv += optind;
176   if (argc > 3) {
177       std::cerr << "Too many parameters\n";
178       usage (progname);
179       return (1);
180     }
181
182   char wdq_fname[MAX_INPUT_STR];
183   if (argc >= 1)
184       strncpy (wdq_fname, argv [0], MAX_INPUT_STR);
185   else {
186     std::cout << "Enter input WinDAQ filename: ";
187       std::cin.getline (wdq_fname, MAX_INPUT_STR);
188     }
189
190     char channel_buf [MAX_INPUT_STR];
191     if (argc >= 2)
192       strncpy (channel_buf, argv[1], MAX_INPUT_STR);
193     else {
194       std::cout << "Enter channel number: ";
195       std::cin.getline (channel_buf, MAX_INPUT_STR);
196     }
197
198     char *channel_endptr;
199     int channel = static_cast<int>(strtol (channel_buf, &channel_endptr, 10));
200     if (*channel_endptr != 0) {
201       std::ostringstream os;
202       os << "Error: Channel " << channel_buf << " is not an integer";
203       error_msg (os.str().c_str());
204       usage (progname);
205       return (1);
206     }
207
208     char wav_fname[MAX_INPUT_STR];
209     if (argc >= 3)
210       strncpy (wav_fname, argv[2], MAX_INPUT_STR);
211     else {
212       std::cout << "Enter output wav filename: ";
213       std::cin.getline (wav_fname, MAX_INPUT_STR);
214     }
215
216     if (! wdq2wav (wdq_fname, channel, wav_fname, play))
217       return 1;
218
219     return 0;
220 }
221
222 bool
223 wdq2wav (const char* wdq_fname, const int channel, const char *wav_fname, bool play)
224 {
225   WindaqFile wdq (wdq_fname);
226
227   if (! wdq.ReadHeader()) {
228     if (wdq.m_error.size()) {
229       std::ostringstream os;
230       os << "Error reading file " << wdq_fname << ": " << wdq.m_error.c_str();
231       error_msg (os.str().c_str());
232     } else {
233       std::ostringstream os;
234       os << "Error reading file " << wdq_fname;
235       error_msg (os.str().c_str());
236     }
237     return false;
238   }
239
240   if (wdq.any_packed_channels()) {
241           std::ostringstream os;
242           os << "File contains 'packed' channels." << std::endl;
243           os << "Convert to 'Advanced CODAS headers' before processing with wdq2wav.";
244           error_msg (os.str().c_str());
245           return false;
246   }
247
248   if (! g_quiet || g_verbose || g_debug) {
249     std::ostringstream os1;
250         os1 << "File: " << wdq_fname;
251     info_msg (os1.str().c_str());
252         std::ostringstream os;
253         os << "Legacy Format: ";
254         if (wdq.m_bLegacy_format)
255                 os << "Yes";
256         else
257                 os << "No";
258         info_msg(os.str().c_str());
259     std::ostringstream os2;
260     time_t time = wdq.m_time_acq_start;
261     struct tm* tm = gmtime (&time);
262     os2 << "  Time File Creation: " << asctime(tm);
263     info_msg_sans_newline (os2.str().c_str());
264     std::ostringstream os3;
265     time = wdq.m_time_acq_stop;
266     tm = gmtime (&time);
267     os3 << "  Time File Written: " << asctime(tm);
268     info_msg_sans_newline (os3.str().c_str());
269     std::ostringstream os4;
270     os4 << "  Samples: " << wdq.m_nSamples <<
271       ", Channels: " << wdq.m_nChannels <<
272       ", Sample Rate: " << wdq.m_sample_rate;
273     info_msg (os4.str().c_str());
274   }
275
276   WindaqChannel wdq_channel (wdq, channel);
277   if (! wdq_channel.m_valid) {
278     error_msg ("Error reading data from channel");
279     return false;
280   }
281
282   if (! g_quiet || g_verbose || g_debug) {
283     std::ostringstream os1;
284     os1 << "Channel " << channel;
285     info_msg (os1.str().c_str());
286     std::ostringstream os2;
287     os2 << "  Units: " << wdq_channel.m_units.c_str();
288     info_msg (os2.str().c_str());
289     std::ostringstream os3;
290     os3 << "  Raw minimum: " << wdq_channel.m_min_raw_data <<
291       ", maximum: " << wdq_channel.m_max_raw_data;
292     info_msg (os3.str().c_str());
293   }
294
295   if (g_debug) {
296     std::ostringstream os4;
297     os4 << "  Scaled minimum: " << wdq_channel.m_min_scaled_data <<
298       ", maximum: " << wdq_channel.m_max_scaled_data;
299     info_msg (os4.str().c_str());
300     std::ostringstream os5;
301     os5 << "  Slope " <<  wdq_channel.m_slope <<
302       ", Intercept " <<  wdq_channel.m_intercept;
303     info_msg (os5.str().c_str());
304   }
305
306   WavFile wav (wdq_channel, wav_fname);
307
308   if (! wav.m_valid) {
309     error_msg ("Error extracting wav from channel");
310     return false;
311   }
312
313   if (! wav.WriteFile ()) {
314     error_msg ("Error writing file");
315     return false;
316   }
317
318   if (play)
319     wav.Play();
320
321   return true;
322 }
323
324
325 WindaqFile::WindaqFile (const char* fname)
326   : m_valid(false), m_fd(0), m_nChannels(0), m_nSamples(0), m_sample_rate(0),
327     m_strFile (fname)
328 {
329 }
330
331 WindaqFile::~WindaqFile ()
332 {
333   if (m_fd != 0)
334     close (m_fd);
335 }
336
337 bool read_int1 (int fd, unsigned char& n)
338 {
339   unsigned char tmp1;
340   if (read (fd, &tmp1, 1) != 1)
341     return false;
342
343   n = tmp1;
344   return true;
345 }
346
347 bool read_int2 (int fd, unsigned short int& n)
348 {
349   unsigned char tmp1;
350   unsigned int tmp2;
351   if (read (fd, &tmp1, 1) != 1)
352     return false;
353   tmp2 = tmp1;
354   if (read (fd, &tmp1, 1) != 1)
355     return false;
356
357   n = tmp2 + (tmp1 * 256);
358   return true;
359 }
360
361 bool read_int4 (int fd, unsigned int& n)
362 {
363   unsigned int tmp4;
364   unsigned short int tmp2;
365   if (! read_int2 (fd, tmp2))
366     return false;
367   tmp4 = tmp2;
368   if (! read_int2 (fd, tmp2))
369     return false;
370
371   n = tmp4 + (tmp2 * 65536);
372   return true;
373 }
374
375 bool read_float8 (int fd, double& f)
376 {
377   unsigned char p[8];
378   if (read (fd, p, 8) != 8)
379     return false;
380
381 #if WORDS_BIG_ENDIAN
382   unsigned char c;
383   c = p[0]; p[0] = p[7]; p[7] = c;
384   c = p[1]; p[1] = p[6]; p[6] = c;
385   c = p[2]; p[2] = p[5]; p[5] = c;
386   c = p[3]; p[3] = p[4]; p[4] = c;
387 #endif
388
389   double *pd = reinterpret_cast<double*>(&p[0]);
390   f = *pd;
391
392   return true;
393 }
394
395 bool
396 WindaqFile::ReadHeader ()
397 {
398   m_valid = false;
399   if ((m_fd = open (m_strFile.c_str(), O_RDONLY | O_BINARY)) < 0) {
400     m_error = "Unable to open file";
401     return false;
402   }
403
404   lseek (0, 0, SEEK_SET);
405   unsigned short int element1;
406   if (! read_int2 (m_fd, element1))
407     return false;
408
409   short unsigned int byte1 = (element1 & 0xFF00) >> 8;
410   short unsigned int byte2 = element1 & 0xFF;
411   if (byte1 == 0 || byte1 == 1) {
412           m_bLegacy_format = false;
413           m_sr_denom = m_sr_numer = 0;
414   } else {
415           m_sr_denom = (element1 & 0x7fff) >> 5;
416           m_sr_numer = (element1 & 0x8000) << 1;
417       m_bLegacy_format = true;
418   }
419   unsigned short int element2;
420   if (! read_int2 (m_fd, element2))
421     return false;
422
423   if (m_bLegacy_format)
424           m_sr_numer |= element2;
425
426   unsigned char element3;
427   if (! read_int1 (m_fd, element3))
428     return false;
429   m_channel_offset = element3;
430   if (g_debug)
431           std::cout << "Channel offset: " << m_channel_offset << std::endl;
432
433   unsigned char element4;
434   if (! read_int1 (m_fd, element4))
435     return false;
436   m_nBytes_channel_header = element4;
437   if (g_debug)
438           std::cout << "Channel header bytes: " << m_nBytes_channel_header << std::endl;
439
440   unsigned short int element5;
441   if (! read_int2 (m_fd, element5))
442     return false;
443   m_nHeader_bytes = element5;
444   if (g_debug)
445           std::cout << "Header bytes: " << m_nHeader_bytes << std::endl;
446
447   m_nMaxChannels = (m_nHeader_bytes - 112) / 36;
448   if (m_nMaxChannels >= 144)
449         m_nChannels = byte2 & 0xFF;
450   else
451     m_nChannels = byte2 & 0x1F;
452
453   unsigned int element6;
454   if (! read_int4 (m_fd, element6))
455     return false;
456   m_nData_bytes = element6;
457   if (g_debug)
458           std::cout << "Data bytes: " << m_nData_bytes << std::endl;
459
460   m_nSamples = (m_nData_bytes / m_nChannels) / 2;
461
462   lseek (m_fd, 28, SEEK_SET);
463   double element13;
464   if (! read_float8 (m_fd, element13))
465           return false;
466   m_time_between_channel_samples = element13;
467
468   if (m_bLegacy_format)
469      m_sample_rate = (double) m_sr_numer / (double) (m_sr_denom * m_nChannels);
470   else
471      m_sample_rate = (double) 1 / m_time_between_channel_samples;
472
473   lseek (m_fd, 36, SEEK_SET);
474   if (! read_int4 (m_fd, m_time_acq_start))
475     return false;
476
477   if (! read_int4 (m_fd, m_time_acq_stop))
478     return false;
479
480   lseek (m_fd, 100, SEEK_SET);
481   unsigned short int element27;
482   if (! read_int2 (m_fd, element27))
483           return false;
484
485   m_bHires = (element27 & 0x0001) ? true : false;
486   if (g_debug) {
487           std::cout << "High resolution: ";
488           if (m_bHires)
489                   std::cout << "Yes";
490           else
491                   std::cout << "No";
492
493           std::cout << std::endl;
494   }
495
496   // Verify Windaq signature
497   lseek (m_fd, m_nHeader_bytes - 2, SEEK_SET);
498   unsigned short int element35;
499   if (! read_int2 (m_fd, element35))
500     return false;
501
502   if (element35 != 0x8001) {
503     std::ostringstream os;
504         m_error = "Incorrect signagure: file is not a valid WinDAQ file";
505     return false;
506   }
507
508   m_valid = true;
509   return true;
510 }
511
512 bool
513 WindaqFile::any_packed_channels ()
514 {
515         for (int iChannel = 0; iChannel < m_nChannels; iChannel++)
516                 if (is_channel_packed (iChannel))
517                         return true;
518
519         return false;
520 }
521
522 bool
523 WindaqFile::is_channel_packed (const int channel)
524 {
525   long iStart = m_channel_offset + channel * m_nBytes_channel_header;
526
527   lseek (m_fd, iStart + 31, SEEK_SET);
528   unsigned char iReadings_per_data_point;
529   if (! read_int1 (m_fd, iReadings_per_data_point))
530         return false;
531
532   if (iReadings_per_data_point > 1)
533           return true;
534
535   return false;
536 }
537
538 WindaqChannel::WindaqChannel (WindaqFile& wdq, const int channel)
539   : r_wdq(wdq), m_data(0), m_slope(0), m_intercept (0), m_channel(channel),
540     m_valid(false)
541 {
542   if (wdq.m_valid) {
543     if (channel >= 1 && channel <= wdq.m_nChannels) {
544       if (read_channel_data())
545         m_valid = true;
546     } else {
547       std::ostringstream os;
548       os << "Channel " << channel << " is invalid, valid range 1-" <<
549         wdq.m_nChannels;
550       error_msg (os.str().c_str());
551     }
552   }
553 }
554
555 WindaqChannel::~WindaqChannel ()
556 {
557   if (m_data)
558     delete m_data;
559 }
560
561 bool
562 WindaqChannel::read_channel_data ()
563 {
564   int fd = r_wdq.m_fd;
565
566   m_data = new signed short int [r_wdq.m_nSamples * 2];
567
568   lseek (fd, r_wdq.m_channel_offset + 8 +
569          (m_channel - 1) * r_wdq.m_nBytes_channel_header,
570          SEEK_SET);
571   if (! read_float8 (fd, m_slope))
572     return false;
573
574   if (! read_float8 (fd, m_intercept))
575     return false;
576
577   char units[7];
578   units[6] = 0;
579   if (read (fd, units, 6) != 6) {
580     error_msg ("Error reading file");
581     return false;
582   }
583   m_units = units;
584
585   long int row_bytes = 2 * r_wdq.m_nChannels;
586
587   signed short int *sample_row = new signed short int [row_bytes];
588
589   signed short int* psample = &sample_row[m_channel - 1];
590
591   lseek (fd, r_wdq.m_nHeader_bytes, SEEK_SET);
592   unsigned long int i;
593   signed short int data_max = 0, data_min = 0;
594   double total_data = 0;
595   for (i = 0; i < r_wdq.m_nSamples; i++) {
596     if (read (fd, sample_row, row_bytes) != row_bytes) {
597       std::ostringstream os;
598       os << "Error reading file at " << i;
599       error_msg (os.str().c_str());
600       delete sample_row;
601       return false;
602     }
603     signed short int v = *psample;
604
605 #if WORDS_BIG_ENDIAN
606     unsigned char* p = reinterpret_cast<unsigned char*>(&v);
607     unsigned char c = p[0]; p[0] = p[1]; p[1] = c;
608 #endif
609
610     signed short int value = v;
611         if (! r_wdq.m_bHires)
612                 value >>= 2;
613
614     m_data[i] = value;
615     total_data += value;
616
617     if (i == 0) {
618       data_max = value;
619       data_min = value;
620     } else {
621       if (value > data_max)
622         data_max = value;
623       else if (value < data_min)
624         data_min = value;
625     }
626   }
627
628   m_max_raw_data = data_max;
629   m_min_raw_data = data_min;
630   m_max_scaled_data = (m_slope * data_max) + m_intercept;
631   m_min_scaled_data = (m_slope * data_min) + m_intercept;
632
633   if (! g_dont_demean) {
634     double dmean = total_data / static_cast<double>(r_wdq.m_nSamples);
635     int mean = nearest<int>(dmean);
636     std::cout << "Removing mean: " << (dmean * m_slope) + m_intercept <<
637       " " << m_units << std::endl;
638
639     for (i = 0; i < r_wdq.m_nSamples; i++)
640       m_data[i] -= mean;
641   }
642
643   delete sample_row;
644   return true;
645 }
646
647
648 WavFile::WavFile (WindaqChannel& wdq_channel, const char* fname)
649   : m_valid(false), m_data(0), m_nSamples(0), m_strFile(fname), m_fd(0)
650 {
651   if (wdq_channel.m_valid) {
652     m_nSamples = wdq_channel.r_wdq.m_nSamples;
653     m_nChannels = 1;
654     m_nBitsPerSample = 16;
655     m_nBytesPerSample = 2;
656     m_rate = wdq_channel.r_wdq.m_sample_rate;
657
658     double data_offset = 0, data_scale = 0;
659     if (g_ignore_zero) {
660       data_offset = -wdq_channel.m_min_scaled_data;
661       if (wdq_channel.m_max_scaled_data != wdq_channel.m_min_scaled_data)
662         data_scale = 65535. / (wdq_channel.m_max_scaled_data -
663                                wdq_channel.m_min_scaled_data);
664     } else {
665       double max_value = fabs(wdq_channel.m_max_scaled_data);
666       if (fabs (wdq_channel.m_min_scaled_data) > max_value)
667         max_value = fabs (wdq_channel.m_min_scaled_data);
668       if (max_value != 0.)
669         data_scale = 32767. / max_value;
670     }
671
672     if (g_debug) {
673       std::ostringstream os;
674       os << "  Wav data_scale: " << data_scale << ", data_offset: " << data_offset;
675       info_msg (os.str().c_str());
676     }
677
678     m_nHeaderBytes = 44;
679     m_nDataBytes = m_nSamples * m_nBytesPerSample * m_nChannels;
680     m_nFileBytes = m_nHeaderBytes + m_nDataBytes;
681
682     unsigned int nHeaderShortInts = m_nHeaderBytes / sizeof(signed short int);
683
684     m_data = new signed short int [m_nSamples + nHeaderShortInts];
685     signed short int* input = wdq_channel.m_data;
686     signed short int* output = &m_data[nHeaderShortInts];
687     double slope = wdq_channel.m_slope;
688     double intercept = wdq_channel.m_intercept;
689
690     if (! fill_header ())
691       return;
692
693     unsigned long int i;
694
695     for (i = 0; i < m_nSamples; i++) {
696       double value = input[i];
697       value = (slope * value) + intercept;
698       if (g_ignore_zero) {
699         value = (value + data_offset) * data_scale;
700         value += 0.5 - 32768;
701       } else {
702         value = value * data_scale;
703       }
704
705       signed short int v = static_cast<signed short int>(value);
706 #if WORDS_BIG_ENDIAN
707       unsigned char* p = reinterpret_cast<unsigned char*>(&v);
708       unsigned char c = p[0]; p[0] = p[1]; p[1] = c;
709 #endif
710       output[i] = v;
711     }
712   }
713
714   m_valid = true;
715 }
716
717
718 WavFile::~WavFile ()
719 {
720   if (m_fd != 0)
721     close (m_fd);
722
723   if (m_data != NULL)
724     delete m_data;
725 }
726
727 void
728 put_int4 (char* p, unsigned int n)
729 {
730   *p = n & 0xFF;
731   *(p+1) = 0xFF & (n >> 8);
732   *(p+2) = 0xFF & (n >> 16);
733   *(p+3) = 0xFF & (n >> 24);
734 }
735
736 void
737 put_int2 (char* p, unsigned short int n)
738 {
739   *p = n & 0xFF;
740   *(p+1) = 0xFF & (n >> 8);
741 }
742
743 bool
744 WavFile::fill_header ()
745 {
746   char* pData = reinterpret_cast<char*> (m_data);
747
748   strncpy (pData, "RIFF", 4);
749
750   // Length of file after 8 byte header
751   put_int4 (pData + 4, 36 + m_nDataBytes);
752
753   strncpy (pData + 8, "WAVEfmt ", 8);
754
755   // Length of header block
756   put_int4 (pData + 16, 0x10);
757
758   // Always 1
759   put_int2 (pData + 20, 1);
760
761   /* Number of channels */
762   put_int2 (pData + 22, m_nChannels);
763
764   // Sample Rate
765   put_int4 (pData + 24, static_cast<int> (m_rate + 0.5));
766
767   // Bytes per second
768   put_int4 (pData + 28, static_cast<int> (m_rate * m_nBytesPerSample + 0.5));
769
770   // Bytes per sample
771   put_int2 (pData + 32, m_nBytesPerSample * m_nChannels);
772
773   // Bits per sample
774   put_int2 (pData + 34, m_nBitsPerSample);
775
776   strncpy (pData + 36, "data", 4);
777
778   put_int4 (pData + 40, m_nDataBytes);
779
780   return true;
781 }
782
783 bool
784 WavFile::WriteFile ()
785 {
786   if (! m_valid)
787     return false;
788
789   if (m_fd == 0)
790     if ((m_fd = open (m_strFile.c_str(), O_WRONLY | O_BINARY | O_TRUNC | O_CREAT, g_fileMode)) == 0) {
791       std::ostringstream os;
792       os << "Error opening output file " << m_strFile.c_str();
793       error_msg (os.str().c_str());
794       return false;
795     }
796
797   lseek (m_fd, 0, SEEK_SET);
798   if (write (m_fd, m_data, m_nFileBytes) != m_nFileBytes) {
799     error_msg ("Error writing file");
800     return false;
801   }
802
803   if (close (m_fd) < 0)
804     error_msg ("Error closing output file");
805
806   m_fd = 0;
807   return true;
808 }
809
810 #ifdef _WIN32
811 #include <windows.h>
812 #include <mmsystem.h>
813 #elif defined(__linux__)
814 #include <sys/ioctl.h>
815 #include <sys/soundcard.h>
816 #endif
817
818 bool
819 WavFile::Play ()
820 {
821 #ifdef _WIN32
822   if (PlaySound ((LPCSTR) m_data, 0, SND_MEMORY | SND_NODEFAULT))
823     return true;
824 #elif defined(__linux__)
825   int fd;
826   if ((fd = open ("/dev/dsp",O_WRONLY)) == -1) {
827     error_msg ("Error opening /dev/dsp");
828     return false;
829   }
830
831   int format = AFMT_S16_LE;
832   if (ioctl (fd, SNDCTL_DSP_SETFMT, &format) == -1) {
833     error_msg ("Error setting DSP format");
834     close(fd); return false;
835   }
836   if (format != AFMT_S16_LE) {
837     error_msg ("DSP Format not set");
838     close(fd); return false;
839   }
840
841   unsigned int channels = m_nChannels;
842   if (ioctl (fd, SNDCTL_DSP_CHANNELS, &format) == -1) {
843     error_msg ("Error setting number of channels");
844     close(fd); return false;
845   }
846   if (channels != m_nChannels) {
847     error_msg ("Number of channels not set");
848     close(fd); return false;
849   }
850
851   unsigned int speed = static_cast<int>(m_rate + 0.5);
852   if (ioctl (fd, SNDCTL_DSP_SPEED, &speed) == -1) {
853     error_msg ("Error setting sample rate");
854     close(fd); return false;
855   }
856   if (speed != m_rate && ! g_quiet) {
857     std::ostringstream os;
858     os << "Warning: Sample rate set to " << speed << ", not " << m_rate;
859     error_msg (os.str().c_str());
860   }
861
862   if (write (fd, reinterpret_cast<char*>(m_data) + m_nHeaderBytes, m_nDataBytes) !=
863       m_nDataBytes) {
864     error_msg ("Error writing audio samples");
865     close(fd); return false;
866   }
867
868   close (fd);
869   return true;
870 #else
871 #endif
872
873   return false;
874 }
875
876