Fix sample rate for multichannel, non-legacy files
[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 buf[8];
378   if (read (fd, &buf, 8) != 8)
379     return false;
380
381 #if WORDS_BIG_ENDIAN
382   unsigned char c;
383   c = buf[0]; buf[0] = buf[7]; buf[7] = c;
384   c = buf[1]; buf[1] = buf[6]; buf[6] = c;
385   c = buf[2]; buf[2] = buf[5]; buf[5] = c;
386   c = buf[3]; buf[3] = buf[4]; buf[4] = c;
387 #endif
388
389   f = *(reinterpret_cast<double*>(buf));
390
391   return true;
392 }
393
394 bool
395 WindaqFile::ReadHeader ()
396 {
397   m_valid = false;
398   if ((m_fd = open (m_strFile.c_str(), O_RDONLY | O_BINARY)) < 0) {
399     m_error = "Unable to open file";
400     return false;
401   }
402
403   lseek (0, 0, SEEK_SET);
404   unsigned short int element1;
405   if (! read_int2 (m_fd, element1))
406     return false;
407
408   short unsigned int byte1 = (element1 & 0xFF00) >> 8;
409   short unsigned int byte2 = element1 & 0xFF;
410   if (byte1 == 0 || byte1 == 1) {
411           m_bLegacy_format = false;
412           m_sr_denom = m_sr_numer = 0;
413   } else {
414           m_sr_denom = (element1 & 0x7fff) >> 5;
415           m_sr_numer = (element1 & 0x8000) << 1;
416       m_bLegacy_format = true;
417   }
418   unsigned short int element2;
419   if (! read_int2 (m_fd, element2))
420     return false;
421
422   if (m_bLegacy_format)
423           m_sr_numer |= element2;
424
425   unsigned char element3;
426   if (! read_int1 (m_fd, element3))
427     return false;
428   m_channel_offset = element3;
429   if (g_debug)
430           std::cout << "Channel offset: " << m_channel_offset << std::endl;
431
432   unsigned char element4;
433   if (! read_int1 (m_fd, element4))
434     return false;
435   m_nBytes_channel_header = element4;
436   if (g_debug)
437           std::cout << "Channel header bytes: " << m_nBytes_channel_header << std::endl;
438
439   unsigned short int element5;
440   if (! read_int2 (m_fd, element5))
441     return false;
442   m_nHeader_bytes = element5;
443   if (g_debug)
444           std::cout << "Header bytes: " << m_nHeader_bytes << std::endl;
445
446   m_nMaxChannels = (m_nHeader_bytes - 112) / 36;
447   if (m_nMaxChannels >= 144)
448         m_nChannels = byte2 & 0xFF;
449   else
450     m_nChannels = byte2 & 0x1F;
451
452   unsigned int element6;
453   if (! read_int4 (m_fd, element6))
454     return false;
455   m_nData_bytes = element6;
456   if (g_debug)
457           std::cout << "Data bytes: " << m_nData_bytes << std::endl;
458
459   m_nSamples = (m_nData_bytes / m_nChannels) / 2;
460
461   lseek (m_fd, 28, SEEK_SET);
462   double element13;
463   if (! read_float8 (m_fd, element13))
464           return false;
465   m_time_between_channel_samples = element13;
466
467   if (m_bLegacy_format)
468      m_sample_rate = (double) m_sr_numer / (double) (m_sr_denom * m_nChannels);
469   else
470      m_sample_rate = (double) 1 / m_time_between_channel_samples;
471
472   lseek (m_fd, 36, SEEK_SET);
473   if (! read_int4 (m_fd, m_time_acq_start))
474     return false;
475
476   if (! read_int4 (m_fd, m_time_acq_stop))
477     return false;
478
479   lseek (m_fd, 100, SEEK_SET);
480   unsigned short int element27;
481   if (! read_int2 (m_fd, element27))
482           return false;
483
484   m_bHires = (element27 & 0x0001) ? true : false;
485   if (g_debug) {
486           std::cout << "High resolution: ";
487           if (m_bHires)
488                   std::cout << "Yes";
489           else
490                   std::cout << "No";
491
492           std::cout << std::endl;
493   }
494
495   // Verify Windaq signature
496   lseek (m_fd, m_nHeader_bytes - 2, SEEK_SET);
497   unsigned short int element35;
498   if (! read_int2 (m_fd, element35))
499     return false;
500
501   if (element35 != 0x8001) {
502     std::ostringstream os;
503         m_error = "Incorrect signagure: file is not a valid WinDAQ file";
504     return false;
505   }
506
507   m_valid = true;
508   return true;
509 }
510
511 bool
512 WindaqFile::any_packed_channels ()
513 {
514         for (int iChannel = 0; iChannel < m_nChannels; iChannel++)
515                 if (is_channel_packed (iChannel))
516                         return true;
517
518         return false;
519 }
520
521 bool
522 WindaqFile::is_channel_packed (const int channel)
523 {
524   long iStart = m_channel_offset + channel * m_nBytes_channel_header;
525
526   lseek (m_fd, iStart + 31, SEEK_SET);
527   unsigned char iReadings_per_data_point;
528   if (! read_int1 (m_fd, iReadings_per_data_point))
529         return false;
530
531   if (iReadings_per_data_point > 1)
532           return true;
533
534   return false;
535 }
536
537 WindaqChannel::WindaqChannel (WindaqFile& wdq, const int channel)
538   : r_wdq(wdq), m_data(0), m_slope(0), m_intercept (0), m_channel(channel),
539     m_valid(false)
540 {
541   if (wdq.m_valid) {
542     if (channel >= 1 && channel <= wdq.m_nChannels) {
543       if (read_channel_data())
544         m_valid = true;
545     } else {
546       std::ostringstream os;
547       os << "Channel " << channel << " is invalid, valid range 1-" <<
548         wdq.m_nChannels;
549       error_msg (os.str().c_str());
550     }
551   }
552 }
553
554 WindaqChannel::~WindaqChannel ()
555 {
556   if (m_data)
557     delete m_data;
558 }
559
560 bool
561 WindaqChannel::read_channel_data ()
562 {
563   int fd = r_wdq.m_fd;
564
565   m_data = new signed short int [r_wdq.m_nSamples * 2];
566
567   lseek (fd, r_wdq.m_channel_offset + 8 +
568          (m_channel - 1) * r_wdq.m_nBytes_channel_header,
569          SEEK_SET);
570   if (! read_float8 (fd, m_slope))
571     return false;
572
573   if (! read_float8 (fd, m_intercept))
574     return false;
575
576   char units[7];
577   units[6] = 0;
578   if (read (fd, units, 6) != 6) {
579     error_msg ("Error reading file");
580     return false;
581   }
582   m_units = units;
583
584   long int row_bytes = 2 * r_wdq.m_nChannels;
585
586   signed short int *sample_row = new signed short int [row_bytes];
587
588   signed short int* psample = &sample_row[m_channel - 1];
589
590   lseek (fd, r_wdq.m_nHeader_bytes, SEEK_SET);
591   unsigned long int i;
592   signed short int data_max = 0, data_min = 0;
593   double total_data = 0;
594   for (i = 0; i < r_wdq.m_nSamples; i++) {
595     if (read (fd, sample_row, row_bytes) != row_bytes) {
596       std::ostringstream os;
597       os << "Error reading file at " << i;
598       error_msg (os.str().c_str());
599       delete sample_row;
600       return false;
601     }
602     signed short int v = *psample;
603
604 #if WORDS_BIG_ENDIAN
605     unsigned char* p = reinterpret_cast<unsigned char*>(&v);
606     unsigned char c = p[0]; p[0] = p[1]; p[1] = c;
607 #endif
608
609     signed short int value = v;
610         if (! r_wdq.m_bHires)
611                 value >>= 2;
612
613     m_data[i] = value;
614     total_data += value;
615
616     if (i == 0) {
617       data_max = value;
618       data_min = value;
619     } else {
620       if (value > data_max)
621         data_max = value;
622       else if (value < data_min)
623         data_min = value;
624     }
625   }
626
627   m_max_raw_data = data_max;
628   m_min_raw_data = data_min;
629   m_max_scaled_data = (m_slope * data_max) + m_intercept;
630   m_min_scaled_data = (m_slope * data_min) + m_intercept;
631
632   if (! g_dont_demean) {
633     double dmean = total_data / static_cast<double>(r_wdq.m_nSamples);
634     int mean = nearest<int>(dmean);
635     std::cout << "Removing mean: " << (dmean * m_slope) + m_intercept <<
636       " " << m_units << std::endl;
637
638     for (i = 0; i < r_wdq.m_nSamples; i++)
639       m_data[i] -= mean;
640   }
641
642   delete sample_row;
643   return true;
644 }
645
646
647 WavFile::WavFile (WindaqChannel& wdq_channel, const char* fname)
648   : m_valid(false), m_data(0), m_nSamples(0), m_strFile(fname), m_fd(0)
649 {
650   if (wdq_channel.m_valid) {
651     m_nSamples = wdq_channel.r_wdq.m_nSamples;
652     m_nChannels = 1;
653     m_nBitsPerSample = 16;
654     m_nBytesPerSample = 2;
655     m_rate = wdq_channel.r_wdq.m_sample_rate;
656
657     double data_offset = 0, data_scale = 0;
658     if (g_ignore_zero) {
659       data_offset = -wdq_channel.m_min_scaled_data;
660       if (wdq_channel.m_max_scaled_data != wdq_channel.m_min_scaled_data)
661         data_scale = 65535. / (wdq_channel.m_max_scaled_data -
662                                wdq_channel.m_min_scaled_data);
663     } else {
664       double max_value = fabs(wdq_channel.m_max_scaled_data);
665       if (fabs (wdq_channel.m_min_scaled_data) > max_value)
666         max_value = fabs (wdq_channel.m_min_scaled_data);
667       if (max_value != 0.)
668         data_scale = 32767. / max_value;
669     }
670
671     if (g_debug) {
672       std::ostringstream os;
673       os << "  Wav data_scale: " << data_scale << ", data_offset: " << data_offset;
674       info_msg (os.str().c_str());
675     }
676
677     m_nHeaderBytes = 44;
678     m_nDataBytes = m_nSamples * m_nBytesPerSample * m_nChannels;
679     m_nFileBytes = m_nHeaderBytes + m_nDataBytes;
680
681     unsigned int nHeaderShortInts = m_nHeaderBytes / sizeof(signed short int);
682
683     m_data = new signed short int [m_nSamples + nHeaderShortInts];
684     signed short int* input = wdq_channel.m_data;
685     signed short int* output = &m_data[nHeaderShortInts];
686     double slope = wdq_channel.m_slope;
687     double intercept = wdq_channel.m_intercept;
688
689     if (! fill_header ())
690       return;
691
692     unsigned long int i;
693
694     for (i = 0; i < m_nSamples; i++) {
695       double value = input[i];
696       value = (slope * value) + intercept;
697       if (g_ignore_zero) {
698         value = (value + data_offset) * data_scale;
699         value += 0.5 - 32768;
700       } else {
701         value = value * data_scale;
702       }
703
704       signed short int v = static_cast<signed short int>(value);
705 #if WORDS_BIG_ENDIAN
706       unsigned char* p = reinterpret_cast<unsigned char*>(&v);
707       unsigned char c = p[0]; p[0] = p[1]; p[1] = c;
708 #endif
709       output[i] = v;
710     }
711   }
712
713   m_valid = true;
714 }
715
716
717 WavFile::~WavFile ()
718 {
719   if (m_fd != 0)
720     close (m_fd);
721
722   if (m_data != NULL)
723     delete m_data;
724 }
725
726 void
727 put_int4 (char* p, unsigned int n)
728 {
729   *p = n & 0xFF;
730   *(p+1) = 0xFF & (n >> 8);
731   *(p+2) = 0xFF & (n >> 16);
732   *(p+3) = 0xFF & (n >> 24);
733 }
734
735 void
736 put_int2 (char* p, unsigned short int n)
737 {
738   *p = n & 0xFF;
739   *(p+1) = 0xFF & (n >> 8);
740 }
741
742 bool
743 WavFile::fill_header ()
744 {
745   char* pData = reinterpret_cast<char*> (m_data);
746
747   strncpy (pData, "RIFF", 4);
748
749   // Length of file after 8 byte header
750   put_int4 (pData + 4, 36 + m_nDataBytes);
751
752   strncpy (pData + 8, "WAVEfmt ", 8);
753
754   // Length of header block
755   put_int4 (pData + 16, 0x10);
756
757   // Always 1
758   put_int2 (pData + 20, 1);
759
760   /* Number of channels */
761   put_int2 (pData + 22, m_nChannels);
762
763   // Sample Rate
764   put_int4 (pData + 24, static_cast<int> (m_rate + 0.5));
765
766   // Bytes per second
767   put_int4 (pData + 28, static_cast<int> (m_rate * m_nBytesPerSample + 0.5));
768
769   // Bytes per sample
770   put_int2 (pData + 32, m_nBytesPerSample * m_nChannels);
771
772   // Bits per sample
773   put_int2 (pData + 34, m_nBitsPerSample);
774
775   strncpy (pData + 36, "data", 4);
776
777   put_int4 (pData + 40, m_nDataBytes);
778
779   return true;
780 }
781
782 bool
783 WavFile::WriteFile ()
784 {
785   if (! m_valid)
786     return false;
787
788   if (m_fd == 0)
789     if ((m_fd = open (m_strFile.c_str(), O_WRONLY | O_BINARY | O_TRUNC | O_CREAT, g_fileMode)) == 0) {
790       std::ostringstream os;
791       os << "Error opening output file " << m_strFile.c_str();
792       error_msg (os.str().c_str());
793       return false;
794     }
795
796   lseek (m_fd, 0, SEEK_SET);
797   if (write (m_fd, m_data, m_nFileBytes) != m_nFileBytes) {
798     error_msg ("Error writing file");
799     return false;
800   }
801
802   if (close (m_fd) < 0)
803     error_msg ("Error closing output file");
804
805   m_fd = 0;
806   return true;
807 }
808
809 #ifdef _WIN32
810 #include <windows.h>
811 #include <mmsystem.h>
812 #elif defined(__linux__)
813 #include <sys/ioctl.h>
814 #include <sys/soundcard.h>
815 #endif
816
817 bool
818 WavFile::Play ()
819 {
820 #ifdef _WIN32
821   if (PlaySound ((LPCSTR) m_data, 0, SND_MEMORY | SND_NODEFAULT))
822     return true;
823 #elif defined(__linux__)
824   int fd;
825   if ((fd = open ("/dev/dsp",O_WRONLY)) == -1) {
826     error_msg ("Error opening /dev/dsp");
827     return false;
828   }
829
830   int format = AFMT_S16_LE;
831   if (ioctl (fd, SNDCTL_DSP_SETFMT, &format) == -1) {
832     error_msg ("Error setting DSP format");
833     close(fd); return false;
834   }
835   if (format != AFMT_S16_LE) {
836     error_msg ("DSP Format not set");
837     close(fd); return false;
838   }
839
840   unsigned int channels = m_nChannels;
841   if (ioctl (fd, SNDCTL_DSP_CHANNELS, &format) == -1) {
842     error_msg ("Error setting number of channels");
843     close(fd); return false;
844   }
845   if (channels != m_nChannels) {
846     error_msg ("Number of channels not set");
847     close(fd); return false;
848   }
849
850   unsigned int speed = static_cast<int>(m_rate + 0.5);
851   if (ioctl (fd, SNDCTL_DSP_SPEED, &speed) == -1) {
852     error_msg ("Error setting sample rate");
853     close(fd); return false;
854   }
855   if (speed != m_rate && ! g_quiet) {
856     std::ostringstream os;
857     os << "Warning: Sample rate set to " << speed << ", not " << m_rate;
858     error_msg (os.str().c_str());
859   }
860
861   if (write (fd, reinterpret_cast<char*>(m_data) + m_nHeaderBytes, m_nDataBytes) !=
862       m_nDataBytes) {
863     error_msg ("Error writing audio samples");
864     close(fd); return false;
865   }
866
867   close (fd);
868   return true;
869 #else
870 #endif
871
872   return false;
873 }
874
875