From 46d12e9ae6fa9c233bc32812b13185ee7df8d3fd Mon Sep 17 00:00:00 2001
From: Paul Adenot <paul@paul.cx>
Date: Thu, 10 Nov 2016 06:20:16 +0100
Subject: [PATCH] Prevent underflowing the number of input frames needed in
 input when resampling. (#188)

---
 src/cubeb_resampler_internal.h | 12 +++++++++---
 1 file changed, 9 insertions(+), 3 deletions(-)

diff --git a/src/cubeb_resampler_internal.h b/src/cubeb_resampler_internal.h
index e165cc2..3c37a04 100644
--- a/src/cubeb_resampler_internal.h
+++ b/src/cubeb_resampler_internal.h
@@ -263,9 +263,15 @@ public:
    * number of output frames will be exactly equal. */
   uint32_t input_needed_for_output(uint32_t output_frame_count)
   {
-    return (uint32_t)ceilf((output_frame_count - samples_to_frames(resampling_out_buffer.length()))
-                           * resampling_ratio);
-
+    int32_t unresampled_frames_left = samples_to_frames(resampling_in_buffer.length());
+    int32_t resampled_frames_left = samples_to_frames(resampling_out_buffer.length());
+    float input_frames_needed =
+      (output_frame_count - unresampled_frames_left) * resampling_ratio
+        - resampled_frames_left;
+    if (input_frames_needed < 0) {
+      return 0;
+    }
+    return (uint32_t)ceilf(input_frames_needed);
   }
 
   /** Returns a pointer to the input buffer, that contains empty space for at
-- 
2.7.4