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