diff --git a/app/src/api.js b/app/src/api.js index c7894edb..b06ef557 100644 --- a/app/src/api.js +++ b/app/src/api.js @@ -249,9 +249,11 @@ export async function updateVideo(fileGroupId, {title, description}) { return data['file_group']; } -export async function transcodeVideo(fileGroupId, {video_codec = null, audio_codec = null, container = 'mp4'}) { +export async function transcodeVideo(fileGroupId, { + video_codec = null, audio_codec = null, container = 'mp4', fragmented = false, +}) { // Queues a transcode Job; returns the job id. Watch it with `getJob`. - const body = {video_codec, audio_codec, container}; + const body = {video_codec, audio_codec, container, fragmented}; const response = await apiPost(`${VIDEOS_API}/${fileGroupId}/transcode`, body); if (!response.ok) { const message = await getErrorMessage(response, 'Unable to queue the transcode. See server logs.'); diff --git a/app/src/components/VideoEditMenu.js b/app/src/components/VideoEditMenu.js index 9af0493e..ce9fd202 100644 --- a/app/src/components/VideoEditMenu.js +++ b/app/src/components/VideoEditMenu.js @@ -2,7 +2,8 @@ import React, {useEffect, useRef, useState} from 'react'; import {cancelJob, fetchVideoDownloadDefaults, getJob, transcodeVideo, updateVideo} from '../api'; import {useWROLMode} from '../hooks/customHooks'; import { - Button, Confirm, Group, Icon, Menu, Modal, Progress, Select, Stack, Status, Text, Textarea, TextInput, toast, + Button, Confirm, Group, Icon, Menu, Modal, Progress, Select, Stack, Status, Text, Textarea, TextInput, Toggle, + toast, } from './ui'; import { audioContainerForCodec, @@ -207,6 +208,7 @@ export function TranscodeModal({ const [videoCodec, setVideoCodec] = useState(TRANSCODE_COPY); const [audioCodec, setAudioCodec] = useState(TRANSCODE_COPY); const [container, setContainer] = useState('mp4'); + const [fragmented, setFragmented] = useState(false); const [defaultsLoaded, setDefaultsLoaded] = useState(false); const [submitting, setSubmitting] = useState(false); @@ -220,6 +222,7 @@ export function TranscodeModal({ return; } setDefaultsLoaded(false); + setFragmented(false); let stale = false; const load = async () => { let nextVideo = TRANSCODE_COPY; @@ -261,6 +264,8 @@ export function TranscodeModal({ const remuxOnly = !removeVideo && videoCodec === TRANSCODE_COPY && audioCodec === TRANSCODE_COPY; const sameContainer = container === currentContainer(video); const containerOptions = audioOutput ? transcodeAudioContainerOptions : transcodeContainerOptions; + // Fragments are an mp4 concept (m4a is an mp4). + const canFragment = container === 'mp4' || container === 'm4a'; const handleStart = async () => { setSubmitting(true); @@ -269,6 +274,7 @@ export function TranscodeModal({ video_codec: videoCodec === TRANSCODE_COPY ? null : videoCodec, audio_codec: audioCodec === TRANSCODE_COPY ? null : audioCodec, container, + fragmented: canFragment && fragmented, }); onQueued(id); } catch (e) { @@ -288,10 +294,14 @@ export function TranscodeModal({ + (audioCodec === TRANSCODE_COPY ? 'The audio is copied without re-encoding.' : `The audio is converted to ${audioCodec}.`); } else if (defaultsLoaded && remuxOnly) { const kept = audioOnly ? 'The audio is kept' : 'Both streams are kept'; - hint = sameContainer - ? `${kept}: the file is rewritten as-is` + (container === 'mp4' || container === 'm4a' - ? ' with fast start (moves the index to the front for quicker playback start).' : '.') - : `${kept}: only the container changes to ${container} (a quick remux, no quality loss).`; + if (sameContainer && canFragment && fragmented) { + hint = `${kept}: the file is rewritten as-is in fragments (a quick remux, no quality loss).`; + } else if (sameContainer) { + hint = `${kept}: the file is rewritten as-is` + (canFragment + ? ' with fast start (moves the index to the front for quicker playback start).' : '.'); + } else { + hint = `${kept}: only the container changes to ${container} (a quick remux, no quality loss).`; + } } const buttonLabel = removeVideo ? 'Extract Audio' : remuxOnly ? 'Remux' : 'Transcode'; @@ -331,6 +341,15 @@ export function TranscodeModal({ disabled={!defaultsLoaded} allowDeselect={false} /> + {canFragment && setFragmented(e.currentTarget.checked)} + disabled={!defaultsLoaded} + info='Splits the index into fragments instead of one block at the front. A video many + hours long then starts and seeks quickly on phones, which otherwise must download the + whole index first.' + />} {hint && {hint}} } {showJob && } diff --git a/app/src/components/VideoEditMenu.test.js b/app/src/components/VideoEditMenu.test.js index 6351d634..c74c4c59 100644 --- a/app/src/components/VideoEditMenu.test.js +++ b/app/src/components/VideoEditMenu.test.js @@ -115,7 +115,7 @@ describe('TranscodeModal', () => { fireEvent.click(screen.getByRole('button', {name: /Transcode/})); await waitFor(() => expect(transcodeVideo).toHaveBeenCalledWith(7, { - video_codec: 'h264', audio_codec: 'aac', container: 'mp4', + video_codec: 'h264', audio_codec: 'aac', container: 'mp4', fragmented: false, })); await waitFor(() => expect(onQueued).toHaveBeenCalledWith('transcode_video-abc')); }); @@ -145,10 +145,38 @@ describe('TranscodeModal', () => { expect(button).toBeEnabled(); fireEvent.click(button); await waitFor(() => expect(transcodeVideo).toHaveBeenCalledWith(7, { - video_codec: null, audio_codec: null, container: 'mp4', + video_codec: null, audio_codec: null, container: 'mp4', fragmented: false, })); }); + test('Fragmented is offered for mp4 and sent with the request', async () => { + fetchVideoDownloadDefaults.mockResolvedValue({video_codecs: [], audio_codecs: []}); + const mp4 = {...video, video_path: 'videos/movie.mp4'}; + renderWithProviders( + , + ); + await waitFor(() => expect(selectInput('Container')).toHaveValue('mp4')); + const toggle = screen.getByRole('switch', {name: /Fragmented/}); + expect(toggle).not.toBeChecked(); + + fireEvent.click(toggle); + expect(await screen.findByText(/rewritten as-is in fragments/)).toBeInTheDocument(); + expect(screen.queryByText(/fast start/)).not.toBeInTheDocument(); + + fireEvent.click(screen.getByRole('button', {name: 'Remux'})); + await waitFor(() => expect(transcodeVideo).toHaveBeenCalledWith(7, { + video_codec: null, audio_codec: null, container: 'mp4', fragmented: true, + })); + }); + + test('Fragmented is not offered for mkv', async () => { + fetchVideoDownloadDefaults.mockResolvedValue({video_codecs: [], audio_codecs: []}); + const mkv = {...video, video_path: 'videos/movie.mkv'}; + renderWithProviders(); + await waitFor(() => expect(selectInput('Container')).toHaveValue('mkv')); + expect(screen.queryByRole('switch', {name: /Fragmented/})).not.toBeInTheDocument(); + }); + test('a remux into the same container is described as a fast-start rewrite', async () => { fetchVideoDownloadDefaults.mockResolvedValue({video_codecs: [], audio_codecs: []}); const mkv = {...video, video_path: 'videos/movie.mkv'}; @@ -180,7 +208,7 @@ describe('TranscodeModal', () => { 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', + video_codec: null, audio_codec: null, container: 'm4a', fragmented: false, })); }); diff --git a/modules/videos/schema.py b/modules/videos/schema.py index bc09da8e..7296d8db 100644 --- a/modules/videos/schema.py +++ b/modules/videos/schema.py @@ -198,6 +198,7 @@ class VideoTranscodeRequest: video_codec: Optional[str] = None # A key of TRANSCODE_VIDEO_TARGETS, or None to copy the stream. audio_codec: Optional[str] = None # A key of TRANSCODE_AUDIO_TARGETS, or None to copy the stream. container: str = 'mp4' + fragmented: bool = False # Fragmented mp4: quick start/seek for very long videos (mp4/m4a only). @dataclass diff --git a/modules/videos/test/test_transcode.py b/modules/videos/test/test_transcode.py index 43a28410..24601e0b 100644 --- a/modules/videos/test/test_transcode.py +++ b/modules/videos/test/test_transcode.py @@ -7,7 +7,7 @@ import pytest from modules.videos.transcode import codecs_match, get_stream_codec_names, get_transcode_target, \ transcode_can_satisfy_codecs, transcode_video_file, TRANSCODE_VIDEO_TARGETS, TRANSCODE_AUDIO_TARGETS, \ - verify_transcode_output + verify_transcode_output, validate_transcode_request, REMOVE_VIDEO, FRAGMENT_DURATION_US from wrolpi.cmd import CommandResult @@ -421,3 +421,56 @@ async def test_transcode_video_file_cancel_removes_tmp(test_directory, async_cli assert video_path.read_bytes() == b'fake video data' assert not (test_directory / 'video.transcode.mp4').exists(), 'The partial output must be removed' + + +@pytest.mark.asyncio +async def test_transcode_video_file_fragmented(test_directory, async_client, mock_probe): + """`fragmented=True` writes a fragmented mp4: a tiny moov, a global seek index, and fragments + at keyframes instead of fast start. Very long videos then start and seek quickly on phones.""" + video_path = test_directory / 'video.mp4' + video_path.write_bytes(b'fake video data') + mock_probe.output = make_probe('vp9', 'opus', 10.0, MP4) # A remux: both streams copied. + + async def fake_run_command(cmd, **kwargs): + if cmd[-1] != '-': + pathlib.Path(cmd[-1]).write_bytes(b'fragmented data') + return CommandResult(return_code=0, cancelled=False, stdout=b'', stderr=b'', elapsed=1) + + with mock.patch('modules.videos.transcode.run_command', side_effect=fake_run_command) as mock_run: + result = await transcode_video_file(video_path, container='mp4', fragmented=True) + + assert result == video_path + cmd = mock_run.call_args_list[0][0][0] + flags = cmd[cmd.index('-movflags') + 1] + for flag in ('frag_keyframe', 'empty_moov', 'default_base_moof', 'global_sidx'): + assert flag in flags, flags + assert 'faststart' not in flags + assert cmd[cmd.index('-frag_duration') + 1] == str(FRAGMENT_DURATION_US) + + +@pytest.mark.asyncio +async def test_transcode_video_file_fragmented_only_mp4(test_directory, async_client, mock_probe): + """Fragments are an mp4 concept; for another container the flag is ignored.""" + video_path = test_directory / 'video.mp4' + video_path.write_bytes(b'fake video data') + mock_probe.output = make_probe('vp9', 'opus', 10.0, 'matroska,webm') + + async def fake_run_command(cmd, **kwargs): + if cmd[-1] != '-': + pathlib.Path(cmd[-1]).write_bytes(b'data') + return CommandResult(return_code=0, cancelled=False, stdout=b'', stderr=b'', elapsed=1) + + with mock.patch('modules.videos.transcode.run_command', side_effect=fake_run_command) as mock_run: + await transcode_video_file(video_path, container='mkv', fragmented=True) + + cmd = mock_run.call_args_list[0][0][0] + assert '-movflags' not in cmd and '-frag_duration' not in cmd + + +def test_validate_fragmented_needs_mp4(): + validate_transcode_request(None, None, 'mp4', fragmented=True) + validate_transcode_request(REMOVE_VIDEO, None, 'm4a', fragmented=True) # m4a is an mp4. + with pytest.raises(ValueError, match='mp4'): + validate_transcode_request(None, None, 'mkv', fragmented=True) + with pytest.raises(ValueError, match='mp4'): + validate_transcode_request(REMOVE_VIDEO, 'mp3', 'mp3', fragmented=True) diff --git a/modules/videos/test/test_transcode_job.py b/modules/videos/test/test_transcode_job.py index eb775c3c..d773f9a5 100644 --- a/modules/videos/test/test_transcode_job.py +++ b/modules/videos/test/test_transcode_job.py @@ -170,7 +170,7 @@ async def test_video_transcode_api(async_client, test_session, video_factory, wr assert record['name'] == 'transcode_video' assert record['description'] == f'Transcode {video.video_path.name}' assert record['kwargs'] == {'file_group_id': video.file_group_id, 'video_codec': 'h264', - 'audio_codec': 'aac', 'container': 'mp4'} + 'audio_codec': 'aac', 'container': 'mp4', 'fragmented': False} # Do not run it (ffmpeg); cancel instead. jobs.cancel_job(job_id) @@ -179,7 +179,7 @@ async def test_video_transcode_api(async_client, test_session, video_factory, wr content=json.dumps({'container': 'mkv'})) assert response.status == 200, response.json assert jobs.get_job(response.json['job_id'])['kwargs'] == { - 'file_group_id': video.file_group_id, 'video_codec': None, 'audio_codec': None, 'container': 'mkv'} + 'file_group_id': video.file_group_id, 'video_codec': None, 'audio_codec': None, 'container': 'mkv', 'fragmented': False} jobs.cancel_job(response.json['job_id']) # WROL mode forbids modifying files. @@ -275,3 +275,21 @@ async def test_transcode_video_file_keep_original(test_directory, async_client): assert result == test_directory / 'video.mp4' and result.is_file() assert video_path.read_bytes() == b'fake video data', 'The original is kept' + + +@pytest.mark.asyncio +async def test_video_transcode_api_fragmented(async_client, test_session, video_factory): + """`fragmented` reaches the Job; it needs an mp4 container.""" + video = video_factory() + test_session.commit() + request, response = await async_client.post(f'/api/videos/{video.file_group_id}/transcode', + content=json.dumps({'container': 'mp4', 'fragmented': True})) + assert response.status == 200, response.json + record = jobs.get_job(response.json['job_id']) + assert record['kwargs']['fragmented'] is True + assert record['description'].startswith('Remux') + jobs.cancel_job(response.json['job_id']) + + request, response = await async_client.post(f'/api/videos/{video.file_group_id}/transcode', + content=json.dumps({'container': 'mkv', 'fragmented': True})) + assert response.status == 400 diff --git a/modules/videos/transcode.py b/modules/videos/transcode.py index 97941daf..701c2440 100644 --- a/modules/videos/transcode.py +++ b/modules/videos/transcode.py @@ -61,6 +61,11 @@ REMOVE_VIDEO = 'none' 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') +# Fragmented mp4 (`fragmented=True`): a tiny moov plus a global seek index, samples described per +# fragment. A very long video's whole-file index can reach tens of MB, which a phone must fetch +# and parse before the first frame; fragments make it start and seek quickly. mp4/m4a only. +FRAGMENTED_MOVFLAGS = '+frag_keyframe+empty_moov+default_base_moof+global_sidx' +FRAGMENT_DURATION_US = 10_000_000 def default_audio_container(codec: Optional[str]) -> str: @@ -149,7 +154,8 @@ async def transcode_video_file(video_path: pathlib.Path, target_acodec: Optional[str] = None, container: str = 'mp4', duration: Optional[float] = None, - keep_original: bool = False) -> pathlib.Path: + keep_original: bool = False, + fragmented: bool = False) -> pathlib.Path: """Transcode a video file in place (same stem, possibly a new container extension). Only one transcode runs at a time machine-wide (across all Sanic workers); this call waits @@ -174,7 +180,7 @@ async def transcode_video_file(video_path: pathlib.Path, lock = await _acquire_transcode_lock() try: return await _transcode_video_file(video_path, target_vcodec, target_acodec, container, duration, - keep_original) + keep_original, fragmented) finally: lock.release() @@ -316,7 +322,8 @@ def resolve_output(source_probe: dict, target_vcodec: Optional[str], target_acod 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: + duration: Optional[float] = None, keep_original: bool = False, + fragmented: bool = False) -> pathlib.Path: """The ffmpeg work of `transcode_video_file`; the caller holds the transcode lock.""" # Notify here, after the lock: the wait for another transcode can last hours, and the user # should hear "Transcoding" only when this file's work actually begins. @@ -348,7 +355,12 @@ async def _transcode_video_file(video_path: pathlib.Path, target_vcodec: Optiona # 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 () + if container in FASTSTART_CONTAINERS and fragmented: + mux_args = ('-movflags', FRAGMENTED_MOVFLAGS, '-frag_duration', str(FRAGMENT_DURATION_US)) + elif container in FASTSTART_CONTAINERS: + mux_args = ('-movflags', '+faststart') + else: + mux_args = () final_path = video_path.with_suffix(f'.{container}') tmp_path = video_path.with_suffix(f'.transcode.{container}') @@ -357,7 +369,7 @@ async def _transcode_video_file(video_path: pathlib.Path, target_vcodec: Optiona *map_args, *video_args, *audio_args, - *faststart_args, + *mux_args, # Machine-readable progress on stdout (the human progress line is suppressed). '-nostats', '-progress', 'pipe:1', str(tmp_path)) @@ -414,9 +426,11 @@ async def _transcode_video_file(video_path: pathlib.Path, target_vcodec: Optiona return final_path -def validate_transcode_request(video_codec: Optional[str], audio_codec: Optional[str], container: str): +def validate_transcode_request(video_codec: Optional[str], audio_codec: Optional[str], container: str, + fragmented: bool = False): """@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.""" + `video_codec=REMOVE_VIDEO` drops the video stream and needs an audio container; `fragmented` + needs an mp4 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: @@ -424,6 +438,8 @@ def validate_transcode_request(video_codec: Optional[str], audio_codec: Optional containers = TRANSCODE_CONTAINERS + TRANSCODE_AUDIO_CONTAINERS if container not in containers: raise ValueError(f'Unsupported container {container!r}; supported: {containers}') + if fragmented and container not in FASTSTART_CONTAINERS: + raise ValueError(f'A fragmented file must be mp4 (or m4a), not {container}') 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: @@ -457,7 +473,8 @@ def retarget_file_group(file_group_id: int, old_path: pathlib.Path, new_path: pa @register_job('transcode_video') async def transcode_video_job(file_group_id: int, video_codec: Optional[str] = None, - audio_codec: Optional[str] = None, container: str = 'mp4') -> dict: + audio_codec: Optional[str] = None, container: str = 'mp4', + fragmented: bool = False) -> dict: """Transcode a Video's file, then re-index it so the FileGroup reflects the new file. Run as a Job (`transcode_video_job.enqueue(...)`) so the user can watch and cancel it.""" @@ -468,7 +485,7 @@ async def transcode_video_job(file_group_id: int, video_codec: Optional[str] = N if wrol_mode_enabled(): raise RuntimeError('Cannot transcode while WROL Mode is enabled') - validate_transcode_request(video_codec, audio_codec, container) + validate_transcode_request(video_codec, audio_codec, container, fragmented) with get_db_session() as session: video = Video.find_by_file_group_id(session, file_group_id) @@ -479,7 +496,7 @@ async def transcode_video_job(file_group_id: int, video_codec: Optional[str] = N # The original is kept until the database points at the new file (below). final_path = await transcode_video_file(video_path, video_codec, audio_codec, container, duration=duration, - keep_original=True) + keep_original=True, fragmented=fragmented) # Point the existing FileGroup at the new file *before* deleting the original and *before* # refreshing. A crash after the delete would leave the database pointing at a missing file; diff --git a/modules/videos/video/api.py b/modules/videos/video/api.py index 1f860647..c1ca769c 100644 --- a/modules/videos/video/api.py +++ b/modules/videos/video/api.py @@ -80,7 +80,7 @@ def video_get_captions(_: Request, file_group_id: int): @wrol_mode_check async def video_transcode(_: Request, file_group_id: int, body: schema.VideoTranscodeRequest): try: - validate_transcode_request(body.video_codec, body.audio_codec, body.container) + validate_transcode_request(body.video_codec, body.audio_codec, body.container, body.fragmented) except ValueError as e: raise InvalidJob(str(e)) # Raises UnknownVideo (404) before anything is queued. @@ -88,13 +88,19 @@ async def video_transcode(_: Request, file_group_id: int, body: schema.VideoTran 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' + if body.video_codec == REMOVE_VIDEO and not is_audio: + action = 'Extract audio from' + elif not body.video_codec and not body.audio_codec: + action = 'Remux' + else: + action = 'Transcode' job_id = transcode_video_job.enqueue( description=f'{action} {video.video_path.name}', file_group_id=file_group_id, video_codec=body.video_codec, audio_codec=body.audio_codec, container=body.container, + fragmented=body.fragmented, ) return json_response({'job_id': job_id})