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 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')
|
2024-07-02 17:25:04 +02:00
|
|
|
const ffmpegHelpers = require('../utils/ffmpegHelpers')
|
2024-07-20 11:28:06 +02:00
|
|
|
const Ffmpeg = require('../libs/fluentFfmpeg')
|
|
|
|
const SocketAuthority = require('../SocketAuthority')
|
2024-07-29 19:19:58 +02:00
|
|
|
const { isWritable, copyToExisting } = require('../utils/fileUtils')
|
2024-07-20 11:28:06 +02:00
|
|
|
const TrackProgressMonitor = require('../objects/TrackProgressMonitor')
|
2022-04-22 01:52:28 +02:00
|
|
|
|
2024-08-01 00:32:51 +02:00
|
|
|
/**
|
|
|
|
* @typedef AbMergeEncodeOptions
|
|
|
|
* @property {string} codec
|
|
|
|
* @property {string} channels
|
|
|
|
* @property {string} bitrate
|
|
|
|
*/
|
|
|
|
|
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
|
|
|
|
2024-08-01 00:32:51 +02:00
|
|
|
/** @type {Task[]} */
|
2022-09-27 01:07:31 +02:00
|
|
|
this.pendingTasks = []
|
2022-04-22 01:52:28 +02:00
|
|
|
}
|
|
|
|
|
2024-08-01 00:32:51 +02:00
|
|
|
/**
|
|
|
|
*
|
|
|
|
* @param {string} libraryItemId
|
|
|
|
* @returns {Task|null}
|
|
|
|
*/
|
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
|
|
|
}
|
|
|
|
|
2024-08-01 00:32:51 +02:00
|
|
|
/**
|
|
|
|
* Cancel and fail running task
|
|
|
|
*
|
|
|
|
* @param {Task} task
|
|
|
|
* @returns {Promise<void>}
|
|
|
|
*/
|
2022-10-02 21:31:04 +02:00
|
|
|
cancelEncode(task) {
|
2024-09-21 00:18:29 +02:00
|
|
|
const taskFailedString = {
|
|
|
|
text: 'Task canceled by user',
|
|
|
|
key: 'MessageTaskCanceledByUser'
|
|
|
|
}
|
|
|
|
task.setFailed(taskFailedString)
|
2022-10-02 21:31:04 +02:00
|
|
|
return this.removeTask(task, true)
|
|
|
|
}
|
|
|
|
|
2024-08-01 00:32:51 +02:00
|
|
|
/**
|
|
|
|
*
|
2024-08-11 22:15:34 +02:00
|
|
|
* @param {string} userId
|
2024-08-01 00:32:51 +02:00
|
|
|
* @param {import('../objects/LibraryItem')} libraryItem
|
|
|
|
* @param {AbMergeEncodeOptions} [options={}]
|
|
|
|
*/
|
2024-08-11 22:15:34 +02:00
|
|
|
async startAudiobookMerge(userId, libraryItem, options = {}) {
|
2022-10-02 21:16:17 +02:00
|
|
|
const task = new Task()
|
|
|
|
|
2024-08-24 11:01:00 +02:00
|
|
|
const audiobookBaseName = libraryItem.isFile ? Path.basename(libraryItem.path, Path.extname(libraryItem.path)) : Path.basename(libraryItem.path)
|
|
|
|
const targetFilename = audiobookBaseName + '.m4b'
|
2022-10-02 21:16:17 +02:00
|
|
|
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')
|
2024-08-24 11:01:00 +02:00
|
|
|
const libraryItemDir = libraryItem.isFile ? Path.dirname(libraryItem.path) : libraryItem.path
|
2022-10-02 21:16:17 +02:00
|
|
|
const taskData = {
|
2022-04-22 01:52:28 +02:00
|
|
|
libraryItemId: libraryItem.id,
|
2024-08-24 11:01:00 +02:00
|
|
|
libraryItemDir,
|
2024-08-11 22:15:34 +02:00
|
|
|
userId,
|
2024-07-02 17:25:04 +02:00
|
|
|
originalTrackPaths: libraryItem.media.tracks.map((t) => t.metadata.path),
|
2024-07-20 11:28:06 +02:00
|
|
|
inos: libraryItem.media.includedAudioFiles.map((f) => f.ino),
|
2022-10-02 21:16:17 +02:00
|
|
|
tempFilepath,
|
|
|
|
targetFilename,
|
2024-08-24 11:01:00 +02:00
|
|
|
targetFilepath: Path.join(libraryItemDir, targetFilename),
|
2022-10-02 21:16:17 +02:00
|
|
|
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,
|
2024-07-20 11:28:06 +02:00
|
|
|
ffmetadataPath,
|
2024-07-31 08:44:24 +02:00
|
|
|
duration: libraryItem.media.duration,
|
|
|
|
encodeOptions: options
|
2022-04-22 01:52:28 +02:00
|
|
|
}
|
2024-09-21 00:18:29 +02:00
|
|
|
|
|
|
|
const taskTitleString = {
|
|
|
|
text: 'Encoding M4b',
|
|
|
|
key: 'MessageTaskEncodingM4b'
|
|
|
|
}
|
|
|
|
const taskDescriptionString = {
|
|
|
|
text: `Encoding audiobook "${libraryItem.media.metadata.title}" into a single m4b file.`,
|
|
|
|
key: 'MessageTaskEncodingM4bDescription',
|
|
|
|
subs: [libraryItem.media.metadata.title]
|
|
|
|
}
|
|
|
|
task.setData('encode-m4b', taskTitleString, taskDescriptionString, 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
|
|
|
}
|
|
|
|
|
2024-08-01 00:32:51 +02:00
|
|
|
/**
|
|
|
|
*
|
|
|
|
* @param {import('../objects/LibraryItem')} libraryItem
|
|
|
|
* @param {Task} task
|
|
|
|
* @param {AbMergeEncodeOptions} encodingOptions
|
|
|
|
*/
|
2022-12-20 00:13:04 +01:00
|
|
|
async runAudiobookMerge(libraryItem, task, encodingOptions) {
|
2024-07-20 11:28:06 +02:00
|
|
|
// Make sure the target directory is writable
|
2024-08-24 11:01:00 +02:00
|
|
|
if (!(await isWritable(task.data.libraryItemDir))) {
|
|
|
|
Logger.error(`[AbMergeManager] Target directory is not writable: ${task.data.libraryItemDir}`)
|
2024-09-21 00:18:29 +02:00
|
|
|
const taskFailedString = {
|
|
|
|
text: 'Target directory is not writable',
|
|
|
|
key: 'MessageTaskTargetDirectoryNotWritable'
|
|
|
|
}
|
|
|
|
task.setFailed(taskFailedString)
|
2024-07-02 17:25:04 +02:00
|
|
|
this.removeTask(task, true)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-07-20 11:28:06 +02:00
|
|
|
// Create ffmetadata file
|
|
|
|
if (!(await ffmpegHelpers.writeFFMetadataFile(task.data.ffmetadataObject, task.data.chapters, task.data.ffmetadataPath))) {
|
|
|
|
Logger.error(`[AudioMetadataManager] Failed to write ffmetadata file for audiobook "${task.data.libraryItemId}"`)
|
2024-09-21 00:18:29 +02:00
|
|
|
const taskFailedString = {
|
|
|
|
text: 'Failed to write metadata file',
|
|
|
|
key: 'MessageTaskFailedToWriteMetadataFile'
|
|
|
|
}
|
|
|
|
task.setFailed(taskFailedString)
|
2022-10-02 21:16:17 +02:00
|
|
|
this.removeTask(task, true)
|
2022-04-22 01:52:28 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-09-27 01:07:31 +02:00
|
|
|
this.pendingTasks.push({
|
2022-10-02 21:16:17 +02:00
|
|
|
id: task.id,
|
2024-07-20 11:28:06 +02:00
|
|
|
task
|
2022-04-22 01:52:28 +02:00
|
|
|
})
|
|
|
|
|
2024-07-20 11:28:06 +02:00
|
|
|
const encodeFraction = 0.95
|
|
|
|
const embedFraction = 1 - encodeFraction
|
|
|
|
try {
|
|
|
|
const trackProgressMonitor = new TrackProgressMonitor(
|
|
|
|
libraryItem.media.tracks.map((t) => t.duration),
|
|
|
|
(trackIndex) => SocketAuthority.adminEmitter('track_started', { libraryItemId: libraryItem.id, ino: task.data.inos[trackIndex] }),
|
|
|
|
(trackIndex, progressInTrack, taskProgress) => {
|
|
|
|
SocketAuthority.adminEmitter('track_progress', { libraryItemId: libraryItem.id, ino: task.data.inos[trackIndex], progress: progressInTrack })
|
|
|
|
SocketAuthority.adminEmitter('task_progress', { libraryItemId: libraryItem.id, progress: taskProgress * encodeFraction })
|
|
|
|
},
|
|
|
|
(trackIndex) => SocketAuthority.adminEmitter('track_finished', { libraryItemId: libraryItem.id, ino: task.data.inos[trackIndex] })
|
|
|
|
)
|
|
|
|
task.data.ffmpeg = new Ffmpeg()
|
|
|
|
await ffmpegHelpers.mergeAudioFiles(libraryItem.media.tracks, task.data.duration, task.data.itemCachePath, task.data.tempFilepath, encodingOptions, (progress) => trackProgressMonitor.update(progress), task.data.ffmpeg)
|
|
|
|
delete task.data.ffmpeg
|
|
|
|
trackProgressMonitor.finish()
|
|
|
|
} catch (error) {
|
|
|
|
if (error.message === 'FFMPEG_CANCELED') {
|
|
|
|
Logger.info(`[AbMergeManager] Task cancelled ${task.id}`)
|
|
|
|
} else {
|
|
|
|
Logger.error(`[AbMergeManager] mergeAudioFiles failed`, error)
|
2024-09-21 00:18:29 +02:00
|
|
|
const taskFailedString = {
|
|
|
|
text: 'Failed to merge audio files',
|
|
|
|
key: 'MessageTaskFailedToMergeAudioFiles'
|
|
|
|
}
|
|
|
|
task.setFailed(taskFailedString)
|
2024-07-20 11:28:06 +02:00
|
|
|
this.removeTask(task, true)
|
|
|
|
}
|
2022-09-27 01:07:31 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Write metadata to merged file
|
2024-07-20 11:28:06 +02:00
|
|
|
try {
|
|
|
|
task.data.ffmpeg = new Ffmpeg()
|
|
|
|
await ffmpegHelpers.addCoverAndMetadataToFile(
|
|
|
|
task.data.tempFilepath,
|
|
|
|
task.data.coverPath,
|
|
|
|
task.data.ffmetadataPath,
|
|
|
|
1,
|
|
|
|
'audio/mp4',
|
|
|
|
(progress) => {
|
|
|
|
Logger.debug(`[AbMergeManager] Embedding metadata progress: ${100 * encodeFraction + progress * embedFraction}`)
|
|
|
|
SocketAuthority.adminEmitter('task_progress', { libraryItemId: libraryItem.id, progress: 100 * encodeFraction + progress * embedFraction })
|
|
|
|
},
|
|
|
|
task.data.ffmpeg
|
|
|
|
)
|
|
|
|
delete task.data.ffmpeg
|
|
|
|
} catch (error) {
|
|
|
|
if (error.message === 'FFMPEG_CANCELED') {
|
|
|
|
Logger.info(`[AbMergeManager] Task cancelled ${task.id}`)
|
|
|
|
} else {
|
|
|
|
Logger.error(`[AbMergeManager] Failed to write metadata to file "${task.data.tempFilepath}"`)
|
2024-09-21 00:18:29 +02:00
|
|
|
const taskFailedString = {
|
|
|
|
text: 'Failed to write metadata to m4b file',
|
|
|
|
key: 'MessageTaskFailedToWriteMetadataToM4bFile'
|
|
|
|
}
|
|
|
|
task.setFailed(taskFailedString)
|
2024-07-20 11:28:06 +02:00
|
|
|
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
|
2024-07-29 19:19:58 +02:00
|
|
|
for (const [index, trackPath] of task.data.originalTrackPaths.entries()) {
|
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}`)
|
2024-07-29 19:19:58 +02:00
|
|
|
if (index === 0) {
|
|
|
|
// copy the first track to the cache directory
|
|
|
|
await fs.copy(trackPath, moveToPath).catch((err) => {
|
|
|
|
Logger.error(`[AbMergeManager] Failed to copy track "${trackPath}" to "${moveToPath}"`, err)
|
|
|
|
})
|
|
|
|
} else {
|
|
|
|
// move the rest of the tracks to the cache directory
|
|
|
|
await fs.move(trackPath, moveToPath, { overwrite: true }).catch((err) => {
|
|
|
|
Logger.error(`[AbMergeManager] Failed to move track "${trackPath}" to "${moveToPath}"`, err)
|
|
|
|
})
|
|
|
|
}
|
2022-09-27 01:07:31 +02:00
|
|
|
}
|
|
|
|
|
2024-07-29 19:19:58 +02:00
|
|
|
// Move m4b to target, preserving the original track's permissions
|
2022-10-02 21:16:17 +02:00
|
|
|
Logger.debug(`[AbMergeManager] Moving m4b from ${task.data.tempFilepath} to ${task.data.targetFilepath}`)
|
2024-07-29 19:19:58 +02:00
|
|
|
try {
|
|
|
|
await copyToExisting(task.data.tempFilepath, task.data.originalTrackPaths[0])
|
|
|
|
await fs.rename(task.data.originalTrackPaths[0], task.data.targetFilepath)
|
|
|
|
await fs.remove(task.data.tempFilepath)
|
|
|
|
} catch (err) {
|
|
|
|
Logger.error(`[AbMergeManager] Failed to move m4b from ${task.data.tempFilepath} to ${task.data.targetFilepath}`, err)
|
2024-09-21 00:18:29 +02:00
|
|
|
const taskFailedString = {
|
|
|
|
text: 'Failed to move m4b file',
|
|
|
|
key: 'MessageTaskFailedToMoveM4bFile'
|
|
|
|
}
|
|
|
|
task.setFailed(taskFailedString)
|
2024-07-29 19:19:58 +02:00
|
|
|
this.removeTask(task, true)
|
|
|
|
return
|
|
|
|
}
|
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
|
|
|
}
|
|
|
|
|
2024-08-01 00:32:51 +02:00
|
|
|
/**
|
|
|
|
* Remove ab merge task
|
|
|
|
*
|
|
|
|
* @param {Task} task
|
|
|
|
* @param {boolean} [removeTempFilepath=false]
|
|
|
|
*/
|
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-20 11:28:06 +02:00
|
|
|
const pendingTask = this.pendingTasks.find((d) => d.id === task.id)
|
|
|
|
if (pendingTask) {
|
2024-07-02 17:25:04 +02:00
|
|
|
this.pendingTasks = this.pendingTasks.filter((d) => d.id !== task.id)
|
2024-07-20 11:28:06 +02:00
|
|
|
if (task.data.ffmpeg) {
|
|
|
|
Logger.warn(`[AbMergeManager] Killing ffmpeg process for task ${task.id}`)
|
|
|
|
task.data.ffmpeg.kill()
|
|
|
|
// wait for ffmpeg to exit, so that the output file is unlocked
|
|
|
|
await new Promise((resolve) => setTimeout(resolve, 500))
|
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
|