summaryrefslogtreecommitdiff
path: root/src/applyplugin.c
blob: 335e89b0e6b63287a06fd18e0da73ce023525c3b (plain)
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
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
/* applyplugin.c

   Free software by Richard W.E. Furse. Do with as you will. No
   warranty. */

/*****************************************************************************/

#include <dlfcn.h>
#include <endian.h>
#include <errno.h>
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

/*****************************************************************************/

#include "ladspa.h"

#include "utils.h"

/*****************************************************************************/

#define BUFFER_SIZE 2048

/*****************************************************************************/

/* Macros provide hook for word-order swapping because of
   big/little-endian issues. */

#ifndef BYTE_ORDER
#error "Could not determine byte order."
#endif

#if (BYTE_ORDER == LITTLE_ENDIAN)

/* (i386 is little-endian.) */

#define WORD_ORDER_SWAP_16BIT(ptr)
#define WORD_ORDER_SWAP_32BIT(ptr)

#else

/* The following isn't ANSI C, but it'll work fine on GCC. To make it
   ANSI compiliant, make cTmp global, remove the braces (etc). Then
   check carefully to see where WORD_ORDER_SWAP_* is
   used. Alternatively, rewrite as procedures. */

#define WORD_ORDER_SWAP_16BIT(pvPtr) {					\
  char cTmp, * pcPtr = (char *)pvPtr;					\
  cTmp = pcPtr[0];							\
  pcPtr[0] = pcPtr[1];							\
  pcPtr[1] = cTmp;							\
}
#define WORD_ORDER_SWAP_32BIT(pvPtr) {					\
  char cTmp, * pcPtr = (char *)pvPtr;					\
  cTmp = pcPtr[0];							\
  pcPtr[0] = pcPtr[3];							\
  pcPtr[3] = cTmp;							\
  cTmp = pcPtr[1];							\
  pcPtr[1] = pcPtr[2];							\
  pcPtr[2] = cTmp;							\
}

#endif

/*****************************************************************************/

/* Horrid hard-coded Wave Interface:
   --------------------------------- */
/* Please please feel free to replace this with something nice. 

   Only handles 16bit PCM files in a single data block. Returns
   channel count and sample rate by reference. Only one file can be
   open for read at a time. */

FILE * g_poInputFile;
FILE * g_poOutputFile;
LADSPA_Data g_fPeakWritten = 0;

unsigned long g_lInputFileChannelCount;
unsigned long g_lOutputFileChannelCount;

short * g_psInputFileBuffer;
short * g_psOutputFileBuffer;

static void 
openWaveFile(const char * pcFilename,
	     unsigned long * plChannelCount,
	     unsigned long * plSampleRate,
	     unsigned long * plLength) {

  char pcHeader[44];
  size_t lReadLength;

  g_poInputFile = fopen(pcFilename, "rb");
  if (!g_poInputFile) {
    fprintf(stderr,
	    "Failed to open input file \"%s\": %s\n",
	    pcFilename,
	    strerror(errno));
    exit(1);
  }

  lReadLength = fread(pcHeader, sizeof(char), 44, g_poInputFile);
  if (lReadLength < 44) {
    fprintf(stderr,
	    "Failed to read header from input file \"%s\": %s\n",
	    pcFilename,
	    strerror(errno));
    exit(1);
  }
  if (strncmp(pcHeader + 0, "RIFF", 4) != 0 ||
      strncmp(pcHeader + 8, "WAVE", 4) != 0 ||
      strncmp(pcHeader + 12, "fmt ", 4) != 0 ||
      pcHeader[20] != 1 || pcHeader[21] != 0 || /* PCM */
      pcHeader[34] != 16 || pcHeader[35] != 0 || /* 16 bit */
      strncmp(pcHeader + 36, "data", 4) != 0) /* Data block elsewhere */ {
    fprintf(stderr,
	    "\"applyplugin\" has very limited support for sound files types. "
	    "The file \"%s\" is not a simple 16bit PCM Wave File.\n",
	    pcFilename);
    exit(1);
  }

  /* Not portable casting (short assumed 16bit, unsigned int assumed
     32bit), alignment assumed not a problem. This is all bad. */
  WORD_ORDER_SWAP_16BIT(pcHeader + 22);
  g_lInputFileChannelCount 
    = *plChannelCount 
    = *((unsigned short *)(pcHeader + 22));
  WORD_ORDER_SWAP_32BIT(pcHeader + 24);
  *plSampleRate
    = *((unsigned int *)(pcHeader + 24));
  WORD_ORDER_SWAP_32BIT(pcHeader + 40);
  *plLength
    = (*((unsigned int *)(pcHeader + 40))
       / (*plChannelCount * sizeof(short)));

  g_psInputFileBuffer
    = (short *)calloc(*plChannelCount * BUFFER_SIZE, sizeof(short));
}

static void 
createWaveFile(const char * pcFilename,
	       unsigned long lChannelCount,
	       unsigned long lSampleRate,
	       unsigned long lLength) {


  char pcHeader[44];
  size_t lWriteLength;

  static const char pcHeaderBase[44] = {
    'R', 'I', 'F', 'F',
    0, 0, 0, 0,
    'W', 'A', 'V', 'E',
    'f', 'm', 't', ' ',
    16, 0, 0, 0,
    1, 0,
    1, 0,
    0, 0, 0, 0,
    0, 0, 0, 0,
    0, 0,
    16, 0,
    'd', 'a', 't', 'a',
    0, 0, 0, 0
  };

  g_poOutputFile = fopen(pcFilename, "wb");
  if (!g_poOutputFile) {
    fprintf(stderr,
	    "Failed to open output file \"%s\": %s\n",
	    pcFilename,
	    strerror(errno));
    exit(1);
  }

  /* Not portable casting (short assumed 16bit, unsigned int assumed
     32bit), alignment assumed not a problem. This is all bad. */
  memcpy(pcHeader, pcHeaderBase, 44);

  *(unsigned int *)(pcHeader + 4) 
    = (unsigned int)(lLength * lChannelCount * sizeof(short) + 36);
  WORD_ORDER_SWAP_32BIT(pcHeader + 4);
  /* (Or should it be +32?) */
  *(unsigned short *)(pcHeader + 22) 
    = (unsigned short)lChannelCount;
  WORD_ORDER_SWAP_16BIT(pcHeader + 22);
  *(unsigned int *)(pcHeader + 24) 
    = (unsigned int)lSampleRate;
  WORD_ORDER_SWAP_32BIT(pcHeader + 24);
  *(unsigned int *)(pcHeader + 28) 
    = (unsigned int)(lSampleRate * lChannelCount * sizeof(short));
  WORD_ORDER_SWAP_32BIT(pcHeader + 28);
  *(unsigned short *)(pcHeader + 32) 
    = (unsigned short)(lChannelCount * sizeof(short));
  WORD_ORDER_SWAP_16BIT(pcHeader + 32);
  *(unsigned int *)(pcHeader + 40) 
    = (unsigned int)(lLength * lChannelCount * sizeof(short));
  WORD_ORDER_SWAP_32BIT(pcHeader + 40);

  g_lOutputFileChannelCount = lChannelCount;

  lWriteLength = fwrite(pcHeader, sizeof(char), 44, g_poOutputFile);
  if (lWriteLength < 44) {
    fprintf(stderr,
	    "Failed to write header to output file \"%s\": %s\n",
	    pcFilename,
	    strerror(errno));
    exit(1);
  }

  g_psOutputFileBuffer 
    = (short *)calloc(lChannelCount * BUFFER_SIZE, sizeof(short));
}

static void
readIntoBuffers(LADSPA_Data ** ppfBuffers, 
		const unsigned long lFrameSize) {

  short * psReadPointer;
  size_t lReadLength;
  unsigned long lChannelIndex;
  unsigned long lFrameIndex;

  lReadLength = fread(g_psInputFileBuffer,
		      sizeof(short) * g_lInputFileChannelCount,
		      lFrameSize,
		      g_poInputFile);
  if (lReadLength < lFrameSize) {
    fprintf(stderr,
	    "Failed to read audio from input file. Is the file damaged?\n");
    exit(1);
  }

  for (lChannelIndex = 0;
       lChannelIndex < g_lInputFileChannelCount; 
       lChannelIndex++) {
    psReadPointer = g_psInputFileBuffer + lChannelIndex;
    for (lFrameIndex = 0; 
	 lFrameIndex < lFrameSize; 
	 lFrameIndex++, psReadPointer += g_lInputFileChannelCount) {
      WORD_ORDER_SWAP_16BIT(psReadPointer);
      ppfBuffers[lChannelIndex][lFrameIndex] 
	= ((LADSPA_Data)*psReadPointer) * (1.0f / 32767.5f);
    }
  }
}

static void
writeFromBuffers(LADSPA_Data ** ppfBuffers, 
		 const unsigned long lFrameSize) {

  LADSPA_Data fValue, fAbsValue;
  short * psWritePointer;
  size_t lWriteLength;
  unsigned long lChannelIndex;
  unsigned long lFrameIndex;

  for (lChannelIndex = 0;
       lChannelIndex < g_lOutputFileChannelCount; 
       lChannelIndex++) {
    psWritePointer = g_psOutputFileBuffer + lChannelIndex;
    for (lFrameIndex = 0; 
	 lFrameIndex < lFrameSize; 
	 lFrameIndex++, psWritePointer += g_lOutputFileChannelCount) {
      fValue = ppfBuffers[lChannelIndex][lFrameIndex] * 32767.5f;
      fAbsValue = fabs(fValue);
      if (fAbsValue > g_fPeakWritten)
	g_fPeakWritten = fAbsValue;
      /* Use hard clipping as it sounds better than wraparound. */
      if (fValue > 32767)
	*psWritePointer = 32767;
      else if (fValue <= -32768)
	*psWritePointer = -32768;
      else
	*psWritePointer = (short)fValue;
      WORD_ORDER_SWAP_16BIT(psWritePointer);
    }
  }

  lWriteLength = fwrite(g_psOutputFileBuffer,
			sizeof(short) * g_lOutputFileChannelCount,
			lFrameSize,
			g_poOutputFile);
  if (lWriteLength < lFrameSize) {
    fprintf(stderr,
	    "Failed to read audio to output file. Is the disk full?\n");
    exit(1);
  }

}

static void
closeFiles(void) {
  fclose(g_poInputFile);
  fclose(g_poOutputFile);
  printf("Peak output: %g\n", g_fPeakWritten);
}

/*****************************************************************************/

static unsigned long
getPortCountByType(const LADSPA_Descriptor     * psDescriptor,
		   const LADSPA_PortDescriptor   iType) {

  unsigned long lCount;
  unsigned long lIndex;

  lCount = 0;
  for (lIndex = 0; lIndex < psDescriptor->PortCount; lIndex++)
    if ((psDescriptor->PortDescriptors[lIndex] & iType) == iType)
      lCount++;

  return lCount;
}

/*****************************************************************************/

static void
listControlsForPlugin(const LADSPA_Descriptor * psDescriptor) {

  int bFound;
  unsigned long lIndex;
  LADSPA_PortRangeHintDescriptor iHintDescriptor;
  LADSPA_Data fBound;
	
  fprintf(stderr,
	  "Plugin \"%s\" has the following control inputs:\n",
	  psDescriptor->Name);

  bFound = 0;
  for (lIndex = 0; lIndex < psDescriptor->PortCount; lIndex++)
    if (LADSPA_IS_PORT_INPUT(psDescriptor->PortDescriptors[lIndex])
	&& LADSPA_IS_PORT_CONTROL(psDescriptor->PortDescriptors[lIndex])) {
      fprintf(stderr,
	      "\t%s",
	      psDescriptor->PortNames[lIndex]);
      bFound = 1;
      iHintDescriptor = psDescriptor->PortRangeHints[lIndex].HintDescriptor;
      if (LADSPA_IS_HINT_BOUNDED_BELOW(iHintDescriptor)
	  || LADSPA_IS_HINT_BOUNDED_ABOVE(iHintDescriptor)) {
	fprintf(stderr, " (");
	if (LADSPA_IS_HINT_BOUNDED_BELOW(iHintDescriptor)) {
	  fBound = psDescriptor->PortRangeHints[lIndex].LowerBound;
	  if (LADSPA_IS_HINT_SAMPLE_RATE(iHintDescriptor)) {
	    if (fBound == 0)
	      fprintf(stderr, "0");
	    else
	      fprintf(stderr, "%g * sample rate", fBound);
	  }
	  else
	    fprintf(stderr, "%g", fBound);
	}
	else
	  fprintf(stderr, "...");
	fprintf(stderr, " to ");
	if (LADSPA_IS_HINT_BOUNDED_ABOVE(iHintDescriptor)) {
	  fBound = psDescriptor->PortRangeHints[lIndex].UpperBound;
	  if (LADSPA_IS_HINT_SAMPLE_RATE(iHintDescriptor)) {
	    if (fBound == 0)
	      fprintf(stderr, "0");
	    else
	      fprintf(stderr, "%g * sample rate", fBound);
	  }
	  else
	    fprintf(stderr, "%g", fBound);
	}
	else
	  fprintf(stderr, "...");
	fprintf(stderr, ")\n");
      }
      else
	fprintf(stderr, "\n");
    }
      
  if (!bFound)
    fprintf(stderr, "\tnone\n");
}

/*****************************************************************************/

/* Note that this procedure leaks memory like mad. */
static void
applyPlugin(const char               * pcInputFilename,
	    const char               * pcOutputFilename,
	    const LADSPA_Data          fExtraSeconds,
	    const unsigned long        lPluginCount,
	    const LADSPA_Descriptor ** ppsPluginDescriptors,
	    LADSPA_Data             ** ppfPluginControlValues) {

  LADSPA_PortDescriptor iPortDescriptor;
  LADSPA_Handle * ppsPlugins;
  LADSPA_Data ** ppfBuffers;
  long lFrameSize;
  unsigned long lAudioInputCount;
  unsigned long lAudioOutputCount;
  unsigned long lPreviousAudioOutputCount;
  unsigned long lBufferCount;
  unsigned long lBufferIndex;
  unsigned long lControlIndex;
  unsigned long lInputFileChannelCount;
  unsigned long lInputFileLength;
  unsigned long lOutputFileChannelCount;
  unsigned long lOutputFileLength;
  unsigned long lPluginIndex;
  unsigned long lPortIndex;
  unsigned long lSampleRate;
  unsigned long lTimeAt;
  LADSPA_Data fDummyControlOutput;

  /* Open input file and output file: 
     -------------------------------- */

  lOutputFileChannelCount
    = getPortCountByType(ppsPluginDescriptors[lPluginCount - 1],
			 LADSPA_PORT_AUDIO | LADSPA_PORT_OUTPUT);
  if (lOutputFileChannelCount == 0) {
    fprintf(stderr,
	    "The last plugin in the chain has no audio outputs.\n");
    exit(1);
  }

  openWaveFile(pcInputFilename, 
	       &lInputFileChannelCount, 
	       &lSampleRate,
	       &lInputFileLength);
  if (lInputFileChannelCount
      != getPortCountByType(ppsPluginDescriptors[0],
			    LADSPA_PORT_AUDIO | LADSPA_PORT_INPUT)) {
    fprintf(stderr,
	    "Mismatch between channel count in input file and audio inputs "
	    "on first plugin in chain.\n");
    exit(1);
  }

  lOutputFileLength 
    = lInputFileLength + (unsigned long)(fExtraSeconds * lSampleRate);

  createWaveFile(pcOutputFilename,
		 lOutputFileChannelCount,
		 lSampleRate,
		 lOutputFileLength);

  /* Count buffers and sanity-check the flow graph:
     ---------------------------------------------- */

  lBufferCount = 0;
  lPreviousAudioOutputCount = 0;
  for (lPluginIndex = 0; lPluginIndex < lPluginCount; lPluginIndex++) {

    lAudioInputCount
      = getPortCountByType(ppsPluginDescriptors[lPluginIndex],
			   LADSPA_PORT_AUDIO | LADSPA_PORT_INPUT);
    lAudioOutputCount
      = getPortCountByType(ppsPluginDescriptors[lPluginIndex],
			   LADSPA_PORT_AUDIO | LADSPA_PORT_OUTPUT);

    if (lBufferCount < lAudioInputCount)
      lBufferCount = lAudioInputCount;

    if (lPluginIndex > 0) 
      if (lAudioInputCount != lPreviousAudioOutputCount) {
	fprintf(stderr,
		"There is a mismatch between the number of output channels "
		"on plugin \"%s\" (%ld) and the number of input channels on "
		"plugin \"%s\" (%ld).\n",
		ppsPluginDescriptors[lPluginIndex - 1]->Name,
		lPreviousAudioOutputCount,
		ppsPluginDescriptors[lPluginIndex]->Name,
		lAudioInputCount);
	exit(1);
      }

    lPreviousAudioOutputCount = lAudioOutputCount;

    if (lBufferCount < lAudioOutputCount)
      lBufferCount = lAudioOutputCount;
  }

  /* Create the buffers, create instances, wire them up:
     --------------------------------------------------- */

  ppsPlugins = (LADSPA_Handle *)calloc(lPluginCount, sizeof(LADSPA_Handle));
  ppfBuffers = (LADSPA_Data **)calloc(lBufferCount, sizeof(LADSPA_Data *));
  for (lBufferIndex = 0; lBufferIndex < lBufferCount; lBufferIndex++)
    ppfBuffers[lBufferIndex] 
      = (LADSPA_Data *)calloc(BUFFER_SIZE, sizeof(LADSPA_Data));

  for (lPluginIndex = 0; lPluginIndex < lPluginCount; lPluginIndex++) {

    ppsPlugins[lPluginIndex]
      = ppsPluginDescriptors[lPluginIndex]
      ->instantiate(ppsPluginDescriptors[lPluginIndex],
		    lSampleRate);
    if (!ppsPlugins[lPluginIndex]) {
      fprintf(stderr,
	      "Failed to instantiate plugin of type \"%s\".\n",
	      ppsPluginDescriptors[lPluginIndex]->Name);
      exit(1);
    }

    /* Controls:
       --------- */

    lControlIndex = 0;
    for (lPortIndex = 0;
	 lPortIndex < ppsPluginDescriptors[lPluginIndex]->PortCount; 
	 lPortIndex++) {

      iPortDescriptor 
	= ppsPluginDescriptors[lPluginIndex]->PortDescriptors[lPortIndex];
      
      if (LADSPA_IS_PORT_CONTROL(iPortDescriptor)) {
	if (LADSPA_IS_PORT_INPUT(iPortDescriptor))
	  ppsPluginDescriptors[lPluginIndex]->connect_port
	    (ppsPlugins[lPluginIndex],
	     lPortIndex,
	     ppfPluginControlValues[lPluginIndex] + (lControlIndex++));
	if (LADSPA_IS_PORT_OUTPUT(iPortDescriptor))
	  ppsPluginDescriptors[lPluginIndex]->connect_port
	    (ppsPlugins[lPluginIndex],
	     lPortIndex,
	     &fDummyControlOutput);
      }
    }

    /* Input Buffers:
       -------------- */

    lBufferIndex = 0;
    for (lPortIndex = 0;
	 lPortIndex < ppsPluginDescriptors[lPluginIndex]->PortCount; 
	 lPortIndex++) {
      iPortDescriptor 
	= ppsPluginDescriptors[lPluginIndex]->PortDescriptors[lPortIndex];
      if (LADSPA_IS_PORT_INPUT(iPortDescriptor) 
	  && LADSPA_IS_PORT_AUDIO(iPortDescriptor))
	ppsPluginDescriptors[lPluginIndex]->connect_port
	  (ppsPlugins[lPluginIndex],
	   lPortIndex,
	   ppfBuffers[lBufferIndex++]);
    }
    

    /* Output Buffers:
       --------------- */

    lBufferIndex = 0;
    for (lPortIndex = 0;
	 lPortIndex < ppsPluginDescriptors[lPluginIndex]->PortCount; 
	 lPortIndex++) {
      iPortDescriptor 
	= ppsPluginDescriptors[lPluginIndex]->PortDescriptors[lPortIndex];
      if (LADSPA_IS_PORT_OUTPUT(iPortDescriptor) 
	  && LADSPA_IS_PORT_AUDIO(iPortDescriptor))
	ppsPluginDescriptors[lPluginIndex]->connect_port
	  (ppsPlugins[lPluginIndex],
	   lPortIndex,
	   ppfBuffers[lBufferIndex++]);
    }
  }

  /* Activate:
     --------- */

  for (lPluginIndex = 0; lPluginIndex < lPluginCount; lPluginIndex++) 
    if (ppsPluginDescriptors[lPluginIndex]->activate != NULL)
      ppsPluginDescriptors[lPluginIndex]->activate(ppsPlugins[lPluginIndex]);

  /* Run:
     ---- */

  lTimeAt = 0;
  while (lTimeAt < lOutputFileLength) {

    lFrameSize = lInputFileLength - lTimeAt;
    if (lFrameSize > BUFFER_SIZE)
      lFrameSize = BUFFER_SIZE;
    else {
      /* We've reached or are reaching the end of the file. We're not
         going to fill the buffer from file. Could just memset the end
         part, but there's only one frame where this is worth the
         effort. */
      for (lBufferIndex = 0; lBufferIndex < lBufferCount; lBufferIndex++)
	memset(ppfBuffers[lBufferIndex], 0, sizeof(LADSPA_Data) * BUFFER_SIZE);
    }

    if (lFrameSize > 0) {
      /* Read from disk. */
      readIntoBuffers(ppfBuffers, lFrameSize);
    }

    /* Run the plugins: */
    lFrameSize = lOutputFileLength - lTimeAt;
    if (lFrameSize > BUFFER_SIZE)
      lFrameSize = BUFFER_SIZE;

    for (lPluginIndex = 0; lPluginIndex < lPluginCount; lPluginIndex++) 
      ppsPluginDescriptors[lPluginIndex]
	->run(ppsPlugins[lPluginIndex],
	      lFrameSize);
    
    /* Write the output to disk. */
    writeFromBuffers(ppfBuffers, lFrameSize);

    lTimeAt += lFrameSize;
  }

  /* Deactivate:
     ----------- */

  for (lPluginIndex = 0; lPluginIndex < lPluginCount; lPluginIndex++) 
    if (ppsPluginDescriptors[lPluginIndex]->deactivate != NULL)
      ppsPluginDescriptors[lPluginIndex]->deactivate(ppsPlugins[lPluginIndex]);

  /* Cleanup:
     -------- */

  for (lPluginIndex = 0; lPluginIndex < lPluginCount; lPluginIndex++) 
    ppsPluginDescriptors[lPluginIndex]->cleanup(ppsPlugins[lPluginIndex]);

  /* Close the input and output files:
     --------------------------------- */

  closeFiles();

}

/*****************************************************************************/

/* Note that this function leaks memory and that dynamic libraries
   that are dlopen()ed are never dlclose()d. */
int 
main(const int iArgc, char * const ppcArgv[]) {

  char * pcEndPointer;
  const char * pcControlValue;
  const char * pcInputFilename;
  const char * pcOutputFilename;
  const LADSPA_Descriptor ** ppsPluginDescriptors;
  LADSPA_Data ** ppfPluginControlValues;
  LADSPA_Data fExtraSeconds;
  int bBadParameters;
  int bBadControls;
  LADSPA_Properties iProperties;
  unsigned long lArgumentIndex;
  unsigned long lControlValueCount;
  unsigned long lControlValueIndex;
  unsigned long lPluginCount;
  unsigned long lPluginCountUpperLimit;
  unsigned long lPluginIndex;
  void ** ppvPluginLibraries;

  bBadParameters = 0;
  fExtraSeconds = 0;

  /* Check for a -s flag, but only at the start. Cannot get use
     getopt() as it gets thoroughly confused when faced with negative
     numbers on the command line. */
  lArgumentIndex = 1;
  if (iArgc >= 3) {
    if (strcmp(ppcArgv[1], "-s") == 0) {
      fExtraSeconds = (LADSPA_Data)strtod(ppcArgv[2], &pcEndPointer);
      bBadControls = (ppcArgv[2] + strlen(ppcArgv[2]) 
		      != pcEndPointer);
      lArgumentIndex = 3;
    }
    else if (strncmp(ppcArgv[1], "-s", 2) == 0) {
      fExtraSeconds = (LADSPA_Data)strtod(ppcArgv[1] + 2, &pcEndPointer);
      bBadControls = (ppcArgv[1] + strlen(ppcArgv[1]) 
		      != pcEndPointer);
      lArgumentIndex = 2;
    }
  }
  
  /* We need to analyse the rest of the parameters. The first two
     should be input and output files involved. */
  if (lArgumentIndex + 4 > (unsigned long)iArgc) {
    /* There aren't enough parameters to include an input file, an
       output file and one plugin. */
    bBadParameters = 1;
  }
  else {

    pcInputFilename = ppcArgv[lArgumentIndex];
    pcOutputFilename = ppcArgv[lArgumentIndex + 1];

    /* Now we need to look through any plugins and plugin parameters
       present. At this stage we're loading plugins and parameters,
       but not attempting to wire them up.

       First we construct some arrays to contain the data we're
       hopefully about to extract. Note that these arrays are usually
       larger than is needed, however they will be large enough.

       WARNING: Note that there is no attempt to tidy up the memory at
       the end of this function and libraries are not unloaded under
       error conditions. This is only a toy program. */

    lPluginCountUpperLimit = (iArgc - lArgumentIndex - 1) / 2;

    ppvPluginLibraries = ((void **)
			  calloc(lPluginCountUpperLimit,
				 sizeof(void *)));
    ppsPluginDescriptors = ((const LADSPA_Descriptor **)
			    calloc(lPluginCountUpperLimit,
				   sizeof(LADSPA_Descriptor *)));
    ppfPluginControlValues = ((LADSPA_Data **)
			      calloc(lPluginCountUpperLimit,
				     sizeof(LADSPA_Data *)));
    lPluginIndex = 0;
    lArgumentIndex += 2;
    bBadControls = 0;
    while (lArgumentIndex < (unsigned long)iArgc && !bBadControls) {

      if (lArgumentIndex + 1 == (unsigned long)iArgc) {
	bBadParameters = 1;
	break;
      }

      /* Parameter should be a plugin file name followed by a
         label. Load the plugin. This call will exit() if the load
         fails. */
      ppvPluginLibraries[lPluginIndex]
	= loadLADSPAPluginLibrary(ppcArgv[lArgumentIndex]);
      ppsPluginDescriptors[lPluginIndex] 
	= findLADSPAPluginDescriptor(ppvPluginLibraries[lPluginIndex],
				     ppcArgv[lArgumentIndex],
				     ppcArgv[lArgumentIndex + 1]);

      /* Check the plugin is in-place compatible. */
      iProperties = ppsPluginDescriptors[lPluginIndex]->Properties;
      if (LADSPA_IS_INPLACE_BROKEN(iProperties)) {
	fprintf(stderr,
		"Plugin \"%s\" is not capable of in-place processing and "
		"therefore cannot be used by this program.\n",
		ppsPluginDescriptors[lPluginIndex]->Name);
	/* This is somewhat lazy - this isn't a difficult problem to
           get around. */
	return(1);
      }

      lControlValueCount
	= getPortCountByType(ppsPluginDescriptors[lPluginIndex],
			     LADSPA_PORT_INPUT | LADSPA_PORT_CONTROL);
      
      bBadControls = (lControlValueCount + lArgumentIndex + 2 
		      > (unsigned long)iArgc);
      if (lControlValueCount > 0 && !bBadControls) {
	ppfPluginControlValues[lPluginIndex]
	  = (LADSPA_Data *)calloc(lControlValueCount, sizeof(LADSPA_Data));
	for (lControlValueIndex = 0; 
	     lControlValueIndex < lControlValueCount && !bBadControls;
	     lControlValueIndex++) {
	  pcControlValue = ppcArgv[lArgumentIndex + 2 + lControlValueIndex];

	  ppfPluginControlValues[lPluginIndex][lControlValueIndex]
	    = (LADSPA_Data)strtod(pcControlValue, &pcEndPointer);

	  bBadControls = (pcControlValue + strlen(pcControlValue) 
			  != pcEndPointer);
	}
      }

      if (bBadControls)
	listControlsForPlugin(ppsPluginDescriptors[lPluginIndex]);

      lArgumentIndex += (2 + lControlValueCount);
      lPluginIndex++;
    }

    lPluginCount = lPluginIndex;

    if (!bBadControls) {

      /* We have all the data we need. Go go go. If this function
	 fails it will exit(). */
      applyPlugin(pcInputFilename,
		  pcOutputFilename,
		  fExtraSeconds,
		  lPluginCount,
		  ppsPluginDescriptors,
		  ppfPluginControlValues);

      for (lPluginIndex = 0; lPluginIndex < lPluginCount; lPluginIndex++)
	unloadLADSPAPluginLibrary(ppvPluginLibraries[lPluginIndex]);
    }
  }

  if (bBadParameters) {
    fprintf(stderr,
	    "Usage:\tapplyplugin [flags] <input Wave file> "
	    "<output Wave file>\n"
	    "\t<LADSPA plugin file name> <plugin label> "
	    "<Control1> <Control2>...\n"
	    "\t[<LADSPA plugin file name> <plugin label> "
	    "<Control1> <Control2>...]...\n"
	    "Flags:"
	    "\t-s<seconds>  Add seconds of silence after end of input file.\n"
	    "\n"
	    "To find out what control values are needed by a plugin, "
	    "use the\n"
	    "\"analyseplugin\" program and check for control input ports.\n"
            "Note that the LADSPA_PATH environment variable is used "
            "to help find plugins.\n");
    return(1);
  }

  return(0);
}

/*****************************************************************************/

/* EOF */