Advertisement
Linkyboy

Tdarr VAAPI Plugin

Mar 6th, 2023 (edited)
238
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // This is a modified script using the "Boosh-Transcode using QSV GPU & FFMPEG"
  2. // and "Remove letterbox script" by control#0405
  3. // This script is WIP and improves the logic for cropping black borders
  4. // It is currently hardcoded to use only QSV vaapi hardware decoding
  5. // Future expansion will include an option to select the hardware decoder for NVENC
  6. // This script is designed to set video files to HEVC mkv and remove black borders
  7.  
  8. const details = () => ({
  9.     id: 'Tdarr_Plugin_Himea_QSV_Optimizer',
  10.     Stage: 'Pre-processing',
  11.     Name: 'Himea QSV Optimizer',
  12.     Type: 'Video',
  13.     Operation: 'Transcode',
  14.     Description: `This is a VAAPI specific plugin. INTEL VAAPI enabled CPU/GPUs are required.
  15.       Files not in H265/HEVC will be transcoded into specified codec (H264/H265) using VAAPI
  16.       via Intel GPU using FFmpeg. Settings are dependant on file bitrate working by the logic that H265 can support
  17.       the same amount of data at half the bitrate of H264. This plugin will skip files already in HEVC, AV1 & VP9
  18.       unless "reconvert_hevc" is marked as true. If it is then these will be reconverted again into HEVC if they
  19.       exceed the bitrate specified in "hevc_max_bitrate". Reminder! An INTEL VAAPI enabled CPU/GPU is required.
  20.       NOTE - Created for use with UNRAID Docker and while it should support Windows/Mac etc, it may require
  21.       a custom version of FFmpeg to work properly.`,
  22.     Version: '1.0',
  23.     Tags: 'pre-processing,ffmpeg,video only,qsv,vaapi,h265,hevc,configurable',
  24.     Inputs: [
  25.     {
  26.       name: 'container',
  27.       type: 'string',
  28.       defaultValue: 'mkv',
  29.       inputUI: {
  30.         type: 'dropdown',
  31.         options: [
  32.           'mkv',
  33.           'mp4',
  34.         ],
  35.       },
  36.       tooltip: `\\n
  37.       ==DESCRIPTION==
  38.       \\n Specifies the output container of the file.
  39.       \\n Ensure that all stream types you may have are supported by your chosen container.
  40.       \\n
  41.       ==INFO==
  42.       \\n Only MP4 & MKV are supported and MKV is recommended.
  43.       \\nExample:\\n
  44.       mkv
  45.       \\nExample:\\n
  46.       mp4`,
  47.     },
  48.     {
  49.       name: 'force_conform',
  50.       type: 'boolean',
  51.       defaultValue: false,
  52.       inputUI: {
  53.         type: 'dropdown',
  54.         options: [
  55.           'false',
  56.           'true',
  57.         ],
  58.       },
  59.       tooltip: `\\n
  60.       ==DESCRIPTION==
  61.       \\n Make the file conform to output containers requirements.
  62.       Use if you need to ensure the encode works from mp4>mkv or mkv>mp4. \\n
  63.       ==WARNING== \\n
  64.       This will remove data of certain types so ensure you are happy with that,
  65.       or use another plugin to convert these data types first!
  66.       \\n
  67.       ==INFO==
  68.       \\n Drop hdmv_pgs_subtitle/eia_608/subrip/timed_id3 for MP4.
  69.       \\n Drop data streams/mov_text/eia_608/timed_id3 for MKV.
  70.       \\n Default is false.
  71.       \\nExample:\\n
  72.       true
  73.       \\nExample:\\n
  74.       false`,
  75.     },
  76.     {
  77.       name: 'output_codec',
  78.       type: 'string',
  79.       defaultValue: 'h265',
  80.       inputUI: {
  81.         type: 'dropdown',
  82.         options: [
  83.           'h264',
  84.           'h265'
  85.         ],
  86.       },
  87.       tooltip: `\\n
  88.       ==DESCRIPTION==
  89.       \\n Specify which codec to output as. h265 is recommended for 4k, h264 for 1080p.`
  90.     },
  91.     {
  92.       name: 'encoder_speedpreset',
  93.       type: 'string',
  94.       defaultValue: 'slow',
  95.       inputUI: {
  96.         type: 'dropdown',
  97.         options: [
  98.           'veryfast',
  99.           'faster',
  100.           'fast',
  101.           'medium',
  102.           'slow',
  103.           'slower',
  104.           'veryslow',
  105.         ],
  106.       },
  107.       tooltip: `\\n
  108.       ==DESCRIPTION==
  109.       \\n Specify the encoder speed/preset to use.
  110.       Slower options mean a slower encode but better quality and faster options mean faster encodes but
  111.       worse quality.
  112.       \\n For more information see intel white paper on FFmpeg results using QSV: \\n`
  113.       // eslint-disable-next-line max-len
  114.       + `https://www.intel.com/content/dam/www/public/us/en/documents/white-papers/cloud-computing-quicksync-video-ffmpeg-white-paper.pdf
  115.       \\n
  116.       ==INFO==
  117.       \\n Default is "slow".
  118.       \\nExample:\\n
  119.       medium
  120.       \\nExample:\\n
  121.       slower`,
  122.     },
  123.     {
  124.       name: 'extra_qsv_options',
  125.       type: 'string',
  126.       defaultValue: '',
  127.       inputUI: {
  128.         type: 'text',
  129.       },
  130.       tooltip: `\\n
  131.       ==DESCRIPTION==
  132.       \\n Here you can add extra options to the FFmpeg QSV ENCODE cmd.
  133.       This does not override the FFmpeg cmd, it just allows additions to it.
  134.       \\n
  135.       There are extra QSV options that can be
  136.       forced on/off as desired. See here for some possible cmds -
  137.       https://ffmpeg.org/ffmpeg-codecs.html#toc-HEVC-Options-1
  138.       \\n
  139.       ==WARNING== \\n
  140.       Just because a cmd is mentioned doesn't mean your installed version of FFmpeg supports it...
  141.      Be certain to verify the cmds work before adding to your workflow. \\n
  142.      Check Tdarr Help Tab. Enter FFmpeg cmd - "-h encoder=hevc_qsv". This will give a list of supported commands.
  143.      \\n
  144.      ==INFO==
  145.      \\n Default is empty but a suggested value is below. If unsure just leave empty.
  146.      \\n Ensure to only use cmds valid to encoding QSV as the script handles other FFmpeg cmds relating to
  147.      bitrate etc. Anything else entered here might be supported but could cause undesired results.
  148.      \\nExample:\\n
  149.      -extbrc 1 -rdo 1 -mbbrc 1 -b_strategy 1 -adaptive_i 1 -adaptive_b 1`,
  150.    },
  151.    {
  152.      name: 'enable_10bit',
  153.      type: 'boolean',
  154.      defaultValue: false,
  155.      inputUI: {
  156.        type: 'dropdown',
  157.        options: [
  158.          'false',
  159.          'true',
  160.        ],
  161.      },
  162.      tooltip: `\\n
  163.      ==DESCRIPTION==
  164.      \\n Specify if we want to enable 10bit encoding.
  165.      \\n If this is enabled files will be processed and converted into 10bit
  166.      HEVC using main10 profile and with p010le pixel format. \n
  167.      If you just want to retain files that are already 10 bit then this can be left as false, as
  168.      10bit to 10bit in FFmpeg should be automatic.
  169.      \\n
  170.      ==INFO==
  171.      \\n Default is "false".
  172.      \\nExample:\\n
  173.      true
  174.      \\nExample:\\n
  175.      false`,
  176.    },
  177.    {
  178.      name: 'bitrate_cutoff',
  179.      type: 'number',
  180.      defaultValue: 1500,
  181.      inputUI: {
  182.        type: 'text',
  183.      },
  184.      tooltip: `\\n
  185.      ==DESCRIPTION==
  186.      \\n Specify bitrate cutoff, files with a total bitrate lower then this will not be processed. \n
  187.      Since getting the bitrate of the video from files is unreliable, bitrate here refers to the total
  188.      bitrate of the file and not just the video steam.
  189.      \\n
  190.      ==INFO==
  191.      \\n Rate is in kbps.
  192.      \\n Defaults to 0 which means this is disabled.
  193.      \\n Enter a valid number to enable.
  194.      \\nExample:\\n
  195.      2500
  196.      \\nExample:\\n
  197.      1500`,
  198.    },
  199.    {
  200.      name: 'max_average_bitrate',
  201.      type: 'number',
  202.      defaultValue: 0,
  203.      inputUI: {
  204.        type: 'text',
  205.      },
  206.      tooltip: `\\n
  207.      ==DESCRIPTION==
  208.      \\n Specify a maximum average video bitrate. When encoding we take the current total bitrate and halve it
  209.      to get an average target. This option sets a upper limit to that average
  210.      (i.e if you have a video bitrate of 10000, half is 5000, if your maximum desired average bitrate is 4000
  211.      then we use that as the target instead of 5000).
  212.      \\n
  213.      ==INFO==
  214.      \\n Bitrate here is referring to video bitrate as we want to set the video bitrate on encode.
  215.      \\n Rate is in kbps.
  216.      \\n Defaults to 0 which means this is disabled.
  217.      \\n Enter a valid number to enable.
  218.      \\nExample:\\n
  219.      4000
  220.      \\nExample:\\n
  221.      3000`,
  222.    },
  223.    {
  224.      name: 'min_average_bitrate',
  225.      type: 'number',
  226.      defaultValue: 0,
  227.      inputUI: {
  228.        type: 'text',
  229.      },
  230.      tooltip: `\\n
  231.      ==DESCRIPTION==
  232.      \\n Specify a minimum average video bitrate. When encoding we take the current total bitrate and halve
  233.      it to get an average target. This option sets a lower limit to that average (i.e if you have a video bitrate
  234.      of 3000, half is 1500, if your minimum desired average bitrate is 2000 then we use that as the target instead
  235.      of 1500).
  236.      \\n
  237.      ==INFO==
  238.      \\n Bitrate here is referring to video bitrate as we want to set the video bitrate on encode.
  239.      \\n Rate is in kbps.
  240.      \\n Defaults to 0 which means this is disabled.
  241.      \\n Enter a valid number to enable.
  242.      \\nExample:\\n
  243.      2000
  244.      \\nExample:\\n
  245.      1000`,
  246.    },
  247.    {
  248.      name: 'reconvert_hevc',
  249.      type: 'boolean',
  250.      defaultValue: false,
  251.      inputUI: {
  252.        type: 'dropdown',
  253.        options: [
  254.          'false',
  255.          'true',
  256.        ],
  257.      },
  258.      tooltip: `\\n
  259.      ==DESCRIPTION==
  260.      \\n Specify if we want to reprocess HEVC, VP9 or AV1 files
  261.      (i.e reduce bitrate of files already in those codecs).
  262.      \\n Since this uses the same logic as normal, halving the current bitrate, this is NOT recommended
  263.      unless you know what you are doing, so leave false if unsure.
  264.      NEEDS to be used in conjunction with "bitrate_cutoff" or "hevc_max_bitrate" otherwise is ignored.
  265.      This is useful in certain situations, perhaps you have a file which is HEVC but has an extremely high
  266.      bitrate and you'd like to reduce it.
  267.       \\n Bare in mind that you can convert a file to HEVC and still be above your cutoff meaning it would
  268.       be converted again if this is set to true (since it's now HEVC). So if you use this be sure to set
  269.      "hevc_max_bitrate" & "max_average_bitrate" to prevent the plugin looping. Also it is highly suggested
  270.      that you have your "hevc_max_bitrate" higher than "max_average_bitrate".
  271.      \\n Again if you are unsure, please leave this as false!
  272.      \\n
  273.      ==WARNING== \\n
  274.      IF YOU HAVE VP9 OR AV1 FILES YOU WANT TO KEEP IN THOSE FORMATS THEN DO NOT USE THIS OPTION.
  275.      \\n
  276.      \\nExample:\\n
  277.      true
  278.      \\nExample:\\n
  279.      false`,
  280.    },
  281.    {
  282.      name: 'hevc_max_bitrate',
  283.      type: 'number',
  284.      defaultValue: 0,
  285.      inputUI: {
  286.        type: 'text',
  287.      },
  288.      tooltip: `\\n
  289.      ==DESCRIPTION==
  290.      \\n Has no effect unless "reconvert_hevc" is set to true. This allows you to specify a maximum
  291.      allowed average bitrate for HEVC or similar files. Much like the "bitrate_cutoff" option, but
  292.      specifically for HEVC files. It should be set HIGHER then your standard cutoff for safety.
  293.      \\n Also, it's highly suggested you use the min & max average bitrate options in combination with this. You
  294.       will want those to control the bitrate otherwise you may end up repeatedly reprocessing HEVC files.
  295.       i.e your file might have a bitrate of 20000, if your hevc cutoff is 5000 then it's going to reconvert
  296.      multiple times before it'll fall below that cutoff. While HEVC reprocessing can be useful
  297.       this is why it is NOT recommended!
  298.       \\n As with the cutoff, getting the bitrate of the video from files is unreliable, so bitrate
  299.       here refers to the total bitrate of the file and not just the video steam.
  300.       \\n
  301.       ==INFO==
  302.       \\n Rate is in kbps.
  303.       \\n Defaults to 0 which means this is disabled.
  304.       \\n Enter a valid number to enable, otherwise we use "bitrate_cutoff" and multiply x2 for a safe limit.
  305.       \\nExample:\\n
  306.       4000
  307.       \\nExample:\\n
  308.       3000`,
  309.     },
  310.   ],
  311. });
  312.  
  313. // eslint-disable-next-line no-unused-vars
  314. const plugin = (file, librarySettings, inputs, otherArguments) => {
  315.   const lib = require('../methods/lib')(); const os = require('os'); const fs = require('fs');
  316.  
  317.   // eslint-disable-next-line no-unused-vars,no-param-reassign
  318.   inputs = lib.loadDefaultValues(inputs, details);
  319.   const response = {
  320.     processFile: false,
  321.     preset: '',
  322.     handBrakeMode: false,
  323.     FFmpegMode: true,
  324.     infoLog: '',
  325.     container: `.${inputs.container}`
  326.   };
  327.  
  328.   // Set up required variables.
  329.   let duration = 0;
  330.   let videoIdx = 0;
  331.   let extraArguments = '';
  332.   let bitrateSettings = '';
  333.   let inflatedCutoff = 0;
  334.  
  335.   // Check if file is a video. If it isn't then exit plugin.
  336.   if (file.fileMedium !== 'video') {
  337.     response.infoLog += 'File is not a video. \n';
  338.     return response;
  339.   }
  340.  
  341.   // Check if duration info is filled, if so times it by 0.0166667 to get time in minutes.
  342.   // If not filled then get duration of stream 0 and do the same.
  343.   if (parseFloat(file.ffProbeData?.format?.duration) > 0) {
  344.     duration = parseFloat(file.ffProbeData?.format?.duration) * 0.0166667;
  345.   } else if (typeof file.meta.Duration !== 'undefined') {
  346.     duration = file.meta.Duration * 0.0166667;
  347.   } else {
  348.     duration = file.ffProbeData.streams[0].duration * 0.0166667;
  349.   }
  350.  
  351.   // Work out currentBitrate using "Bitrate = file size / (number of minutes * .0075)"
  352.   // Used from here https://blog.frame.io/2017/03/06/calculate-video-bitrates/
  353.   const currentBitrate = Math.round(file.file_size / (duration * 0.0075));
  354.   // Use the same calculation used for currentBitrate but divide it in half to get targetBitrate.
  355.   // Logic of h265 can be half the bitrate as h264 without losing quality.
  356.   let targetBitrate = Math.round((file.file_size / (duration * 0.0075)) / 2);
  357.   // Allow some leeway under and over the targetBitrate.
  358.   let minimumBitrate = Math.round(targetBitrate * 0.75);
  359.   let maximumBitrate = Math.round(targetBitrate * 1.25);
  360.  
  361.   response.infoLog += `☑ It looks like the current bitrate is ${currentBitrate}k. \n`;
  362.  
  363.   // Check if the file needs to be cropped or if file is in 10bit (Plex does not support 10bit HEVC)
  364.   crop_values = generate_crop_values(file, Math.round(duration/0.0166667), otherArguments);
  365.   response.infoLog += `Crop values detected: ${crop_values.w}:${crop_values.h}:${crop_values.x}:${crop_values.y} \n`;
  366.   if (crop_values.x > 10 || crop_values.y > 10
  367.     || file.ffProbeData.streams[0].profile === 'High 10'
  368.     || file.ffProbeData.streams[0].profile === 'Main 10'
  369.     || file.ffProbeData.streams[0].bits_per_raw_sample === '10')
  370.   {
  371.     if (crop_values.x > 10 || crop_values.y > 10) {
  372.       response.infoLog += `☒ File needs to be cropped Skipping bitrate cutoffs. \n`;
  373.     }
  374.     else if (file.ffProbeData.streams[0].profile === 'High 10'
  375.     || file.ffProbeData.streams[0].profile === 'Main 10'
  376.     || file.ffProbeData.streams[0].bits_per_raw_sample === '10')
  377.     {
  378.       response.infoLog += `☒ File is in 10bit. Skipping bitrate cutoffs. \n`;
  379.     }
  380.   }
  381.   else {
  382.     // If targetBitrate or currentBitrate comes out as 0 then something
  383.     // has gone wrong and bitrates could not be calculated.
  384.     // Cancel plugin completely.
  385.     if (targetBitrate <= 0 || currentBitrate <= 0) {
  386.       response.infoLog += '☒ Target bitrate could not be calculated. Skipping this plugin. \n';
  387.       return response;
  388.     }
  389.  
  390.     // If targetBitrate is equal or greater than currentBitrate then something
  391.     // has gone wrong as that is not what we want.
  392.     // Cancel plugin completely.
  393.     if (targetBitrate >= currentBitrate) {
  394.       response.infoLog += `☒ Target bitrate has been calculated as ${targetBitrate}k. This is equal or greater
  395.       than the current bitrate... Something has gone wrong and this shouldn't happen! Skipping this plugin. \n`;
  396.      return response;
  397.    }
  398.  
  399.    // Ensure that bitrate_cutoff is set if reconvert_hevc is true since we need some protection against a loop
  400.    // Cancel the plugin
  401.    if (inputs.reconvert_hevc === true && inputs.bitrate_cutoff <= 0 && inputs.hevc_max_bitrate <= 0) {
  402.      response.infoLog += `☒ Reconvert HEVC is ${inputs.reconvert_hevc}, however there is no bitrate cutoff
  403.      or HEVC specific cutoff set so we have no way to know when to stop processing this file.
  404.      Either set reconvert_HEVC to false or set a bitrate cutoff and set a hevc_max_bitrate cutoff.
  405.      Skipping this plugin. \n`;
  406.      return response;
  407.    }
  408.  
  409.    // Check if inputs.bitrate cutoff has something entered.
  410.    // (Entered means user actually wants something to happen, empty would disable this).
  411.    if (inputs.bitrate_cutoff > 0) {
  412.      // Checks if currentBitrate is below inputs.bitrate_cutoff.
  413.      // If so then cancel plugin without touching original files.
  414.      if (currentBitrate <= inputs.bitrate_cutoff) {
  415.        response.infoLog += `☑ Current bitrate is below set cutoff of ${inputs.bitrate_cutoff}k. Cancelling plugin. \n`;
  416.        return response;
  417.      }
  418.      // If above cutoff then carry on
  419.      if (currentBitrate > inputs.bitrate_cutoff && inputs.reconvert_hevc === false) {
  420.        response.infoLog += `☒ Current bitrate appears to be above the cutoff of ${inputs.bitrate_cutoff}k. Need to process \n`;
  421.      }
  422.    }
  423.  
  424.    if (inputs.max_average_bitrate > 0) {
  425.      // Checks if targetBitrate is above inputs.max_average_bitrate.
  426.      // If so then clamp target bitrate
  427.      if (targetBitrate > inputs.max_average_bitrate) {
  428.        response.infoLog += `Our target bitrate is above the max_average_bitrate so
  429.        target average bitrate clamped at max of ${inputs.max_average_bitrate}k. \n`;
  430.        targetBitrate = Math.round(inputs.max_average_bitrate);
  431.        minimumBitrate = Math.round(targetBitrate * 0.75);
  432.        maximumBitrate = Math.round(targetBitrate * 1.25);
  433.      }
  434.    }
  435.  
  436.    // Check if inputs.min_average_bitrate has something entered.
  437.    // (Entered means user actually wants something to happen, empty would disable this).
  438.    if (inputs.min_average_bitrate > 0) {
  439.      // Exit the plugin is the cutoff is less than the min average bitrate. Most likely user error
  440.      if (inputs.bitrate_cutoff < inputs.min_average_bitrate) {
  441.        response.infoLog += `☒ Bitrate cutoff ${inputs.bitrate_cutoff}k is less than the set minimum
  442.        average bitrate set of ${inputs.min_average_bitrate}k. We don't want this. Cancelling plugin. \n`;
  443.         return response;
  444.       }
  445.       // Checks if inputs.bitrate_cutoff is below inputs.min_average_bitrate.
  446.       // If so then set currentBitrate to the minimum allowed.)
  447.       if (targetBitrate < inputs.min_average_bitrate) {
  448.         response.infoLog += `Target average bitrate clamped at min of ${inputs.min_average_bitrate}k. \n`;
  449.         targetBitrate = Math.round(inputs.min_average_bitrate);
  450.         minimumBitrate = Math.round(targetBitrate * 0.75);
  451.         maximumBitrate = Math.round(targetBitrate * 1.25);
  452.       }
  453.     }
  454.  
  455.     // It's possible to remux or flat out convert from mp4 to mkv so we need to conform to standards
  456.     // So check streams and add any extra parameters required to make file conform with output format.
  457.     // i.e drop mov_text for mkv files and drop pgs_subtitles for mp4
  458.     if (inputs.force_conform === true) {
  459.       if (inputs.container.toLowerCase() === 'mkv') {
  460.         extraArguments += '-map -0:d ';
  461.         for (let i = 0; i < file.ffProbeData.streams.length; i += 1) {
  462.           try {
  463.             if (
  464.               file.ffProbeData.streams[i].codec_name
  465.                 .toLowerCase() === 'mov_text'
  466.               || file.ffProbeData.streams[i].codec_name
  467.                 .toLowerCase() === 'eia_608'
  468.               || file.ffProbeData.streams[i].codec_name
  469.                 .toLowerCase() === 'timed_id3'
  470.             ) {
  471.               extraArguments += `-map -0:${i} `;
  472.             }
  473.           } catch (err) {
  474.             // Error
  475.           }
  476.         }
  477.       }
  478.       if (inputs.container.toLowerCase() === 'mp4') {
  479.         for (let i = 0; i < file.ffProbeData.streams.length; i += 1) {
  480.           try {
  481.             if (
  482.               file.ffProbeData.streams[i].codec_name
  483.                 .toLowerCase() === 'hdmv_pgs_subtitle'
  484.               || file.ffProbeData.streams[i].codec_name
  485.                 .toLowerCase() === 'eia_608'
  486.               || file.ffProbeData.streams[i].codec_name
  487.                 .toLowerCase() === 'subrip'
  488.               || file.ffProbeData.streams[i].codec_name
  489.                 .toLowerCase() === 'timed_id3'
  490.             ) {
  491.               extraArguments += `-map -0:${i} `;
  492.             }
  493.           } catch (err) {
  494.             // Error
  495.           }
  496.         }
  497.       }
  498.     }
  499.  
  500.     // Go through each stream in the file.
  501.     for (let i = 0; i < file.ffProbeData.streams.length; i += 1) {
  502.       // Check if stream is a video.
  503.       if (file.ffProbeData.streams[i].codec_type.toLowerCase() === 'video') {
  504.         // Check if codec of stream is mjpeg/png, if so then remove this "video" stream.
  505.         // mjpeg/png are usually embedded pictures that can cause havoc with plugins.
  506.         if (file.ffProbeData.streams[i].codec_name === 'mjpeg' || file.ffProbeData.streams[i].codec_name === 'png') {
  507.           extraArguments += `-map -v:${videoIdx} `;
  508.         }
  509.  
  510.         // Now check if we're reprocessing HEVC files, if not then ensure we don't convert HEVC again
  511.         if (inputs.reconvert_hevc === false && (file.ffProbeData.streams[i].codec_name === 'hevc'
  512.           || file.ffProbeData.streams[i].codec_name === 'vp9' || file.ffProbeData.streams[i].codec_name === 'av1')) {
  513.           // Check if codec of stream is HEVC, VP9 or AV1 AND check if file.container matches inputs.container.
  514.           // If so nothing for plugin to do.
  515.           if ((file.ffProbeData.streams[i].codec_name === 'hevc' || file.ffProbeData.streams[i].codec_name === 'vp9'
  516.             || file.ffProbeData.streams[i].codec_name === 'av1') && file.container === inputs.container) {
  517.             response.infoLog += `☑ File is already HEVC, VP9 or AV1 & in ${inputs.container}. \n`;
  518.             return response;
  519.           }
  520.  
  521.           // Check if codec of stream is HEVC, Vp9 or AV1
  522.           // AND check if file.container does NOT match inputs.container.
  523.           // If so remux file.
  524.           if ((file.ffProbeData.streams[i].codec_name === 'hevc' || file.ffProbeData.streams[i].codec_name === 'vp9'
  525.             || file.ffProbeData.streams[i].codec_name === 'av1') && file.container !== inputs.container) {
  526.             response.infoLog += `☒ File is HEVC, VP9 or AV1 but is not in ${inputs.container} container. Remuxing. \n`;
  527.             response.preset = `<io> -map 0 -c copy ${extraArguments}`;
  528.             response.processFile = true;
  529.             return response;
  530.           }
  531.  
  532.           // New logic for reprocessing HEVC. Mainly done for my own use. Since we're reprocessing we're checking
  533.           // bitrate again and since this can be inaccurate (It calculates overall bitrate not video specific)
  534.           // we have to inflate the current bitrate so we don't keep looping this logic.
  535.         } else if (inputs.reconvert_hevc === true && (file.ffProbeData.streams[i].codec_name === 'hevc'
  536.           || file.ffProbeData.streams[i].codec_name === 'vp9' || file.ffProbeData.streams[i].codec_name === 'av1')) {
  537.           // If we're using the hevc max bitrate then update the cutoff to use it
  538.           if (inputs.hevc_max_bitrate > 0) {
  539.             if (currentBitrate > inputs.hevc_max_bitrate) {
  540.               // If bitrate is higher then hevc_max_bitrate then need to re-encode
  541.               response.infoLog += `☒ Reconvert_hevc is ${inputs.reconvert_hevc} & the file is already HEVC, VP9 or AV1.
  542.               Using HEVC specific cutoff of ${inputs.hevc_max_bitrate}k. \n
  543.               ☒ The file is still above this new cutoff! Reconverting. \n\n`;
  544.             } else {
  545.               // Otherwise we're now below the hevc cutoff and we can exit
  546.               response.infoLog += `☑ Reconvert_hevc is ${inputs.reconvert_hevc} & the file is already HEVC, VP9 or AV1.
  547.               Using HEVC specific cutoff of ${inputs.hevc_max_bitrate}k. \n
  548.               ☑ The file is NOT above this new cutoff. Exiting plugin. \n\n`;
  549.               return response;
  550.             }
  551.  
  552.             // If we're not using the hevc max bitrate then we need a safety net to try and ensure we don't keep
  553.             // looping this plugin. For maximum safety we simply multiply the cutoff by 2.
  554.           } else if (currentBitrate > (inputs.bitrate_cutoff * 2)) {
  555.             inflatedCutoff = Math.round(inputs.bitrate_cutoff * 2);
  556.             response.infoLog += `☒ Reconvert_hevc is ${inputs.reconvert_hevc} & the file is already HEVC, VP9 or AV1.
  557.             HEVC specific cutoff not set so bitrate_cutoff is multiplied by 2 for safety!
  558.             Cutoff now temporarily ${inflatedCutoff}k. \n The file is still above this new cutoff! Reconverting. \n\n`;
  559.           } else {
  560.             // File is below cutoff so we can exit
  561.             inflatedCutoff = Math.round(inputs.bitrate_cutoff * 2);
  562.             response.infoLog += `☑ Reconvert_hevc is ${inputs.reconvert_hevc} & the file is already HEVC, VP9 or AV1
  563.             so bitrate_cutoff is multiplied by 2! Cutoff now temporarily ${inflatedCutoff}k. \n
  564.             The file is NOT above this new cutoff. Exiting plugin. \n\n`;
  565.             return response;
  566.           }
  567.         }
  568.  
  569.         // Increment video index. Needed to keep track of video id in case there is more than one video track.
  570.         // (i.e png or mjpeg which we would remove at the start of the loop)
  571.         videoIdx += 1;
  572.       }
  573.     }
  574.   };
  575.  
  576.   // Set bitrateSettings variable using bitrate information calculated earlier.
  577.   bitrateSettings = `-minrate ${minimumBitrate}k `
  578.     + `-maxrate ${inputs.bitrate_cutoff}k -bufsize ${currentBitrate}k`;
  579.   // Print to infoLog information around file & bitrate settings.
  580.   response.infoLog += `\nContainer for output selected as ${inputs.container}. \n`;
  581.   response.infoLog += 'Encode variable bitrate settings: \n';
  582.   response.infoLog += `Target = ${targetBitrate}k \n`;
  583.   response.infoLog += `Minimum = ${minimumBitrate}k \n`;
  584.   response.infoLog += `Maximum = ${inputs.bitrate_cutoff}k \n`;
  585.  
  586.   // START PRESET
  587.   // DECODE FLAGS
  588.   // -fflags +genpts should regenerate timestamps if they end up missing...
  589.   response.preset = '-fflags +genpts ';
  590.  
  591.   //Add hardware acceleration if no cropping needed, otherwise use software decode
  592.   if (inputs.output_codec === 'h264') {
  593.     if (crop_values.x < 10 && crop_values.y < 10) {
  594.       response.preset += '-hwaccel vaapi -hwaccel_device /dev/dri/renderD128 -hwaccel_output_format vaapi <io> -map 0 -c:v h264_vaapi';
  595.     }
  596.     else {
  597.       response.preset += '-init_hw_device vaapi=intel:/dev/dri/renderD128 <io> -map 0 -c:v h264_vaapi';
  598.     }
  599.     // Add the rest of the FFmpeg command
  600.     response.preset += ` ${bitrateSettings} `
  601.       + `-preset ${inputs.encoder_speedpreset} ${inputs.extra_qsv_options}
  602.       -c:a copy -c:s copy -max_muxing_queue_size 9999 ${extraArguments} -crf 24 -qp 24 `;
  603.  
  604.     // Add crop values to preset if they exist.
  605.     if (crop_values.x > 10 || crop_values.y > 10) {
  606.       response.preset += `-vf crop=${crop_values.w}:${crop_values.h}:${crop_values.x}:${crop_values.y},format=yuv420p,hwupload`;
  607.     }
  608.   }
  609.   else if (inputs.output_codec === 'h265') {
  610.     if (crop_values.x < 10 && crop_values.y < 10) {
  611.       response.preset += '-hwaccel vaapi -hwaccel_device /dev/dri/renderD128 -hwaccel_output_format vaapi <io> -map 0 -c:v hevc_vaapi';
  612.     }
  613.     else {
  614.       response.preset += '-init_hw_device vaapi=intel:/dev/dri/renderD128 <io> -map 0 -c:v hevc_vaapi';
  615.     };
  616.     // Add the rest of the FFmpeg command
  617.     response.preset += ` ${bitrateSettings} `
  618.       + `-preset ${inputs.encoder_speedpreset} ${inputs.extra_qsv_options}
  619.       -c:a copy -c:s copy -max_muxing_queue_size 9999 ${extraArguments} -crf 24 -qp 24 -profile:v main `;
  620.  
  621.     // Add crop values to preset if they exist.
  622.     if (crop_values.x > 10 || crop_values.y > 10) {
  623.       response.preset += `-vf crop=${crop_values.w}:${crop_values.h}:${crop_values.x}:${crop_values.y},format=nv12,hwupload`;
  624.     }
  625.   };
  626.  
  627.   response.processFile = true;
  628.   response.infoLog += 'File Transcoding... \n';
  629.  
  630.   return response;
  631. };
  632.  
  633. module.exports.details = details;
  634. module.exports.plugin = plugin;
  635.  
  636. // Custom function to find the mode of a list
  637. function findMode(lst) {
  638.   const counts = {};
  639.   let maxCount = 0;
  640.   let modes = [];
  641.  
  642.   for (const num of lst) {
  643.     if (!counts[num]) {
  644.       counts[num] = 0;
  645.     }
  646.     counts[num]++;
  647.     if (counts[num] > maxCount) {
  648.       maxCount = counts[num];
  649.     }
  650.   }
  651.  
  652.   for (const num in counts) {
  653.     if (counts[num] === maxCount) {
  654.       modes.push(parseInt(num));
  655.     }
  656.   }
  657.  
  658.   return modes;
  659. }
  660.  
  661. // Use ffmpeg cropdetect to detect black bars.
  662. // If black bars are detected then set the crop variable to the detected values.
  663. function generate_crop_values(file, duration, otherArguments) {
  664.   const fs = require('fs');
  665.   const path = require('path');
  666.   const { execSync } = require('child_process');
  667.  
  668.   const sourceFile = file.meta.SourceFile;
  669.   // const txtFile = path.join(path.dirname(sourceFile), path.basename(sourceFile, path.extname(sourceFile))) + ".txt";
  670.  
  671.   // // Check if txtFile exists, and return the crop values from the file if it does
  672.   // if (fs.existsSync(txtFile)) {
  673.   //   const cropValues = fs.readFileSync(txtFile, 'utf8');
  674.   //   const crop = cropValues.split(':');
  675.   //   return {w: parseInt(crop[0]), h: parseInt(crop[1]), x: parseInt(crop[2]), y: parseInt(crop[3])};
  676.   // }
  677.  
  678.   // FFmpeg command to extract crop information and frames from the video
  679.   const ffmpegCropCommand = `${otherArguments.ffmpegPath} -ss 120 -i \"${sourceFile}\" -t 9:00 -vf fps=1/2,cropdetect -f null - 2>&1`;
  680.  const output = execSync(ffmpegCropCommand);
  681.  
  682.  // Extract crop values from output using regex
  683.  const crops = output
  684.    .toString()
  685.    .match(/crop=\S+/g)
  686.    .map((crop) => crop.substring(5));
  687.  
  688.  //Get the most commonly returned number and set that as the crop value
  689.  //ffmpeg returns 4 values for cropdetect: width:height:x:y
  690.  var crop_w_mode = [];
  691.  var crop_h_mode = [];
  692.  var crop_x_mode = [];
  693.  var crop_y_mode = [];
  694.  for (var c = 0; c < crops.length; c++) {
  695.    crop = crops[c].split(':');
  696.    crop_w_mode.push(parseInt(crop[0]));
  697.    crop_h_mode.push(parseInt(crop[1]));
  698.    crop_x_mode.push(parseInt(crop[2]));
  699.    crop_y_mode.push(parseInt(crop[3]));
  700.  }
  701.  wMode = findMode(crop_w_mode);
  702.  hMode = findMode(crop_h_mode);
  703.  xMode = findMode(crop_x_mode);
  704.  yMode = findMode(crop_y_mode);
  705.  
  706.  // // Write the crop values to txtFile
  707.  // const cropValuesStr = `${wMode}:${hMode}:${xMode}:${yMode}`;
  708.  // fs.writeFileSync(txtFile, cropValuesStr);
  709.  
  710.  // Return a dict of the crop values
  711.  return {w:wMode, h:hMode, x:xMode, y:yMode};
  712. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement