File: Util.cpp

package info (click to toggle)
darkice 1.3-0.1
  • links: PTS
  • area: main
  • in suites: stretch
  • size: 2,024 kB
  • sloc: cpp: 32,044; sh: 11,508; makefile: 129
file content (540 lines) | stat: -rw-r--r-- 16,202 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
/*------------------------------------------------------------------------------

   Copyright (c) 2000-2007 Tyrell Corporation. All rights reserved.

   Tyrell DarkIce

   File     : Util.cpp
   Version  : $Revision$
   Author   : $Author$
   Location : $HeadURL$
   
   Copyright notice:

    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License  
    as published by the Free Software Foundation; either version 3
    of the License, or (at your option) any later version.
   
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of 
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
    GNU General Public License for more details.
   
    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

------------------------------------------------------------------------------*/

/* ============================================================ include files */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#ifdef HAVE_ERRNO_H
#include <errno.h>
#else
#error need errno.h
#endif

#ifdef HAVE_STRING_H
#include <string.h>
#else
#error need string.h
#endif

#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#else
#error need stdlib.h
#endif

#ifdef HAVE_LIMITS_H
#include <limits.h>
#else
#error need limits.h
#endif

#ifdef HAVE_MATH_H
#include <math.h>
#else
#error need math.h
#endif

#ifdef HAVE_TIME_H
#include <time.h>
#else
#error need time.h
#endif

#ifdef HAVE_UNISTD_H
#include <unistd.h>
#else
#error need unistd.h
#endif

#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#else
#error need sys/time.h
#endif

#ifdef HAVE_SIGNAL_H
#include <signal.h>
#else
#error need signal.h
#endif

#ifdef HAVE_ERRNO_H
#include <errno.h>
#endif

#include "Util.h"


/* ===================================================  local data structures */


/* ================================================  local constants & macros */

/*------------------------------------------------------------------------------
 *  File identity
 *----------------------------------------------------------------------------*/
static const char fileid[] = "$Id$";


/* ===============================================  local function prototypes */


/* =============================================================  module code */

char
Util :: base64Table[] = {
    'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P',
    'Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f',
    'g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v',
    'w','x','y','z','0','1','2','3','4','5','6','7','8','9','+','/'
};


/*------------------------------------------------------------------------------
 *  Calculate the length of a zero-terminated C string,
 *  w/o the zero-termination
 *----------------------------------------------------------------------------*/
unsigned int
Util :: strLen( const char    * str )                   throw ( Exception )
{
    size_t      len;

    if ( !str ) {
        throw Exception( __FILE__, __LINE__, "no str");
    }

    len = strlen( str);

    return len;
}


/*------------------------------------------------------------------------------
 *  Copy the contents of a string into another
 *----------------------------------------------------------------------------*/
void
Util :: strCpy (    char          * dest,
                    const char    * src )               throw ( Exception )
{
    if ( !dest || !src ) {
        throw Exception( __FILE__, __LINE__, "no src or dest");
    }

    strcpy( dest, src);
}


/*------------------------------------------------------------------------------
 *  Concatenate the contents of a string onto another
 *----------------------------------------------------------------------------*/
void
Util :: strCat (    char          * dest,
                    const char    * src )               throw ( Exception )
{
    if ( !dest || !src ) {
        throw Exception( __FILE__, __LINE__, "no src or dest");
    }

    strcat( dest, src);
}


/*------------------------------------------------------------------------------
 *  Duplicate a string by allocating space with new[]
 *  The returned string must be freed with delete[]
 *----------------------------------------------------------------------------*/
char *
Util :: strDup( const char    * str )                   throw ( Exception )
{
    size_t      len;
    char      * s;

    if ( !str ) {
        throw Exception( __FILE__, __LINE__, "no str");
    }

    len = strlen( str) + 1;
    s   = new char[len];
    memcpy( s, str, len);

    return s;
}


/*------------------------------------------------------------------------------
 *  Convert a string into base64 encoding.
 *----------------------------------------------------------------------------*/
char *
Util :: base64Encode( const char  * str )               throw ( Exception )
{
    if ( !str ) {
        throw Exception( __FILE__, __LINE__, "no str");
    }

    const char    * data    = str;
    size_t          len     = strlen( data);
    char          * out     = new char[len * 4 / 3 + 4];
    char          * result  = out;
    unsigned        chunk;

    while ( len > 0 ) {
        chunk = (len > 3) ? 3 : len;
        *out++ = base64Table[(*data & 0xfc) >> 2];
        *out++ = base64Table[((*data & 0x03) << 4) | ((*(data+1) & 0xf0) >> 4)];
        switch ( chunk ) {
            case 3:
                *out++ = base64Table[((*(data+1) & 0x0f) << 2) |
                                     ((*(data+2) & 0xc0) >> 6)];
                *out++ = base64Table[(*(data+2)) & 0x3f];
                break;
            case 2:
                *out++ = base64Table[((*(data+1) & 0x0f) << 2)];
                *out++ = '=';
                break;
            case 1:
                *out++ = '=';
                *out++ = '=';
                break;
        }
        data += chunk;
        len  -= chunk;
    }
    *out = 0;

    return result;
}


/*------------------------------------------------------------------------------
 *  Check whether two strings are equal
 *----------------------------------------------------------------------------*/
bool
Util :: strEq( const char    * str1,
               const char    * str2,
               unsigned int    len )                    throw ( Exception )
{
    if ( !str1 || !str2 ) {
        throw Exception( __FILE__, __LINE__, "no str1 or no str2");
    }

    return len == 0 ? !strcmp( str1, str2) : !strncmp( str1, str2, len);
}


/*------------------------------------------------------------------------------
 *  Convert a string to a long integer
 *----------------------------------------------------------------------------*/
long int
Util :: strToL( const char *str) throw ( Exception )
{
    long int   val;
    char      *end;

    if ( NULL == str ) 
        throw Exception( __FILE__, __LINE__, "null pointer parameter, not string");
    
    errno = 0; // set it, strtol() can change it 
    val = strtol( str, &end, 10); 
    
    if (end == str)
        throw Exception( __FILE__, __LINE__, "number conversion error, not a decimal string");
    
    if ((LONG_MIN == val || LONG_MAX ==  val) && ERANGE == errno) 
        throw Exception( __FILE__, __LINE__, "number conversion error, out of range of type long");
    
    return val;
}


/*------------------------------------------------------------------------------
 *  Convert a string to a double
 *----------------------------------------------------------------------------*/
double
Util :: strToD( const char    * str )                   throw ( Exception )
{
    double      val;
    char      * s;

    if ( !str ) {
        throw Exception( __FILE__, __LINE__, "no str");
    }

    val = strtod( str, &s);
    if ( s == str || errno == ERANGE ) {
        throw Exception( __FILE__, __LINE__, "number conversion error");
    }

    return val;
}


/*------------------------------------------------------------------------------
 *  add current date to a file name, before the file extension (if any)
 *----------------------------------------------------------------------------*/
char *
Util :: fileAddDate ( const char * str,
                      const char * format )             throw ( Exception )
{
    unsigned int    size;
    const char          * last; 
    char          * s;
    char          * strdate;
    time_t          now;

    if ( !str ) {
        throw Exception( __FILE__, __LINE__, "no str");
    }

    strdate = new char[128];
    now     = time(NULL);    
    strftime( strdate, 128, format, localtime (&now));

    // search for the part before the extension of the file name
    if ( !(last = strrchr( str, '.')) ) {
        last = (char *) str + strlen( str);
    }

    size = strlen( str) + strlen( strdate) + 1;
    s    = new char [size];

    memcpy( s, str, strlen (str)-strlen(last));
    memcpy( s + strlen(str) -  strlen(last), strdate, strlen (strdate));
    memcpy( s + strlen(str) -  strlen(last) + strlen(strdate),
            last,
            strlen(last));
    s[size-1] = '\0';

    delete[] strdate;   
    return s;
}

/*------------------------------------------------------------------------------
 *  Convert an unsigned char buffer holding 8 or 16 bit PCM values with
 *  channels interleaved to a short int buffer, still with channels interleaved
 *----------------------------------------------------------------------------*/
void
Util :: conv (  unsigned int        bitsPerSample,
                unsigned char     * pcmBuffer,
                unsigned int        lenPcmBuffer,
                short int         * outBuffer,
                bool                isBigEndian )           throw ( Exception )
{
    if ( bitsPerSample == 8 ) {
        unsigned int    i, j;

        for ( i = 0, j = 0; i < lenPcmBuffer; ) {
            outBuffer[j] = pcmBuffer[i++];
            ++j;
        }
    } else if ( bitsPerSample == 16 ) {

        if ( isBigEndian ) {
            unsigned int    i, j;

            for ( i = 0, j = 0; i < lenPcmBuffer; ) {
                short int       value;

                value         = pcmBuffer[i++] << 8;
                value        |= pcmBuffer[i++];
                outBuffer[j]  = value;
                ++j;
            }
        } else {
            unsigned int    i, j;

            for ( i = 0, j = 0; i < lenPcmBuffer; ) {
                short int       value;

                value         = pcmBuffer[i++];
                value        |= pcmBuffer[i++] << 8;
                outBuffer[j]  = value;
                ++j;
            }
        }
    } else {
        throw Exception( __FILE__, __LINE__,
                         "this number of bits per sample not supported",
                         bitsPerSample);
    }
}


/*------------------------------------------------------------------------------
 *  Convert a short buffer holding PCM values with channels interleaved
 *  to one or more float buffers, one for each channel
 *----------------------------------------------------------------------------*/
void
Util :: conv (  short int         * shortBuffer,
                unsigned int        lenShortBuffer,
                float            ** floatBuffers,
                unsigned int        channels )              throw ( Exception )
{
    unsigned int    i, j;

    for ( i = 0, j = 0; i < lenShortBuffer; ) {
        for ( unsigned int c = 0; c < channels; ++c ) {
            floatBuffers[c][j] = ((float) shortBuffer[i++]) / 32768.f;
        }
        ++j;
    }
}


/*------------------------------------------------------------------------------
 *  Convert an unsigned char buffer holding 8 bit PCM values with channels
 *  interleaved to two short int buffers (one for each channel)
 *----------------------------------------------------------------------------*/
void
Util :: conv8 (     unsigned char     * pcmBuffer,
                    unsigned int        lenPcmBuffer,
                    short int         * leftBuffer,
                    short int         * rightBuffer,
                    unsigned int        channels )          throw ( Exception )
{
    if ( channels == 1 ) {
        unsigned int    i, j;

        for ( i = 0, j = 0; i < lenPcmBuffer; ) {
            unsigned short int  value;

            value         = pcmBuffer[i++];
            leftBuffer[j] = (short int) value;
            ++j;
        }
    } else if ( channels == 2 ) {
        unsigned int    i, j;

        for ( i = 0, j = 0; i < lenPcmBuffer; ) {
            unsigned short int  value;

            value          = pcmBuffer[i++];
            leftBuffer[j]  = (short int) value;
            value          = pcmBuffer[i++];
            rightBuffer[j] = (short int) value;
            ++j;
        }
    } else {
        throw Exception( __FILE__, __LINE__,
                         "this number of channels not supported", channels);
    }
}


/*------------------------------------------------------------------------------
 *  Convert an unsigned char buffer holding 16 bit PCM values with channels
 *  interleaved to two short int buffers (one for each channel)
 *----------------------------------------------------------------------------*/
void
Util :: conv16 (    unsigned char     * pcmBuffer,
                    unsigned int        lenPcmBuffer,
                    short int         * leftBuffer,
                    short int         * rightBuffer,
                    unsigned int        channels,
                    bool                isBigEndian )       throw ( Exception )
{
    if ( isBigEndian ) {
        if ( channels == 1 ) {
            unsigned int    i, j;

            for ( i = 0, j = 0; i < lenPcmBuffer; ) {
                unsigned short int   value;

                value           = pcmBuffer[i++] << 8;
                value          |= pcmBuffer[i++];
                leftBuffer[j]  = (short int) value;
                ++j;
            }
        } else {
            unsigned int    i, j;

            for ( i = 0, j = 0; i < lenPcmBuffer; ) {
                unsigned short int   value;

                value           = pcmBuffer[i++] << 8;
                value          |= pcmBuffer[i++];
                leftBuffer[j]   = (short int) value;
                value           = pcmBuffer[i++] << 8;
                value          |= pcmBuffer[i++];
                rightBuffer[j]  = (short int) value;
                ++j;
            }
        }
    } else {
        if ( channels == 1 ) {
            unsigned int    i, j;

            for ( i = 0, j = 0; i < lenPcmBuffer; ) {
                unsigned short int   value;

                value          = pcmBuffer[i++];
                value         |= pcmBuffer[i++] << 8;
                leftBuffer[j]  = (short int) value;
                ++j;
            }
        } else {
            unsigned int    i, j;

            for ( i = 0, j = 0; i < lenPcmBuffer; ) {
                unsigned short int   value;

                value           = pcmBuffer[i++];
                value          |= pcmBuffer[i++] << 8;
                leftBuffer[j]   = (short int) value;
                value           = pcmBuffer[i++];
                value          |= pcmBuffer[i++] << 8;
                rightBuffer[j]  = (short int) value;
                ++j;
            }
        }
    }
}


/*------------------------------------------------------------------------------
 *  Make a thread sleep for a specified amount of time.
 *----------------------------------------------------------------------------*/
void
Util :: sleep   (   long            sec,
                    long            nsec)
{
    struct timespec     timespec;
    sigset_t            sigset;

    timespec.tv_sec  = sec;
    timespec.tv_nsec = nsec;

    // mask out SIGUSR1, as we're expecting that signal for other reasons
    sigemptyset(&sigset);
    sigaddset(&sigset, SIGUSR1);

    pselect( 0, NULL, NULL, NULL, &timespec, &sigset);
}