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