39b5a81c693ce2a0e87ae2efffe7c02cf471c89b
[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 **  $Id$
12 **
13 **  This program is free software; you can redistribute it and/or modify
14 **  it under the terms of the GNU General Public License (version 2) as
15 **  published by the Free Software Foundation.
16 **
17 **  This program is distributed in the hope that it will be useful,
18 **  but WITHOUT ANY WARRANTY; without even the implied warranty of
19 **  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20 **  GNU General Public License for more details.
21 **
22 **  You should have received a copy of the GNU General Public License
23 **  along with this program; if not, write to the Free Software
24 **  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
25 ******************************************************************************/
26
27 #include <wdq2wav.h>
28
29 const char* g_szIdStr = "$Id$";
30
31 bool g_quiet = false;
32 bool g_verbose = false;
33 bool g_debug = false;
34 bool g_ignore_zero = false;
35 bool g_dont_demean = false;
36
37
38 #ifdef WIN32
39 #define lseek _lseek
40 #define close _close
41 #define open _open
42 #define read _read
43 #define write _write
44 #define O_BINARY _O_BINARY
45 #define O_RDONLY _O_RDONLY
46 #define O_WRONLY _O_WRONLY
47 #define O_RDWR _O_RDRW
48 #define O_TRUNC _O_TRUNC
49 #define O_CREAT _O_CREAT
50 const int g_fileMode = _S_IWRITE | _S_IREAD;
51 struct fpos_t std::_Fpz = {0,0};
52 #else
53 const int g_fileMode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
54 // Define as NULL for non-Windows platforms
55 #ifndef O_BINARY
56 #define O_BINARY 0
57 #endif
58 #endif
59  
60
61 void
62 error_msg (const char *msg)
63 {
64   std::cerr << msg << "\n";
65 }
66
67 void
68 info_msg (const char* msg)
69 {
70   std::cout << msg << "\n";
71 }
72
73 void
74 info_msg_sans_newline (const char* msg)
75 {
76   std::cout << msg;
77 }
78
79 const char*
80 fileBasename (const char* filename)
81 {
82   const char* pslash = strrchr (filename, '/');
83   const char* pbackslash = strrchr (filename, '\\');
84   const char* p = filename;
85   if (pbackslash && (! pslash || pbackslash >= pslash))
86         p = pbackslash+1;
87   else if (pslash && (! pbackslash || pslash >= pbackslash))
88     p = pslash+1;
89
90   return p;
91 }
92
93 char *
94 str_rm_tail (char *str, const char* const charlist)
95 {
96   size_t i;
97
98   for (i = strlen(str) - 1; i >= 0; i--)
99     if (strchr (charlist, str[i]) != NULL)
100       str[i] = 0;
101     else
102       break;            /* found non-specified char, all done */
103
104   return (str);
105 }
106
107 char *
108 str_wrm_tail (char *str)
109 {
110   return (str_rm_tail(str, "\b\t\n\r"));
111 }
112
113
114 void
115 usage (const char* progname)
116 {
117   std::cout << "usage: " << fileBasename (progname) << " [OPTIONS] <wdq-file> <channel-number> <wav-file>\n";
118   std::cout << "OPTIONS\n";
119   std::cout << "  -p   Play channel through audio system\n";
120   std::cout << "  -q   Supress all messages\n";
121   std::cout << "  -z   Scale output without preserving zero point\n";
122   std::cout << "  -m   Do not demean the data (don't subtract the mean value from each sample)\n";
123   std::cout << "  -v   Verbose mode\n";
124   std::cout << "  -d   Debug mode\n";
125   std::cout << "  -r   Print program version and exit\n";
126   std::cout << "  -h   Print this help message\n";
127 }
128
129
130 int
131 main (int argc, char *argv[])
132 {
133   int c;
134   bool play = false;
135
136   const char* progname = argv[0];
137   
138   while ((c = getopt (argc, argv, "rqvzmdph")) != -1) {
139     switch (c) {
140     case 'r':
141         std::cout << "Version " << g_szIdStr << std::endl;
142                 exit(0);
143         break;
144     case 'q':
145       g_quiet = true;
146       break;
147     case 'm':
148       g_dont_demean = true;
149       break;
150     case 'z':
151       g_ignore_zero = true;
152       break;
153     case 'v':
154       g_verbose = true;
155       break;
156     case 'd':
157       g_debug = true;
158       break;
159     case 'p':
160       play = true;
161       break;
162     case 'h':
163       usage (progname);
164       return (0);
165     case '?':
166     default:
167         usage (progname);
168         return (1);
169       }
170     }
171
172   if (g_verbose || g_debug)
173           std::cout << "Version " << g_szIdStr << std::endl;
174
175   argc -= optind;
176   argv += optind;
177   if (argc > 3) {
178       std::cerr << "Too many parameters\n";
179       usage (progname);
180       return (1);
181     }
182
183   char wdq_fname[MAX_INPUT_STR];
184   if (argc >= 1)
185       strncpy (wdq_fname, argv [0], MAX_INPUT_STR);
186   else {
187     std::cout << "Enter input WinDAQ filename: ";
188       std::cin.getline (wdq_fname, MAX_INPUT_STR);
189     }
190
191     char channel_buf [MAX_INPUT_STR];
192     if (argc >= 2)
193       strncpy (channel_buf, argv[1], MAX_INPUT_STR);
194     else {
195       std::cout << "Enter channel number: ";
196       std::cin.getline (channel_buf, MAX_INPUT_STR);
197     }
198     
199     char *channel_endptr;
200     int channel = static_cast<int>(strtol (channel_buf, &channel_endptr, 10));
201     if (*channel_endptr != 0) {
202       std::ostringstream os;
203       os << "Error: Channel " << channel_buf << " is not an integer";
204       error_msg (os.str().c_str());
205       usage (progname);
206       return (1);
207     }
208
209     char wav_fname[MAX_INPUT_STR];
210     if (argc >= 3)
211       strncpy (wav_fname, argv[2], MAX_INPUT_STR);
212     else {
213       std::cout << "Enter output wav filename: ";
214       std::cin.getline (wav_fname, MAX_INPUT_STR);
215     }
216       
217     if (! wdq2wav (wdq_fname, channel, wav_fname, play))
218       return 1;
219     
220     return 0;
221 }
222
223 bool
224 wdq2wav (const char* wdq_fname, const int channel, const char *wav_fname, bool play)
225 {
226   WindaqFile wdq (wdq_fname);
227
228   if (! wdq.ReadHeader()) {
229     if (wdq.m_error.size()) {
230       std::ostringstream os;
231       os << "Error reading file " << wdq_fname << ": " << wdq.m_error.c_str();
232       error_msg (os.str().c_str());
233     } else {
234       std::ostringstream os;
235       os << "Error reading file " << wdq_fname;
236       error_msg (os.str().c_str());
237     }
238     return false;
239   }
240
241   if (wdq.any_packed_channels()) {
242           std::ostringstream os;
243           os << "File contains 'packed' channels." << std::endl;
244           os << "Convert to 'Advanced CODAS headers' before processing with wdq2wav.";
245           error_msg (os.str().c_str());
246           return false;
247   }
248
249   if (! g_quiet || g_verbose || g_debug) {
250     std::ostringstream os1;
251         os1 << "File: " << wdq_fname;
252     info_msg (os1.str().c_str());
253         std::ostringstream os;
254         os << "Legacy Format: ";
255         if (wdq.m_bLegacy_format)
256                 os << "Yes";
257         else
258                 os << "No";
259         info_msg(os.str().c_str());
260     std::ostringstream os2;
261     time_t time = wdq.m_time_acq_start;
262     struct tm* tm = gmtime (&time);
263     os2 << "  Time File Creation: " << asctime(tm);
264     info_msg_sans_newline (os2.str().c_str());
265     std::ostringstream os3;
266     time = wdq.m_time_acq_stop;
267     tm = gmtime (&time);
268     os3 << "  Time File Written: " << asctime(tm);
269     info_msg_sans_newline (os3.str().c_str());
270     std::ostringstream os4;
271     os4 << "  Samples: " << wdq.m_nSamples <<
272       ", Channels: " << wdq.m_nChannels <<
273       ", Sample Rate: " << wdq.m_sample_rate;
274     info_msg (os4.str().c_str());
275   }
276   
277   WindaqChannel wdq_channel (wdq, channel);
278   if (! wdq_channel.m_valid) {
279     error_msg ("Error reading data from channel");
280     return false;
281   }
282
283   if (! g_quiet || g_verbose || g_debug) {
284     std::ostringstream os1;
285     os1 << "Channel " << channel;
286     info_msg (os1.str().c_str());
287     std::ostringstream os2;
288     os2 << "  Units: " << wdq_channel.m_units.c_str();
289     info_msg (os2.str().c_str());
290     std::ostringstream os3;
291     os3 << "  Raw minimum: " << wdq_channel.m_min_raw_data <<
292       ", maximum: " << wdq_channel.m_max_raw_data;
293     info_msg (os3.str().c_str());
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   WavFile wav (wdq_channel, wav_fname);
308
309   if (! wav.m_valid) {
310     error_msg ("Error extracting wav from channel");
311     return false;
312   }
313
314   if (! wav.WriteFile ()) {
315     error_msg ("Error writing file");
316     return false;
317   }
318
319   if (play)
320     wav.Play();
321   
322   return true;
323 }
324
325
326 WindaqFile::WindaqFile (const char* fname)
327   : m_valid(false), m_fd(0), m_nChannels(0), m_nSamples(0), m_sample_rate(0),
328     m_strFile (fname)
329 {
330 }
331
332 WindaqFile::~WindaqFile ()
333 {
334   if (m_fd != 0)
335     close (m_fd);
336 }
337
338 bool read_int1 (int fd, unsigned char& n)
339 {
340   unsigned char tmp1;
341   if (read (fd, &tmp1, 1) != 1)
342     return false;
343
344   n = tmp1;
345   return true;
346 }
347
348 bool read_int2 (int fd, unsigned short int& n)
349 {
350   unsigned char tmp1;
351   unsigned int tmp2;
352   if (read (fd, &tmp1, 1) != 1)
353     return false;
354   tmp2 = tmp1;
355   if (read (fd, &tmp1, 1) != 1)
356     return false;
357   
358   n = tmp2 + (tmp1 * 256);
359   return true;
360 }
361
362 bool read_int4 (int fd, unsigned int& n)
363 {
364   unsigned int tmp4;
365   unsigned short int tmp2;
366   if (! read_int2 (fd, tmp2))
367     return false;
368   tmp4 = tmp2;
369   if (! read_int2 (fd, tmp2))
370     return false;
371   
372   n = tmp4 + (tmp2 * 65536);
373   return true;
374 }
375
376 bool read_float8 (int fd, double& f)
377 {
378   unsigned char buf[8];
379   if (read (fd, &buf, 8) != 8)
380     return false;
381
382 #if WORDS_BIG_ENDIAN
383   unsigned char c;
384   c = buf[0]; buf[0] = buf[7]; buf[7] = c;
385   c = buf[1]; buf[1] = buf[6]; buf[6] = c;
386   c = buf[2]; buf[2] = buf[5]; buf[5] = c;
387   c = buf[3]; buf[3] = buf[4]; buf[4] = c;
388 #endif
389
390   f = *(reinterpret_cast<double*>(buf));
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) m_nChannels / 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