Merge master.
[dcpomatic.git] / src / lib / audio_buffers.cc
index a15288a3b86c64b66f5567a3f93e7321e6e48279..4ada94db867b59d4fe7425fc6b048e0a251ae721 100644 (file)
@@ -19,6 +19,7 @@
 
 #include <cassert>
 #include <cstring>
+#include <cmath>
 #include <stdexcept>
 #include "audio_buffers.h"
 
@@ -72,6 +73,9 @@ AudioBuffers::~AudioBuffers ()
 void
 AudioBuffers::allocate (int channels, int frames)
 {
+       assert (frames >= 0);
+       assert (channels >= 0);
+
        _channels = channels;
        _frames = frames;
        _allocated_frames = frames;
@@ -171,6 +175,11 @@ AudioBuffers::make_silent (int from, int frames)
 void
 AudioBuffers::copy_from (AudioBuffers const * from, int frames_to_copy, int read_offset, int write_offset)
 {
+       if (frames_to_copy == 0) {
+               /* Prevent the asserts from firing if there is nothing to do */
+               return;
+       }
+       
        assert (from->channels() == channels());
 
        assert (from);
@@ -209,9 +218,11 @@ AudioBuffers::move (int from, int to, int frames)
        }
 }
 
-/** Add data from from `from', `from_channel' to our channel `to_channel' */
+/** Add data from from `from', `from_channel' to our channel `to_channel'.
+ *  @param gain Linear gain to apply to the data before it is added.
+ */
 void
-AudioBuffers::accumulate_channel (AudioBuffers const * from, int from_channel, int to_channel)
+AudioBuffers::accumulate_channel (AudioBuffers const * from, int from_channel, int to_channel, float gain)
 {
        int const N = frames ();
        assert (from->frames() == N);
@@ -221,7 +232,7 @@ AudioBuffers::accumulate_channel (AudioBuffers const * from, int from_channel, i
        float* d = _data[to_channel];
 
        for (int i = 0; i < N; ++i) {
-               *d++ += *s++;
+               *d++ += (*s++) * gain;
        }
 }
 
@@ -252,6 +263,8 @@ void
 AudioBuffers::accumulate_frames (AudioBuffers const * from, int read_offset, int write_offset, int frames)
 {
        assert (_channels == from->channels ());
+       assert (read_offset >= 0);
+       assert (write_offset >= 0);
 
        for (int i = 0; i < _channels; ++i) {
                for (int j = 0; j < frames; ++j) {
@@ -260,3 +273,15 @@ AudioBuffers::accumulate_frames (AudioBuffers const * from, int read_offset, int
        }
 }
 
+/** @param dB gain in dB */
+void
+AudioBuffers::apply_gain (float dB)
+{
+       float const linear = pow (10, dB / 20);
+       
+       for (int i = 0; i < _channels; ++i) {
+               for (int j = 0; j < _frames; ++j) {
+                       _data[i][j] *= linear;
+               }
+       }
+}