| 1 | class BassBackingTrackJob < ApplicationJob |
| 2 | # TODO: Set priority based on account type. |
| 3 | queue_as :default |
| 4 | def perform(audio_file_id) |
| 5 | # Get the file to split. |
| 6 | file = AudioFile.find_by(id: audio_file_id) |
| 7 | |
| 8 | # Make sure the actual file is attached. |
| 9 | # Otherwise, we don't want to do the job. |
| 10 | return if file.nil? || !file.source_file.attached? || !file.splitfire_results.count.positive? |
| 11 | |
| 12 | # Create the object now |
| 13 | result_bass_backing_track = BassBackingTrackFile.new(audio_file_id: file.id) |
| 14 | result_bass_backing_track.save |
| 15 | |
| 16 | result_drums_path = ActiveStorage::Blob.service.send(:path_for, file.drums_file.source_file.key) |
| 17 | result_vocals_path = ActiveStorage::Blob.service.send(:path_for, file.vocals_file.source_file.key) |
| 18 | result_piano_path = ActiveStorage::Blob.service.send(:path_for, file.piano_file.source_file.key) |
| 19 | result_other_path = ActiveStorage::Blob.service.send(:path_for, file.other_file.source_file.key) |
| 20 | |
| 21 | unless result_drums_path.present? && result_vocals_path.present? && result_piano_path.present? && result_other_path.present? |
| 22 | return |
| 23 | end |
| 24 | |
| 25 | # Prepare working directory. |
| 26 | working_directory_path = if Rails.env.production? |
| 27 | '/home/deploy/apps/ffmpeg/' |
| 28 | else |
| 29 | '../ffmpeg/' |
| 30 | end |
| 31 | |
| 32 | Dir.chdir(working_directory_path) |
| 33 | |
| 34 | codec = 'mp3' |
| 35 | |
| 36 | file_output_directory = file.source_file.blob.key.to_s |
| 37 | |
| 38 | result_bass_backing_track_filename = "bass-backing-track-#{file.id}.#{codec}" |
| 39 | |
| 40 | system("ffmpeg -i #{result_drums_path} -i #{result_vocals_path} -i #{result_piano_path} -i #{result_other_path} -filter_complex amix=inputs=4:duration=longest -y '#{result_bass_backing_track_filename}'") |
| 41 | |
| 42 | status_progress = 10 |
| 43 | until File.exist?(result_bass_backing_track_filename) |
| 44 | system("echo 'We are waiting for #{result_bass_backing_track_filename}...'") |
| 45 | result_bass_backing_track.update_attribute(:status_progress, status_progress) |
| 46 | result_bass_backing_track.save |
| 47 | |
| 48 | status_progress += 1 if status_progress < 100 |
| 49 | |
| 50 | sleep 1 |
| 51 | end |
| 52 | result_bass_backing_track_file = File.open(result_bass_backing_track_filename) |
| 53 | result_bass_backing_track.source_file.attach( |
| 54 | io: result_bass_backing_track_file, |
| 55 | filename: result_bass_backing_track_filename |
| 56 | ) |
| 57 | result_bass_backing_track.update_attribute(:status, :done) |
| 58 | result_bass_backing_track.update_attribute(:status_progress, 100) |
| 59 | result_bass_backing_track.save |
| 60 | |
| 61 | # Cleanup Spleeter output folder |
| 62 | system("rm #{result_bass_backing_track_filename}") |
| 63 | end |
| 64 | end |