File: speex_a.c

package info (click to toggle)
timidity 2.14.0-8
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 11,364 kB
  • sloc: ansic: 168,735; sh: 3,729; makefile: 1,405; tcl: 1,048; perl: 285; ruby: 126
file content (656 lines) | stat: -rw-r--r-- 17,130 bytes parent folder | download
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
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
/*
    TiMidity++ -- MIDI to WAVE converter and player
    Copyright (C) 1999-2002 Masanao Izumo <mo@goice.co.jp>
    Copyright (C) 1995 Tuukka Toivonen <tt@cgs.fi>

    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 2 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

    speex_a.c
	Written by Iwata <b6330015@kit.jp>
    Functions to output Ogg Speex (*.ogg).
*/

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif /* HAVE_CONFIG_H */
#include <stdio.h>
#include <stdlib.h>
#if HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_FCNTL_H
#include <fcntl.h>
#endif
#if TIME_WITH_SYS_TIME
# include <sys/time.h>
# include <time.h>
#else
# if HAVE_SYS_TIME_H
#  include <sys/time.h>
# else
#  include <time.h>
# endif
#endif  /* TIME_WITH_SYS_TIME */

#include <speex/speex.h>
#include <speex/speex_header.h>
#include <speex/speex_stereo.h>
#include <ogg/ogg.h>

#include "timidity.h"
#include "common.h"
#include "output.h"
#include "controls.h"
#include "timer.h"
#include "instrum.h"
#include "playmidi.h"
#include "readmidi.h"
#include "miditrace.h"

static int open_output(void); /* 0=success, 1=warning, -1=fatal error */
static void close_output(void);
static int output_data(char *buf, int32 nbytes);
static int acntl(int request, void *arg);

/* export the playback mode */

#define dpm speex_play_mode

PlayMode dpm = {
  DEFAULT_RATE, PE_SIGNED|PE_16BIT, PF_PCM_STREAM|PF_FILE_OUTPUT,
  -1,
  {0},
  "Ogg Speex", 'S',
  NULL,
  open_output,
  close_output,
  output_data,
  acntl
};


#define MAX_FRAME_SIZE 2000
#define MAX_FRAME_BYTES 2000

typedef struct {
  /* Ogg */
  ogg_stream_state os;
  ogg_page         og;
  ogg_packet       op;
  int              ogg_packetid;

  /* Speex */
  SpeexHeader      header;
  SpeexBits        bits;
  const SpeexMode* mode;
  void*            state;
  int              frame_size;
  int              nframes;
  int              channels;

  /* state */
  unsigned long    in_bytes;
  unsigned long    out_bytes;

  /* simple buffer */
  float            *input;
  int              input_idx;
} Speex_ctx;

static int ogg_seqnum = 0;

static Speex_ctx *speex_ctx = NULL;

typedef struct {
  int quality;
  int vbr;
  int abr;
  int vad;
  int dtx;
  int complexity;
  int nframes;
} Speex_options;

Speex_options speex_options = {
  8, /* quality */
  0, /* vbr */
  0, /* abr */
  0, /* vad */
  0, /* dtx */
  3, /* complexity */
  1  /* nframes */
};


/*
  code from speexenc.c
 */
static int speex_mode_preset()
{
  int rate = dpm.rate;
  Speex_ctx *ctx = speex_ctx;

  if (speex_ctx == NULL)
    return 0;

  if (ctx->mode == NULL) {
    if (rate > 48000) {
      ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
		"sampling rate too high: %d Hz,\n"
		"try down-sampling\n", rate);
      return 0;
    }
    else if (rate > 25000) {
      ctx->mode = &speex_uwb_mode;
    }
    else if (rate > 12500) {
      ctx->mode = &speex_wb_mode;
    }
    else if (rate >= 6000) {
      ctx->mode = &speex_nb_mode;
    }
    else {
      ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
		"Sampling rate too low: %d Hz\n", rate);
      return 0;
    }
  }
 
  if (rate != 8000 && rate != 16000 && rate != 32000)
    ctl->cmsg(CMSG_WARNING, VERB_NORMAL,
	      "Speex is only optimized for 8, 16 and 32 kHz.\n"
	      "It will still work at %d Hz but your mileage may vary", rate);

  return 1;
}

void speex_set_option_quality(int quality)
{
  speex_options.quality = quality;
  if (quality < 0)
    speex_options.quality = 0;
  if (10 < quality)
    speex_options.quality = 10;
}
void speex_set_option_vbr(int vbr)
{
  speex_options.vbr = vbr;
}
void speex_set_option_abr(int rate)
{
  speex_options.abr = rate;
}
void speex_set_option_vad(int vad)
{
  speex_options.vad = vad;
}
void speex_set_option_dtx(int dtx)
{
  speex_options.dtx = dtx;
}
void speex_set_option_complexity(int complexity)
{
  speex_options.complexity = complexity;
  if (complexity < 0)
    speex_options.complexity = 0;
  if (10 < complexity)
      speex_options.complexity = 10;
}
void speex_set_option_nframes(int nframes)
{
  speex_options.nframes = nframes;
  if (nframes < 1)
    speex_options.nframes = 0;
  if (10 < nframes)
    speex_options.nframes = 10;
}

/*
  Write an Ogg page to a file pointer
  code from speexenc.c
*/
int oe_write_page(ogg_page *page, int fd)
{
  int written = 0;
  written += std_write(fd, page->header, page->header_len);
  written += std_write(fd, page->body,   page->body_len);

  return written;
}

#define writeint(buf, base, val) do { buf[base+3]=((val)>>24)&0xff; \
                                      buf[base+2]=((val)>>16)&0xff; \
                                      buf[base+1]=((val)>>8)&0xff; \
                                      buf[base]=(val)&0xff; \
                                 } while(0)
void comment_init(char **comments, int* length, char *vendor_string)
{
  int vendor_length = strlen(vendor_string);
  int user_comment_list_length = 0;
  int len= 4 + vendor_length + 4;
  char *p = (char*)safe_malloc(len);

  writeint(p, 0, vendor_length);
  memcpy(p + 4, vendor_string, vendor_length);
  writeint(p, 4 + vendor_length, user_comment_list_length);
  *length = len;
  *comments = p;
}
/*
  Write header (format will change)
  code from speexenc.c
*/
int write_ogg_header(Speex_ctx *ctx, int fd, char *comments)
{
  int ret, result;
  char *vendor_string = "Encoded with Timidity++-" VERSION;
  int comments_length = strlen(comments);

  comment_init(&comments, &comments_length, vendor_string);

  ctx->op.packet = (unsigned char *)speex_header_to_packet(&ctx->header, (int*)&(ctx->op.bytes));
  ctx->op.b_o_s = 1;
  ctx->op.e_o_s = 0;
  ctx->op.granulepos = 0;
  ctx->op.packetno = 0;
  ogg_stream_packetin(&ctx->os, &ctx->op);
  free(ctx->op.packet);

  ctx->op.packet = (unsigned char *)comments;
  ctx->op.bytes = comments_length;

  ctx->op.b_o_s = 0;
  ctx->op.e_o_s = 0;
  ctx->op.granulepos = 0;
  ctx->op.packetno = 1;
  ogg_stream_packetin(&ctx->os, &ctx->op);

  while((result = ogg_stream_flush(&ctx->os, &ctx->og))) {
    if(!result) break;
    ret = oe_write_page(&ctx->og, fd);
    if(ret != ctx->og.header_len + ctx->og.body_len) {
      ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "failed writing header to output Ogg stream\n");
      return 1;
    }
    else
      ctx->out_bytes += ret;
  }
  return 0;
}

static int speex_output_open(const char *fname, const char *comment)
{
  Speex_ctx *ctx;
  int fd;

  if (!(speex_ctx = (Speex_ctx *)calloc(sizeof(Speex_ctx), 1))) {
    ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "%s", strerror(errno));
    return -1;
  }
  ctx = speex_ctx;

  /* init id */
  ctx->in_bytes = ctx->out_bytes = 0;
  ctx->ogg_packetid = -1;
  ctx->channels = (dpm.encoding & PE_MONO) ? 1 : 2;

  if(strcmp(fname, "-") == 0) {
    fd = 1; /* data to stdout */
    if(comment == NULL)
      comment = "(stdout)";
  } else {
    /* Open the audio file */
    fd = open(fname, FILE_OUTPUT_MODE);
    if (fd < 0) {
      ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "%s: %s",
                fname, strerror(errno));
      return -1;
    }
  }

  /*Initialize Ogg stream struct*/
  if (ogg_seqnum == 0) {
    srand(time(NULL));
    ogg_seqnum = rand();
  }
  if (ogg_stream_init(&ctx->os, ogg_seqnum++) == -1) {
    ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "Ogg stream init failed\n");
    return -1;
  }

  if (!speex_mode_preset())
    return -1;

  speex_init_header(&ctx->header, dpm.rate, 1, ctx->mode);
  ctx->header.nb_channels = ctx->channels;

  ctx->header.frames_per_packet = ctx->nframes = speex_options.nframes;

  ctx->state = speex_encoder_init(ctx->mode);

  /*Set the quality to 8 (15 kbps)*/
  speex_encoder_ctl(ctx->state, SPEEX_SET_QUALITY, &speex_options.quality);

  if(strcmp(fname, "-") == 0) {
    fd = 1; /* data to stdout */
    if(comment == NULL)
      comment = "(stdout)";
  } else {
    /* Open the audio file */
    fd = open(fname, FILE_OUTPUT_MODE);
    if(fd < 0) {
      ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "%s: %s",
                fname, strerror(errno));
      return -1;
    }
    if(comment == NULL)
      comment = fname;
  }

  write_ogg_header(ctx, fd, (char *)comment);

  speex_encoder_ctl(ctx->state, SPEEX_GET_FRAME_SIZE, &ctx->frame_size);
  speex_encoder_ctl(ctx->state, SPEEX_SET_COMPLEXITY, &speex_options.complexity);
  speex_encoder_ctl(ctx->state, SPEEX_SET_SAMPLING_RATE, &dpm.rate);

  if (speex_options.vbr) {
    speex_encoder_ctl(ctx->state, SPEEX_SET_VBR, &speex_options.vbr);
  }
  else if (speex_options.vad) {
    speex_encoder_ctl(ctx->state, SPEEX_SET_VAD, &speex_options.vad);
  }
  if (speex_options.dtx)
    speex_encoder_ctl(ctx->state, SPEEX_SET_DTX, &speex_options.dtx);
  if (speex_options.dtx && !(speex_options.vbr ||
			     speex_options.abr ||
			     speex_options.vad)) {
    ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
	      "--speex-dtx is useless without --speex-vad, --speex-vbr or --speex-abr");
  }
  else if ((speex_options.vbr || speex_options.abr) && (speex_options.vad)) {
    ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
	      "--speex-vad is already implied by --speex-vbr or --speex-abr");
  }
  if (speex_options.abr) {
    speex_encoder_ctl(ctx->state, SPEEX_SET_ABR, &speex_options.abr);
  }

  speex_bits_init(&ctx->bits);

  ctx->input = (float *)safe_malloc(sizeof(float) * MAX_FRAME_SIZE * ctx->channels);
  ctx->input_idx = 0;

  return fd;
}

/*
  code from vorbis_a.c
 */
extern char *create_auto_output_name(const char *input_filename, char *ext_str, char *output_dir, int mode);

static int auto_speex_output_open(const char *input_filename, const char *title)
{
  char *output_filename;

#if !defined ( IA_W32GUI ) && !defined ( IA_W32G_SYN )
  output_filename = create_auto_output_name(input_filename, "ogg", NULL, 0);
#else
  output_filename = create_auto_output_name(input_filename, "ogg", w32g_output_dir, w32g_auto_output_mode);
#endif
  if (output_filename == NULL){
    ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "unknown output file name");
    return -1;
  }
  if ((dpm.fd = speex_output_open(output_filename, input_filename)) == -1) {
    ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "files open failed %s->%s",
	      output_filename, input_filename);
    free(output_filename);
    return -1;
  }
  if (dpm.name != NULL)
    free(dpm.name);
  dpm.name = output_filename;

  ctl->cmsg(CMSG_INFO, VERB_NORMAL, "Output: %s", dpm.name);
  {
    char *st_string="mono";
    if (speex_ctx->channels == 2)
      st_string = "stereo";
    ctl->cmsg(CMSG_INFO, VERB_NORMAL, "Encoding %d Hz audio using %s mode (%s)",
	      speex_ctx->header.rate, speex_ctx->mode->modeName, st_string);
   }

  return 0;
}

static int open_output(void)
{
  int include_enc, exclude_enc;

  include_enc = exclude_enc = 0;

  /* only 16 bit is supported */
  include_enc |= PE_16BIT|PE_SIGNED;
  exclude_enc |= PE_BYTESWAP|PE_24BIT;
  dpm.encoding = validate_encoding(dpm.encoding, include_enc, exclude_enc);

#if !defined (IA_W32GUI) && !defined (IA_W32G_SYN)
  if (dpm.name == NULL) {
    dpm.flag |= PF_AUTO_SPLIT_FILE;
  }
  else {
    dpm.flag &= ~PF_AUTO_SPLIT_FILE;
    if ((dpm.fd = speex_output_open(dpm.name, NULL)) == -1)
      return -1;
  }
#else
  if (w32g_auto_output_mode > 0){
    dpm.flag |= PF_AUTO_SPLIT_FILE;
    dpm.name = NULL;
  }
  else {
    dpm.flag &= ~PF_AUTO_SPLIT_FILE;
    if ((dpm.fd = speex_output_open(dpm.name, NULL)) == -1)
      return -1;
  }
#endif
  return 0;
}

static int output_data(char *buf, int32 nbytes)
{
  char cbits[MAX_FRAME_BYTES];
  Speex_ctx *ctx = speex_ctx;
  int nbBytes;
  int16 *s;
  int i;
  int ret;
  int nbytes_left;

  if (dpm.fd < 0)
    return 0;

  ctx->in_bytes += nbytes;

  /*
    Main encoding loop (one frame per iteration)
  */
  nbytes_left = nbytes;
  s = (int16 *)buf;
  while (1) {
    ctx->ogg_packetid++;
    /*
      packing 16 bit -> float sample
    */
    for (i = ctx->input_idx; i < ctx->frame_size * ctx->channels; i++) {
      /* stream is ended, and buffer is not full. wait next spooling */
      if (nbytes_left < 0) {
	/* canceling ogg packet */
	ctx->ogg_packetid--;
	return 0;
      }
      ctx->input[i] = *s++;
      nbytes_left -= 2; /* -16 bit*/
      ctx->input_idx++;
    }
    /*
      buffer is full. encode now.
    */
    ctx->input_idx = 0;

    if (ctx->channels == 2)
      speex_encode_stereo(ctx->input, ctx->frame_size, &ctx->bits);
    /* Encode the frame */
    speex_encode(ctx->state, ctx->input, &ctx->bits);

    if ((ctx->ogg_packetid + 1) % ctx->nframes != 0)
      continue;

    speex_bits_insert_terminator(&ctx->bits);
    /* Copy the bits to an array of char that can be written */
    nbBytes = speex_bits_write(&ctx->bits, cbits, MAX_FRAME_BYTES);
    
    /* Flush all the bits in the struct so we can encode a new frame */
    speex_bits_reset(&ctx->bits);

    /* ogg packet setup */
    ctx->op.packet = (unsigned char *)cbits;
    ctx->op.bytes = nbBytes;
    ctx->op.b_o_s = 0;
    ctx->op.e_o_s = 0;

    ctx->op.granulepos = (ctx->ogg_packetid + ctx->nframes) * ctx->frame_size;
    ctx->op.packetno = 2 + ctx->ogg_packetid / ctx->nframes;
    ogg_stream_packetin(&ctx->os, &ctx->op);

    /* Write all new pages (most likely 0 or 1) */
    while (ogg_stream_pageout(&ctx->os, &ctx->og)) {
      ret = oe_write_page(&ctx->og, dpm.fd);
      if (ret != ctx->og.header_len + ctx->og.body_len) {
	ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "failed writing header to output stream");
	return -1;
      }
      else
	ctx->out_bytes += ret;
    }
  }
  
  return 0;
}

static void close_output(void)
{
  int i;
  char cbits[MAX_FRAME_BYTES];
  Speex_ctx *ctx = speex_ctx;
  int nbBytes;
  int ret;

  if (ctx == NULL)
    return;

  if (dpm.fd < 0)
    return;

  /*
    Write last frame
  */
  if (speex_ctx != NULL) {
    if ((ctx->ogg_packetid + 1) % ctx->nframes != 0) {
      while ((ctx->ogg_packetid + 1) % ctx->nframes != 0) {
	ctx->ogg_packetid++;
	speex_bits_pack(&ctx->bits, 15, 5);
      }
      nbBytes = speex_bits_write(&ctx->bits, cbits, MAX_FRAME_BYTES);
      ctx->op.packet = (unsigned char *)cbits;
      ctx->op.bytes = nbBytes;
      ctx->op.b_o_s = 0;
      ctx->op.e_o_s = 1;
      ctx->op.granulepos = (ctx->ogg_packetid + ctx->nframes) * ctx->frame_size;
      ctx->op.packetno = 2 + ctx->ogg_packetid / ctx->nframes;
      ogg_stream_packetin(&ctx->os, &ctx->op);
    }
    for (i = ctx->input_idx; i < ctx->frame_size * ctx->channels; i++) {
      /* left is zero-cleaned */
      ctx->input[i] = 0;
    }
    if (ctx->channels == 2)
      speex_encode_stereo(ctx->input, ctx->frame_size, &ctx->bits);
    /* Encode the frame */
    speex_encode(ctx->state, ctx->input, &ctx->bits);
    speex_bits_insert_terminator(&ctx->bits);
    /* Copy the bits to an array of char that can be written */
    nbBytes = speex_bits_write(&ctx->bits, cbits, MAX_FRAME_BYTES);
    
    /* Flush all the bits in the struct so we can encode a new frame */
    speex_bits_reset(&ctx->bits);

    /* ogg packet setup */
    ctx->op.packet = (unsigned char *)cbits;
    ctx->op.bytes = nbBytes;
    ctx->op.b_o_s = 0;
    ctx->op.e_o_s = 1;

    ctx->op.granulepos = (ctx->ogg_packetid + ctx->nframes) * ctx->frame_size;
    ctx->op.packetno = 2 + ctx->ogg_packetid / ctx->nframes;
    ogg_stream_packetin(&ctx->os, &ctx->op);

    /* Write all new pages (most likely 0 or 1) */
    while (ogg_stream_pageout(&ctx->os, &ctx->og)) {
      ret = oe_write_page(&ctx->og, dpm.fd);
      if (ret != ctx->og.header_len + ctx->og.body_len) {
	ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "failed writing header to output stream");
	return;
      }
      else
	ctx->out_bytes += ret;
    }

    ogg_stream_clear(&speex_ctx->os);
    speex_bits_destroy(&speex_ctx->bits);
    speex_encoder_destroy(speex_ctx->state);
    close(dpm.fd);
    dpm.fd = -1;
    free(speex_ctx->input);

    ctl->cmsg(CMSG_INFO, VERB_NORMAL, "Wrote %lu/%lu bytes(%g%% compressed)",
	      ctx->out_bytes, ctx->in_bytes, ((double)ctx->out_bytes / (double)ctx->in_bytes) * 100.0);

    speex_ctx->input = NULL;
    free(speex_ctx);
    speex_ctx = NULL;
  }
  return;
}

static int acntl(int request, void *arg)
{
  switch(request) {
  case PM_REQ_PLAY_START:
    if(dpm.flag & PF_AUTO_SPLIT_FILE){
      if(  ( NULL == current_file_info ) || (NULL == current_file_info->filename ) )
        return auto_speex_output_open("Output.mid",NULL);
      return auto_speex_output_open(current_file_info->filename, current_file_info->seq_name);
   }
    return 0;
  case PM_REQ_PLAY_END:
    if(dpm.flag & PF_AUTO_SPLIT_FILE)
      close_output();
    return 0;
  case PM_REQ_DISCARD:
    return 0;
  }
  return -1;
}