File Sizes
Older video codecs are significantly less efficient than the newer H.264 (AVC), H.265 (HEVC), and AV1 codecs. … read more
File Sizes
Older video codecs are significantly less efficient than the newer H.264 (AVC), H.265 (HEVC), and AV1 codecs. These days, pretty much every device supports H.264 and AV1 and most devices also support H.265. There’s very little reason to use anything other than these three codecs, but many ripped or original media files are still in older codecs. Any device I use to stream is new enough to have H.265 support, so I’m assuming support for my server. While AV1 technically has better compression performance and availability (due to its open source, royalty free model), it primarily excels at lower bitrates and quality levels. The primary target for AV1 is 720p-1080p web streaming, but for higher quality targets H.265 is preferred.
To take advantage of this reduced file size, I use Tdarr to automatically re-encode media streams with older codecs into H.265.
In addition to codecs, many media files contain several video or audio streams. We typically only need one or two of each: An “ideal” video stream, plus one for compatability, and an English audio stream, potentially alongside an original language audio stream. Some media containers can also embed subtitles, which similarly only need English and original language formats.
These changes alone to reduce file sizes a moderate amount. With these changes, I accept output files that are between 40% and 120% the size of the orignal file. Size increases are uncommon, but can happen. Further optimizations are needed to ensure performance outside of storage space.
The Direct Play Problem
Jellyfin can stream media in three ways: Direct Play, Direct Stream, and transcoded media. The goal is to always Direct Play media. Direct Play means the container, video, audio, and subtitles are all compatible with the client. For this to happen, the formats must be supported by the Jellyfin server, Jellyfin client application/browser, and client hardware/OS. If this isn’t true, Jellyfin will either Direct Stream (remux audio, container, or subtitles. Typically isn’t intensive, but still takes server load.), or fully transcode media (convert video to an entirely different format).
Container and subtitles are the easy part: MKV supports basically every A/V codec and subtitle format, but unfortunately isn’t compatable with Firefox or Safari at the moment. For video, all of my devices support H.265 so I can just use it for reduced file sizes and overall compatability. Audio is a bit more of a mixed bag. While transcoding audio isn’t very intensive, my devices have mixed compatability. My TV supports Dolby Atmos and DTS Virtual:X, but many other devices that use my server do not. Due to this, I need to be able to get the full quality audio whenver possible as it’s capable of mimicing surround sound. To account for these differences, I add two additional audio streams if they don’t exist to all files: 6 channel AC3 and 2 channel AC3. Most notably, I don’t remove any existing audio codecs as they’re typically higher quality or more compatable anyways.
While all these changes don’t perfectly account for all scenarios, they handle the vast majority of cases for my setup and pretty much always result in Direct Play and reasonable file sizes.
Miscellany
Since transcoding takes quite a lot of resources on my desktop, I have it scheduled to only occur during the night. This avoids issues while trying to do any CPU intensive tasks, which otherwise are brutal while transcoding is occuring. Another quirk about Tdarr is initially setting it up, especially when the server and client OSes are different. First, all files to transcode must be accessible on a network share. If they can’t be directly accessed, the Tdarr client has no way to function. Second, the transcoder itself expects all files to be on the exact same path on the server and client. This is easily resolved with “path translators” in the client, but this took a while to get right. If data is stored at /media on the server and on a network drive, the mapping should look like /media -> \\192.168.1.22\sambashare.
Additionally, the Tdarr_Plugin_silicon_Keep_Native_Lang_Plus_Eng seen above is a custom edit of the plugin Tdarr_Plugin_henk_Keep_Native_Lang_Plus_Eng. This edit doesn’t need a TMDB API key like the original one does. The code for this is below:
Keep Native Language Plus English Plugin
/* eslint-disable no-await-in-loop */
module.exports.dependencies = ['axios@0.27.2', '@cospired/i18n-iso-languages@4.2.0'];
// tdarrSkipTest
const details = () => ({
id: 'Tdarr_Plugin_silicon_Keep_Native_Lang_Plus_Eng',
Stage: 'Pre-processing',
Name: 'Remove All Langs Except Native And English',
Type: 'Audio',
Operation: 'Transcode',
Description: `This plugin will remove all language audio tracks except the 'native' and English.
'Native' languages are the ones that are listed on radarr/sonarr. It does an API call to
Radarr, Sonarr to check if the movie/series exists and grabs the language`,
Version: '1.2',
Tags: 'pre-processing,configurable',
Inputs: [
{
name: 'user_langs',
type: 'string',
defaultValue: '',
inputUI: {
type: 'text',
},
tooltip:
'Input a comma separated list of ISO-639-2 languages. It will still keep English and undefined tracks.'
+ '(https://en.wikipedia.org/wiki/List_of_ISO_639-2_codes 639-2 column)'
+ '\\nExample:\\n'
+ 'nld,nor',
},
{
name: 'priority',
type: 'string',
defaultValue: 'Radarr',
inputUI: {
type: 'text',
},
tooltip:
'Priority for either Radarr or Sonarr. Leaving it empty defaults to Radarr first.'
+ '\\nExample:\\n'
+ 'sonarr',
},
{
name: 'radarr_api_key',
type: 'string',
defaultValue: '',
inputUI: {
type: 'text',
},
tooltip: 'Input your Radarr api key here.',
},
{
name: 'radarr_url',
type: 'string',
defaultValue: '192.168.1.2:7878',
inputUI: {
type: 'text',
},
tooltip:
'Input your Radarr url here. Supports http://, https://, or'
+ ' just host:port (defaults to http://).'
+ '\\nExamples:\\n'
+ '192.168.1.2:7878 or https://radarr.example.com',
},
{
name: 'sonarr_api_key',
type: 'string',
defaultValue: '',
inputUI: {
type: 'text',
},
tooltip: 'Input your Sonarr api key here.',
},
{
name: 'sonarr_url',
type: 'string',
defaultValue: '192.168.1.2:8989',
inputUI: {
type: 'text',
},
tooltip:
'Input your Sonarr url here. Supports http://, https://, or'
+ ' just host:port (defaults to http://).'
+ '\\nExamples:\\n'
+ '192.168.1.2:8989 or https://sonarr.example.com',
},
],
});
const response = {
processFile: false,
preset: ', -map 0 ',
container: '.',
handBrakeMode: false,
FFmpegMode: true,
reQueueAfter: false,
infoLog: '',
};
// Helper function to normalize URLs - adds http:// if no protocol is specified
const normalizeUrl = (url) => {
if (!url) return '';
// Check if URL already has a protocol (http:// or https://)
if (url.startsWith('http://') || url.startsWith('https://')) {
return url;
}
// Otherwise, default to http://
return `http://${url}`;
};
const processStreams = (result, file, user_langs) => {
// eslint-disable-next-line import/no-unresolved,import/no-extraneous-dependencies
const languages = require('@cospired/i18n-iso-languages');
const tracks = {
keep: [],
remove: [],
remLangs: '',
};
let streamIndex = 0;
// If the original language is pulled as Chinese 'cn' is used. iso-language expects 'zh' for Chinese.
const langsTemp = result.original_language === 'cn' ? 'zh' : result.original_language;
let langs = [];
langs.push(languages.alpha2ToAlpha3B(langsTemp));
// Some console reporting for clarification of what the plugin is using and reporting.
response.infoLog += `Original language: ${langsTemp}, Using code: ${languages.alpha2ToAlpha3B(
langsTemp,
)}\n`;
if (user_langs) {
langs = langs.concat(user_langs);
}
if (!langs.includes('eng')) langs.push('eng');
if (!langs.includes('und')) langs.push('und');
response.infoLog += 'Keeping languages: ';
// Print languages to UI
langs.forEach((l) => {
response.infoLog += `${languages.getName(l, 'en')}, `;
});
response.infoLog = `${response.infoLog.slice(0, -2)}\n`;
// eslint-disable-next-line no-restricted-syntax
for (const stream of file.ffProbeData.streams) {
if (stream.codec_type === 'audio') {
if (!stream.tags) {
response.infoLog += `☒No tags found on audio track ${streamIndex}. Keeping it. \n`;
tracks.keep.push(streamIndex);
streamIndex += 1;
// eslint-disable-next-line no-continue
continue;
}
if (stream.tags.language) {
if (langs.includes(stream.tags.language)) {
tracks.keep.push(streamIndex);
} else {
tracks.remove.push(streamIndex);
response.preset += `-map -0:a:${streamIndex} `;
tracks.remLangs += `${languages.getName(
stream.tags.language,
'en',
)}, `;
}
streamIndex += 1;
} else {
response.infoLog += `☒No language tag found on audio track ${streamIndex}. Keeping it. \n`;
}
}
}
response.preset += ' -c copy -max_muxing_queue_size 9999';
return tracks;
};
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const plugin = async (file, librarySettings, inputs, otherArguments) => {
const lib = require('../methods/lib')();
// eslint-disable-next-line @typescript-eslint/no-unused-vars,no-param-reassign
inputs = lib.loadDefaultValues(inputs, details);
// eslint-disable-next-line import/no-unresolved,import/no-extraneous-dependencies
const axios = require('axios').default;
response.container = `.${file.container}`;
let prio = ['radarr', 'sonarr'];
let radarrResult = null;
let sonarrResult = null;
let langResult = null;
if (inputs.priority) {
if (inputs.priority === 'sonarr') {
prio = ['sonarr', 'radarr'];
}
}
const fileNameEncoded = encodeURIComponent(file.meta.FileName);
// eslint-disable-next-line no-restricted-syntax
for (const arr of prio) {
// eslint-disable-next-line default-case
switch (arr) {
case 'radarr':
if (langResult) break;
if (inputs.radarr_api_key) {
radarrResult = await axios
.get(
`${normalizeUrl(inputs.radarr_url)}`
+ `/api/v3/parse?apikey=${inputs.radarr_api_key}`
+ `&title=${fileNameEncoded}`,
)
.then((resp) => resp.data);
if (radarrResult) {
if (!radarrResult.movie) {
response.infoLog += "Error while grabbing lang from Radarr";
console.log(radarrResult);
continue;
}
lan = radarrResult.movie.originalLanguage.name;
response.infoLog += `Grabbed Language (${lan}) from Radarr \n`;
// eslint-disable-next-line import/no-unresolved,import/no-extraneous-dependencies
const languages = require('@cospired/i18n-iso-languages');
langResult = { original_language: languages.getAlpha2Code(lan, 'en') };
} else {
response.infoLog += "Couldn't grab lang from Radarr \n";
}
}
break;
case 'sonarr':
if (langResult) break;
if (inputs.sonarr_api_key) {
sonarrResult = await axios.get(
`${normalizeUrl(inputs.sonarr_url)}`
+ `/api/v3/parse?apikey=${inputs.sonarr_api_key}`
+ `&title=${fileNameEncoded}`,
)
.then((resp) => resp.data);
if (sonarrResult) {
if (!sonarrResult.series) {
response.infoLog += "Error while grabbing lang from Sonarr";
console.log(sonarrResult);
continue;
}
lan = sonarrResult.series.originalLanguage.name;
response.infoLog += `Grabbed Language (${lan}) from Sonarr \n`;
const languages = require('@cospired/i18n-iso-languages');
langResult = { original_language: languages.getAlpha2Code(lan, 'en') };
} else {
response.infoLog += "Couldn't grab lang from Sonarr \n";
}
}
}
}
if (langResult) {
const tracks = processStreams(
langResult,
file,
inputs.user_langs ? inputs.user_langs.split(',') : '',
);
if (tracks.remove.length > 0) {
if (tracks.keep.length > 0) {
response.infoLog += `☑Removing tracks with languages: ${tracks.remLangs.slice(
0,
-2,
)}. \n`;
response.processFile = true;
response.infoLog += '\n';
} else {
response.infoLog
+= '☒Cancelling plugin otherwise all audio tracks would be removed. \n';
}
} else {
response.infoLog += '☒No audio tracks to be removed. \n';
}
} else {
response.infoLog += "☒Couldn't find the original language of this file. Skipping. \n";
}
return response;
};
module.exports.details = details;
module.exports.plugin = plugin;