2022-04-22 01:52:28 +02:00
const Path = require ( 'path' )
2022-07-06 02:53:01 +02:00
const fs = require ( '../libs/fsExtra' )
2022-04-22 01:52:28 +02:00
const workerThreads = require ( 'worker_threads' )
const Logger = require ( '../Logger' )
2023-10-20 23:39:32 +02:00
const TaskManager = require ( './TaskManager' )
2022-10-02 21:16:17 +02:00
const Task = require ( '../objects/Task' )
2022-09-27 01:07:31 +02:00
const { writeConcatFile } = require ( '../utils/ffmpegHelpers' )
2024-07-02 17:25:04 +02:00
const ffmpegHelpers = require ( '../utils/ffmpegHelpers' )
2022-04-22 01:52:28 +02:00
class AbMergeManager {
2023-10-20 23:39:32 +02:00
constructor ( ) {
2022-10-02 21:16:17 +02:00
this . itemsCacheDir = Path . join ( global . MetadataPath , 'cache/items' )
2022-04-22 01:52:28 +02:00
2022-09-27 01:07:31 +02:00
this . pendingTasks = [ ]
2022-04-22 01:52:28 +02:00
}
2022-10-02 21:31:04 +02:00
getPendingTaskByLibraryItemId ( libraryItemId ) {
2024-07-02 17:25:04 +02:00
return this . pendingTasks . find ( ( t ) => t . task . data . libraryItemId === libraryItemId )
2022-10-02 21:31:04 +02:00
}
cancelEncode ( task ) {
return this . removeTask ( task , true )
}
2022-12-20 00:13:04 +01:00
async startAudiobookMerge ( user , libraryItem , options = { } ) {
2022-10-02 21:16:17 +02:00
const task = new Task ( )
const audiobookDirname = Path . basename ( libraryItem . path )
const targetFilename = audiobookDirname + '.m4b'
const itemCachePath = Path . join ( this . itemsCacheDir , libraryItem . id )
const tempFilepath = Path . join ( itemCachePath , targetFilename )
2024-07-02 17:25:04 +02:00
const ffmetadataPath = Path . join ( itemCachePath , 'ffmetadata.txt' )
2022-10-02 21:16:17 +02:00
const taskData = {
2022-04-22 01:52:28 +02:00
libraryItemId : libraryItem . id ,
2022-09-27 01:07:31 +02:00
libraryItemPath : libraryItem . path ,
2022-10-02 21:16:17 +02:00
userId : user . id ,
2024-07-02 17:25:04 +02:00
originalTrackPaths : libraryItem . media . tracks . map ( ( t ) => t . metadata . path ) ,
2022-10-02 21:16:17 +02:00
tempFilepath ,
targetFilename ,
targetFilepath : Path . join ( libraryItem . path , targetFilename ) ,
itemCachePath ,
2024-07-02 17:25:04 +02:00
ffmetadataObject : ffmpegHelpers . getFFMetadataObject ( libraryItem , 1 ) ,
chapters : libraryItem . media . chapters ? . map ( ( c ) => ( { ... c } ) ) ,
coverPath : libraryItem . media . coverPath ,
ffmetadataPath
2022-04-22 01:52:28 +02:00
}
2022-10-02 21:16:17 +02:00
const taskDescription = ` Encoding audiobook " ${ libraryItem . media . metadata . title } " into a single m4b file. `
2023-05-27 21:51:03 +02:00
task . setData ( 'encode-m4b' , 'Encoding M4b' , taskDescription , false , taskData )
2023-10-20 23:39:32 +02:00
TaskManager . addTask ( task )
2022-10-02 21:16:17 +02:00
Logger . info ( ` Start m4b encode for ${ libraryItem . id } - TaskId: ${ task . id } ` )
2022-04-22 01:52:28 +02:00
2024-07-02 17:25:04 +02:00
if ( ! ( await fs . pathExists ( taskData . itemCachePath ) ) ) {
2022-10-02 21:16:17 +02:00
await fs . mkdir ( taskData . itemCachePath )
2022-04-22 01:52:28 +02:00
}
2022-12-20 00:13:04 +01:00
this . runAudiobookMerge ( libraryItem , task , options || { } )
2022-04-22 01:52:28 +02:00
}
2022-12-20 00:13:04 +01:00
async runAudiobookMerge ( libraryItem , task , encodingOptions ) {
2024-07-02 17:25:04 +02:00
// Create ffmetadata file
const success = await ffmpegHelpers . writeFFMetadataFile ( task . data . metadataObject , task . data . chapters , task . data . ffmetadataPath )
if ( ! success ) {
Logger . error ( ` [AudioMetadataManager] Failed to write ffmetadata file for audiobook " ${ task . data . libraryItemId } " ` )
task . setFailed ( 'Failed to write metadata file.' )
this . removeTask ( task , true )
return
}
2023-07-11 23:57:30 +02:00
const audioBitrate = encodingOptions . bitrate || '128k'
2022-12-20 00:13:04 +01:00
const audioCodec = encodingOptions . codec || 'aac'
const audioChannels = encodingOptions . channels || 2
2022-04-22 01:52:28 +02:00
// If changing audio file type then encoding is needed
2022-12-20 00:13:04 +01:00
const audioTracks = libraryItem . media . tracks
// TODO: Updated in 2.2.11 to always encode even if merging multiple m4b. This is because just using the file extension as was being done before is not enough. This can be an option or do more to check if a concat is possible.
// const audioRequiresEncode = audioTracks[0].metadata.ext !== '.m4b'
const audioRequiresEncode = true
const firstTrackIsM4b = audioTracks [ 0 ] . metadata . ext . toLowerCase ( ) === '.m4b'
const isOneTrack = audioTracks . length === 1
2022-04-22 01:52:28 +02:00
const ffmpegInputs = [ ]
if ( ! isOneTrack ) {
2022-12-20 00:13:04 +01:00
const concatFilePath = Path . join ( task . data . itemCachePath , 'files.txt' )
2022-04-22 01:52:28 +02:00
await writeConcatFile ( audioTracks , concatFilePath )
ffmpegInputs . push ( {
input : concatFilePath ,
options : [ '-safe 0' , '-f concat' ]
} )
} else {
ffmpegInputs . push ( {
input : audioTracks [ 0 ] . metadata . path ,
options : firstTrackIsM4b ? [ '-f mp4' ] : [ ]
} )
}
const logLevel = process . env . NODE _ENV === 'production' ? 'error' : 'warning'
2022-12-20 00:13:04 +01:00
let ffmpegOptions = [ ` -loglevel ${ logLevel } ` ]
const ffmpegOutputOptions = [ '-f mp4' ]
2022-04-22 01:52:28 +02:00
if ( audioRequiresEncode ) {
2024-07-02 17:25:04 +02:00
ffmpegOptions = ffmpegOptions . concat ( [ '-map 0:a' , ` -acodec ${ audioCodec } ` , ` -ac ${ audioChannels } ` , ` -b:a ${ audioBitrate } ` ] )
2022-04-22 01:52:28 +02:00
} else {
ffmpegOptions . push ( '-max_muxing_queue_size 1000' )
2022-10-02 21:16:17 +02:00
if ( isOneTrack && firstTrackIsM4b ) {
2022-04-22 01:52:28 +02:00
ffmpegOptions . push ( '-c copy' )
} else {
ffmpegOptions . push ( '-c:a copy' )
}
}
2022-12-20 00:13:04 +01:00
const workerData = {
2022-04-22 01:52:28 +02:00
inputs : ffmpegInputs ,
options : ffmpegOptions ,
outputOptions : ffmpegOutputOptions ,
2022-10-02 21:16:17 +02:00
output : task . data . tempFilepath
2022-04-22 01:52:28 +02:00
}
2022-12-20 00:13:04 +01:00
let worker = null
2022-04-22 01:52:28 +02:00
try {
2022-12-20 00:13:04 +01:00
const workerPath = Path . join ( global . appRoot , 'server/utils/downloadWorker.js' )
2022-04-22 01:52:28 +02:00
worker = new workerThreads . Worker ( workerPath , { workerData } )
} catch ( error ) {
Logger . error ( ` [AbMergeManager] Start worker thread failed ` , error )
2022-10-02 21:16:17 +02:00
task . setFailed ( 'Failed to start worker thread' )
this . removeTask ( task , true )
2022-04-22 01:52:28 +02:00
return
}
worker . on ( 'message' , ( message ) => {
if ( message != null && typeof message === 'object' ) {
if ( message . type === 'RESULT' ) {
2022-10-02 21:16:17 +02:00
this . sendResult ( task , message )
2022-04-22 01:52:28 +02:00
} else if ( message . type === 'FFMPEG' ) {
if ( Logger [ message . level ] ) {
Logger [ message . level ] ( message . log )
}
}
}
} )
2022-09-27 01:07:31 +02:00
this . pendingTasks . push ( {
2022-10-02 21:16:17 +02:00
id : task . id ,
task ,
2022-04-22 01:52:28 +02:00
worker
} )
}
2022-10-02 21:16:17 +02:00
async sendResult ( task , result ) {
2022-09-27 01:07:31 +02:00
// Remove pending task
2024-07-02 17:25:04 +02:00
this . pendingTasks = this . pendingTasks . filter ( ( d ) => d . id !== task . id )
2022-04-22 01:52:28 +02:00
if ( result . isKilled ) {
2022-10-02 21:16:17 +02:00
task . setFailed ( 'Ffmpeg task killed' )
this . removeTask ( task , true )
2022-04-22 01:52:28 +02:00
return
}
if ( ! result . success ) {
2022-10-02 21:16:17 +02:00
task . setFailed ( 'Encoding failed' )
this . removeTask ( task , true )
2022-09-27 01:07:31 +02:00
return
}
// Write metadata to merged file
2024-07-02 17:25:04 +02:00
const success = await ffmpegHelpers . addCoverAndMetadataToFile ( task . data . tempFilepath , task . data . coverPath , task . data . ffmetadataPath , 1 , 'audio/mp4' )
2022-09-27 01:07:31 +02:00
if ( ! success ) {
2022-10-02 21:16:17 +02:00
Logger . error ( ` [AbMergeManager] Failed to write metadata to file " ${ task . data . tempFilepath } " ` )
task . setFailed ( 'Failed to write metadata to m4b file' )
this . removeTask ( task , true )
2022-04-22 01:52:28 +02:00
return
}
2022-09-27 01:07:31 +02:00
// Move library item tracks to cache
2022-10-02 21:16:17 +02:00
for ( const trackPath of task . data . originalTrackPaths ) {
2022-09-27 01:07:31 +02:00
const trackFilename = Path . basename ( trackPath )
2022-10-02 21:16:17 +02:00
const moveToPath = Path . join ( task . data . itemCachePath , trackFilename )
2022-09-27 01:07:31 +02:00
Logger . debug ( ` [AbMergeManager] Backing up original track " ${ trackPath } " to ${ moveToPath } ` )
await fs . move ( trackPath , moveToPath , { overwrite : true } ) . catch ( ( err ) => {
Logger . error ( ` [AbMergeManager] Failed to move track " ${ trackPath } " to " ${ moveToPath } " ` , err )
} )
}
2022-10-02 21:16:17 +02:00
// Move m4b to target
Logger . debug ( ` [AbMergeManager] Moving m4b from ${ task . data . tempFilepath } to ${ task . data . targetFilepath } ` )
await fs . move ( task . data . tempFilepath , task . data . targetFilepath )
2022-04-22 01:52:28 +02:00
2024-07-02 17:25:04 +02:00
// Remove ffmetadata file
await fs . remove ( task . data . ffmetadataPath )
2022-10-02 21:16:17 +02:00
task . setFinished ( )
await this . removeTask ( task , false )
Logger . info ( ` [AbMergeManager] Ab task finished ${ task . id } ` )
2022-04-22 01:52:28 +02:00
}
2022-10-02 21:16:17 +02:00
async removeTask ( task , removeTempFilepath = false ) {
Logger . info ( '[AbMergeManager] Removing task ' + task . id )
2022-04-22 01:52:28 +02:00
2024-07-02 17:25:04 +02:00
const pendingDl = this . pendingTasks . find ( ( d ) => d . id === task . id )
2022-04-22 01:52:28 +02:00
if ( pendingDl ) {
2024-07-02 17:25:04 +02:00
this . pendingTasks = this . pendingTasks . filter ( ( d ) => d . id !== task . id )
2022-04-22 01:52:28 +02:00
if ( pendingDl . worker ) {
2022-11-19 20:28:06 +01:00
Logger . warn ( ` [AbMergeManager] Removing download in progress - stopping worker ` )
2022-04-22 01:52:28 +02:00
try {
pendingDl . worker . postMessage ( 'STOP' )
2022-10-02 21:31:04 +02:00
return
2022-04-22 01:52:28 +02:00
} catch ( error ) {
Logger . error ( '[AbMergeManager] Error posting stop message to worker' , error )
}
2022-11-19 20:28:06 +01:00
} else {
Logger . debug ( ` [AbMergeManager] Removing download in progress - no worker ` )
2022-04-22 01:52:28 +02:00
}
}
2024-07-02 17:25:04 +02:00
if ( removeTempFilepath ) {
// On failed tasks remove the bad file if it exists
2022-10-02 21:16:17 +02:00
if ( await fs . pathExists ( task . data . tempFilepath ) ) {
2024-07-02 17:25:04 +02:00
await fs
. remove ( task . data . tempFilepath )
. then ( ( ) => {
Logger . info ( '[AbMergeManager] Deleted target file' , task . data . tempFilepath )
} )
. catch ( ( err ) => {
Logger . error ( '[AbMergeManager] Failed to delete target file' , err )
} )
}
if ( await fs . pathExists ( task . data . ffmetadataPath ) ) {
await fs
. remove ( task . data . ffmetadataPath )
. then ( ( ) => {
Logger . info ( '[AbMergeManager] Deleted ffmetadata file' , task . data . ffmetadataPath )
} )
. catch ( ( err ) => {
Logger . error ( '[AbMergeManager] Failed to delete ffmetadata file' , err )
} )
2022-10-02 21:16:17 +02:00
}
}
2023-10-20 23:39:32 +02:00
TaskManager . taskFinished ( task )
2022-04-22 01:52:28 +02:00
}
}
2022-06-05 02:50:26 +02:00
module . exports = AbMergeManager