offset audio after playback and add songs

This commit is contained in:
Thomas Demirdjian
2026-03-12 10:58:43 +01:00
parent fd299e8543
commit ebdf9862a7
25 changed files with 4794 additions and 449 deletions
+1 -1
View File
@@ -92,7 +92,7 @@ android {
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 1
versionName "2026.03.02"
versionName "2026.03.12"
}
signingConfigs {
debug {
+1 -1
View File
@@ -11,7 +11,7 @@
"deeplinks": [
"musicland://"
],
"version": "2026.03.02",
"version": "2026.03.12",
"icon": "./assets/icon.png",
"backgroundColor": "#0F0C14",
"jsEngine": "hermes",
+3587
View File
File diff suppressed because it is too large Load Diff
+63 -80
View File
@@ -1,5 +1,3 @@
// functions/mergeVideoAndAudio.js (ou dans index.js)
const { onCall, HttpsError } = require('firebase-functions/v2/https')
const admin = require('firebase-admin')
const logger = require('firebase-functions/logger')
@@ -19,33 +17,50 @@ ffmpeg.setFfmpegPath(ffmpegInstaller.path)
const db = admin.firestore()
const PLAYBACK_CODEC_TAG = 'h264-v1'
const MAX_SYNC_OFFSET_SECONDS = 2
const SCALE_FILTER =
"scale='trunc(min(1920,iw)/2)*2':'trunc(min(1920,ih)/2)*2':force_original_aspect_ratio=decrease"
const toFiniteNumber = (value) => {
const numericValue = Number(value ?? 0)
return Number.isFinite(numericValue) ? numericValue : 0
}
const clampSyncOffsetSeconds = (value) => {
const safeValue = toFiniteNumber(value)
return Math.min(MAX_SYNC_OFFSET_SECONDS, Math.max(-MAX_SYNC_OFFSET_SECONDS, safeValue))
}
const formatSecondsForFfmpeg = (value) => clampSyncOffsetSeconds(value).toFixed(3)
async function downloadToFile(url, destPath) {
if (!/^https?:\/\//i.test(url || '')) {
throw new HttpsError('invalid-argument', `URL non supportée: ${url}`)
}
const res = await axios.get(url, { responseType: 'arraybuffer' })
await fs.writeFile(destPath, Buffer.from(res.data))
return res.headers?.['content-type'] || ''
}
const SCALE_FILTER =
"scale='trunc(min(1920,iw)/2)*2':'trunc(min(1920,ih)/2)*2':force_original_aspect_ratio=decrease"
// functions/mergeVideoAndAudio.js
async function muxAudioIntoVideo({ videoPath, audioPath, outPath, syncOffset = 0 }) {
const safeSyncOffset = clampSyncOffsetSeconds(syncOffset)
const videoTrimSeconds = safeSyncOffset > 0 ? safeSyncOffset : 0
const audioTrimSeconds = safeSyncOffset < 0 ? Math.abs(safeSyncOffset) : 0
return new Promise((resolve, reject) => {
let command = ffmpeg()
const command = ffmpeg()
// L'offset : si > 0, on retarde la vidéo. Si < 0, on retarde l'audio.
if (syncOffset > 0) command.inputOptions(['-itsoffset', String(syncOffset)])
command.input(videoPath)
if (videoTrimSeconds > 0) {
command.inputOptions(['-ss', formatSecondsForFfmpeg(videoTrimSeconds)])
}
if (syncOffset < 0) command.inputOptions(['-itsoffset', String(Math.abs(syncOffset))])
command.input(audioPath)
if (audioTrimSeconds > 0) {
command.inputOptions(['-ss', formatSecondsForFfmpeg(audioTrimSeconds)])
}
// Remplace le bloc .save(outPath) par celui-ci :
command
.outputOptions([
'-map',
@@ -70,16 +85,20 @@ async function muxAudioIntoVideo({ videoPath, audioPath, outPath, syncOffset = 0
'+faststart',
'-shortest',
])
.on('error', (err) => {
console.error('FFmpeg Error:', err)
reject(err)
.on('error', (error) => {
logger.error('FFmpeg Error', { error: error?.message || String(error) })
reject(error)
})
.on('end', () => {
console.log('Processing finished !')
logger.info('FFmpeg processing finished', {
syncOffset: safeSyncOffset,
videoTrimSeconds,
audioTrimSeconds,
})
resolve()
})
.output(outPath) // On définit la sortie ici
.run() // Et on lance l'exécution ici
.output(outPath)
.run()
})
}
@@ -88,6 +107,7 @@ async function uploadPlaybackAsset({ videoUrl, audioUrl, storagePath, syncOffset
const videoPath = path.join(tmpDir, 'video.mp4')
const audioPath = path.join(tmpDir, 'audio.mp3')
const outPath = path.join(tmpDir, 'output.mp4')
const safeSyncOffset = clampSyncOffsetSeconds(syncOffset)
try {
logger.info('[merge] téléchargement des sources', { videoUrl, audioUrl })
@@ -95,8 +115,12 @@ async function uploadPlaybackAsset({ videoUrl, audioUrl, storagePath, syncOffset
await downloadToFile(videoUrl, videoPath)
await downloadToFile(audioUrl, audioPath)
logger.info('[merge] transcodage/mux ffmpeg', { syncOffset })
await muxAudioIntoVideo({ videoPath, audioPath, outPath, syncOffset })
logger.info('[merge] transcodage/mux ffmpeg', {
syncOffset: safeSyncOffset,
videoTrimSeconds: safeSyncOffset > 0 ? safeSyncOffset : 0,
audioTrimSeconds: safeSyncOffset < 0 ? Math.abs(safeSyncOffset) : 0,
})
await muxAudioIntoVideo({ videoPath, audioPath, outPath, syncOffset: safeSyncOffset })
const bucket = admin.storage().bucket()
const downloadToken = crypto.randomUUID()
@@ -122,10 +146,10 @@ async function uploadPlaybackAsset({ videoUrl, audioUrl, storagePath, syncOffset
contentType: 'video/mp4',
storagePath,
}
} catch (err) {
logger.error('[merge] échec', { error: err?.message || String(err) })
if (err instanceof HttpsError) throw err
throw new HttpsError('internal', err?.message || 'Fusion échouée')
} catch (error) {
logger.error('[merge] échec', { error: error?.message || String(error) })
if (error instanceof HttpsError) throw error
throw new HttpsError('internal', error?.message || 'Fusion échouée')
} finally {
await fs.rm(tmpDir, { recursive: true, force: true })
}
@@ -133,6 +157,7 @@ async function uploadPlaybackAsset({ videoUrl, audioUrl, storagePath, syncOffset
async function markPlaybackCompatibility({ projectId, initiatorUid = null }) {
if (!projectId) return
const docRef = db.collection('projects').doc(projectId)
await docRef.set(
{
@@ -163,72 +188,26 @@ exports.mergeVideoAndAudio = onCall(
throw new HttpsError('permission-denied', `storagePath doit commencer par ${expectedPrefix}`)
}
const result = await uploadPlaybackAsset({ videoUrl, audioUrl, storagePath, syncOffset })
if (projectId) {
await markPlaybackCompatibility({ projectId, initiatorUid: uid })
}
return result
}
)
/**
* Fusionne une vidéo et un audio avec correction de synchronisation.
* Gère les paramètres : videoUrl, audioUrl, storagePath, projectId, syncOffset
*/
exports.mergeVideoAndAudio = onCall(
{ region: REGION, timeoutSeconds: 540, memory: '1GiB' },
async (request) => {
// Dans v2, les arguments sont dans request.data
const { data, auth } = request;
const uid = auth?.uid;
logger.info('[merge] request received', {
projectId: projectId || null,
initiator: uid,
syncOffset: clampSyncOffsetSeconds(syncOffset),
})
if (!uid) {
throw new HttpsError('unauthenticated', 'Authentification requise');
}
const { videoUrl, audioUrl, storagePath, projectId, syncOffset } = data || {};
// 1. Validation des paramètres
if (!videoUrl || !audioUrl || !storagePath) {
throw new HttpsError(
'invalid-argument',
'Paramètres manquants : videoUrl, audioUrl et storagePath sont requis.'
);
}
// 2. Sécurité : Vérifier que l'utilisateur écrit dans son propre dossier
const expectedPrefix = `users/${uid}/`;
if (!storagePath.startsWith(expectedPrefix)) {
throw new HttpsError(
'permission-denied',
`Accès refusé : le chemin doit commencer par ${expectedPrefix}`
);
}
try {
logger.info(`[merge] Début du traitement pour le projet : ${projectId || 'inconnu'}`);
// 3. Appel de la logique de traitement (download -> ffmpeg -> upload)
// On passe le syncOffset s'il existe (ex: -0.150 pour 150ms de latence)
const result = await uploadPlaybackAsset({
videoUrl,
audioUrl,
storagePath,
syncOffset: syncOffset || 0
});
syncOffset: clampSyncOffsetSeconds(syncOffset),
})
// 4. Marquer la compatibilité dans Firestore si un ID de projet est fourni
if (projectId) {
await markPlaybackCompatibility({ projectId, initiatorUid: uid });
await markPlaybackCompatibility({ projectId, initiatorUid: uid })
}
return result;
} catch (error) {
logger.error('[merge] Erreur fatale lors de la fusion', error);
if (error instanceof HttpsError) throw error;
throw new HttpsError('internal', error.message || 'Erreur interne de fusion');
return result
}
}
);
)
exports.reencodePlayback = onCall(
{ region: REGION, timeoutSeconds: 540, memory: '1GiB' },
@@ -245,6 +224,7 @@ exports.reencodePlayback = onCall(
projectId,
initiator: uid,
})
const projectRef = db.collection('projects').doc(projectId)
const projectSnap = await projectRef.get()
if (!projectSnap.exists) {
@@ -254,6 +234,7 @@ exports.reencodePlayback = onCall(
})
throw new HttpsError('not-found', 'Projet introuvable')
}
const project = projectSnap.data() || {}
const videoUrl = project.playbackUrl
const audioUrl = project.songUrl
@@ -279,12 +260,14 @@ exports.reencodePlayback = onCall(
},
{ merge: true }
)
await markPlaybackCompatibility({ projectId, initiatorUid: uid })
logger.info('[reencodePlayback] success', {
projectId,
initiator: uid,
storagePath,
})
return result
}
)
+8
View File
@@ -122,6 +122,14 @@
},
"private": true,
"expo": {
"autolinking": {
"android": {
"exclude": [
"expo-minuit-shake-report",
"expo-sensors"
]
}
},
"doctor": {
"reactNativeDirectoryCheck": {
"exclude": [
+7 -2
View File
@@ -15,6 +15,7 @@ export default ({
maxValue,
progress,
onSeek,
onValueChange,
onSeekStart,
onSeekEnd,
seekEnabled = false,
@@ -42,9 +43,13 @@ export default ({
const handleValueChange = useCallback(
(nextValue) => {
if (!seekEnabled) return
setSliderValue(clamp01(nextValue))
const ratio = clamp01(nextValue)
setSliderValue(ratio)
if (typeof onValueChange === 'function') {
onValueChange(ratio)
}
},
[seekEnabled]
[onValueChange, seekEnabled]
)
const handleSlidingComplete = useCallback(
+13 -5
View File
@@ -14,6 +14,7 @@ const Slider = ({
maxValue,
progress,
onSeek,
onValueChange,
onSeekStart,
onSeekEnd,
seekEnabled = false,
@@ -34,11 +35,12 @@ const Slider = ({
const available = Math.max(layoutWidth - INITIAL_BOX_SIZE, 0)
if (available <= 0) {
setRatio(0)
return
return 0
}
const clampedX = Math.min(Math.max(x, 0), layoutWidth)
const nextRatio = clamp01(clampedX / available)
setRatio(nextRatio)
return nextRatio
},
[layoutWidth]
)
@@ -47,20 +49,26 @@ const Slider = ({
(event) => {
if (!seekEnabled) return
draggingRef.current = true
updateRatioFromX(event?.nativeEvent?.locationX || 0)
const nextRatio = updateRatioFromX(event?.nativeEvent?.locationX || 0)
if (typeof nextRatio === 'number' && typeof onValueChange === 'function') {
onValueChange(nextRatio)
}
if (typeof onSeekStart === 'function') {
onSeekStart()
}
},
[seekEnabled, updateRatioFromX, onSeekStart]
[seekEnabled, updateRatioFromX, onSeekStart, onValueChange]
)
const handleMove = useCallback(
(event) => {
if (!seekEnabled || !draggingRef.current) return
updateRatioFromX(event?.nativeEvent?.locationX || 0)
const nextRatio = updateRatioFromX(event?.nativeEvent?.locationX || 0)
if (typeof nextRatio === 'number' && typeof onValueChange === 'function') {
onValueChange(nextRatio)
}
},
[seekEnabled, updateRatioFromX]
[seekEnabled, updateRatioFromX, onValueChange]
)
const finishSeeking = useCallback(() => {
@@ -0,0 +1,314 @@
import { Image as ExpoImage } from 'expo-image'
import React, { useCallback, useEffect, useMemo, useState } from 'react'
import { Image, Pressable, ScrollView, StyleSheet, Text, View } from 'react-native'
import { SheetManager } from 'react-native-actions-sheet'
import useMinuit from 'react-native-minuit/src/hooks/useMinuit'
import { icons, img } from '../../assets'
import usePlaylistMusicSearch from '../../hooks/usePlaylistMusicSearch'
import { isWeb } from '../../hooks/useLayoutType'
import { addMusicToPlaylist } from '../../screens/Library/Playlists/playlist'
import { Palette, Style } from '../../styles'
import { FONT_FAMILY } from '../../styles/Fonts'
import { size } from '../../styles/Style'
import AppActionSheet from '../AppActionSheet'
import SearchBar from '../SearchBar'
const SHEET_ID = 'PlaylistAddTracks'
const resolveCoverUri = (project) => {
const isValid = (value) => typeof value === 'string' && value.trim().length > 0
if (!project) {
return null
}
if (isValid(project?.coverUrl)) {
return project.coverUrl
}
const cover = project?.cover
if (!cover || typeof cover !== 'object') {
return null
}
const coverCandidates = [cover?.result, cover?.finalUrl, cover?.generatedBackground]
if (Array.isArray(cover?.options)) {
coverCandidates.push(
...cover.options.flatMap((option) => [option?.finalUrl, option?.generatedUrl])
)
}
return coverCandidates.find(isValid) || null
}
const PlaylistAddTracksModal = (props) => {
const { setTooltip } = useMinuit()
const { search, setSearch, musics = [], loading, hasSearch } = usePlaylistMusicSearch()
const [addedMusicIds, setAddedMusicIds] = useState([])
const [pendingMusicIds, setPendingMusicIds] = useState([])
const [webVisible, setWebVisible] = useState(true)
const playlistId = props?.payload?.playlistId
const existingMusicIds = useMemo(() => {
if (!Array.isArray(props?.payload?.existingMusicIds)) {
return []
}
return props.payload.existingMusicIds.filter((item) => typeof item === 'string')
}, [props?.payload?.existingMusicIds])
const addedMusicIdSet = useMemo(() => new Set(addedMusicIds), [addedMusicIds])
const pendingMusicIdSet = useMemo(() => new Set(pendingMusicIds), [pendingMusicIds])
const existingMusicIdSet = useMemo(() => new Set(existingMusicIds), [existingMusicIds])
useEffect(() => {
setWebVisible(true)
setSearch('')
setAddedMusicIds([])
setPendingMusicIds([])
}, [props?.payload, setSearch])
const hideSheet = useCallback(() => {
if (isWeb) {
setWebVisible(false)
}
try {
return Promise.resolve(SheetManager.hide(SHEET_ID))
} catch (error) {
console.error('[PlaylistAddTracks] hide error', error?.message || error)
return Promise.resolve()
}
}, [])
const handleAddTrack = useCallback(
async (project) => {
const projectId = project?.id
if (typeof playlistId !== 'string' || typeof projectId !== 'string') {
return
}
if (existingMusicIdSet.has(projectId) || addedMusicIdSet.has(projectId)) {
return
}
if (pendingMusicIdSet.has(projectId)) {
return
}
setPendingMusicIds((previous) => [...previous, projectId])
try {
await addMusicToPlaylist({ playlistId, projectId })
setAddedMusicIds((previous) =>
previous.includes(projectId) ? previous : [...previous, projectId]
)
setTooltip({
type: 'success',
text: 'Morceau ajouté à la playlist',
})
} catch (error) {
console.log('PlaylistAddTracksModal add track error', error?.message || error)
setTooltip({
type: 'error',
text: error?.message || 'Ajout impossible',
})
} finally {
setPendingMusicIds((previous) => previous.filter((item) => item !== projectId))
}
},
[addedMusicIdSet, existingMusicIdSet, pendingMusicIdSet, playlistId, setTooltip]
)
if (isWeb && !webVisible) {
return null
}
return (
<AppActionSheet id={SHEET_ID} webModal={isWeb} onClose={hideSheet}>
<View style={styles.container}>
<View style={styles.headerRow}>
<View style={{ flex: 1, gap: 6 }}>
<Text style={styles.title}>Ajouter des morceaux</Text>
<Text style={styles.description}>
Recherche un morceau puis ajoute-le directement dans cette playlist.
</Text>
</View>
<Pressable onPress={hideSheet} hitSlop={12} style={styles.closeButton}>
<Image source={icons.close} style={size({ size: 16 })} resizeMode="contain" />
</Pressable>
</View>
<SearchBar
placeholder="Rechercher un morceau"
textInputProps={{
value: search,
onChangeText: setSearch,
autoFocus: true,
autoCorrect: false,
autoCapitalize: 'none',
}}
/>
<ScrollView
style={styles.resultsContainer}
contentContainerStyle={styles.resultsContent}
keyboardShouldPersistTaps="handled"
showsVerticalScrollIndicator={false}
>
{!hasSearch ? (
<Text style={styles.emptyText}>Commence par rechercher un titre ou un artiste.</Text>
) : null}
{hasSearch && loading ? <Text style={styles.emptyText}>Chargement</Text> : null}
{hasSearch && !loading && musics.length === 0 ? (
<Text style={styles.emptyText}>Aucun morceau trouvé.</Text>
) : null}
{hasSearch &&
musics.map((music) => {
const projectId = music?.id
const isExisting = typeof projectId === 'string' && existingMusicIdSet.has(projectId)
const isAdded = typeof projectId === 'string' && addedMusicIdSet.has(projectId)
const isPending = typeof projectId === 'string' && pendingMusicIdSet.has(projectId)
const isDisabled = isExisting || isAdded || isPending
const coverUri = resolveCoverUri(music)
return (
<View key={projectId || music?.objectID} style={styles.resultCard}>
{coverUri ? (
<ExpoImage
source={{ uri: coverUri }}
cachePolicy="memory-disk"
priority="high"
contentFit="cover"
transition={100}
style={styles.cover}
/>
) : (
<Image source={img.placeholder} style={styles.cover} resizeMode="cover" />
)}
<View style={styles.resultTextContainer}>
<Text numberOfLines={2} style={styles.resultTitle}>
{music?.title || 'Sans titre'}
</Text>
<Text numberOfLines={1} style={styles.resultSubtitle}>
{music?.userName || 'MusicLand'}
</Text>
</View>
<Pressable
onPress={() => handleAddTrack(music)}
disabled={isDisabled}
style={[
styles.actionButton,
isDisabled ? styles.actionButtonDisabled : styles.actionButtonEnabled,
]}
>
<Text style={styles.actionButtonText}>
{isPending ? 'Ajout...' : isDisabled ? 'Ajouté' : 'Ajouter'}
</Text>
</Pressable>
</View>
)
})}
</ScrollView>
</View>
</AppActionSheet>
)
}
export default PlaylistAddTracksModal
const styles = StyleSheet.create({
container: {
gap: 18,
},
headerRow: {
...Style.containerRow,
alignItems: 'flex-start',
gap: 12,
},
title: {
fontSize: 22,
color: Palette.white,
fontFamily: FONT_FAMILY.InterSemiBold,
},
description: {
fontSize: 14,
lineHeight: 20,
color: Palette.white,
opacity: 0.82,
fontFamily: FONT_FAMILY.InterRegular,
},
closeButton: {
width: 32,
height: 32,
borderRadius: 16,
backgroundColor: Palette.ultraLightWhite,
...Style.containerCenter,
},
resultsContainer: {
maxHeight: 420,
},
resultsContent: {
gap: 10,
paddingVertical: 2,
},
emptyText: {
textAlign: 'center',
color: Palette.white,
opacity: 0.82,
fontSize: 14,
lineHeight: 20,
fontFamily: FONT_FAMILY.InterRegular,
paddingVertical: 24,
},
resultCard: {
...Style.containerRow,
gap: 12,
padding: 12,
borderRadius: 16,
backgroundColor: Palette.ultraLightWhite,
alignItems: 'center',
},
cover: {
width: 56,
height: 56,
borderRadius: 14,
},
resultTextContainer: {
flex: 1,
gap: 4,
},
resultTitle: {
fontSize: 16,
lineHeight: 18,
color: Palette.white,
fontFamily: FONT_FAMILY.OwnersRegular,
},
resultSubtitle: {
fontSize: 12,
color: Palette.white,
opacity: 0.85,
fontFamily: FONT_FAMILY.InterRegular,
},
actionButton: {
minWidth: 88,
height: 38,
borderRadius: 12,
paddingHorizontal: 14,
...Style.containerCenter,
},
actionButtonEnabled: {
backgroundColor: '#F94697',
},
actionButtonDisabled: {
backgroundColor: Palette.glass,
},
actionButtonText: {
color: Palette.white,
fontSize: 13,
fontFamily: FONT_FAMILY.InterSemiBold,
},
})
+4 -5
View File
@@ -4,9 +4,8 @@ import { SheetManager } from 'react-native-actions-sheet'
import useMinuit from 'react-native-minuit/src/hooks/useMinuit'
import SwiperFlatList from 'react-native-swiper-flatlist'
import { icons } from '../../assets'
import { arrayUnion, playlistsRef } from '../../config/firebase'
import { useUserData } from '../../providers/UserDataProvider'
import { createPlaylist } from '../../screens/Library/Playlists/playlist'
import { addMusicToPlaylist, createPlaylist } from '../../screens/Library/Playlists/playlist'
import { Palette } from '../../styles'
import { FONT_FAMILY } from '../../styles/Fonts'
import Style, { size } from '../../styles/Style'
@@ -112,9 +111,9 @@ const PlaylistModal = (props) => {
const projectId = props?.payload?.projectId
if (!selectedId) return
if (projectId) {
await playlistsRef.doc(selectedId).update({
musics: arrayUnion(projectId),
updatedAt: new Date(),
await addMusicToPlaylist({
playlistId: selectedId,
projectId,
})
const addedPlaylist = sanitizedPlaylists.find((p) => p?.id === selectedId)
const name = addedPlaylist?.name || 'la playlist'
+4 -5
View File
@@ -6,9 +6,8 @@ import { SheetManager, useProviderContext } from 'react-native-actions-sheet'
import { actionSheetEventManager } from 'react-native-actions-sheet/dist/src/eventmanager'
import useMinuit from 'react-native-minuit/src/hooks/useMinuit'
import { icons } from '../../assets'
import { arrayUnion, playlistsRef } from '../../config/firebase'
import { useUserData } from '../../providers/UserDataProvider'
import { createPlaylist } from '../../screens/Library/Playlists/playlist'
import { addMusicToPlaylist, createPlaylist } from '../../screens/Library/Playlists/playlist'
import { Palette } from '../../styles'
import { FONT_FAMILY } from '../../styles/Fonts'
import Style, { size } from '../../styles/Style'
@@ -64,9 +63,9 @@ const PlaylistModal = (props) => {
try {
const projectId = props?.payload?.projectId
if (projectId) {
await playlistsRef.doc(selectedId).update({
musics: arrayUnion(projectId),
updatedAt: new Date(),
await addMusicToPlaylist({
playlistId: selectedId,
projectId,
})
const addedPlaylist = sanitizedPlaylists.find((p) => p?.id === selectedId)
const name = addedPlaylist?.name || 'la playlist'
+85
View File
@@ -0,0 +1,85 @@
import React, { useCallback, useMemo } from 'react'
import { StyleSheet, Text, View } from 'react-native'
import Slider from '../Slider'
import { Palette } from '../../styles'
import { FONT_FAMILY } from '../../styles/Fonts'
import {
MAX_SYNC_OFFSET_MS,
clampSyncOffsetMs,
formatSyncOffsetMs,
snapSyncOffsetMs,
} from '../../utils/playbackSync'
const clamp01 = (value) => Math.min(1, Math.max(0, Number(value) || 0))
const SyncOffsetSlider = ({
valueMs = 0,
onChange,
disabled = false,
title = 'Ajuster la synchro',
}) => {
const safeValueMs = useMemo(() => snapSyncOffsetMs(valueMs), [valueMs])
const progress = useMemo(() => {
return clamp01((safeValueMs + MAX_SYNC_OFFSET_MS) / (MAX_SYNC_OFFSET_MS * 2))
}, [safeValueMs])
const handleChange = useCallback(
(ratio) => {
if (disabled || typeof onChange !== 'function') return
const clampedRatio = clamp01(ratio)
const rawValueMs = clampedRatio * (MAX_SYNC_OFFSET_MS * 2) - MAX_SYNC_OFFSET_MS
onChange(snapSyncOffsetMs(rawValueMs))
},
[disabled, onChange]
)
return (
<View style={styles.container}>
<View style={styles.header}>
<Text style={styles.title}>{title}</Text>
<Text style={styles.value}>{formatSyncOffsetMs(clampSyncOffsetMs(safeValueMs))}</Text>
</View>
<Text style={styles.caption}>Gauche = audio en avance. Droite = audio en retard.</Text>
<Slider
value="Audio en avance"
maxValue="Audio en retard"
progress={progress}
seekEnabled={!disabled}
onValueChange={handleChange}
onSeek={handleChange}
/>
</View>
)
}
const styles = StyleSheet.create({
container: {
width: '100%',
gap: 8,
},
header: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
gap: 12,
},
title: {
color: Palette.white,
fontFamily: FONT_FAMILY.InterSemiBold,
fontSize: 15,
},
value: {
color: '#F94697',
fontFamily: FONT_FAMILY.InterSemiBold,
fontSize: 15,
},
caption: {
color: Palette.white,
opacity: 0.8,
fontFamily: FONT_FAMILY.InterRegular,
fontSize: 12,
},
})
export default SyncOffsetSlider
+95
View File
@@ -0,0 +1,95 @@
import { projectsRef } from '../config/firebase'
const isValidUri = (value) => typeof value === 'string' && value.trim().length > 0
export const hasCoverAsset = (project) => {
if (!project) return false
if (isValidUri(project?.coverUrl)) {
return true
}
const cover = project?.cover
if (!cover || typeof cover !== 'object') {
return false
}
const coverCandidates = [cover?.result, cover?.finalUrl, cover?.generatedBackground]
if (Array.isArray(cover?.options)) {
coverCandidates.push(
...cover.options.flatMap((option) => [option?.finalUrl, option?.generatedUrl])
)
}
return coverCandidates.some(isValidUri)
}
export const hasThumbnailAsset = (project) =>
isValidUri(project?.thumbnailUrl) || isValidUri(project?.songThumbnailUrl)
const mergeProjectAssets = (
project,
firestoreData,
{ mergeCover = false, mergeThumbnails = false } = {}
) => {
if (!firestoreData || typeof firestoreData !== 'object') {
return project
}
const mergedProject = { ...project }
if (mergeCover) {
if (!isValidUri(mergedProject.coverUrl) && isValidUri(firestoreData.coverUrl)) {
mergedProject.coverUrl = firestoreData.coverUrl
}
const firestoreCover =
firestoreData.cover && typeof firestoreData.cover === 'object' ? firestoreData.cover : null
if (firestoreCover) {
mergedProject.cover = {
...(typeof mergedProject.cover === 'object' ? mergedProject.cover : {}),
...firestoreCover,
}
}
}
if (mergeThumbnails) {
if (!isValidUri(mergedProject.thumbnailUrl) && isValidUri(firestoreData.thumbnailUrl)) {
mergedProject.thumbnailUrl = firestoreData.thumbnailUrl
}
if (!isValidUri(mergedProject.songThumbnailUrl) && isValidUri(firestoreData.songThumbnailUrl)) {
mergedProject.songThumbnailUrl = firestoreData.songThumbnailUrl
}
}
return mergedProject
}
export const hydrateProjects = async (
projects = [],
{ ensureCover = false, ensureThumbnails = false } = {}
) => {
if (!Array.isArray(projects) || projects.length === 0) {
return []
}
return Promise.all(
projects.map(async (project) => {
const needsCover = ensureCover && !hasCoverAsset(project)
const needsThumbnail = ensureThumbnails && !hasThumbnailAsset(project)
if ((!needsCover && !needsThumbnail) || !project?.id) {
return project
}
try {
const snapshot = await projectsRef.doc(project.id).get()
if (!snapshot.exists) {
return project
}
const firestoreData = snapshot.data() || {}
return mergeProjectAssets(project, firestoreData, {
mergeCover: needsCover,
mergeThumbnails: needsThumbnail,
})
} catch (error) {
console.log('hydrateProjects error', error?.message || error)
return project
}
})
)
}
+59
View File
@@ -0,0 +1,59 @@
import { useEffect, useMemo, useState } from 'react'
import useAlgoliaSearch from 'react-native-minuit/src/hooks/useAlgoliaSearch'
import { AlgoliaProjectConfig } from '../data/keys'
import { hasCoverAsset, hydrateProjects } from './searchProjectAssets'
const batchSize = 12
const usePlaylistMusicSearch = () => {
const [search, setSearch] = useState('')
const [hydratedMusics, setHydratedMusics] = useState(null)
const normalizedSearch = useMemo(() => search.trim(), [search])
const { hits: musics, loading } = useAlgoliaSearch({
query: normalizedSearch,
algoliaObject: AlgoliaProjectConfig,
batch: batchSize,
condition: normalizedSearch.length > 0,
searchParams: {
filters: 'hasSong:true',
},
})
useEffect(() => {
let isCancelled = false
const nextMusics = Array.isArray(musics) ? musics : []
const requiresHydration =
nextMusics.length > 0 && nextMusics.some((project) => !hasCoverAsset(project))
if (!requiresHydration) {
setHydratedMusics(null)
return () => {
isCancelled = true
}
}
setHydratedMusics(null)
;(async () => {
const hydrated = await hydrateProjects(nextMusics, { ensureCover: true })
if (!isCancelled) {
setHydratedMusics(hydrated)
}
})()
return () => {
isCancelled = true
}
}, [musics])
return {
search,
setSearch,
musics: hydratedMusics ?? musics,
loading,
hasSearch: normalizedSearch.length > 0,
}
}
export default usePlaylistMusicSearch
+1 -95
View File
@@ -1,108 +1,14 @@
import { useEffect, useState } from 'react'
import useAlgoliaSearch from 'react-native-minuit/src/hooks/useAlgoliaSearch'
import { AlgoliaUserConfig, AlgoliaProjectConfig } from '../data/keys'
import { projectsRef } from '../config/firebase'
import { useUserData } from '../providers/UserDataProvider'
import { hasCoverAsset, hasThumbnailAsset, hydrateProjects } from './searchProjectAssets'
const batchSizes = {
users: 5,
projects: 6,
}
const isValidUri = (value) => typeof value === 'string' && value.trim().length > 0
const hasCoverAsset = (project) => {
if (!project) return false
if (isValidUri(project?.coverUrl)) {
return true
}
const cover = project?.cover
if (!cover || typeof cover !== 'object') {
return false
}
const coverCandidates = [cover?.result, cover?.finalUrl, cover?.generatedBackground]
if (Array.isArray(cover?.options)) {
coverCandidates.push(
...cover.options.flatMap((option) => [option?.finalUrl, option?.generatedUrl])
)
}
return coverCandidates.some(isValidUri)
}
const hasThumbnailAsset = (project) =>
isValidUri(project?.thumbnailUrl) || isValidUri(project?.songThumbnailUrl)
const mergeProjectAssets = (
project,
firestoreData,
{ mergeCover = false, mergeThumbnails = false } = {}
) => {
if (!firestoreData || typeof firestoreData !== 'object') {
return project
}
const mergedProject = { ...project }
if (mergeCover) {
if (!isValidUri(mergedProject.coverUrl) && isValidUri(firestoreData.coverUrl)) {
mergedProject.coverUrl = firestoreData.coverUrl
}
const firestoreCover =
firestoreData.cover && typeof firestoreData.cover === 'object' ? firestoreData.cover : null
if (firestoreCover) {
mergedProject.cover = {
...(typeof mergedProject.cover === 'object' ? mergedProject.cover : {}),
...firestoreCover,
}
}
}
if (mergeThumbnails) {
if (!isValidUri(mergedProject.thumbnailUrl) && isValidUri(firestoreData.thumbnailUrl)) {
mergedProject.thumbnailUrl = firestoreData.thumbnailUrl
}
if (!isValidUri(mergedProject.songThumbnailUrl) && isValidUri(firestoreData.songThumbnailUrl)) {
mergedProject.songThumbnailUrl = firestoreData.songThumbnailUrl
}
}
return mergedProject
}
const hydrateProjects = async (
projects = [],
{ ensureCover = false, ensureThumbnails = false } = {}
) => {
if (!Array.isArray(projects) || projects.length === 0) {
return []
}
return Promise.all(
projects.map(async (project) => {
const needsCover = ensureCover && !hasCoverAsset(project)
const needsThumbnail = ensureThumbnails && !hasThumbnailAsset(project)
if ((!needsCover && !needsThumbnail) || !project?.id) {
return project
}
try {
const snapshot = await projectsRef.doc(project.id).get()
if (!snapshot.exists) {
return project
}
const firestoreData = snapshot.data() || {}
return mergeProjectAssets(project, firestoreData, {
mergeCover: needsCover,
mergeThumbnails: needsThumbnail,
})
} catch (error) {
console.log('useSearch.hydrateProjects error', error?.message || error)
return project
}
})
)
}
const useSearch = () => {
const [selected, setSelected] = useState(null)
const [search, setSearch] = useState('')
+35
View File
@@ -129,6 +129,17 @@ const AllMyPlaylist = ({ route }) => {
})
}
const openAddTracks = useCallback(() => {
if (!selectedPlaylistId) return
SheetManager.show('PlaylistAddTracks', {
payload: {
playlistId: selectedPlaylistId,
existingMusicIds: Array.isArray(playlist?.musics) ? playlist.musics : [],
},
})
}, [playlist?.musics, selectedPlaylistId])
return (
<Page
headerType="NAVIGATION"
@@ -141,9 +152,18 @@ const AllMyPlaylist = ({ route }) => {
rightComponent={() => (
<>
{selectedPlaylistId != null && (
<View style={{ flexDirection: 'row', alignItems: 'center', gap: 10 }}>
<Pressable onPress={openAddTracks}>
<BlurView intensity={20} tint="dark" style={styles.addTracksButton}>
<Text numberOfLines={1} style={styles.addTracksText}>
Ajouter des morceaux
</Text>
</BlurView>
</Pressable>
<Pressable onPress={confirmDelete}>
<Image source={icons.trash} style={{ width: 24, height: 24 }} />
</Pressable>
</View>
)}
</>
)}
@@ -288,3 +308,18 @@ const AllMyPlaylist = ({ route }) => {
}
export default AllMyPlaylist
const styles = {
addTracksButton: {
paddingHorizontal: 12,
paddingVertical: 8,
borderRadius: 999,
overflow: 'hidden',
backgroundColor: Palette.glass,
},
addTracksText: {
color: Palette.white,
fontSize: 12,
fontFamily: FONT_FAMILY.InterSemiBold,
},
}
+39 -2
View File
@@ -1,6 +1,7 @@
import { BlurView } from 'expo-blur'
import { useRoute } from '@react-navigation/native'
import React, { useCallback, useMemo, useState } from 'react'
import { Image, Pressable, View } from 'react-native'
import { Image, Pressable, Text, View } from 'react-native'
import { SheetManager } from 'react-native-actions-sheet'
import { useDataFromRef } from 'react-native-minuit/src/hooks'
import useDataFromArrayId from 'react-native-minuit/src/hooks/useDataFromArrayId'
@@ -12,7 +13,8 @@ import useNavigateToMusicDetails from '../../hooks/useNavigateToMusicDetails'
import usePlayer from '../../hooks/usePlayer'
import Page from '../../layouts/Page'
import { goBack } from '../../navigation/NavigationService'
import { gutters } from '../../styles'
import { gutters, Palette } from '../../styles'
import { FONT_FAMILY } from '../../styles/Fonts'
import { getProjectLikes, LIKE_TARGET } from '../../utils/likes'
import MusicCard from './components/MusicCard'
@@ -130,15 +132,35 @@ const PlaylistDetails = () => {
})
}
const openAddTracks = useCallback(() => {
if (!playlistId) return
SheetManager.show('PlaylistAddTracks', {
payload: {
playlistId,
existingMusicIds: Array.isArray(playlist?.musics) ? playlist.musics : [],
},
})
}, [playlist?.musics, playlistId])
return (
<Page
headerType="NAVIGATION"
backgroundImg={background.libraryBG}
title={playlist?.name || 'Playlist'}
rightComponent={() => (
<View style={{ flexDirection: 'row', alignItems: 'center', gap: 10 }}>
<Pressable onPress={openAddTracks}>
<BlurView intensity={20} tint="dark" style={styles.addTracksButton}>
<Text numberOfLines={1} style={styles.addTracksText}>
Ajouter des morceaux
</Text>
</BlurView>
</Pressable>
<Pressable onPress={confirmDelete}>
<Image source={icons.trash} style={{ width: 24, height: 24 }} />
</Pressable>
</View>
)}
contentContainerStyle={{ paddingBottom: gutters * 2 }}
>
@@ -177,3 +199,18 @@ const PlaylistDetails = () => {
}
export default PlaylistDetails
const styles = {
addTracksButton: {
paddingHorizontal: 12,
paddingVertical: 8,
borderRadius: 999,
overflow: 'hidden',
backgroundColor: Palette.glass,
},
addTracksText: {
color: Palette.white,
fontSize: 12,
fontFamily: FONT_FAMILY.InterSemiBold,
},
}
+17 -1
View File
@@ -1,4 +1,4 @@
import { playlistsRef } from '../../../config/firebase'
import { arrayUnion, playlistsRef } from '../../../config/firebase'
export const createPlaylist = async (payload = {}) => {
try {
@@ -21,3 +21,19 @@ export const createPlaylist = async (payload = {}) => {
throw error
}
}
export const addMusicToPlaylist = async ({ playlistId, projectId }) => {
try {
if (typeof playlistId !== 'string' || typeof projectId !== 'string') {
throw new Error('Identifiants de playlist ou de morceau invalides')
}
await playlistsRef.doc(playlistId).update({
musics: arrayUnion(projectId),
updatedAt: new Date(),
})
} catch (error) {
console.error('Error adding music to playlist:', error)
throw error
}
}
+2 -2
View File
@@ -20,8 +20,8 @@ import Palette from '../styles/Palette.js'
export default ({ navigation }) => {
const [, setTooltip] = useGlobal('_tooltip')
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const [email, setEmail] = useState(__DEV__ ? 'az@az.az' : '')
const [password, setPassword] = useState(__DEV__ ? 'Minuit33' : '')
const [loading, setLoading] = useState(false)
const afterLoginNavigate = useCallback(async () => {
const uid = firebase.auth().currentUser?.uid
+2 -2
View File
@@ -18,13 +18,13 @@ import { Routes } from '../../navigation'
import { goBack, navigate } from '../../navigation/NavigationService'
import { gutters, Palette } from '../../styles'
import { FONT_FAMILY } from '../../styles/Fonts'
import { clampSyncOffsetMs } from '../../utils/playbackSync'
import trimLeadingDuplicateSection from '../../utils/trimLeadingDuplicateSection'
import CreateLyricsHeader from '../Writing/components/CreateLyricsHeader'
const TIME_BEFORE_INCREMENT_MS = 20000 // 20s
const COUNTDOWN_SECONDS = 10
const CAMERA_STARTUP_DELAY_MS = 250
const MAX_SYNC_OFFSET_MS = 2000
const KARAOKE_LEAD_S = 0.18
const LOG_PREFIX = '[RecordPlayback]'
const KEEP_AWAKE_TAG = 'record-playback'
@@ -758,7 +758,7 @@ const RecordPlayback = ({ route }) => {
playbackStartedAtRef.current && recordingStartTimeRef.current
? playbackStartedAtRef.current - recordingStartTimeRef.current
: 0
const syncOffsetMs = Math.max(0, Math.min(MAX_SYNC_OFFSET_MS, Math.round(rawOffsetMs || 0)))
const syncOffsetMs = clampSyncOffsetMs(Math.round(rawOffsetMs || 0))
log('Computed sync offset', { rawOffsetMs, syncOffsetMs })
if (video?.uri) {
+2 -2
View File
@@ -20,6 +20,7 @@ import CreateLyricsHeader from '../Writing/components/CreateLyricsHeader'
import { background } from '../../assets'
import RestartSpinnerIcon from '../../assets/UI/RestartSpinnerIcon'
import { registerBlobUrl, releaseBlobUrl } from '../../utils/blobUrlCache'
import { clampSyncOffsetMs } from '../../utils/playbackSync'
import trimLeadingDuplicateSection from '../../utils/trimLeadingDuplicateSection'
const TIME_BEFORE_INCREMENT_MS = 20000
@@ -29,7 +30,6 @@ const MEDIA_BOOTSTRAP_DELAY_MS = 250
const MEDIA_RETRY_DELAY_MS = 700
const MEDIA_MAX_RETRIES = 2
const CAMERA_STARTUP_DELAY_MS = 250
const MAX_SYNC_OFFSET_MS = 2000
const KARAOKE_LEAD_S = 0.18
const toSeconds = (v) => {
@@ -547,7 +547,7 @@ const RecordPlayback = ({ route }) => {
playbackStartedAtRef.current != null && recordingStartAtRef.current != null
? playbackStartedAtRef.current - recordingStartAtRef.current
: 0
const syncOffsetMs = Math.max(0, Math.min(MAX_SYNC_OFFSET_MS, Math.round(rawOffsetMs || 0)))
const syncOffsetMs = clampSyncOffsetMs(Math.round(rawOffsetMs || 0))
navigate(Routes.RecordedPlayback, {
project,
+157 -57
View File
@@ -4,18 +4,28 @@ import * as FileSystem from 'expo-file-system'
import { VideoView, useVideoPlayer } from 'expo-video'
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { Image, Pressable, View } from 'react-native'
import { background, icons } from '../../assets'
import { icons } from '../../assets'
import BorderGradientButton from '../../components/BorderGradientButton'
import GradientButton from '../../components/GradientButton'
import MusicLandHeader from '../../components/MusicLandHeader'
import ProgressSlider from '../../components/player/ProgressSlider'
import SyncOffsetSlider from '../../components/player/SyncOffsetSlider'
import Page from '../../layouts/Page'
import { Routes } from '../../navigation'
import { goBack, navigate } from '../../navigation/NavigationService'
import { gutters, Palette } from '../../styles'
import { FONT_FAMILY } from '../../styles/Fonts'
import {
clampSyncOffsetMs,
getAudioPositionMs,
getTimelineDurationMs,
getTimelinePositionMs,
getVideoPositionMs,
snapSyncOffsetMs,
} from '../../utils/playbackSync'
const RecordedPlayback = ({ route }) => {
const { videoUri, project, syncOffsetMs = 0 } = route.params || {}
const initialSyncOffsetMs = useMemo(() => snapSyncOffsetMs(syncOffsetMs), [syncOffsetMs])
const songUrl = project?.songUrl || null
const audioPlayer = useSharedAudioPlayer(songUrl ? { uri: songUrl } : undefined, {
@@ -26,10 +36,10 @@ const RecordedPlayback = ({ route }) => {
coverUrl: project?.coverUrl || null,
metadata: { projectId: project?.id, screen: 'RecordedPlayback' },
})
const videoPlayer = useVideoPlayer(videoUri || null, (p) => {
p.loop = false
p.muted = true // recorded video has no audio; keep muted anyway
p.timeUpdateEventInterval = 0.2
const videoPlayer = useVideoPlayer(videoUri || null, (player) => {
player.loop = false
player.muted = true
player.timeUpdateEventInterval = 0.2
})
const [progressInfo, setProgressInfo] = useState({
@@ -37,11 +47,39 @@ const RecordedPlayback = ({ route }) => {
dur: 0,
isPlaying: false,
})
const [currentSyncOffsetMs, setCurrentSyncOffsetMs] = useState(initialSyncOffsetMs)
const playbackEndedRef = useRef(false)
const syncOffsetRef = useRef(initialSyncOffsetMs)
const syncOffsetRef = useRef(Math.max(0, Number(syncOffsetMs) || 0))
const getCurrentRawAudioPositionMs = useCallback(
() => Math.max(0, (audioPlayer?.currentTime || 0) * 1000),
[audioPlayer]
)
const getCurrentRawAudioDurationMs = useCallback(
() => Math.max(0, (audioPlayer?.duration || 0) * 1000),
[audioPlayer]
)
const alignPlaybackToTimeline = useCallback(
async (timelineMs, offsetMs = syncOffsetRef.current) => {
const safeOffsetMs = clampSyncOffsetMs(offsetMs)
const safeTimelineMs = Math.max(0, Number(timelineMs) || 0)
const audioTargetMs = getAudioPositionMs(safeTimelineMs, safeOffsetMs)
const videoTargetMs = getVideoPositionMs(safeTimelineMs, safeOffsetMs)
if (audioPlayer) {
await audioPlayer.seekTo?.(audioTargetMs / 1000)
}
if (videoPlayer) {
videoPlayer.currentTime = videoTargetMs / 1000
}
},
[audioPlayer, videoPlayer]
)
// Start both players on mount
const stopPlayback = useCallback(async () => {
try {
if (audioPlayer) await audioPlayer.pause?.()
@@ -61,57 +99,67 @@ const RecordedPlayback = ({ route }) => {
useEffect(() => {
playbackEndedRef.current = false
syncOffsetRef.current = initialSyncOffsetMs
setCurrentSyncOffsetMs(initialSyncOffsetMs)
const start = async () => {
try {
if (videoPlayer && syncOffsetRef.current > 0) {
videoPlayer.currentTime = syncOffsetRef.current / 1000
}
await alignPlaybackToTimeline(0, initialSyncOffsetMs)
if (audioPlayer && songUrl) await audioPlayer.play?.()
if (videoPlayer) videoPlayer.play()
} catch (e) {}
}
start()
void start()
return () => {
playbackEndedRef.current = false
void stopPlayback()
}
}, [audioPlayer, songUrl, stopPlayback, videoPlayer])
}, [alignPlaybackToTimeline, audioPlayer, initialSyncOffsetMs, songUrl, stopPlayback, videoPlayer])
// Poll from audio player for progress display; keep video in sync if drifting
useEffect(() => {
const id = global.setInterval(() => {
try {
const dur = (audioPlayer?.duration || 0) * 1000
const pos = (audioPlayer?.currentTime || 0) * 1000
const playing = !!audioPlayer?.playing || !!videoPlayer?.playing
setProgressInfo({ pos, dur, isPlaying: playing })
const rawDurationMs = getCurrentRawAudioDurationMs()
const rawAudioMs = getCurrentRawAudioPositionMs()
const nextDurationMs = getTimelineDurationMs(rawDurationMs, syncOffsetRef.current)
const nextPositionMs = getTimelinePositionMs(rawAudioMs, syncOffsetRef.current)
const safePositionMs =
nextDurationMs > 0 ? Math.min(nextPositionMs, nextDurationMs) : nextPositionMs
const isPlaying = !!audioPlayer?.playing || !!videoPlayer?.playing
setProgressInfo({
pos: safePositionMs,
dur: nextDurationMs,
isPlaying,
})
// basic drift correction: if desync > 300ms, align video
if (videoPlayer && !Number.isNaN(videoPlayer.currentTime)) {
const offset = syncOffsetRef.current || 0
const expected = Math.max(0, (pos || 0) + offset)
const v = (videoPlayer.currentTime || 0) * 1000
const drift = Math.abs(v - expected)
if (drift > 350) {
videoPlayer.currentTime = Math.max(0, expected / 1000)
const expectedVideoMs = getVideoPositionMs(safePositionMs, syncOffsetRef.current)
const currentVideoMs = (videoPlayer.currentTime || 0) * 1000
const driftMs = Math.abs(currentVideoMs - expectedVideoMs)
if (driftMs > 350) {
videoPlayer.currentTime = Math.max(0, expectedVideoMs / 1000)
}
}
} catch (e) {}
}, 250)
return () => global.clearInterval(id)
}, [audioPlayer, videoPlayer])
const onSeek = async (targetMs) => {
return () => global.clearInterval(id)
}, [audioPlayer, getCurrentRawAudioDurationMs, getCurrentRawAudioPositionMs, videoPlayer])
const onSeek = useCallback(
async (targetMs) => {
try {
const dur = progressInfo.dur || 0
const pos = Math.max(0, Math.min(dur, Math.floor(targetMs)))
if (audioPlayer && dur > 0) await audioPlayer.seekTo?.(Math.floor(pos / 1000))
if (videoPlayer) {
const offset = syncOffsetRef.current || 0
videoPlayer.currentTime = Math.max(0, (pos + offset) / 1000)
}
const durationMs = progressInfo.dur || 0
const safeTargetMs = Math.max(0, Math.min(durationMs, Math.floor(targetMs)))
await alignPlaybackToTimeline(safeTargetMs)
} catch (e) {}
}
},
[alignPlaybackToTimeline, progressInfo.dur]
)
const onSeekStart = useCallback(() => {
playbackEndedRef.current = false
@@ -139,30 +187,66 @@ const RecordedPlayback = ({ route }) => {
} catch (e) {}
}, [audioPlayer, videoPlayer])
const sliderProgress = useMemo(() => {
return progressInfo.dur ? Math.min(1, (progressInfo.pos || 0) / progressInfo.dur) : 0
}, [progressInfo])
const handleSyncOffsetChange = useCallback(
(nextOffsetMs) => {
const safeOffsetMs = snapSyncOffsetMs(nextOffsetMs)
setCurrentSyncOffsetMs((prevOffsetMs) =>
prevOffsetMs === safeOffsetMs ? prevOffsetMs : safeOffsetMs
)
const previousOffsetMs = syncOffsetRef.current
if (safeOffsetMs === previousOffsetMs) return
playbackEndedRef.current = false
const rawAudioMs = getCurrentRawAudioPositionMs()
const rawDurationMs = getCurrentRawAudioDurationMs()
const currentTimelineMs = getTimelinePositionMs(rawAudioMs, previousOffsetMs)
const nextDurationMs = getTimelineDurationMs(rawDurationMs, safeOffsetMs)
const nextTimelineMs =
nextDurationMs > 0 ? Math.min(currentTimelineMs, nextDurationMs) : currentTimelineMs
syncOffsetRef.current = safeOffsetMs
setProgressInfo({
pos: nextTimelineMs,
dur: nextDurationMs,
isPlaying: !!audioPlayer?.playing || !!videoPlayer?.playing,
})
void alignPlaybackToTimeline(nextTimelineMs, safeOffsetMs)
},
[
alignPlaybackToTimeline,
audioPlayer?.playing,
getCurrentRawAudioDurationMs,
getCurrentRawAudioPositionMs,
videoPlayer?.playing,
]
)
useEffect(() => {
const duration = progressInfo?.dur || 0
if (!duration) return
const position = progressInfo?.pos || 0
if (playbackEndedRef.current && duration - position > 1000) {
const durationMs = progressInfo?.dur || 0
if (!durationMs) return
const positionMs = progressInfo?.pos || 0
if (playbackEndedRef.current && durationMs - positionMs > 1000) {
playbackEndedRef.current = false
return
}
const remaining = Math.max(0, duration - position)
if (remaining <= 400 && !playbackEndedRef.current) {
const remainingMs = Math.max(0, durationMs - positionMs)
if (remainingMs <= 400 && !playbackEndedRef.current) {
playbackEndedRef.current = true
void stopPlayback()
}
}, [progressInfo, stopPlayback])
const handleTogglePlayback = async () => {
const handleTogglePlayback = useCallback(async () => {
try {
const duration = progressInfo?.dur || 0
const position = progressInfo?.pos || 0
const isAtEnd = duration > 0 && duration - position < 1000
const durationMs = progressInfo?.dur || 0
const positionMs = progressInfo?.pos || 0
const isAtEnd = durationMs > 0 && durationMs - positionMs < 1000
const isCurrentlyPlaying = !!audioPlayer?.playing || !!videoPlayer?.playing
if (isCurrentlyPlaying) {
@@ -173,18 +257,22 @@ const RecordedPlayback = ({ route }) => {
}
if (isAtEnd) {
if (audioPlayer) await audioPlayer.seekTo?.(0)
if (videoPlayer) {
const offset = syncOffsetRef.current || 0
videoPlayer.currentTime = Math.max(0, offset / 1000)
}
await alignPlaybackToTimeline(0)
}
playbackEndedRef.current = false
if (songUrl && audioPlayer) await audioPlayer.play?.()
if (songUrl && audioPlayer) {
if (audioPlayer?.resume) {
await audioPlayer.resume?.()
} else {
await audioPlayer.play?.()
}
}
if (videoPlayer) videoPlayer.play()
} catch (e) {}
}
}, [alignPlaybackToTimeline, audioPlayer, progressInfo, songUrl, videoPlayer])
return (
<Page backgroundColor={Palette.grayMid} headerType="NONE">
@@ -206,6 +294,8 @@ const RecordedPlayback = ({ route }) => {
}}
/>
)}
<View style={{ width: '80%', alignSelf: 'center', gap: 18 }}>
<ProgressSlider
positionMs={progressInfo.pos}
durationMs={progressInfo.dur}
@@ -216,6 +306,13 @@ const RecordedPlayback = ({ route }) => {
onPlay={resumeAfterSeek}
disabled={!songUrl}
/>
<SyncOffsetSlider
valueMs={currentSyncOffsetMs}
onChange={handleSyncOffsetChange}
disabled={!songUrl}
/>
</View>
<Pressable
onPress={handleTogglePlayback}
style={{
@@ -237,6 +334,7 @@ const RecordedPlayback = ({ route }) => {
/>
</Pressable>
</View>
<View style={{ width: '80%', alignSelf: 'center', marginTop: 4, gap: 12 }}>
<GradientButton
title="Je valide"
@@ -248,6 +346,7 @@ const RecordedPlayback = ({ route }) => {
action: 'playback',
uri: videoUri,
project,
syncOffsetMs: syncOffsetRef.current,
})
}}
/>
@@ -260,11 +359,12 @@ const RecordedPlayback = ({ route }) => {
try {
if (videoUri) {
const info = await FileSystem.getInfoAsync(videoUri)
if (info?.exists)
if (info?.exists) {
await FileSystem.deleteAsync(videoUri, {
idempotent: true,
})
}
}
} catch (e) {}
navigate(Routes.RecordPlayback, { project })
}}
+179 -135
View File
@@ -1,11 +1,12 @@
import { useFocusEffect } from '@react-navigation/native'
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { Image, Pressable, Text, View } from 'react-native'
import { background, icons } from '../../assets'
import { icons } from '../../assets'
import BorderGradientButton from '../../components/BorderGradientButton'
import GradientButton from '../../components/GradientButton'
import MusicLandHeader from '../../components/MusicLandHeader'
import Slider from '../../components/Slider'
import ProgressSlider from '../../components/player/ProgressSlider'
import SyncOffsetSlider from '../../components/player/SyncOffsetSlider'
import Page from '../../layouts/Page'
import { Routes } from '../../navigation'
import { goBack, navigate } from '../../navigation/NavigationService'
@@ -13,26 +14,22 @@ import { gutters, Palette } from '../../styles'
import { isWeb } from '../../hooks/useLayoutType'
import useSharedAudioPlayer from '../../hooks/useSharedAudioPlayer'
import { releaseBlobUrl } from '../../utils/blobUrlCache'
const fmtSeconds = (s) => {
const total = Math.max(0, Math.floor(Number(s || 0)))
const m = Math.floor(total / 60).toString()
const sec = (total % 60).toString().padStart(2, '0')
return `${m}:${sec}`
}
const toSeconds = (value) => {
const n = Number(value ?? 0)
if (!Number.isFinite(n) || n < 0) return 0
return n > 10000 ? n / 1000 : n // heuristique ms → s
}
import {
clampSyncOffsetMs,
getAudioPositionMs,
getTimelineDurationMs,
getTimelinePositionMs,
getVideoPositionMs,
snapSyncOffsetMs,
} from '../../utils/playbackSync'
const WEB_PREVIEW_WIDTH = 360
const RecordedPlayback = ({ route }) => {
const { videoUri, project, syncOffsetMs = 0 } = route.params || {}
const initialSyncOffsetMs = useMemo(() => snapSyncOffsetMs(syncOffsetMs), [syncOffsetMs])
const songUrl = project?.songUrl || null
// AUDIO PLAYER (expo-audio → seconds)
const audioPlayer = useSharedAudioPlayer(songUrl ? { uri: songUrl } : undefined, {
id: project?.id ? `recorded-${project.id}` : songUrl ? `recorded-${songUrl}` : undefined,
title: typeof project?.title === 'string' ? project.title : 'Sans titre',
@@ -42,17 +39,45 @@ const RecordedPlayback = ({ route }) => {
metadata: { projectId: project?.id, screen: 'RecordedPlayback' },
})
// Optionnel: si tu veux quand même un rendu vidéo sur web si tu as une source
const videoElRef = useRef(null)
const syncOffsetRef = useRef(Math.max(0, Number(syncOffsetMs) || 0) / 1000)
const playbackEndedRef = useRef(false)
const shouldPreserveBlobRef = useRef(false)
const syncOffsetRef = useRef(initialSyncOffsetMs)
const [progress, setProgress] = useState({
posS: 0, // secondes
durS: 0, // secondes
playing: false,
const [progressInfo, setProgressInfo] = useState({
pos: 0,
dur: 0,
isPlaying: false,
})
const [currentSyncOffsetMs, setCurrentSyncOffsetMs] = useState(initialSyncOffsetMs)
const getCurrentRawAudioPositionMs = useCallback(
() => Math.max(0, (audioPlayer?.currentTime || 0) * 1000),
[audioPlayer]
)
const getCurrentRawAudioDurationMs = useCallback(
() => Math.max(0, (audioPlayer?.duration || 0) * 1000),
[audioPlayer]
)
const alignPlaybackToTimeline = useCallback(
async (timelineMs, offsetMs = syncOffsetRef.current) => {
const safeOffsetMs = clampSyncOffsetMs(offsetMs)
const safeTimelineMs = Math.max(0, Number(timelineMs) || 0)
const audioTargetMs = getAudioPositionMs(safeTimelineMs, safeOffsetMs)
const videoTargetMs = getVideoPositionMs(safeTimelineMs, safeOffsetMs)
if (audioPlayer) {
await audioPlayer.seekTo?.(audioTargetMs / 1000)
}
if (videoElRef.current && videoUri) {
videoElRef.current.currentTime = Math.max(0, videoTargetMs / 1000)
}
},
[audioPlayer, videoUri]
)
const stopPlayback = useCallback(async () => {
try {
@@ -81,153 +106,166 @@ const RecordedPlayback = ({ route }) => {
}
}, [videoUri])
// Démarrage / arrêt
useEffect(() => {
playbackEndedRef.current = false
syncOffsetRef.current = initialSyncOffsetMs
setCurrentSyncOffsetMs(initialSyncOffsetMs)
const start = async () => {
try {
if (videoElRef.current && videoUri && syncOffsetRef.current > 0) {
videoElRef.current.currentTime = Math.max(0, syncOffsetRef.current)
}
await alignPlaybackToTimeline(0, initialSyncOffsetMs)
if (audioPlayer && songUrl) {
await audioPlayer.play?.()
}
if (videoElRef.current && videoUri) {
// Lecture vidéo HTML5 (muet pour éviter les policies)
videoElRef.current.muted = true
videoElRef.current.play().catch(() => {})
}
} catch {}
}
start()
void start()
return () => {
playbackEndedRef.current = false
void stopPlayback()
}
}, [audioPlayer, songUrl, stopPlayback, videoUri])
}, [alignPlaybackToTimeline, audioPlayer, initialSyncOffsetMs, songUrl, stopPlayback, videoUri])
// Boucle de progression + éventuelle sync de la vidéo si fournie
useEffect(() => {
const id = setInterval(() => {
try {
const durS = toSeconds(audioPlayer?.duration) // secondes
const posS = toSeconds(audioPlayer?.currentTime) // secondes
const rawDurationMs = getCurrentRawAudioDurationMs()
const rawAudioMs = getCurrentRawAudioPositionMs()
const nextDurationMs = getTimelineDurationMs(rawDurationMs, syncOffsetRef.current)
const nextPositionMs = getTimelinePositionMs(rawAudioMs, syncOffsetRef.current)
const safePositionMs =
nextDurationMs > 0 ? Math.min(nextPositionMs, nextDurationMs) : nextPositionMs
const isVideoPlaying = !!(videoElRef.current && !videoElRef.current.paused)
const isPlaying = !!audioPlayer?.playing || isVideoPlaying
setProgress({
posS,
durS,
playing: !!audioPlayer?.playing,
setProgressInfo({
pos: safePositionMs,
dur: nextDurationMs,
isPlaying,
})
// Sync vidéo si on a une source vidéo
if (videoElRef.current && videoUri && !Number.isNaN(videoElRef.current.currentTime)) {
const v = Number(videoElRef.current.currentTime || 0)
const expected = Math.max(0, posS + (syncOffsetRef.current || 0))
const drift = Math.abs(v - expected)
if (drift > 0.35) {
videoElRef.current.currentTime = expected
const expectedVideoMs = getVideoPositionMs(safePositionMs, syncOffsetRef.current)
const currentVideoMs = Number(videoElRef.current.currentTime || 0) * 1000
const driftMs = Math.abs(currentVideoMs - expectedVideoMs)
if (driftMs > 350) {
videoElRef.current.currentTime = Math.max(0, expectedVideoMs / 1000)
}
}
} catch {}
}, 250)
return () => clearInterval(id)
}, [audioPlayer, videoUri])
// Slider: ratio 0..1
const sliderProgress = useMemo(() => {
return progress.durS > 0 ? Math.min(1, progress.posS / progress.durS) : 0
}, [progress])
const pendingSeekRef = useRef(null)
useEffect(() => {
const duration = progress?.durS || 0
if (!duration) return
const position = progress?.posS || 0
if (playbackEndedRef.current && duration - position > 1) {
playbackEndedRef.current = false
return
}
const remaining = Math.max(0, duration - position)
if (remaining <= 0.35 && !playbackEndedRef.current) {
playbackEndedRef.current = true
void (async () => {
await stopPlayback()
try {
if (audioPlayer) await audioPlayer.seekTo?.(0)
} catch { }
try {
if (videoElRef.current) {
videoElRef.current.currentTime = Math.max(0, syncOffsetRef.current || 0)
}
} catch { }
})()
}
}, [progress, stopPlayback, audioPlayer])
}, [audioPlayer, getCurrentRawAudioDurationMs, getCurrentRawAudioPositionMs, videoUri])
const onSeek = useCallback(
async (ratio) => {
const durS = Number(progress.durS || 0)
const target = durS > 0 ? durS * ratio : 0 // secondes
const promise = (async () => {
async (targetMs) => {
try {
if (audioPlayer && durS > 0) {
await audioPlayer.seekTo?.(Math.max(0, target))
}
if (videoElRef.current && videoUri) {
const offset = syncOffsetRef.current || 0
videoElRef.current.currentTime = Math.max(0, target + offset)
}
const durationMs = progressInfo.dur || 0
const safeTargetMs = Math.max(0, Math.min(durationMs, Math.floor(targetMs)))
await alignPlaybackToTimeline(safeTargetMs)
} catch {}
})()
pendingSeekRef.current = promise
await promise
},
[audioPlayer, progress.durS, videoUri]
[alignPlaybackToTimeline, progressInfo.dur]
)
const waitForPendingSeek = useCallback(async () => {
const promise = pendingSeekRef.current
pendingSeekRef.current = null
if (!promise) return
try {
await promise
} catch { }
const onSeekStart = useCallback(() => {
playbackEndedRef.current = false
}, [])
const wasPlayingRef = useRef(false)
const isSeekingRef = useRef(false)
const onSeekStart = useCallback(async () => {
const pauseDuringSeek = useCallback(async () => {
try {
if (isSeekingRef.current) return
isSeekingRef.current = true
wasPlayingRef.current = !!audioPlayer?.playing
pendingSeekRef.current = null
playbackEndedRef.current = false
if (audioPlayer?.playing) await audioPlayer.pause?.()
} catch {}
try {
if (videoElRef.current && !videoElRef.current.paused) {
videoElRef.current.pause()
}
} catch {}
}, [audioPlayer])
const onSeekEnd = useCallback(async () => {
const resumeAfterSeek = useCallback(async () => {
try {
if (!isSeekingRef.current) return
await waitForPendingSeek()
isSeekingRef.current = false
if (wasPlayingRef.current) {
if (audioPlayer) await audioPlayer.resume?.()
if (videoElRef.current && videoUri) videoElRef.current.play().catch(() => { })
if (audioPlayer?.resume) {
await audioPlayer.resume?.()
} else if (audioPlayer) {
await audioPlayer.play?.()
}
} catch {}
}, [audioPlayer, videoUri, waitForPendingSeek])
try {
if (videoElRef.current && videoUri) {
videoElRef.current.muted = true
videoElRef.current.play().catch(() => {})
}
} catch {}
}, [audioPlayer, videoUri])
const handleSyncOffsetChange = useCallback(
(nextOffsetMs) => {
const safeOffsetMs = snapSyncOffsetMs(nextOffsetMs)
setCurrentSyncOffsetMs((prevOffsetMs) =>
prevOffsetMs === safeOffsetMs ? prevOffsetMs : safeOffsetMs
)
const previousOffsetMs = syncOffsetRef.current
if (safeOffsetMs === previousOffsetMs) return
playbackEndedRef.current = false
const rawAudioMs = getCurrentRawAudioPositionMs()
const rawDurationMs = getCurrentRawAudioDurationMs()
const currentTimelineMs = getTimelinePositionMs(rawAudioMs, previousOffsetMs)
const nextDurationMs = getTimelineDurationMs(rawDurationMs, safeOffsetMs)
const nextTimelineMs =
nextDurationMs > 0 ? Math.min(currentTimelineMs, nextDurationMs) : currentTimelineMs
const isVideoPlaying = !!(videoElRef.current && !videoElRef.current.paused)
syncOffsetRef.current = safeOffsetMs
setProgressInfo({
pos: nextTimelineMs,
dur: nextDurationMs,
isPlaying: !!audioPlayer?.playing || isVideoPlaying,
})
void alignPlaybackToTimeline(nextTimelineMs, safeOffsetMs)
},
[alignPlaybackToTimeline, audioPlayer?.playing, getCurrentRawAudioDurationMs, getCurrentRawAudioPositionMs]
)
useEffect(() => {
const durationMs = progressInfo?.dur || 0
if (!durationMs) return
const positionMs = progressInfo?.pos || 0
if (playbackEndedRef.current && durationMs - positionMs > 1000) {
playbackEndedRef.current = false
return
}
const remainingMs = Math.max(0, durationMs - positionMs)
if (remainingMs <= 400 && !playbackEndedRef.current) {
playbackEndedRef.current = true
void stopPlayback()
}
}, [progressInfo, stopPlayback])
const handleTogglePlayback = useCallback(async () => {
try {
const duration = Number(progress?.durS || 0)
const position = Number(progress?.posS || 0)
const isAtEnd = duration > 0 && duration - position < 0.35
const isCurrentlyPlaying = !!audioPlayer?.playing
const durationMs = progressInfo?.dur || 0
const positionMs = progressInfo?.pos || 0
const isAtEnd = durationMs > 0 && durationMs - positionMs < 1000
const isVideoPlaying = !!(videoElRef.current && !videoElRef.current.paused)
const isCurrentlyPlaying = !!audioPlayer?.playing || isVideoPlaying
if (isCurrentlyPlaying) {
playbackEndedRef.current = false
@@ -236,22 +274,25 @@ const RecordedPlayback = ({ route }) => {
}
if (isAtEnd) {
if (audioPlayer) await audioPlayer.seekTo?.(0)
if (videoElRef.current && videoUri) {
videoElRef.current.currentTime = Math.max(0, syncOffsetRef.current || 0)
}
await alignPlaybackToTimeline(0)
}
playbackEndedRef.current = false
if (songUrl && audioPlayer) {
if (audioPlayer?.resume) {
await audioPlayer.resume?.()
} else {
await audioPlayer.play?.()
}
}
if (videoElRef.current && videoUri) {
videoElRef.current.muted = true
videoElRef.current.play().catch(() => {})
}
} catch {}
}, [audioPlayer, songUrl, stopPlayback, progress, videoUri])
}, [alignPlaybackToTimeline, audioPlayer, progressInfo, songUrl, stopPlayback, videoUri])
return (
<Page
@@ -273,7 +314,6 @@ const RecordedPlayback = ({ route }) => {
width: '100%',
}}
>
{/* Bloc vidéo optionnel si jamais tu as un videoUri sur web */}
{videoUri ? (
<Pressable
onPress={handleTogglePlayback}
@@ -301,7 +341,7 @@ const RecordedPlayback = ({ route }) => {
}}
controls={false}
/>
{!progress.playing && (
{!progressInfo.isPlaying && (
<View
pointerEvents="none"
style={{
@@ -324,7 +364,6 @@ const RecordedPlayback = ({ route }) => {
)}
</Pressable>
) : (
// Placeholder quand pas de vidéo sur web
<View
style={{
width: isWeb ? WEB_PREVIEW_WIDTH : '80%',
@@ -349,21 +388,25 @@ const RecordedPlayback = ({ route }) => {
width: isWeb ? WEB_PREVIEW_WIDTH : '80%',
maxWidth: '100%',
alignSelf: 'center',
marginTop: 6,
alignItems: 'center',
marginTop: 12,
gap: 18,
}}
>
<View style={{ width: '100%' }}>
<Slider
value={fmtSeconds(progress.posS)} // mm:ss (seconds)
maxValue={fmtSeconds(progress.durS)} // mm:ss (seconds)
progress={sliderProgress}
seekEnabled={!!songUrl}
<ProgressSlider
positionMs={progressInfo.pos}
durationMs={progressInfo.dur}
isPlaying={progressInfo.isPlaying}
onSeek={onSeek}
onSeekStart={onSeekStart}
onSeekEnd={onSeekEnd}
onPause={pauseDuringSeek}
onPlay={resumeAfterSeek}
disabled={!songUrl}
/>
<SyncOffsetSlider
valueMs={currentSyncOffsetMs}
onChange={handleSyncOffsetChange}
disabled={!songUrl}
/>
</View>
</View>
</View>
@@ -385,8 +428,9 @@ const RecordedPlayback = ({ route }) => {
} catch {}
navigate(Routes.PlaybackDownload, {
action: 'playback',
uri: videoUri || null, // peut être null sur web
uri: videoUri || null,
project,
syncOffsetMs: syncOffsetRef.current,
})
}}
/>
+6 -2
View File
@@ -24,6 +24,7 @@ import CreateLyricsHeader from '../Writing/components/CreateLyricsHeader'
import { Image as ExpoImage } from 'expo-image'
import SubscriptionConfirmModal from '../../components/SubscriptionConfirmModal'
import { isWeb } from '../../hooks/useLayoutType'
import { clampSyncOffsetMs, toSyncOffsetSeconds } from '../../utils/playbackSync'
const triggerDownload = async (url, title) => {
if (!url) return
@@ -144,13 +145,15 @@ const PlaybackDownload = ({ route }) => {
const { currentUID, selectedProject } = useUserData()
const { hasActiveSubscription, hasPurchased, videos } = useUser() || {}
const { createPlaybackDownloadCheckout } = useStripe()
const { action: routeAction, uri, project: routeProject } = route.params || {}
const { action: routeAction, uri, project: routeProject, syncOffsetMs: routeSyncOffsetMs = 0 } = route.params || {}
const action = routeAction || 'playback'
const syncOffsetMs = clampSyncOffsetMs(routeSyncOffsetMs)
console.log('[PlaybackDownload] route params', {
action,
projectId: routeProject?.id,
hasUri: Boolean(uri),
currentUID,
syncOffsetMs,
})
const { setIsLoading, setTooltip } = useMinuit()
const [isAfterPlaybackVideoVisible, setIsAfterPlaybackVideoVisible] = useState(false)
@@ -259,6 +262,7 @@ const PlaybackDownload = ({ route }) => {
videoUrl,
audioUrl,
storagePath: `users/${currentUID}/projects/${projectForDownload.id}/playback.mp4`,
syncOffset: toSyncOffsetSeconds(syncOffsetMs),
}
console.log('[PlaybackDownload] calling upload-mergeVideoAndAudio', payload)
@@ -297,7 +301,7 @@ const PlaybackDownload = ({ route }) => {
releaseBlobUrl(uri || null)
setIsLoading(false)
}
}, [action, currentUID, pendingPlaybackUrl, projectForDownload, resolveAudioUrl, setIsLoading, uri])
}, [action, currentUID, pendingPlaybackUrl, projectForDownload, resolveAudioUrl, setIsLoading, syncOffsetMs, uri])
const handleDownloadUri = useCallback(async () => {
if (isPublishing || isDownloading) return
+2
View File
@@ -5,6 +5,7 @@ import DeleteAccountModal from '../components/modal/DeleteAccountModal'
import DeletePlaybackModal from '../components/modal/DeletePlaybackModal'
import DeleteAudioModal from '../components/modal/DeleteAudioModal'
import PlaylistModal from '../components/modal/PlaylistModal'
import PlaylistAddTracksModal from '../components/modal/PlaylistAddTracksModal'
import PlaybackPickerModal from '../components/modal/PlaybackPickerModal'
import ShareModal from '../components/modal/ShareModal'
import ReportModal from '../components/modal/ReportModal'
@@ -16,6 +17,7 @@ registerSheet('DeleteAccount', DeleteAccountModal)
registerSheet('DeletePlayback', DeletePlaybackModal)
registerSheet('DeleteAudio', DeleteAudioModal)
registerSheet('Playlist', PlaylistModal)
registerSheet('PlaylistAddTracks', PlaylistAddTracksModal)
registerSheet('PlaybackPicker', PlaybackPickerModal)
registerSheet('Share', ShareModal)
registerSheet('Report', ReportModal)
+59
View File
@@ -0,0 +1,59 @@
export const MAX_SYNC_OFFSET_MS = 2000
export const SYNC_OFFSET_STEP_MS = 50
const toFiniteNumber = (value) => {
const numericValue = Number(value ?? 0)
return Number.isFinite(numericValue) ? numericValue : 0
}
export const clampSyncOffsetMs = (value, maxOffsetMs = MAX_SYNC_OFFSET_MS) => {
const safeMax = Math.max(0, toFiniteNumber(maxOffsetMs))
const safeValue = toFiniteNumber(value)
return Math.min(safeMax, Math.max(-safeMax, safeValue))
}
export const snapSyncOffsetMs = (
value,
stepMs = SYNC_OFFSET_STEP_MS,
maxOffsetMs = MAX_SYNC_OFFSET_MS
) => {
const safeStep = Math.max(1, Math.round(toFiniteNumber(stepMs) || 1))
const clampedValue = clampSyncOffsetMs(value, maxOffsetMs)
return clampSyncOffsetMs(Math.round(clampedValue / safeStep) * safeStep, maxOffsetMs)
}
export const getSyncTrimMs = (syncOffsetMs = 0) => {
const safeOffsetMs = clampSyncOffsetMs(syncOffsetMs)
return {
audioTrimMs: safeOffsetMs < 0 ? Math.abs(safeOffsetMs) : 0,
videoTrimMs: safeOffsetMs > 0 ? safeOffsetMs : 0,
}
}
export const getTimelinePositionMs = (audioPositionMs = 0, syncOffsetMs = 0) => {
const { audioTrimMs } = getSyncTrimMs(syncOffsetMs)
return Math.max(0, toFiniteNumber(audioPositionMs) - audioTrimMs)
}
export const getTimelineDurationMs = (audioDurationMs = 0, syncOffsetMs = 0) => {
const { audioTrimMs } = getSyncTrimMs(syncOffsetMs)
return Math.max(0, toFiniteNumber(audioDurationMs) - audioTrimMs)
}
export const getAudioPositionMs = (timelinePositionMs = 0, syncOffsetMs = 0) => {
const { audioTrimMs } = getSyncTrimMs(syncOffsetMs)
return Math.max(0, toFiniteNumber(timelinePositionMs) + audioTrimMs)
}
export const getVideoPositionMs = (timelinePositionMs = 0, syncOffsetMs = 0) => {
const { videoTrimMs } = getSyncTrimMs(syncOffsetMs)
return Math.max(0, toFiniteNumber(timelinePositionMs) + videoTrimMs)
}
export const formatSyncOffsetMs = (value) => {
const safeValue = snapSyncOffsetMs(value)
if (safeValue === 0) return '0 ms'
return `${safeValue > 0 ? '+' : ''}${safeValue} ms`
}
export const toSyncOffsetSeconds = (value) => clampSyncOffsetMs(value) / 1000