From 749e4be79600c8100cc3f78f5b9a9bded4298736 Mon Sep 17 00:00:00 2001
From: philippegorley <philippe.gorley@savoirfairelinux.com>
Date: Thu, 8 Aug 2019 11:42:32 -0400
Subject: [PATCH] encoder: clamp video bitrate

If requested bitrate is too low or too high, the computed crf value may
not be within FFmpeg's acceptable range.

Change-Id: I0f1ce0b73e0c99bc48166d89bbdb21f4e658dc6d
---
 src/media/media_encoder.cpp | 15 ++++++++++++++-
 1 file changed, 14 insertions(+), 1 deletion(-)

diff --git a/src/media/media_encoder.cpp b/src/media/media_encoder.cpp
index c01df5e173..a5400b9840 100644
--- a/src/media/media_encoder.cpp
+++ b/src/media/media_encoder.cpp
@@ -226,7 +226,20 @@ MediaEncoder::initStream(const SystemCodecInfo& systemCodecInfo, AVBufferRef* fr
     }
 #endif
 
-    uint64_t maxBitrate = 1000 * std::atoi(libav_utils::getDictValue(options_, "max_rate"));
+    uint64_t maxBitrate = std::atoi(libav_utils::getDictValue(options_, "max_rate"));
+    // Only clamp video bitrate
+    if (systemCodecInfo.mediaType == MEDIA_VIDEO && maxBitrate > 0) {
+        if (maxBitrate < SystemCodecInfo::DEFAULT_MIN_BITRATE) {
+            JAMI_WARN("Requested bitrate %lu too low, setting to %u",
+                maxBitrate, SystemCodecInfo::DEFAULT_MIN_BITRATE);
+            maxBitrate = SystemCodecInfo::DEFAULT_MIN_BITRATE;
+        } else if (maxBitrate > SystemCodecInfo::DEFAULT_MAX_BITRATE) {
+            JAMI_WARN("Requested bitrate %lu too high, setting to %u",
+                maxBitrate, SystemCodecInfo::DEFAULT_MAX_BITRATE);
+            maxBitrate = SystemCodecInfo::DEFAULT_MAX_BITRATE;
+        }
+    }
+    maxBitrate *= 1000; // convert to b/s for FFmpeg
     uint8_t crf = (uint8_t) std::round(LOGREG_PARAM_A + log(pow(maxBitrate, LOGREG_PARAM_B)));     // CRF = A + B*ln(maxBitrate)
     uint64_t bufSize = 2 * maxBitrate;
 
-- 
GitLab