r4131: *** empty log message ***
[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: wdq2wav.cpp,v 1.26 2003/02/28 04:12:17 kevin Exp $
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: wdq2wav.cpp,v 1.26 2003/02/28 04:12:17 kevin Exp $";
30
31 bool g_quiet = false;
32 bool g_verbose = false;
33 bool g_debug = false;
34 bool g_preserve_zero = false;
35 bool g_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* p = strrchr (filename, '/');
83   return (p ? p + 1 : filename);
84 }
85
86 char *
87 str_rm_tail (char *str, const char* const charlist)
88 {
89   size_t i;
90
91   for (i = strlen(str) - 1; i >= 0; i--)
92     if (strchr (charlist, str[i]) != NULL)
93       str[i] = 0;
94     else
95       break;            /* found non-specified char, all done */
96
97   return (str);
98 }
99
100 char *
101 str_wrm_tail (char *str)
102 {
103   return (str_rm_tail(str, "\b\t\n\r"));
104 }
105
106
107 void
108 usage (const char* progname)
109 {
110   std::cout << "usage: " << fileBasename (progname) << " [OPTIONS] <wdq-file> <channel-number> <wav-file>\n";
111   std::cout << "OPTIONS\n";
112   std::cout << "  -p   Play channel through audio system\n";
113   std::cout << "  -q   Supress all messages\n";
114   std::cout << "  -z   Scale output with preserving zero point\n";
115   std::cout << "  -m   Demean the data (subtract the mean value from each sample)\n";
116   std::cout << "       [Selecting this option automatically sets the -z option]\n";
117   std::cout << "  -v   Verbose mode\n";
118   std::cout << "  -d   Debug mode\n";
119   std::cout << "  -r   Print program version\n";
120   std::cout << "  -h   Print this help message\n";
121 }
122
123
124 int
125 main (int argc, char *argv[])
126 {
127   int c;
128   bool play = false;
129
130   const char* progname = argv[0];
131   
132   while ((c = getopt (argc, argv, "rqvzmdph")) != -1) {
133     switch (c) {
134     case 'r':
135         std::cout << "Version " << g_szIdStr << std::endl;
136         break;
137     case 'q':
138       g_quiet = true;
139       break;
140     case 'm':
141       g_demean = true;
142       g_preserve_zero = true; // auto set
143       break;
144     case 'z':
145       g_preserve_zero = true;
146       break;
147     case 'v':
148       g_verbose = true;
149       break;
150     case 'd':
151       g_debug = true;
152       break;
153     case 'p':
154       play = true;
155       break;
156     case 'h':
157       usage (progname);
158       return (0);
159     case '?':
160     default:
161         usage (progname);
162         return (1);
163       }
164     }
165   argc -= optind;
166   argv += optind;
167   if (argc > 3) {
168       std::cerr << "Too many parameters\n";
169       usage (progname);
170       return (1);
171     }
172
173   char wdq_fname[MAX_INPUT_STR];
174   if (argc >= 1)
175       strncpy (wdq_fname, argv [0], MAX_INPUT_STR);
176   else {
177     std::cout << "Enter input WinDAQ filename: ";
178       std::cin.getline (wdq_fname, MAX_INPUT_STR);
179     }
180
181     char channel_buf [MAX_INPUT_STR];
182     if (argc >= 2)
183       strncpy (channel_buf, argv[1], MAX_INPUT_STR);
184     else {
185       std::cout << "Enter channel number: ";
186       std::cin.getline (channel_buf, MAX_INPUT_STR);
187     }
188     
189     char *channel_endptr;
190     int channel = static_cast<int>(strtol (channel_buf, &channel_endptr, 10));
191     if (*channel_endptr != 0) {
192       std::ostringstream os;
193       os << "Error: Channel " << channel_buf << " is not an integer";
194       error_msg (os.str().c_str());
195       usage (progname);
196       return (1);
197     }
198
199     char wav_fname[MAX_INPUT_STR];
200     if (argc >= 3)
201       strncpy (wav_fname, argv[2], MAX_INPUT_STR);
202     else {
203       std::cout << "Enter output wav filename: ";
204       std::cin.getline (wav_fname, MAX_INPUT_STR);
205     }
206       
207     if (! wdq2wav (wdq_fname, channel, wav_fname, play))
208       return 1;
209     
210     return 0;
211 }
212
213 bool
214 wdq2wav (const char* wdq_fname, const int channel, const char *wav_fname, bool play)
215 {
216   WindaqFile wdq (wdq_fname);
217
218   if (! wdq.ReadHeader()) {
219     if (wdq.m_error.size()) {
220       std::ostringstream os;
221       os << "Error reading file " << wdq_fname << ": " << wdq.m_error.c_str();
222       error_msg (os.str().c_str());
223     } else {
224       std::ostringstream os;
225       os << "Error reading file " << wdq_fname;
226       error_msg (os.str().c_str());
227     }
228     return false;
229   }
230   if (! g_quiet || g_verbose || g_debug) {
231     std::ostringstream os1;
232     os1 << "File " << wdq_fname;
233     info_msg (os1.str().c_str());
234     std::ostringstream os2;
235     time_t time = wdq.m_time_acq_start;
236     struct tm* tm = gmtime (&time);
237     os2 << "  Time File Creation: " << asctime(tm);
238     info_msg_sans_newline (os2.str().c_str());
239     std::ostringstream os3;
240     time = wdq.m_time_acq_stop;
241     tm = gmtime (&time);
242     os3 << "  Time File Written: " << asctime(tm);
243     info_msg_sans_newline (os3.str().c_str());
244     std::ostringstream os4;
245     os4 << "  Samples: " << wdq.m_nSamples <<
246       ", Channels: " << wdq.m_nChannels <<
247       ", Sample Rate: " << wdq.m_sample_rate;
248     info_msg (os4.str().c_str());
249   }
250   
251   WindaqChannel wdq_channel (wdq, channel);
252   if (! wdq_channel.m_valid) {
253     error_msg ("Error reading data from channel");
254     return false;
255   }
256
257   if (! g_quiet || g_verbose || g_debug) {
258     std::ostringstream os1;
259     os1 << "Channel " << channel;
260     info_msg (os1.str().c_str());
261     std::ostringstream os2;
262     os2 << "  Units: " << wdq_channel.m_units.c_str();
263     info_msg (os2.str().c_str());
264     std::ostringstream os3;
265     os3 << "  Raw minimum: " << wdq_channel.m_min_raw_data <<
266       ", maximum: " << wdq_channel.m_max_raw_data;
267     info_msg (os3.str().c_str());
268   }
269   
270   if (g_debug) {
271     std::ostringstream os4;
272     os4 << "  Scaled minimum: " << wdq_channel.m_min_scaled_data <<
273       ", maximum: " << wdq_channel.m_max_scaled_data;
274     info_msg (os4.str().c_str());
275     std::ostringstream os5;
276     os5 << "  Slope " <<  wdq_channel.m_slope <<
277       ", Intercept " <<  wdq_channel.m_intercept;
278     info_msg (os5.str().c_str());
279   }
280
281   WavFile wav (wdq_channel, wav_fname);
282
283   if (! wav.m_valid) {
284     error_msg ("Error extracting wav from channel");
285     return false;
286   }
287
288   if (! wav.WriteFile ()) {
289     error_msg ("Error writing file");
290     return false;
291   }
292
293   if (play)
294     wav.Play();
295   
296   return true;
297 }
298
299
300 WindaqFile::WindaqFile (const char* fname)
301   : m_valid(false), m_fd(0), m_nChannels(0), m_nSamples(0), m_sample_rate(0),
302     m_strFile (fname)
303 {
304 }
305
306 WindaqFile::~WindaqFile ()
307 {
308   if (m_fd != 0)
309     close (m_fd);
310 }
311
312 bool read_int2 (int fd, unsigned short int& n)
313 {
314   unsigned char tmp1;
315   unsigned int tmp2;
316   if (read (fd, &tmp1, 1) != 1)
317     return false;
318   tmp2 = tmp1;
319   if (read (fd, &tmp1, 1) != 1)
320     return false;
321   
322   n = tmp2 + (tmp1 * 256);
323   return true;
324 }
325
326 bool read_int4 (int fd, unsigned int& n)
327 {
328   unsigned int tmp4;
329   unsigned short int tmp2;
330   if (! read_int2 (fd, tmp2))
331     return false;
332   tmp4 = tmp2;
333   if (! read_int2 (fd, tmp2))
334     return false;
335   
336   n = tmp4 + (tmp2 * 65536);
337   return true;
338 }
339
340 bool
341 WindaqFile::ReadHeader ()
342 {
343   unsigned short int tmp2;
344
345   m_valid = false;
346   if ((m_fd = open (m_strFile.c_str(), O_RDONLY | O_BINARY)) < 0) {
347     m_error = "Unable to open file";
348     return false;
349   }
350
351   lseek (0, 0, SEEK_SET);
352   if (! read_int2 (m_fd, tmp2))
353     return false;
354
355   m_nChannels = tmp2 & 0x1f;
356   m_sr_denom = (tmp2 & 0x7fff) >> 5;
357   m_sr_numer = (tmp2 & 0x8000) << 1;
358   
359   if (! read_int2 (m_fd, tmp2))
360     return false;
361
362   m_sr_numer |= tmp2;
363   m_sample_rate = (double) m_sr_numer / (double) (m_sr_denom * m_nChannels);
364
365   if (! read_int2 (m_fd, tmp2))
366     return false;
367
368   m_channel_offset = tmp2 & 0xFF;
369   m_nBytes_channel_header = tmp2 >> 8;
370   
371   if (! read_int2 (m_fd, m_nHeader_bytes))
372     return false;
373   
374   if (! read_int4 (m_fd, m_nData_bytes))
375     return false;
376
377   m_nSamples = (m_nData_bytes / m_nChannels) / 2;
378
379   lseek (m_fd, 36, SEEK_SET);
380   if (! read_int4 (m_fd, m_time_acq_start))
381     return false;
382
383   if (! read_int4 (m_fd, m_time_acq_stop))
384     return false;
385
386   // Verify Windaq signature
387   lseek (m_fd, m_nHeader_bytes - 2, SEEK_SET);
388   if (! read_int2 (m_fd, tmp2))
389     return false;
390
391   if (tmp2 != 0x8001) {
392     std::ostringstream os;
393     m_error = "File is not a valid WinDAQ file";
394     return false;
395   }
396
397   m_valid = true;
398   return true;
399 }
400
401   
402 WindaqChannel::WindaqChannel (WindaqFile& wdq, const int channel)
403   : r_wdq(wdq), m_data(0), m_slope(0), m_intercept (0), m_channel(channel),
404     m_valid(false)
405 {
406   if (wdq.m_valid) {
407     if (channel >= 1 && channel <= wdq.m_nChannels) {
408       if (read_channel_data())
409         m_valid = true;
410     } else {
411       std::ostringstream os;
412       os << "Channel " << channel << " is invalid, valid range 1-" <<
413         wdq.m_nChannels;
414       error_msg (os.str().c_str());
415     }
416   }
417 }
418
419 WindaqChannel::~WindaqChannel ()
420 {
421   if (m_data)
422     delete m_data;
423 }
424
425 bool get_float8 (int fd, double& f)
426 {
427   unsigned char buf[8];
428   if (read (fd, &buf, 8) != 8)
429     return false;
430
431 #if WORDS_BIG_ENDIAN
432   unsigned char c;
433   c = buf[0]; buf[0] = buf[7]; buf[7] = c;
434   c = buf[1]; buf[1] = buf[6]; buf[6] = c;
435   c = buf[2]; buf[2] = buf[5]; buf[5] = c;
436   c = buf[3]; buf[3] = buf[4]; buf[4] = c;
437 #endif
438
439   f = *(reinterpret_cast<double*>(buf));
440
441   return true;
442 }
443
444
445 bool
446 WindaqChannel::read_channel_data ()
447 {
448   int fd = r_wdq.m_fd;
449
450   m_data = new signed short int [r_wdq.m_nSamples * 2];
451
452   lseek (fd, r_wdq.m_channel_offset + 8 + 
453          (m_channel - 1) * r_wdq.m_nBytes_channel_header,
454          SEEK_SET);
455   if (! get_float8 (fd, m_slope))
456     return false;
457
458   if (! get_float8 (fd, m_intercept))
459     return false;
460
461   char units[7];
462   units[6] = 0;
463   if (read (fd, units, 6) != 6) {
464     error_msg ("Error reading file");
465     return false;
466   }
467   m_units = units;
468  
469   long int row_bytes = 2 * r_wdq.m_nChannels;
470   signed short int *sample_row = new signed short int [row_bytes];
471   
472   signed short int* psample = &sample_row[m_channel - 1];
473
474   lseek (fd, r_wdq.m_nHeader_bytes, SEEK_SET);
475   unsigned long int i;
476   signed short int data_max = 0, data_min = 0;
477   double total_data = 0;
478   for (i = 0; i < r_wdq.m_nSamples; i++) {
479     if (read (fd, sample_row, row_bytes) != row_bytes) {
480       std::ostringstream os;
481       os << "Error reading file at " << i;
482       error_msg (os.str().c_str());
483       delete sample_row;
484       return false;
485     }
486     signed short int v = *psample;
487
488 #if WORDS_BIG_ENDIAN
489     unsigned char* p = reinterpret_cast<unsigned char*>(&v);
490     unsigned char c = p[0]; p[0] = p[1]; p[1] = c; 
491 #endif
492
493     signed short int value = v >> 2;
494     m_data[i] = value;
495     total_data += value;
496     
497     if (i == 0) {
498       data_max = value;
499       data_min = value;
500     } else {
501       if (value > data_max)
502         data_max = value;
503       else if (value < data_min)
504         data_min = value;
505     }
506   }
507
508   m_max_raw_data = data_max;
509   m_min_raw_data = data_min;
510   m_max_scaled_data = (m_slope * data_max) + m_intercept;
511   m_min_scaled_data = (m_slope * data_min) + m_intercept;
512
513   if (g_demean) {
514     double dmean = total_data / static_cast<double>(r_wdq.m_nSamples);
515     int mean = nearest<int>(dmean);
516     std::cout << "Removing mean: " << (dmean * m_slope) + m_intercept <<
517       " " << m_units << std::endl;
518     
519     for (i = 0; i < r_wdq.m_nSamples; i++)
520       m_data[i] -= mean;
521   }
522   
523   delete sample_row;
524   return true;
525 }
526
527
528 WavFile::WavFile (WindaqChannel& wdq_channel, const char* fname)
529   : m_valid(false), m_data(0), m_nSamples(0), m_strFile(fname), m_fd(0)
530 {
531   if (wdq_channel.m_valid) {
532     m_nSamples = wdq_channel.r_wdq.m_nSamples;
533     m_nChannels = 1;
534     m_nBitsPerSample = 16;
535     m_nBytesPerSample = 2;
536     m_rate = wdq_channel.r_wdq.m_sample_rate;
537
538     double data_offset = 0, data_scale = 0;
539     if (g_preserve_zero) {
540       double max_value = fabs(wdq_channel.m_max_scaled_data);
541       if (fabs (wdq_channel.m_min_scaled_data) > max_value)
542         max_value = fabs (wdq_channel.m_min_scaled_data);
543       if (max_value != 0.)
544         data_scale = 32767. / max_value;
545     } else {
546       data_offset = -wdq_channel.m_min_scaled_data;
547       if (wdq_channel.m_max_scaled_data != wdq_channel.m_min_scaled_data)
548         data_scale = 65535. / (wdq_channel.m_max_scaled_data -
549                                wdq_channel.m_min_scaled_data);
550     }
551     
552     if (g_debug) {
553       std::ostringstream os;
554       os << "  Wav data_scale: " << data_scale << ", data_offset: " << data_offset;
555       info_msg (os.str().c_str());
556     }
557     
558     m_nHeaderBytes = 44;
559     m_nDataBytes = m_nSamples * m_nBytesPerSample * m_nChannels;
560     m_nFileBytes = m_nHeaderBytes + m_nDataBytes;
561
562     unsigned int nHeaderShortInts = m_nHeaderBytes / sizeof(signed short int);
563
564     m_data = new signed short int [m_nSamples + nHeaderShortInts];
565     signed short int* input = wdq_channel.m_data;
566     signed short int* output = &m_data[nHeaderShortInts];
567     double slope = wdq_channel.m_slope;
568     double intercept = wdq_channel.m_intercept;
569     
570     if (! fill_header ())
571       return;
572
573     unsigned long int i;
574     for (i = 0; i < m_nSamples; i++) {
575       double value = input[i];
576       value = (slope * value) + intercept;
577       if (g_preserve_zero) {
578         value = value * data_scale;
579       } else {
580         value = (value + data_offset) * data_scale;
581         value += 0.5 - 32768;
582       }
583       
584       signed short int v = static_cast<signed short int>(value);
585 #if WORDS_BIG_ENDIAN
586       unsigned char* p = reinterpret_cast<unsigned char*>(&v);
587       unsigned char c = p[0]; p[0] = p[1]; p[1] = c; 
588 #endif
589       output[i] = v;
590     }
591   }
592
593   m_valid = true;
594 }
595
596
597 WavFile::~WavFile ()
598 {
599   if (m_fd != 0)
600     close (m_fd);
601     
602   if (m_data != NULL)
603     delete m_data;
604 }
605
606 void
607 put_int4 (char* p, unsigned int n)
608 {
609   *p = n & 0xFF;
610   *(p+1) = 0xFF & (n >> 8);
611   *(p+2) = 0xFF & (n >> 16);
612   *(p+3) = 0xFF & (n >> 24);
613 }
614
615 void
616 put_int2 (char* p, unsigned short int n)
617 {
618   *p = n & 0xFF;
619   *(p+1) = 0xFF & (n >> 8);
620 }
621
622 bool
623 WavFile::fill_header ()
624 {
625   char* pData = reinterpret_cast<char*> (m_data);
626
627   strncpy (pData, "RIFF", 4);
628
629   // Length of file after 8 byte header
630   put_int4 (pData + 4, 36 + m_nDataBytes);
631
632   strncpy (pData + 8, "WAVEfmt ", 8);
633
634   // Length of header block
635   put_int4 (pData + 16, 0x10);
636
637   // Always 1
638   put_int2 (pData + 20, 1);
639
640   /* Number of channels */
641   put_int2 (pData + 22, m_nChannels);
642
643   // Sample Rate
644   put_int4 (pData + 24, static_cast<int> (m_rate + 0.5));
645
646   // Bytes per second 
647   put_int4 (pData + 28, static_cast<int> (m_rate * m_nBytesPerSample + 0.5));
648
649   // Bytes per sample
650   put_int2 (pData + 32, m_nBytesPerSample * m_nChannels);
651
652   // Bits per sample 
653   put_int2 (pData + 34, m_nBitsPerSample);
654
655   strncpy (pData + 36, "data", 4);
656
657   put_int4 (pData + 40, m_nDataBytes);
658
659   return true;
660 }
661
662 bool
663 WavFile::WriteFile ()
664 {
665   if (! m_valid)
666     return false;
667
668   if (m_fd == 0)
669     if ((m_fd = open (m_strFile.c_str(), O_WRONLY | O_BINARY | O_TRUNC | O_CREAT, g_fileMode)) == 0) {
670       std::ostringstream os;
671       os << "Error opening output file " << m_strFile.c_str();
672       error_msg (os.str().c_str());
673       return false;
674     }
675
676   lseek (m_fd, 0, SEEK_SET);
677   if (write (m_fd, m_data, m_nFileBytes) != m_nFileBytes) {
678     error_msg ("Error writing file");
679     return false;
680   }
681
682   if (close (m_fd) < 0)
683     error_msg ("Error closing output file");
684   
685   m_fd = 0;
686   return true;
687 }
688
689 #ifdef WIN32
690 #include <windows.h>
691 #include <mmsystem.h>
692 #elif defined(LINUX)
693 #include <sys/ioctl.h>
694 #include <sys/soundcard.h>
695 #endif
696
697 bool
698 WavFile::Play ()
699 {
700 #ifdef WIN32
701   if (PlaySound ((LPCSTR) m_data, 0, SND_MEMORY | SND_NODEFAULT))
702     return true;
703 #elif defined(LINUX)
704   int fd;
705   if ((fd = open ("/dev/dsp",O_WRONLY)) == -1) {
706     error_msg ("Error opening /dev/dsp");
707     return false;
708   }
709   
710   int format = AFMT_S16_LE;
711   if (ioctl (fd, SNDCTL_DSP_SETFMT, &format) == -1) {
712     error_msg ("Error setting DSP format");
713     close(fd); return false;
714   }
715   if (format != AFMT_S16_LE) {
716     error_msg ("DSP Format not set");
717     close(fd); return false;
718   }
719   
720   unsigned int channels = m_nChannels;
721   if (ioctl (fd, SNDCTL_DSP_CHANNELS, &format) == -1) {
722     error_msg ("Error setting number of channels");
723     close(fd); return false;
724   }
725   if (channels != m_nChannels) {
726     error_msg ("Number of channels not set");
727     close(fd); return false;
728   }
729
730   unsigned int speed = static_cast<int>(m_rate + 0.5);
731   if (ioctl (fd, SNDCTL_DSP_SPEED, &speed) == -1) {
732     error_msg ("Error setting sample rate");
733     close(fd); return false;
734   }
735   if (speed != m_rate && ! g_quiet) {
736     std::ostringstream os;
737     os << "Warning: Sample rate set to " << speed << ", not " << m_rate;
738     error_msg (os.str().c_str());
739   }
740     
741   if (write (fd, reinterpret_cast<char*>(m_data) + m_nHeaderBytes, m_nDataBytes) !=
742       m_nDataBytes) {
743     error_msg ("Error writing audio samples");
744     close(fd); return false;
745   }
746
747   close (fd);
748   return true;
749 #else
750 #endif
751   
752   return false;
753 }
754
755