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