Transcode: audio files, and Remove video to turn a video into an audio file

video_codec 'none' (REMOVE_VIDEO) drops the video stream (-vn, audio
required); an audio-only source is audio-only output whatever the video
target says, and a video target on it is refused.  Audio output gets an
audio container (m4a/ogg/mp3) checked against the codec it will hold, and
a video container asked for audio output is replaced by the codec's
natural one.  faststart only for mp4/m4a.  Verification learned the
audio-only shape and ffprobe's container names (mkv reports matroska).

The modal offers 'Remove video (audio only)', switches to audio
containers and follows the audio codec, reads Extract Audio, and opens
for audio files (no video codec select).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
Roland 2026-09-15 10:54:54 -06:00
parent bd6b0012b7
commit e37b0f5305
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
6 changed files with 547 additions and 59 deletions

View file

@ -161,9 +161,12 @@ export const downloadAudioCodecOptions = [
// Codecs WROLPi's ffmpeg step can produce. Mirrors TRANSCODE_VIDEO_TARGETS / TRANSCODE_AUDIO_TARGETS /
// TRANSCODE_CONTAINERS in modules/videos/transcode.py; the API rejects anything else.
export const TRANSCODE_COPY = 'copy';
// REMOVE_VIDEO in modules/videos/transcode.py: drop the video stream, the result is an audio file.
export const TRANSCODE_REMOVE_VIDEO = 'none';
export const transcodeVideoCodecOptions = [
{value: TRANSCODE_COPY, label: 'Keep (copy)'},
{value: 'h264', label: 'h264 (avc1)'},
{value: TRANSCODE_REMOVE_VIDEO, label: 'Remove video (audio only)'},
];
export const transcodeAudioCodecOptions = [
{value: TRANSCODE_COPY, label: 'Keep (copy)'},
@ -171,10 +174,24 @@ export const transcodeAudioCodecOptions = [
{value: 'opus', label: 'opus'},
{value: 'mp3', label: 'mp3'},
];
// Containers for output with a video stream ...
export const transcodeContainerOptions = [
{value: 'mp4', label: 'mp4'},
{value: 'mkv', label: 'mkv'},
];
// ... and for audio-only output. AUDIO_CONTAINER_CODECS in transcode.py says what each holds.
export const transcodeAudioContainerOptions = [
{value: 'm4a', label: 'm4a (aac)'},
{value: 'ogg', label: 'ogg (opus)'},
{value: 'mp3', label: 'mp3'},
];
/** The audio container a player expects for a codec (default_audio_container in transcode.py). */
export function audioContainerForCodec(codec) {
if (codec === 'mp3') return 'mp3';
if (['opus', 'vorbis', 'flac'].includes(codec)) return 'ogg';
return 'm4a';
}
export const Downloaders = {
Archive: 'archive',

View file

@ -5,8 +5,11 @@ import {
Button, Confirm, Group, Icon, Menu, Modal, Progress, Select, Stack, Status, Text, Textarea, TextInput, toast,
} from './ui';
import {
audioContainerForCodec,
TRANSCODE_COPY,
TRANSCODE_REMOVE_VIDEO,
transcodeAudioCodecOptions,
transcodeAudioContainerOptions,
transcodeContainerOptions,
transcodeVideoCodecOptions,
} from './Vars';
@ -41,10 +44,25 @@ export function preferredTarget(preferences, options) {
return TRANSCODE_COPY;
}
/** The container of a video file, when it is one ffmpeg can write for us. */
/** The container of a video (or audio) file, when it is one ffmpeg can write for us. */
export function currentContainer(video) {
const suffix = String(video?.video_path || '').split('.').pop().toLowerCase();
return transcodeContainerOptions.some(i => i.value === suffix) ? suffix : null;
const known = [...transcodeContainerOptions, ...transcodeAudioContainerOptions];
return known.some(i => i.value === suffix) ? suffix : null;
}
/**
* The container to offer for the chosen codecs: audio-only output gets the natural container of
* the audio codec that will be in it (the target, or the source's when copied); output with video
* keeps the file's own container when possible.
*/
export function containerFor({audioOutput, audioCodec, video}) {
if (audioOutput) {
const codec = audioCodec !== TRANSCODE_COPY ? audioCodec : currentCodecs(video).audio[0];
return audioContainerForCodec(codec);
}
const current = currentContainer(video);
return transcodeContainerOptions.some(i => i.value === current) ? current : 'mp4';
}
const statusKind = (status) => {
@ -175,7 +193,10 @@ export function JobProgress({job, onCancel}) {
*
* The selects start at the user's preferred codecs from the Videos settings.
*/
export function TranscodeModal({open, onClose, fileGroupId, video, job, jobId, onQueued, onCancelJob}) {
export function TranscodeModal({
open, onClose, fileGroupId, video, audioOnly = false, job, jobId, onQueued,
onCancelJob,
}) {
const wrolModeEnabled = useWROLMode();
const [videoCodec, setVideoCodec] = useState(TRANSCODE_COPY);
const [audioCodec, setAudioCodec] = useState(TRANSCODE_COPY);
@ -184,24 +205,34 @@ export function TranscodeModal({open, onClose, fileGroupId, video, job, jobId, o
const [submitting, setSubmitting] = useState(false);
const current = currentCodecs(video);
const removeVideo = videoCodec === TRANSCODE_REMOVE_VIDEO;
// An audio file has no video stream to keep or remove; removing the video makes an audio file.
const audioOutput = audioOnly || removeVideo;
useEffect(() => {
if (!open) {
return;
}
setDefaultsLoaded(false);
setContainer(currentContainer(video) || 'mp4');
let stale = false;
const load = async () => {
let nextVideo = TRANSCODE_COPY;
let nextAudio = TRANSCODE_COPY;
try {
const defaults = await fetchVideoDownloadDefaults();
if (stale) return;
setVideoCodec(preferredTarget(defaults?.video_codecs, transcodeVideoCodecOptions));
setAudioCodec(preferredTarget(defaults?.audio_codecs, transcodeAudioCodecOptions));
nextVideo = audioOnly ? TRANSCODE_COPY
: preferredTarget(defaults?.video_codecs, transcodeVideoCodecOptions);
nextAudio = preferredTarget(defaults?.audio_codecs, transcodeAudioCodecOptions);
} catch (e) {
console.error(e);
} finally {
if (!stale) setDefaultsLoaded(true);
if (!stale) {
setVideoCodec(nextVideo);
setAudioCodec(nextAudio);
setContainer(containerFor({audioOutput: audioOnly, audioCodec: nextAudio, video}));
setDefaultsLoaded(true);
}
}
};
load();
@ -210,8 +241,20 @@ export function TranscodeModal({open, onClose, fileGroupId, video, job, jobId, o
};
}, [open]);
const remuxOnly = videoCodec === TRANSCODE_COPY && audioCodec === TRANSCODE_COPY;
const changeVideoCodec = (value) => {
const next = value || TRANSCODE_COPY;
setVideoCodec(next);
setContainer(containerFor({audioOutput: audioOnly || next === TRANSCODE_REMOVE_VIDEO, audioCodec, video}));
};
const changeAudioCodec = (value) => {
const next = value || TRANSCODE_COPY;
setAudioCodec(next);
setContainer(containerFor({audioOutput, audioCodec: next, video}));
};
const remuxOnly = !removeVideo && videoCodec === TRANSCODE_COPY && audioCodec === TRANSCODE_COPY;
const sameContainer = container === currentContainer(video);
const containerOptions = audioOutput ? transcodeAudioContainerOptions : transcodeContainerOptions;
const handleStart = async () => {
setSubmitting(true);
@ -234,44 +277,54 @@ export function TranscodeModal({open, onClose, fileGroupId, video, job, jobId, o
// A queued or finished Job replaces the form until the parent forgets it.
const showJob = !!jobId;
let hint = null;
if (defaultsLoaded && removeVideo) {
hint = `The video stream is removed; the result is an audio file (.${container}). `
+ (audioCodec === TRANSCODE_COPY ? 'The audio is copied without re-encoding.' : `The audio is converted to ${audioCodec}.`);
} else if (defaultsLoaded && remuxOnly) {
hint = sameContainer
? 'Both streams are kept: the file is rewritten as-is with fast start (moves the index to the front for quicker playback start).'
: `Both streams are kept: only the container changes to ${container} (a quick remux, no quality loss).`;
}
const buttonLabel = removeVideo ? 'Extract Audio' : remuxOnly ? 'Remux' : 'Transcode';
return <Modal open={open} onClose={onClose} size='small'>
<Modal.Header>Transcode Video</Modal.Header>
<Modal.Header>{audioOnly ? 'Transcode Audio' : 'Transcode Video'}</Modal.Header>
<Modal.Content>
<Stack gap='md'>
<Text size='sm' c='var(--muted)'>
Current codecs: video {describe(current.video)}, audio {describe(current.audio)}.
{audioOnly
? `Current codec: audio ${describe(current.audio)}. `
: `Current codecs: video ${describe(current.video)}, audio ${describe(current.audio)}. `}
Streams set to Keep are copied without re-encoding. Transcoding is slow and slightly
reduces quality; the original file is replaced when it finishes.
</Text>
{!showJob && <>
<Select
{!audioOnly && <Select
label='Video codec'
data={transcodeVideoCodecOptions}
value={videoCodec}
onChange={value => setVideoCodec(value || TRANSCODE_COPY)}
onChange={changeVideoCodec}
disabled={!defaultsLoaded}
allowDeselect={false}
/>
/>}
<Select
label='Audio codec'
data={transcodeAudioCodecOptions}
value={audioCodec}
onChange={value => setAudioCodec(value || TRANSCODE_COPY)}
onChange={changeAudioCodec}
disabled={!defaultsLoaded}
allowDeselect={false}
/>
<Select
label='Container'
data={transcodeContainerOptions}
data={containerOptions}
value={container}
onChange={value => setContainer(value || 'mp4')}
onChange={value => setContainer(value || containerOptions[0].value)}
disabled={!defaultsLoaded}
allowDeselect={false}
/>
{remuxOnly && defaultsLoaded && <Text size='sm' c='var(--muted)'>
{sameContainer
? 'Both streams are kept: the file is rewritten as-is with fast start (moves the index to the front for quicker playback start).'
: `Both streams are kept: only the container changes to ${container} (a quick remux, no quality loss).`}
</Text>}
{hint && <Text size='sm' c='var(--muted)'>{hint}</Text>}
</>}
{showJob && <JobProgress job={job} onCancel={onCancelJob}/>}
</Stack>
@ -285,7 +338,7 @@ export function TranscodeModal({open, onClose, fileGroupId, video, job, jobId, o
loading={submitting}
disabled={submitting || !defaultsLoaded || !!wrolModeEnabled}
>
{remuxOnly ? 'Remux' : 'Transcode'}
{buttonLabel}
</Button>}
</Modal.Actions>
</Modal>
@ -444,6 +497,7 @@ export function VideoEditMenu({
};
const isVideo = !!videoFile?.mimetype?.startsWith('video/');
const isAudio = !!videoFile?.mimetype?.startsWith('audio/');
const transcoding = !!jobId && !isJobFinished(job);
return <>
@ -469,7 +523,7 @@ export function VideoEditMenu({
<Menu.Item
leftSection={<Icon name='film'/>}
onClick={() => setTranscodeOpen(true)}
disabled={!isVideo || (!!wrolModeEnabled && !transcoding)}
disabled={!(isVideo || isAudio) || (!!wrolModeEnabled && !transcoding)}
>
{transcoding ? 'Transcoding...' : 'Transcode...'}
</Menu.Item>
@ -489,6 +543,7 @@ export function VideoEditMenu({
onClose={handleTranscodeClose}
fileGroupId={videoFile?.id}
video={video}
audioOnly={isAudio}
job={job}
jobId={jobId}
onQueued={setJobId}

View file

@ -2,10 +2,13 @@ import React from 'react';
import {act, fireEvent, screen, waitFor} from '@testing-library/react';
import {renderWithProviders} from '../test-utils';
import {
currentCodecs, currentContainer, EditVideoModal, JobProgress, preferredTarget, TranscodeModal, useJob,
VideoEditMenu,
containerFor, currentCodecs, currentContainer, EditVideoModal, JobProgress, preferredTarget, TranscodeModal,
useJob, VideoEditMenu,
} from './VideoEditMenu';
import {TRANSCODE_COPY, transcodeAudioCodecOptions, transcodeVideoCodecOptions} from './Vars';
import {
audioContainerForCodec, TRANSCODE_COPY, TRANSCODE_REMOVE_VIDEO, transcodeAudioCodecOptions,
transcodeVideoCodecOptions,
} from './Vars';
jest.mock('../api', () => ({
cancelJob: jest.fn(),
@ -23,6 +26,8 @@ const video = {
video_path: 'videos/movie.webm',
};
const videoFile = {id: 7, url: 'https://example.com/watch?v=1', mimetype: 'video/webm', title: 'Old Title', video};
const audio = {codec_names: ['aac'], codec_types: ['audio'], video_path: 'videos/song.m4a'};
const audioFile = {id: 8, url: null, mimetype: 'audio/mp4', title: 'Song', video: audio};
// Mantine's Select renders a hidden input next to the visible one, both tied to the label.
const selectInput = (label) => screen.getAllByLabelText(label).find(i => i.type !== 'hidden');
@ -47,10 +52,31 @@ describe('helpers', () => {
test('currentContainer reads the file suffix, only for containers we can write', () => {
expect(currentContainer({video_path: 'videos/a/movie.MP4'})).toBe('mp4');
expect(currentContainer({video_path: 'videos/a/movie.mkv'})).toBe('mkv');
expect(currentContainer({video_path: 'videos/a/song.m4a'})).toBe('m4a');
expect(currentContainer({video_path: 'videos/a/movie.webm'})).toBeNull();
expect(currentContainer(null)).toBeNull();
});
test('audioContainerForCodec mirrors the backend default', () => {
expect(audioContainerForCodec('aac')).toBe('m4a');
expect(audioContainerForCodec('mp3')).toBe('mp3');
expect(audioContainerForCodec('opus')).toBe('ogg');
expect(audioContainerForCodec('vorbis')).toBe('ogg');
expect(audioContainerForCodec(undefined)).toBe('m4a');
});
test('containerFor follows the audio codec for audio output, the file for video output', () => {
// Removing the video from a vp9/opus webm, copying the audio: opus lives in ogg.
expect(containerFor({audioOutput: true, audioCodec: TRANSCODE_COPY, video})).toBe('ogg');
expect(containerFor({audioOutput: true, audioCodec: 'aac', video})).toBe('m4a');
expect(containerFor({audioOutput: true, audioCodec: 'mp3', video})).toBe('mp3');
// Video output keeps a container we can write, else mp4.
expect(containerFor({audioOutput: false, audioCodec: 'aac', video})).toBe('mp4');
expect(containerFor({audioOutput: false, audioCodec: 'aac', video: {video_path: 'a.mkv'}})).toBe('mkv');
// An audio file's own suffix is not a video container.
expect(containerFor({audioOutput: false, audioCodec: TRANSCODE_COPY, video: audio})).toBe('mp4');
});
test('preferredTarget picks the first preference ffmpeg can produce', () => {
expect(preferredTarget(['vp9', 'h264'], transcodeVideoCodecOptions)).toBe('h264');
expect(preferredTarget(['vp9', 'av1'], transcodeVideoCodecOptions)).toBe(TRANSCODE_COPY);
@ -127,6 +153,36 @@ describe('TranscodeModal', () => {
expect(screen.getByRole('button', {name: 'Remux'})).toBeEnabled();
});
test('an audio file offers audio codecs and containers only', async () => {
fetchVideoDownloadDefaults.mockResolvedValue({video_codecs: ['h264'], audio_codecs: []});
renderWithProviders(
<TranscodeModal open={true} onClose={jest.fn()} fileGroupId={8} video={audio} audioOnly={true}
onQueued={jest.fn()}/>,
);
expect(screen.getByText('Transcode Audio')).toBeInTheDocument();
expect(screen.getByText(/Current codec: audio aac/)).toBeInTheDocument();
// The aac source, copied, belongs in m4a; the file already is one.
await waitFor(() => expect(selectInput('Container')).toHaveValue('m4a (aac)'));
expect(screen.queryAllByLabelText('Video codec')).toHaveLength(0);
expect(await screen.findByText(/rewritten as-is with fast start/)).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', {name: 'Remux'}));
// No video codec is sent for an audio file, whatever the video preferences say.
await waitFor(() => expect(transcodeVideo).toHaveBeenCalledWith(8, {
video_codec: null, audio_codec: null, container: 'm4a',
}));
});
test('the Remove video option is offered for videos', async () => {
renderWithProviders(
<TranscodeModal open={true} onClose={jest.fn()} fileGroupId={7} video={video} onQueued={jest.fn()}/>,
);
await waitFor(() => expect(selectInput('Video codec')).toHaveValue('h264 (avc1)'));
expect(transcodeVideoCodecOptions.some(i => i.value === TRANSCODE_REMOVE_VIDEO)).toBe(true);
// Selecting it is exercised through containerFor (Mantine's dropdown is not driveable in jsdom).
});
test('WROL Mode disables starting a transcode', async () => {
renderWithProviders(
<TranscodeModal open={true} onClose={jest.fn()} fileGroupId={7} video={video}/>,
@ -345,14 +401,22 @@ describe('VideoEditMenu', () => {
expect(screen.getByLabelText('Title')).toHaveValue('Old Title');
});
test('Refresh is unavailable without a URL, Transcode for non-video files', async () => {
const audioFile = {...videoFile, url: null, mimetype: 'audio/mpeg'};
renderWithProviders(<VideoEditMenu videoFile={audioFile} video={video} onRefresh={jest.fn()}/>);
test('Refresh is unavailable without a URL; audio files can be transcoded', async () => {
renderWithProviders(<VideoEditMenu videoFile={audioFile} video={audio} onRefresh={jest.fn()}/>);
fireEvent.click(screen.getByRole('button', {name: /Edit/}));
const refresh = await screen.findByRole('menuitem', {name: /Refresh/});
expect(refresh).toBeDisabled();
expect(screen.getByRole('menuitem', {name: /Transcode/})).toBeDisabled();
expect(screen.getByRole('menuitem', {name: /Transcode/})).toBeEnabled();
fireEvent.click(screen.getByRole('menuitem', {name: /Transcode/}));
expect(await screen.findByText('Transcode Audio')).toBeInTheDocument();
});
test('Transcode is unavailable for files that are neither video nor audio', async () => {
const other = {...videoFile, mimetype: 'application/pdf'};
renderWithProviders(<VideoEditMenu videoFile={other} video={video} onRefresh={jest.fn()}/>);
fireEvent.click(screen.getByRole('button', {name: /Edit/}));
expect(await screen.findByRole('menuitem', {name: /Transcode/})).toBeDisabled();
});
test('WROL Mode disables every item', async () => {

View file

@ -0,0 +1,265 @@
"""Audio-only transcodes: removing the video stream from a video, and transcoding audio files."""
import json
import pathlib
import shutil
from unittest import mock
import pytest
from modules.videos.transcode import transcode_video_file, validate_transcode_request, verify_transcode_output, \
REMOVE_VIDEO, TRANSCODE_AUDIO_CONTAINERS, default_audio_container, transcode_video_job
from wrolpi import jobs
from wrolpi.cmd import CommandResult
from wrolpi.vars import PROJECT_DIR
MP4 = 'mov,mp4,m4a,3gp,3g2,mj2'
def make_probe(vcodec, acodec, duration=10.0, format_name=MP4):
streams = []
if vcodec:
streams.append({'codec_type': 'video', 'codec_name': vcodec})
if acodec:
streams.append({'codec_type': 'audio', 'codec_name': acodec})
return {'streams': streams, 'format': {'format_name': format_name, 'duration': str(duration)}}
class FakeProbes:
def __init__(self, source, output):
self.source, self.output = source, output
def __call__(self, path: pathlib.Path):
return self.output if '.transcode.' in path.name else self.source
def fake_ffmpeg(cmd, **kwargs):
"""Writes the output file; the tail-decode check writes nothing."""
if cmd[-1] != '-':
pathlib.Path(cmd[-1]).write_bytes(b'output data')
return CommandResult(return_code=0, cancelled=False, stdout=b'', stderr=b'', elapsed=1)
async def async_fake_ffmpeg(cmd, **kwargs):
return fake_ffmpeg(cmd, **kwargs)
# ------------------------------------------------------------------ validation
def test_validate_remove_video():
"""Removing the video needs an audio container; an audio container needs a compatible codec."""
validate_transcode_request(REMOVE_VIDEO, 'aac', 'm4a')
validate_transcode_request(REMOVE_VIDEO, None, 'ogg') # Copy: checked against the source later.
validate_transcode_request(REMOVE_VIDEO, 'mp3', 'mp3')
with pytest.raises(ValueError, match='audio container'):
validate_transcode_request(REMOVE_VIDEO, 'aac', 'mp4')
with pytest.raises(ValueError, match='ogg'):
validate_transcode_request(REMOVE_VIDEO, 'aac', 'ogg')
with pytest.raises(ValueError, match='mp3'):
validate_transcode_request(REMOVE_VIDEO, 'opus', 'mp3')
with pytest.raises(ValueError, match='video'):
validate_transcode_request('h264', 'aac', 'm4a') # A video stream cannot live in m4a.
assert set(TRANSCODE_AUDIO_CONTAINERS) == {'m4a', 'ogg', 'mp3'}
def test_default_audio_container():
assert default_audio_container('aac') == 'm4a'
assert default_audio_container('opus') == 'ogg'
assert default_audio_container('vorbis') == 'ogg'
assert default_audio_container('mp3') == 'mp3'
assert default_audio_container('flac') == 'ogg'
assert default_audio_container(None) == 'm4a'
# ------------------------------------------------------------------ verification
def test_verify_audio_only_output():
source = make_probe('vp9', 'opus', 100.0, 'matroska,webm')
good = make_probe(None, 'aac', 100.0)
verify_transcode_output(source, good, REMOVE_VIDEO, 'aac', 'm4a')
# The video stream must be gone.
with pytest.raises(RuntimeError, match='video stream'):
verify_transcode_output(source, make_probe('vp9', 'aac', 100.0), REMOVE_VIDEO, 'aac', 'm4a')
# An embedded cover is not a video stream.
verify_transcode_output(source, make_probe('mjpeg', 'aac', 100.0), REMOVE_VIDEO, 'aac', 'm4a')
# Audio is required.
with pytest.raises(RuntimeError, match='audio'):
verify_transcode_output(source, make_probe(None, None, 100.0), REMOVE_VIDEO, 'aac', 'm4a')
def test_verify_container_names():
"""ffprobe names containers differently than the file suffix does."""
source = make_probe('h264', 'aac', 10.0)
verify_transcode_output(source, make_probe('h264', 'aac', 10.0, 'matroska,webm'), None, None, 'mkv')
verify_transcode_output(source, make_probe(None, 'opus', 10.0, 'ogg'), REMOVE_VIDEO, 'opus', 'ogg')
verify_transcode_output(source, make_probe(None, 'mp3', 10.0, 'mp3'), REMOVE_VIDEO, 'mp3', 'mp3')
verify_transcode_output(source, make_probe(None, 'aac', 10.0, MP4), REMOVE_VIDEO, None, 'm4a')
with pytest.raises(RuntimeError, match='container'):
verify_transcode_output(source, make_probe(None, 'mp3', 10.0, 'mp3'), REMOVE_VIDEO, 'mp3', 'ogg')
def test_verify_audio_source():
"""An audio-only source has no video to demand; the output is audio-only too."""
source = make_probe(None, 'mp3', 100.0, 'mp3')
verify_transcode_output(source, make_probe(None, 'aac', 100.0), None, 'aac', 'm4a')
verify_transcode_output(source, make_probe(None, 'mp3', 100.0, 'mp3'), None, None, 'mp3')
# ------------------------------------------------------------------ transcode_video_file
@pytest.mark.asyncio
async def test_remove_video(test_directory, async_client):
"""Removing the video: no video map, `-vn`, the audio is required, the output is an audio file
named for its container, and the original is replaced."""
video_path = test_directory / 'movie.mp4'
video_path.write_bytes(b'fake video data')
probes = FakeProbes(make_probe('h264', 'aac', 10.0), make_probe(None, 'aac', 10.0))
with mock.patch('modules.videos.transcode.probe_for_verify', side_effect=probes), \
mock.patch('modules.videos.transcode.run_command', side_effect=async_fake_ffmpeg) as mock_run:
result = await transcode_video_file(video_path, target_vcodec=REMOVE_VIDEO, target_acodec=None,
container='m4a')
assert result == test_directory / 'movie.m4a' and result.is_file()
assert not video_path.exists()
cmd = mock_run.call_args_list[0][0][0]
assert '-vn' in cmd
assert '0:V:0' not in cmd
assert cmd[cmd.index('-map') + 1] == '0:a:0', 'Audio is required, not optional'
assert '-c:v' not in cmd
assert cmd[cmd.index('-c:a') + 1] == 'copy'
assert '+faststart' in cmd, 'm4a is an mp4; fast start applies'
assert str(cmd[-1]).endswith('movie.transcode.m4a')
@pytest.mark.asyncio
async def test_remove_video_to_ogg_no_faststart(test_directory, async_client):
video_path = test_directory / 'movie.webm'
video_path.write_bytes(b'fake video data')
probes = FakeProbes(make_probe('vp9', 'opus', 10.0, 'matroska,webm'), make_probe(None, 'opus', 10.0, 'ogg'))
with mock.patch('modules.videos.transcode.probe_for_verify', side_effect=probes), \
mock.patch('modules.videos.transcode.run_command', side_effect=async_fake_ffmpeg) as mock_run:
result = await transcode_video_file(video_path, target_vcodec=REMOVE_VIDEO, container='ogg')
assert result == test_directory / 'movie.ogg'
cmd = mock_run.call_args_list[0][0][0]
assert '-movflags' not in cmd, 'movflags is an mp4 muxer option'
@pytest.mark.asyncio
async def test_audio_source_is_audio_output(test_directory, async_client):
"""An audio file has no video to keep or remove: the output is audio-only whatever the video
target says, and an unsuitable container is replaced by the codec's natural one."""
audio_path = test_directory / 'song.webm'
audio_path.write_bytes(b'fake audio data')
probes = FakeProbes(make_probe(None, 'opus', 10.0, 'matroska,webm'), make_probe(None, 'opus', 10.0, 'ogg'))
with mock.patch('modules.videos.transcode.probe_for_verify', side_effect=probes), \
mock.patch('modules.videos.transcode.run_command', side_effect=async_fake_ffmpeg) as mock_run:
result = await transcode_video_file(audio_path, target_vcodec=None, target_acodec=None, container='mp4')
assert result == test_directory / 'song.ogg', 'opus copied: ogg, not the video container asked for'
cmd = mock_run.call_args_list[0][0][0]
assert '-vn' in cmd and '0:V:0' not in cmd
@pytest.mark.asyncio
async def test_copy_audio_into_incompatible_container_is_refused(test_directory, async_client):
"""Copying opus into m4a cannot work; refuse before ffmpeg runs."""
video_path = test_directory / 'movie.webm'
video_path.write_bytes(b'fake video data')
probes = FakeProbes(make_probe('vp9', 'opus', 10.0, 'matroska,webm'), make_probe(None, 'opus', 10.0))
with mock.patch('modules.videos.transcode.probe_for_verify', side_effect=probes), \
mock.patch('modules.videos.transcode.run_command', side_effect=async_fake_ffmpeg) as mock_run:
with pytest.raises(RuntimeError, match='m4a'):
await transcode_video_file(video_path, target_vcodec=REMOVE_VIDEO, target_acodec=None, container='m4a')
mock_run.assert_not_called()
assert video_path.is_file()
@pytest.mark.asyncio
async def test_video_target_on_audio_source_is_refused(test_directory, async_client):
audio_path = test_directory / 'song.mp3'
audio_path.write_bytes(b'fake audio data')
probes = FakeProbes(make_probe(None, 'mp3', 10.0, 'mp3'), make_probe(None, 'mp3', 10.0, 'mp3'))
with mock.patch('modules.videos.transcode.probe_for_verify', side_effect=probes), \
mock.patch('modules.videos.transcode.run_command', side_effect=async_fake_ffmpeg) as mock_run:
with pytest.raises(RuntimeError, match='no video stream'):
await transcode_video_file(audio_path, target_vcodec='h264', container='mp4')
mock_run.assert_not_called()
# ------------------------------------------------------------------ Job + API
@pytest.mark.asyncio
async def test_remove_video_job(test_session, test_directory, async_client, video_factory):
"""The FileGroup follows the video into its audio-only life: same id, new suffix and mimetype."""
from modules.videos.models import Video
from wrolpi.files.models import FileGroup
video = video_factory()
video.file_group.length = 5
test_session.commit()
file_group_id = video.file_group_id
video_path = video.video_path
probes = FakeProbes(make_probe('h264', 'aac', 5.3), make_probe(None, 'mp3', 5.3, 'mp3'))
async def fake_run_command(cmd, stdout_callback=None, **kwargs):
if cmd[-1] != '-':
shutil.copy(PROJECT_DIR / 'test/big_buck_bunny.mp3', cmd[-1])
return CommandResult(return_code=0, cancelled=False, stdout=b'', stderr=b'', elapsed=1)
with mock.patch('modules.videos.transcode.probe_for_verify', side_effect=probes), \
mock.patch('wrolpi.cmd.run_command', side_effect=fake_run_command):
job_id = transcode_video_job.enqueue(file_group_id=file_group_id, video_codec=REMOVE_VIDEO,
audio_codec='mp3', container='mp3')
record = await jobs.wait_for_job(job_id)
assert record['status'] == jobs.COMPLETE, record
new_path = video_path.with_suffix('.mp3')
assert new_path.is_file() and not video_path.exists()
test_session.expire_all()
video = Video.find_by_file_group_id(test_session, file_group_id)
assert video.video_path == new_path
assert video.file_group.mimetype.startswith('audio/')
assert test_session.query(FileGroup).count() == 1
@pytest.mark.asyncio
async def test_transcode_api_audio_file(async_client, test_session, audio_factory):
"""An audio file can be transcoded (audio codec / audio container); a video target is a 400."""
audio = audio_factory()
test_session.commit()
request, response = await async_client.post(f'/api/videos/{audio.file_group_id}/transcode',
content=json.dumps({'video_codec': 'h264', 'container': 'mp4'}))
assert response.status == 400, response.json
assert 'audio' in response.json['message'].lower() or 'audio' in response.json['error'].lower()
request, response = await async_client.post(f'/api/videos/{audio.file_group_id}/transcode',
content=json.dumps({'audio_codec': 'aac', 'container': 'm4a'}))
assert response.status == 200, response.json
jobs.cancel_job(response.json['job_id'])
# Remove-video on an audio file is a no-op wording-wise but allowed (it is already audio).
request, response = await async_client.post(f'/api/videos/{audio.file_group_id}/transcode',
content=json.dumps({'video_codec': REMOVE_VIDEO, 'container': 'mp3'}))
assert response.status == 200, response.json
jobs.cancel_job(response.json['job_id'])
@pytest.mark.asyncio
async def test_transcode_api_remove_video_needs_audio_container(async_client, test_session, video_factory):
video = video_factory()
test_session.commit()
request, response = await async_client.post(f'/api/videos/{video.file_group_id}/transcode',
content=json.dumps({'video_codec': REMOVE_VIDEO, 'container': 'mp4'}))
assert response.status == 400, response.json
request, response = await async_client.post(f'/api/videos/{video.file_group_id}/transcode',
content=json.dumps({'video_codec': REMOVE_VIDEO, 'audio_codec': 'aac',
'container': 'm4a'}))
assert response.status == 200, response.json
jobs.cancel_job(response.json['job_id'])

View file

@ -44,7 +44,31 @@ TRANSCODE_AUDIO_TARGETS = {
}
# Containers that can hold an h264/aac transcode result. webm cannot.
TRANSCODE_CONTAINERS = ('mp4', 'mkv')
TRANSCODE_CONTAINERS = ('mp4', 'mkv') # For output with a video stream.
# For audio-only output: the video stream removed (`REMOVE_VIDEO`), or an audio-only source.
TRANSCODE_AUDIO_CONTAINERS = ('m4a', 'ogg', 'mp3')
# ffprobe codec names each audio container can hold without re-encoding.
# Ordered: `default_audio_container` picks the first container that holds a codec, so the most
# specific container comes first (mp3 fits in m4a too, but an .mp3 is what a user expects).
AUDIO_CONTAINER_CODECS = {
'mp3': {'mp3'},
'ogg': {'opus', 'vorbis', 'flac'},
'm4a': {'aac', 'mp3', 'alac'},
}
# `target_vcodec` value meaning "drop the video stream"; the output is an audio file.
REMOVE_VIDEO = 'none'
# ffprobe's `format_name` token for each container (mkv reports "matroska,webm").
CONTAINER_FORMAT_NAMES = {'mp4': 'mp4', 'mkv': 'matroska', 'm4a': 'm4a', 'ogg': 'ogg', 'mp3': 'mp3'}
# `-movflags +faststart` is an mp4-muxer option; other muxers warn about it.
FASTSTART_CONTAINERS = ('mp4', 'm4a')
def default_audio_container(codec: Optional[str]) -> str:
"""The natural audio container for a codec: what a player expects from the suffix."""
for container, codecs in AUDIO_CONTAINER_CODECS.items():
if codec in codecs:
return container
return 'm4a'
TRANSCODE_TIMEOUT = 4 * 60 * 60 # A long video on a Raspberry Pi can take hours.
@ -143,11 +167,9 @@ async def transcode_video_file(video_path: pathlib.Path,
"""
if not FFMPEG_BIN:
raise RuntimeError('ffmpeg was not found')
# No target for either stream is a remux: both streams are copied into the (new) container
# with faststart. Cheap, and what a user wants when only the container is wrong.
if container not in TRANSCODE_CONTAINERS:
logger.info(f'Forcing mp4 container for transcode of {video_path} ({container} is not supported)')
container = 'mp4'
# No target for either stream is a remux: both streams are copied into the (new) container.
# `target_vcodec=REMOVE_VIDEO` (or an audio-only source) makes the output an audio file; see
# `resolve_output`, which also settles an unsuitable container.
lock = await _acquire_transcode_lock()
try:
@ -184,10 +206,11 @@ def verify_transcode_output(source: dict, output: dict, target_vcodec: Optional[
@raise RuntimeError: describing the first failed check.
"""
if not output or not output.get('streams'):
if not output or output.get('streams') is None:
raise RuntimeError('Transcode output could not be probed (no streams); its index may be missing')
if container not in _format_names(output):
expected_format = CONTAINER_FORMAT_NAMES.get(container, container)
if expected_format not in _format_names(output):
raise RuntimeError(f'Transcode output container is {_format_names(output)}, expected {container}')
source_video = get_stream_codec_names(source, 'video')
@ -195,14 +218,20 @@ def verify_transcode_output(source: dict, output: dict, target_vcodec: Optional[
output_video = get_stream_codec_names(output, 'video')
output_audio = get_stream_codec_names(output, 'audio')
if not output_video:
raise RuntimeError('Transcode output has no video stream')
if source_audio and not output_audio:
raise RuntimeError('Transcode output has no audio stream, but the source has one')
expected_video = target_vcodec or (source_video[0] if source_video else None)
if expected_video and output_video[0] != expected_video:
raise RuntimeError(f'Transcode output video codec is {output_video[0]}, expected {expected_video}')
audio_only = target_vcodec == REMOVE_VIDEO or not source_video
if audio_only:
if output_video:
raise RuntimeError(f'Transcode output still has a video stream ({output_video[0]})')
if not output_audio:
raise RuntimeError('Transcode output has no audio stream')
else:
if not output_video:
raise RuntimeError('Transcode output has no video stream')
if source_audio and not output_audio:
raise RuntimeError('Transcode output has no audio stream, but the source has one')
expected_video = target_vcodec or (source_video[0] if source_video else None)
if expected_video and output_video[0] != expected_video:
raise RuntimeError(f'Transcode output video codec is {output_video[0]}, expected {expected_video}')
expected_audio = target_acodec or (source_audio[0] if source_audio else None)
if output_audio and expected_audio and output_audio[0] != expected_audio:
raise RuntimeError(f'Transcode output audio codec is {output_audio[0]}, expected {expected_audio}')
@ -251,6 +280,40 @@ def make_ffmpeg_progress_parser(duration: Optional[float], set_progress: Callabl
return parse
def resolve_output(source_probe: dict, target_vcodec: Optional[str], target_acodec: Optional[str],
container: str) -> Tuple[bool, str]:
"""Decide whether the output is audio-only and which container it gets.
Audio-only when the video is to be removed, or the source has no video stream. An audio
container that cannot hold the (copied or target) audio codec is refused; a video container
asked for an audio-only output is replaced by the codec's natural one.
@raise RuntimeError: when the request cannot be satisfied by this source."""
source_video = get_stream_codec_names(source_probe, 'video')
source_audio = get_stream_codec_names(source_probe, 'audio')
if target_vcodec and target_vcodec != REMOVE_VIDEO and not source_video:
raise RuntimeError(f'Cannot transcode video to {target_vcodec}: the file has no video stream')
audio_only = target_vcodec == REMOVE_VIDEO or not source_video
if not audio_only:
if container not in TRANSCODE_CONTAINERS:
logger.info(f'Forcing mp4 container ({container} cannot hold a video stream)')
container = 'mp4'
return False, container
if not source_audio:
raise RuntimeError('Cannot produce an audio file: the source has no audio stream')
effective_acodec = target_acodec or source_audio[0]
if container not in TRANSCODE_AUDIO_CONTAINERS:
container = default_audio_container(effective_acodec)
logger.info(f'Using {container} container for audio-only output ({effective_acodec})')
elif effective_acodec not in AUDIO_CONTAINER_CODECS[container]:
raise RuntimeError(
f'{effective_acodec} audio cannot be stored in {container}; choose another container or codec')
return True, container
async def _transcode_video_file(video_path: pathlib.Path, target_vcodec: Optional[str],
target_acodec: Optional[str], container: str,
duration: Optional[float] = None, keep_original: bool = False) -> pathlib.Path:
@ -270,25 +333,35 @@ async def _transcode_video_file(video_path: pathlib.Path, target_vcodec: Optiona
raise RuntimeError(
f'Not enough free space to transcode {video_path} ({free} bytes free, source is {source_size} bytes)')
video_args = TRANSCODE_VIDEO_TARGETS[target_vcodec] if target_vcodec else ('-c:v', 'copy')
# Probed before ffmpeg: the command depends on the source's streams, and verification compares
# against the file as it was.
source_probe = await probe_for_verify(video_path)
audio_only, container = resolve_output(source_probe, target_vcodec, target_acodec, container)
audio_args = TRANSCODE_AUDIO_TARGETS[target_acodec] if target_acodec else ('-c:a', 'copy')
if audio_only:
# `-vn` also drops embedded cover art; the audio stream is required.
map_args = ('-map', '0:a:0', '-vn')
video_args = ()
else:
# 0:V:0 excludes attached-picture streams (embedded thumbnails); 0:a:0? tolerates a video
# with no audio stream.
map_args = ('-map', '0:V:0', '-map', '0:a:0?')
video_args = TRANSCODE_VIDEO_TARGETS[target_vcodec] if target_vcodec else ('-c:v', 'copy')
faststart_args = ('-movflags', '+faststart') if container in FASTSTART_CONTAINERS else ()
final_path = video_path.with_suffix(f'.{container}')
tmp_path = video_path.with_suffix(f'.transcode.{container}')
# 0:V:0 excludes attached-picture streams (embedded thumbnails); 0:a:0? tolerates a video
# with no audio stream.
cmd = (FFMPEG_BIN, '-y',
'-i', video_path,
'-map', '0:V:0', '-map', '0:a:0?',
*map_args,
*video_args,
*audio_args,
'-movflags', '+faststart',
*faststart_args,
# Machine-readable progress on stdout (the human progress line is suppressed).
'-nostats', '-progress', 'pipe:1',
str(tmp_path))
logger.warning(f'Transcoding {video_path} to {final_path} (video={target_vcodec}, audio={target_acodec})')
# Probed before ffmpeg so verification compares against the file as it was.
source_probe = await probe_for_verify(video_path)
try:
job = get_current_job()
runner = job.run_command if job else run_command
@ -340,13 +413,23 @@ async def _transcode_video_file(video_path: pathlib.Path, target_vcodec: Optiona
def validate_transcode_request(video_codec: Optional[str], audio_codec: Optional[str], container: str):
"""@raise ValueError: when the request cannot be transcoded. No codec at all is a remux."""
if video_codec and video_codec not in TRANSCODE_VIDEO_TARGETS:
"""@raise ValueError: when the request cannot be transcoded. No codec at all is a remux;
`video_codec=REMOVE_VIDEO` drops the video stream and needs an audio container."""
if video_codec and video_codec != REMOVE_VIDEO and video_codec not in TRANSCODE_VIDEO_TARGETS:
raise ValueError(f'Cannot transcode video to {video_codec!r}; supported: {sorted(TRANSCODE_VIDEO_TARGETS)}')
if audio_codec and audio_codec not in TRANSCODE_AUDIO_TARGETS:
raise ValueError(f'Cannot transcode audio to {audio_codec!r}; supported: {sorted(TRANSCODE_AUDIO_TARGETS)}')
if container not in TRANSCODE_CONTAINERS:
raise ValueError(f'Unsupported container {container!r}; supported: {TRANSCODE_CONTAINERS}')
containers = TRANSCODE_CONTAINERS + TRANSCODE_AUDIO_CONTAINERS
if container not in containers:
raise ValueError(f'Unsupported container {container!r}; supported: {containers}')
if video_codec == REMOVE_VIDEO and container not in TRANSCODE_AUDIO_CONTAINERS:
raise ValueError(f'Removing the video needs an audio container ({TRANSCODE_AUDIO_CONTAINERS}), not {container}')
if container in TRANSCODE_AUDIO_CONTAINERS:
if video_codec and video_codec != REMOVE_VIDEO:
raise ValueError(f'A video stream cannot be stored in {container}; remove the video or choose a video container')
if audio_codec and audio_codec not in AUDIO_CONTAINER_CODECS[container]:
raise ValueError(f'{audio_codec} audio cannot be stored in {container}; '
f'it holds {sorted(AUDIO_CONTAINER_CODECS[container])}')
def retarget_file_group(file_group_id: int, old_path: pathlib.Path, new_path: pathlib.Path):

View file

@ -12,7 +12,7 @@ from wrolpi.errors import InvalidOrderBy, InvalidJob
from wrolpi.schema import JSONErrorResponse
from . import lib
from .. import schema
from ..transcode import transcode_video_job, validate_transcode_request
from ..transcode import transcode_video_job, validate_transcode_request, REMOVE_VIDEO
video_bp = Blueprint('Video', '/api/videos')
@ -85,8 +85,12 @@ async def video_transcode(_: Request, file_group_id: int, body: schema.VideoTran
raise InvalidJob(str(e))
# Raises UnknownVideo (404) before anything is queued.
video = lib.get_video(file_group_id)
is_audio = (video.file_group.mimetype or '').startswith('audio/')
if is_audio and body.video_codec and body.video_codec != REMOVE_VIDEO:
raise InvalidJob(f'This is an audio file; it has no video stream to transcode to {body.video_codec}')
action = 'Extract audio from' if body.video_codec == REMOVE_VIDEO and not is_audio else 'Transcode'
job_id = transcode_video_job.enqueue(
description=f'Transcode {video.video_path.name}',
description=f'{action} {video.video_path.name}',
file_group_id=file_group_id,
video_codec=body.video_codec,
audio_codec=body.audio_codec,