title: Reduce FFmpeg CPU Usage with cpulimit and PHP
body: <p>I run <a href="https://ffmpeg.org/" rel="nofollow noreferrer">FFmpeg</a> on my server using PHP <code>exec()</code>.</p>
  
  <p>It currently uses 100% of the cpu thread while encoding. </p>
  
  <p>I followed <a href="https://lorenzo.mile.si/2016/07/limiting-cpu-usage-and-server-load-with-ffmpeg/" rel="nofollow noreferrer">this gude</a> that uses a program called <a href="https://github.com/opsengine/cpulimit" rel="nofollow noreferrer">cpulimit</a> to reduce it to 30%.</p>
  
  <hr>
  
  <p><strong>PHP</strong></p>
  
  <pre><code>$args = "nice -19 cpulimit -l 30 -- ffmpeg -y -i intput.avi -vcodec libx264 -acodec aac -b:a 192k -threads 1 output.mp4"
  exec(escapeshellcmd($args));
  </code></pre>
  
  <p>FFmpeg/PHP works, and it will work with <code>nice</code>/<code>cpulimit</code> through the terminal, but after adding<br>
   <code>nice -19 cpulimit -l 30 --</code> to the PHP script it no longer works with <code>exec()</code>.</p>
  
  <hr>
  
  <p><strong>Output</strong></p>
  
  <p>FFmpeg output returns blank. I'm not able to see the full output, I tried using:</p>
  
  <pre><code>$output = shell_exec($args);
  echo "&lt;p&gt;$output&lt;/p&gt;"
  </code></pre>
  
  <p>and</p>
  
  <pre><code>file_put_contents("/var/www/mysite/logs/$output.log", $line . PHP_EOL, FILE_APPEND);
  </code></pre>
  
  <p>But they return 1 empty line.</p>
  
  <hr>
  
  <p><strong>Solution</strong></p>
  
  <p>My thought is that www-data runs FFmpeg and <code>nice</code>/<code>cpulimit</code> may need root?</p>
  
  <p>How can I get PHP <code>exec()</code> to work with FFmpeg args and cpulimit? </p>
  
  <p>Or is there an alternative way to limit the usage %?</p>