summaryrefslogtreecommitdiffstats
path: root/nebu/audio/SourceSample.cpp
blob: 8e8ffb52c610e733783a5a101a701b1bd35cfd56 (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
#include "audio/nebu_SourceSample.h"

#include <assert.h>
#include <string.h>

namespace Sound {
  SourceSample::SourceSample(System *system) { 
    _system = system;

    _buffer = NULL;
    _buffersize = 8192;

    _position = 0;
    _decoded = 0;
  }

  SourceSample::~SourceSample() {
    // fprintf(stderr, "nebu_SourceSample destructor called\n");
    if(_buffer)
      delete _buffer;
    // Source::~Source();
  }

  void SourceSample::Load(char *filename) {
#define BUFSIZE 1024 * 1024
    SDL_RWops *rwops;

    rwops = SDL_RWFromFile(filename, "rb");

    Sound_Sample *sample = Sound_NewSample(rwops, NULL,
					   _system->GetAudioInfo(),
					   _buffersize );
    if(sample == NULL) {
      fprintf(stderr, "[error] failed loading sample from '%s': %s\n", 
	      filename, Sound_GetError());
      return;
    }
    
    Sound_DecodeAll(sample);

    _buffersize = sample->buffer_size;
    _buffer = new Uint8[_buffersize];
    memcpy(_buffer, sample->buffer, _buffersize);

    Sound_FreeSample(sample);
    
    // fprintf(stderr, "done decoding sample '%s'\n", filename);
    _position = 0;
  }

  int SourceSample::Mix(Uint8 *data, int len) {
    if(_buffer == NULL)
      return 0;

    int volume = (int)(_volume * SDL_MIX_MAXVOLUME);
    assert(len < _buffersize);

    if(len < _buffersize - _position) {
      SDL_MixAudio(data, _buffer + _position, len, volume);
      _position += len;
    } else { 
      SDL_MixAudio(data, _buffer + _position, _buffersize - _position,
		   volume);
      len -= _buffersize - _position;

      // printf("end of sample reached!\n");
      if(_loop) {
	if(_loop != 255) 
	  _loop--;

	_position = 0;
	SDL_MixAudio(data, _buffer + _position, len, volume);
	_position += len;
      } else {
	_isPlaying = 0;
      }
    }
    return 1;
  }
}