decoder.c 14.3 KB
Newer Older
1
2
3
#include <libretro.h>
#include <audio/audio_mix.h>
#include <audio/conversion/float_to_s16.h>
4
5
#include <errno.h>
#include <string.h>
6

7
#include "lutro_assert.h"
8
9
10
#include "decoder.h"
#include "audio.h"

11
12
13
14
15
16
17
#if !defined(__always_inline)
#  ifdef _MSC_VER
#    define __always_inline  // microsoft has no equivalent to always_inline in C
#  else
#    define __always_inline  __attribute((always_inline))
#  endif
#endif
18

19
20
21
22
// the exposed Decoder API in Love2D is pretty much garbage and I don't think we should
// make any attempt to replicate it here (there are plenty of GH issues complaining that it
// can't realoly do anything, and it has some nonsense things like 'seek' that aren't clear
// if they impact sources or not). --jstine
23
//
24
25
26
27
28
29
30
31
32
33
34
35
// This file follows Decoder slightly for historical reasons but should really be thought
// of as a streaming Source API.

//
void decOgg_destroy(dec_OggData *data)
{
   ov_clear(&data->vf);
}

//
bool decOgg_init(dec_OggData *data, const char *filename)
{
36
37
   memset(data, 0, sizeof(*data));

38
39
   if (ov_fopen(filename, &data->vf) < 0)
   {
40
41
42
43
44
45
46
47
48
      // only print for file not found errors.
      // caller's intent might be to silently try opening "optional" files until one succeeeds.
      if (errno == ENOENT)
      {
         fprintf(stderr, "vorbis file not found: %s\n", filename);
         return false;
      }

      lutro_errorf("vorbis: Failed to open file: %s", filename, strerror(errno));
49
50
51
52
53
54
55
56
57
      return false;
   }

   printf("vorbis info:\n");
   printf("\tnum streams: %d\n",  ov_streams(&data->vf));

   data->info = (vorbis_info*)ov_info(&data->vf, 0);
   if (!data->info)
   {
58
      lutro_errorf("vorbis: couldn't get info for file: %s", filename);
59
60
61
62
63
64
65
66
      return false;
   }

   printf("\tnum channels: %d\n", data->info->channels);
   printf("\tsample rate: %d\n", data->info->rate);

   if (data->info->channels != 1 && data->info->channels != 2)
   {
67
      lutro_errorf("vorbis: unsupported number of channels");
68
69
70
71
72
      return false;
   }
   
   if (data->info->rate != 44100)
   {
73
      lutro_errorf("vorbis: unsupported sample rate");
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
      return false;
   }

   printf("vorbis init success\n");
   return true;
}

//
bool decOgg_seek(dec_OggData *data, intmax_t pos)
{
   // ogg doesn't do a cheap tell-check before invoking a very expensive seek operation internally,
   // so let's help it out here...
   if (ov_pcm_tell(&data->vf) != pos) {
      return ov_pcm_seek(&data->vf, pos) == 0;
   }
   return true;
}

//
intmax_t decOgg_sampleTell(dec_OggData *data)
{
   return ov_pcm_tell(&data->vf);
}

//
intmax_t decOgg_sampleLength(dec_OggData *data)
{
   return ov_pcm_total(&data->vf, -1);
}

// decoded data is mixed (added) into the presaturated mixer buffer.
// the buffer must be manually cleared to zero for non-mixing (raw) use cases.
bool decOgg_decode(dec_OggData *data, presaturate_buffer_desc *buffer, float volume, bool loop)
{
   //printf("decOgg_decode\n");

   bool finished = false;

   size_t rendered = 0;
   intmax_t bufsz = buffer->samplelen;
   mixer_presaturate_t* dst = buffer->data;

   while (bufsz)
   {
      float **pcm;
      int bitstream;
      //printf("pcmoffs: %d\n", data->vf.pcm_offset);
      intmax_t ret = ov_read_float(&data->vf, &pcm, bufsz, &bitstream);

      if (ret < 0)
      {
125
         lutro_errorf("Vorbis decoding failed with: %jd", ret);
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
         return true;
      }

      if (ret == 0) // EOF
      {
         if (loop)
         {
            if (ov_time_seek(&data->vf, 0.0) == 0)
               continue;               
            else
               finished = true;
         }
         else
            finished = true;

         break;
      }

      if (data->info->channels == 2)
      {
         if (buffer->channels == 1)
         {
            // correct downmixing of stereo to mono is actually quite tricky, and requires advanced
            // waveform analysis to maintain volume and avoid cancelling out, but for now this will suffice. --jstine
            for (long i = 0; i < ret; i++)
            {
               dst[i] += pcm[0][i] * volume;
               dst[i] += pcm[1][i] * volume;
            }
         }

         if (buffer->channels == 2)
         {
            for (long i = 0; i < ret; i++)
            {
               dst[(i * 2) + 0] += pcm[0][i] * volume;
               dst[(i * 2) + 1] += pcm[1][i] * volume;
            }
         }
      }
      else
      {
         if (buffer->channels == 1)
         {
            for (long i = 0; i < ret; i++)
            {
               dst[i] += pcm[0][i] * volume;
            }
         }

         if (buffer->channels == 2)
         {
            for (long i = 0; i < ret; i++)
            {
               dst[(i * 2) + 0] += pcm[0][i] * volume;
               dst[(i * 2) + 1] += pcm[0][i] * volume;
            }
         }
      }

      dst += ret * data->info->channels;
      bufsz -= ret;
      rendered += ret;
   }
   
   return finished;
}

// ===================================== WAVFILE =====================================

void decWav_destroy(dec_WavData *data)
{
   if (data->fp)
   {
      fclose(data->fp);
      data->fp = NULL;
   }
}

//
bool decWav_init(dec_WavData *data, const char *filename)
207
{
208
   memset(data, 0, sizeof(*data));
209
210
211
212
213
214

   FILE *fp = fopen(filename, "rb");
   if (!fp)
   {
      int err = errno;

215
      // only print for file not found errors.
216
217
      // caller's intent might be to silently try opening "optional" files until one succeeeds.
      if (errno == ENOENT)
218
      {
219
         fprintf(stderr, "wavfile not found: %s\n", filename);
220
         return 0;
221
      }
222

223
      lutro_errorf("Failed to open wavfile '%s': %s", filename, strerror(err));
224
225
226
      return 0;
   }

227
228
229
230
231
232
233
   fread(&data->headc1, WAV_HEADER_CHUNK1_SIZE, 1, fp);

   if (feof(fp)
      || memcmp(data->headc1.ChunkID,      "RIFF", 4)
      || memcmp(data->headc1.Format,       "WAVE", 4)
      || memcmp(data->headc1.Subchunk1ID,  "fmt ", 4)
   ) {
234
      lutro_errorf("%s is not a valid wav file or is truncated.", filename);
235
      fclose(fp);      
236
237
238
      return 0;
   }

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
   if (data->headc1.Subchunk1Size < 16)
   {
      lutro_errorf("%s has invalid subchunk size=%u. Expected size >= 16.", filename, data->headc1.Subchunk1Size);
      fclose(fp);      
      return 0;
   }

   if (data->headc1.Subchunk1Size != 16)
   {
      int extra = data->headc1.Subchunk1Size - 16;
      fseek(fp, extra, SEEK_CUR);
   }

   while (1)
   {
      if (fread(&data->headc2, WAV_HEADER_CHUNK2_SIZE, 1, fp) == 0)
      {
         lutro_errorf("%s is not a supported wav file. No data subchunk was found.", filename);
         return 0;
      }

      if (memcmp(data->headc2.Subchunk2ID, "data", 4) == 0)
      {
         data->seekPosSubChunk2 = ftell(fp);
         data->fp = fp;
         return 1;
      }

      fseek(fp, data->headc2.Subchunk2Size, SEEK_CUR);
   }
   dbg_assumef(false, "unreachable");
   return 0;
}

int decWav_CalcOffsetDataStart(const dec_WavData* wavData)
{
   return wavData ? wavData->seekPosSubChunk2 : 0;
276
277
278
}

//
279
bool decWav_seek(dec_WavData *data, intmax_t samplepos)
280
{
281
282
   int bps = ((data->headc1.BitsPerSample + 7) / 8) * data->headc1.NumChannels;
   int numSamples = data->headc2.Subchunk2Size / bps;
283

284
285
286
287
288
289
290
291
292
293
294
295
296
297
   // fseek will let us seek past the end of file without returning an error.
   // So it is best to verify positions against the know sample size.
   // TODO: Verify Love2D Behavior? Love2D doesn't specify behavior in this case.
   //       Options are set the seekpos to 0, or set the seekpos to numSamples.

   if (samplepos > numSamples)
   {
      // set to numSamples
      //  * if the sample is set to loop it will restart immediately from loop pos
      //  * If not set to loop, it will stop immediately.
      samplepos = numSamples;
   }

   intmax_t bytepos = samplepos * bps;
298
   intmax_t seekpos = decWav_CalcOffsetDataStart(data) + bytepos;
299
300
301
302
303

   // spurious calls to fseek have overhead, so early out if the internal managed
   // seek pos matches
   if (data->pos == bytepos)
   {
304
      tool_assert(ftell(data->fp) == seekpos);
305
306
307
      return 1;
   }

308
   if (fseek(data->fp, seekpos, SEEK_SET))
309
310
311
   {
      // logging here could be unnecessarily spammy. If we add a log it should be gated by
      // some audio diagnostic output switch/mode.
312
      //fprintf(stderr, "WAV decoder seek failed: %s\n", strerror(errno));
313
314
      return 0;
   }
315
   data->pos = bytepos;
316
   return 1;
317
318
319
}

//
320
321
intmax_t decWav_sampleTell(dec_WavData *data)
{
322
   int bps = ((data->headc1.BitsPerSample + 7) / 8) * data->headc1.NumChannels;
323
   
324
   intmax_t ret = ftell(data->fp) - decWav_CalcOffsetDataStart(data);
325
326
327
328
329
330
   if (ret >= 0)
   {
      if ((ret % bps) != 0)
      {
         // print size, it helps identify the offender.
         fprintf(stderr, "Unaligned read position in wav decoder stream. size=%d bps=%d channels=%d pos=%jd\n",
331
332
333
            data->headc2.Subchunk2Size,
            data->headc1.BitsPerSample,
            data->headc1.NumChannels,
334
335
336
337
338
339
340
341
            ret
         );
      }
   }
   return ret / bps;
}

static __always_inline int inl_get_sample(const uint8_t* sample_raw, int sz, int chan)
342
{
343
344
345
346
347
348
349
350
351
352
353
   if(sz == 1)
      return ((int)sample_raw[chan] - 128) * 128;

   if(sz == 2)
      return (int)(((int16_t*)sample_raw)[chan]);

   return 0;
}

// this is a pseudo template with several cont literal parameters.
// it should always be agressively inlined.
354
static __always_inline bool _inl_decode_wav(dec_WavData *data, intmax_t bufsz, mixer_presaturate_t* dst, int bytesPerSamplePerChan, int chan_src, int chan_dst, float volume, bool loop)
355
356
357
358
359
360
{
   // a normalized sound sample is considered range -1.0 to 1.0
   // 16-bit wav outputs values range 32767 to -32768
   // 8-bit wav is scaled up to 16 bit and then normalized using 16-bit divisor.
   float mul_volume_and_normalize = volume / 32767;

361
   int bytesPerMultiSample = bytesPerSamplePerChan * chan_src;
362

363
364
365
366
   int byteLen    = data->headc2.Subchunk2Size;
   int numSamples = data->headc2.Subchunk2Size / bytesPerMultiSample;

   for (int j = 0; j < bufsz; j++, data->pos += bytesPerMultiSample)
367
368
369
   {  
      uint8_t sample_raw[8];
      int readResult = 0;
370
371
372
373

   reloadSample:
      if (data->pos < byteLen)
         readResult = (int)fread(sample_raw, bytesPerMultiSample, 1, data->fp);
374
375
376

      if (!readResult)
      {
377
378
         dbg_assertf(data->pos == ftell(data->fp) - decWav_CalcOffsetDataStart(data), "numSamples=%jd byteLen=%jd dataPos=%jd and ftell=%jd",
            (intmax_t)numSamples, (intmax_t)byteLen, (intmax_t)data->pos, (intmax_t)ftell(data->fp)
379
         );
380
381
382
383
384
385
386
387
388
389
 
         if (!loop)
         {
            // love2D does not specify if seek/tell position should reset to zero or
            // point to the position past the last sample when a sample reaches its end.
            // Assuming ftell (position past end of stream) for now ...
            return 1;
         }

         data->pos = 0;
390
391
         fseek(data->fp, decWav_CalcOffsetDataStart(data), SEEK_SET);
         --j; goto reloadSample;    // attempt to re-read sample.
392
393
394
395
396
397
      }
      
      if (chan_src == 2)
      {
         if (chan_dst == 1)
         {
398
399
            dst[j] += inl_get_sample(sample_raw, bytesPerSamplePerChan, 0) * mul_volume_and_normalize;
            dst[j] += inl_get_sample(sample_raw, bytesPerSamplePerChan, 1) * mul_volume_and_normalize;
400
401
402
403
         }

         if (chan_dst == 2)
         {
404
405
            dst[(j*2)+0] += inl_get_sample(sample_raw, bytesPerSamplePerChan, 0) * mul_volume_and_normalize;
            dst[(j*2)+1] += inl_get_sample(sample_raw, bytesPerSamplePerChan, 1) * mul_volume_and_normalize;
406
407
408
409
410
411
412
         }
      }

      if (chan_src == 1)
      {
         if (chan_dst == 1)
         {
413
            dst[j] += inl_get_sample(sample_raw, bytesPerSamplePerChan, 0) * mul_volume_and_normalize;
414
415
416
417
         }

         if (chan_dst == 2)
         {
418
419
            dst[(j*2)+0] += inl_get_sample(sample_raw, bytesPerSamplePerChan, 0) * mul_volume_and_normalize;
            dst[(j*2)+1] += inl_get_sample(sample_raw, bytesPerSamplePerChan, 0) * mul_volume_and_normalize;
420
421
422
423
         }
      }
   }

424
425
   dbg_assertf(data->pos == ftell(data->fp) - decWav_CalcOffsetDataStart(data), "numSamples=%jd byteLen=%jd dataPos=%jd and ftell=%jd",
      (intmax_t)numSamples, (intmax_t)byteLen, (intmax_t)data->pos, (intmax_t)ftell(data->fp)
426
   );
427
   return 0;
428
429
}

430
431
// decoded data is mixed (added) into the presaturated mixer buffer.
// the buffer must be manually cleared to zero for non-mixing (raw) use cases.
432
bool decWav_decode(dec_WavData *data, presaturate_buffer_desc *buffer, float volume, bool loop)
433
{
434
435
436
437
438
439
440
441
442
   intmax_t bufsz = buffer->samplelen;
   mixer_presaturate_t* dst = buffer->data;

   // 8-bit samples are multiplied by 128 rather than the more mathematically appropriate 256 due to a
   // precedent in the authoring of 8-bit samples: due to their limited range of data, 8-bit samples
   // tend to be recorded at higher valumes in order to make full use of the dynamic range allowed, and
   // to avoid "hiss" that plagues 8-bit at low volumes. Therefore, as a rule of thumb, 8-bit samples
   // mixed at half volume will "match" better with 16-bit samples mixed at full volume. --jstine

443
444
445
446
   if (data->headc1.BitsPerSample == 8  && data->headc1.NumChannels == 2 && buffer->channels == 2) return _inl_decode_wav(data, bufsz, dst, 1, 2, 2, volume, loop); 
   if (data->headc1.BitsPerSample == 8  && data->headc1.NumChannels == 2 && buffer->channels == 1) return _inl_decode_wav(data, bufsz, dst, 1, 2, 1, volume, loop);
   if (data->headc1.BitsPerSample == 8  && data->headc1.NumChannels == 1 && buffer->channels == 2) return _inl_decode_wav(data, bufsz, dst, 1, 1, 2, volume, loop); 
   if (data->headc1.BitsPerSample == 8  && data->headc1.NumChannels == 1 && buffer->channels == 1) return _inl_decode_wav(data, bufsz, dst, 1, 1, 1, volume, loop);
447

448
449
450
451
   if (data->headc1.BitsPerSample == 16 && data->headc1.NumChannels == 2 && buffer->channels == 2) return _inl_decode_wav(data, bufsz, dst, 2, 2, 2, volume, loop); 
   if (data->headc1.BitsPerSample == 16 && data->headc1.NumChannels == 2 && buffer->channels == 1) return _inl_decode_wav(data, bufsz, dst, 2, 2, 1, volume, loop);
   if (data->headc1.BitsPerSample == 16 && data->headc1.NumChannels == 1 && buffer->channels == 2) return _inl_decode_wav(data, bufsz, dst, 2, 1, 2, volume, loop); 
   if (data->headc1.BitsPerSample == 16 && data->headc1.NumChannels == 1 && buffer->channels == 1) return _inl_decode_wav(data, bufsz, dst, 2, 1, 1, volume, loop);
452

453
454
455
   // TODO: some unsupported format (32-bit float?)
   // Return true to ensure the mixer stops and unrefs the sound data
   return true;
456
}