Optical flow-guided video-to-music generation with semantic and temporal alignment

Optical flow-guided video-to-music generation with semantic and temporal alignment

In this section, we introduce FlowHarmony, a latent diffusion approach leveraging optical flow features to generate music that is closely aligned with video content in terms of semantics, temporal progression, and rhythm. The proposed pipeline architecture is illustrated in Fig. 1.

FlowHarmony integrates the semantic representations of video frames with dynamic optical flow features and achieves precise alignment between music and video across semantic, temporal, and rhythmic dimensions through a cross-modal interaction-driven co-constraint mechanism. To ensure rhythmic synchronization, FlowHarmony incorporates an OF-BA, which leverages frame-level optical flow and scene transition information to accurately align musical beats with visual events. In fast-paced scenarios, OF-BA effectively captures motion variations and rhythmic fluctuations within the video, thereby enhancing the dynamic expressiveness and temporal consistency of the generated music. This approach achieves a tight fusion of visual semantics, dynamic optical flow, and rhythmic information, providing a solid foundation for high-quality video-to-music generation.

Fig. 1Fig. 1

The framework of FlowHarmony. The system operates in a latent diffusion framework.

OverView

We propose FlowHarmony, a latent-diffusion-based video-to-music generation framework designed to achieve coordinated alignment between an input video and the generated music at three complementary levels: semantic content, temporal dynamics, and rhythmic structure. The overall framework consists of several tightly coupled components, including multimodal input parsing, modality-specific feature encoding, cross-modal synergistic modeling, optical-flow-guided rhythm alignment, conditional latent diffusion generation, and audio reconstruction. By jointly modeling visual semantics, continuous motion dynamics, textual descriptions, temporal information, and scene-transition events, FlowHarmony constructs hierarchical conditioning representations with semantic, temporal, and rhythmic awareness, thereby providing structured multimodal guidance for subsequent music generation.

Given an input video, FlowHarmony first performs hierarchical video parsing to extract a global emotion label, an overall textual description, local video clips, and their associated temporal information. In parallel, optical flow is computed between adjacent video frames to characterize continuous visual motion, while scene-transition detection is employed to identify salient structural changes in the video. During training, the paired reference music is transformed into time–frequency representations using the Short-Time Fourier Transform (STFT) followed by Mel filtering. Beat detection is additionally applied to the reference music to extract rhythmic event locations, which provide supervision for music generation and visual–rhythmic consistency modeling. Importantly, the paired reference music and its beat information are used only during training and are not required as additional inputs during inference.

After multimodal input parsing, each modality is processed by a dedicated feature encoder. The textual description is encoded by a pretrained text encoder to capture high-level semantic information. Video frames and local video clips are processed by a pretrained visual/video encoder to obtain visual semantic representations. Optical-flow signals are encoded by a motion encoder to characterize continuous motion dynamics, whereas timestamps and clip-position information are modeled through learnable temporal embeddings.

Because these modalities originate from heterogeneous feature spaces and exhibit substantially different dimensionalities and statistical distributions, directly combining their raw representations may result in ineffective multimodal interaction. FlowHarmony therefore first employs modality-specific projection layers to map the heterogeneous features into a unified representation space. The projected features are subsequently processed by the proposed Cross-Modal Synergistic Constraint (CMSC) module to enable multimodal information interaction and fusion.

Specifically, CMSC treats the visual representation at each temporal position as a content-dependent query and employs cross-modal feature attention to adaptively retrieve the optical-flow motion information and textual semantic information that are most relevant to the current visual content. By applying this interaction mechanism to all temporal positions, CMSC produces a temporally ordered cross-modal conditional sequence

$$\begin{aligned} \textbf{F}^{\textrm{cross}} = \begin{bmatrix} \textbf{f}_{1}^{\textrm{cross}} \\ \textbf{f}_{2}^{\textrm{cross}} \\ \vdots \\ \textbf{f}_{T}^{\textrm{cross}} \end{bmatrix} \in \mathbb {R}^{T \times d}, \end{aligned}$$

(1)

where \(\textbf{f}_{t}^{\textrm{cross}}\) denotes the cross-modal representation associated with the t-th video position. It jointly encodes the visual content at the current temporal location together with the motion dynamics and textual semantics that are adaptively associated with that content.

At the overall generation level, the complete cross-modal sequence in Eq. (1) is further organized into a unified cross-modal contextual condition, denoted by \(Z_0\). Accordingly, \(Z_0\) should not be interpreted as a raw feature derived from any individual modality. Instead, it represents a unified contextual representation constructed from the multimodal interactions modeled by CMSC. The modality-specific feature projections, cross-modal attention operations, and contextual representation construction underlying \(Z_0\) are described in detail in the subsequent presentation of the CMSC module.

In addition to semantic correspondence, video-to-music generation requires an explicit temporal relationship between visual dynamics and musical rhythm. To this end, FlowHarmony introduces an Optical Flow-Guided Beat Aligner (OF-BA), which jointly exploits continuous optical-flow variations and discrete scene-transition events to characterize the intrinsic visual rhythmic structure of the input video.

OF-BA first derives a temporally resolved rhythmic representation from visual motion and structural changes, expressed as

$$\begin{aligned} \mathscr {B} = \left\{ \textbf{b}_{1}, \textbf{b}_{2}, \ldots , \textbf{b}_{T} \right\} , \end{aligned}$$

(2)

where \(\textbf{b}_{t}\) denotes the visual rhythmic response at temporal position t. By simultaneously modeling continuous motion variations and salient structural events such as scene transitions, \(\mathscr {B}\) provides an explicit visual-side rhythmic prior for organizing the beat structure of the generated music.

The resulting visual rhythmic sequence is subsequently processed by a learnable temporal modeling network to obtain the final rhythm-aligned condition used for conditional music generation:

$$\begin{aligned} \textbf{r} = E_{\textrm{rhythm}} \left( \textbf{b}_{1}, \textbf{b}_{2}, \ldots , \textbf{b}_{T} \right) , \end{aligned}$$

(3)

where \(E_{\textrm{rhythm}}(\cdot )\) denotes the learnable temporal rhythm encoder. In this formulation, \(\textbf{b}_{t}\) characterizes the instantaneous visual rhythmic response derived from motion variations and scene events, whereas \(\textbf{r}\) denotes the temporally contextualized rhythmic representation supplied to the latent diffusion model. This design enables FlowHarmony to construct rhythm-aware generation conditions solely from optical flow and scene-transition information during inference, without requiring paired reference music or ground-truth beat annotations.

Meanwhile, the sampled video frames are further processed by the visual encoding pathway to construct a fine-grained frame-level visual condition, denoted by \(\textbf{v}\). Accordingly, FlowHarmony employs three complementary conditioning representations for music generation: the cross-modal contextual condition \(Z_0\), the rhythm-aligned condition \(\textbf{r}\), and the fine-grained frame-level visual condition \(\textbf{v}\). Specifically, \(Z_0\) provides multimodal semantic and contextual information, \(\textbf{r}\) captures rhythmic structures associated with visual dynamics, and \(\textbf{v}\) supplies fine-grained visual content at the frame level. Together, these three conditioning representations provide complementary guidance for the subsequent latent diffusion process from the perspectives of semantic context, temporal rhythm, and local visual content.

The core music generation process of FlowHarmony is implemented using a conditional Latent Diffusion Model (LDM). Rather than directly synthesizing music in the high-dimensional waveform space, the proposed model performs iterative generation in a compact music latent space, thereby reducing the dimensionality of the generative process while retaining the structural capacity required for high-quality music synthesis.

At the beginning of the reverse diffusion process, the latent state is initialized by sampling from a standard Gaussian distribution:

$$\begin{aligned} \textbf{x}_{K} \sim \mathscr {N} \left( \textbf{0}, \textbf{I} \right) , \end{aligned}$$

(4)

where \(\textbf{x}_{K}\) denotes the initial latent state of the reverse diffusion process, K is the terminal diffusion step, and \(\textbf{I}\) denotes the identity covariance matrix. Starting from this stochastic latent state, the model progressively reconstructs a structured music representation through iterative conditional denoising.

where K denotes the initial diffusion step of the reverse generation process. Conditioned jointly on the cross-modal context \(Z_0\), the rhythm representation \(\textbf{r}\), and the frame-level visual representation \(\textbf{v}\), the model progressively transforms the random latent variable into a structured music representation through multiple reverse diffusion steps. The overall conditional generation process can be compactly expressed as

$$\begin{aligned} \hat{\textbf{x}}_{0} = \operatorname {LDM}_{\theta } \left( \textbf{x}_{K}; Z_{0}, \textbf{r}, \textbf{v} \right) , \end{aligned}$$

(5)

where \(\operatorname {LDM}_{\theta }(\cdot )\) denotes the complete conditional latent diffusion procedure parameterized by \(\theta \), and \(\hat{\textbf{x}}_0\) denotes the final generated music latent representation obtained after iterative reverse diffusion. Importantly, Eq. (5) provides a compact abstraction of the entire multi-step reverse diffusion trajectory; it should not be interpreted as a single-step deterministic mapping from \(\textbf{x}_K\) directly to \(\hat{\textbf{x}}_0\).

During reverse diffusion, the model starts from the randomly initialized latent variable and progressively restores structured musical information. All three conditioning representations participate in the generation process. Specifically, \(Z_0\) provides high-level information concerning the video theme, emotion, visual semantics, and motion-related contextual cues; \(\textbf{r}\) regulates the correspondence between musical rhythm and visual dynamics; and \(\textbf{v}\) supplies additional fine-grained frame-level visual evidence. Their joint participation enables the generated music latent representation to respond simultaneously to the semantic content, temporal evolution, and rhythmic structure of the input video.

After completing all reverse diffusion steps, the final music latent representation \(\hat{\textbf{x}}_0\) is decoded by an audio variational autoencoder (VAE):

$$\begin{aligned} \hat{\textbf{S}} = D_{\textrm{VAE}} \left( \hat{\textbf{x}}_{0} \right) , \end{aligned}$$

(6)

where \(D_{\textrm{VAE}}(\cdot )\) denotes the audio VAE decoder and \(\hat{\textbf{S}}\) represents the predicted time–frequency representation of the generated music. An appropriate audio reconstruction operation is subsequently employed to transform the decoded time–frequency representation into the final waveform

$$\begin{aligned} \hat{\textbf{a}} = \mathscr {R} \left( \hat{\textbf{S}} \right) , \end{aligned}$$

(7)

where \(\mathscr {R}(\cdot )\) denotes the corresponding spectrogram-to-waveform reconstruction operator. Therefore, the conditional LDM is responsible for stochastic initialization and iterative reverse generation in the music latent space, whereas the VAE decoding and audio reconstruction stages map the generated latent representation back to the perceptually accessible audio domain.

The training data provide paired reference music in the observable audio domain rather than an independently annotated target representation corresponding to the specific latent trajectory produced during reverse diffusion. Accordingly, FlowHarmony does not introduce an artificially constructed music latent target solely for direct latent-space reconstruction. Instead, the paired reference music is exploited to constrain the final generation result in observable acoustic representation spaces. This formulation allows the video-to-music generation process to be supervised using perceptually meaningful acoustic targets while retaining the flexibility of latent-space generative modeling.

Let \(\textbf{S}\) denote the time–frequency representation of the paired reference music and \(\hat{\textbf{S}}\) denote the corresponding representation of the generated music. The spectral reconstruction loss is defined as

$$\begin{aligned} \mathscr {L}_{\textrm{spec}} = \left\Vert \hat{\textbf{S}}-\textbf{S} \right\Vert _{1}. \end{aligned}$$

(8)

To further constrain perceptually relevant spectral structures, supervision is additionally imposed in the Mel-frequency domain. Let \(\textbf{M}\) and \(\hat{\textbf{M}}\) denote the Mel-spectrogram representations of the reference and generated music, respectively. The Mel reconstruction loss is formulated as

$$\begin{aligned} \mathscr {L}_{\textrm{mel}} = \left\Vert \hat{\textbf{M}}-\textbf{M} \right\Vert _{1}, \end{aligned}$$

(9)

The basic music generation objective is therefore defined as

$$\begin{aligned} \mathscr {L}_{\textrm{gen}} = \mathscr {L}_{\textrm{spec}} + \lambda _{\textrm{mel}} \mathscr {L}_{\textrm{mel}}. \end{aligned}$$

(10)

where \(\lambda _{\textrm{mel}}\) controls the relative contribution of the Mel-domain reconstruction constraint.

The losses in Eqs. (8)–(10) provide output-level supervision for the conditional latent generation process through observable acoustic representations. It should be emphasized that the term latent diffusion in FlowHarmony refers to the stochastic initialization and iterative reverse-generation mechanism operating in the music latent space. The framework-level formulation does not require all supervision terms to be expressed exclusively through a particular denoising or noise-prediction parameterization. Instead, the proposed acoustic reconstruction losses and cross-modal consistency objectives can be incorporated as complementary supervision terms while remaining conceptually independent of the specific internal parameterization adopted by the latent diffusion backbone.

Beyond the basic music generation supervision, FlowHarmony introduces auxiliary consistency constraints at the semantic, temporal, and rhythmic levels to further strengthen the correspondence between the input video and the generated music.

The cross-modal representations produced by CMSC and the generated music latent representations naturally reside in different feature spaces. Directly minimizing their distances in the original heterogeneous spaces is therefore neither theoretically well motivated nor sufficiently stable. To establish a meaningful semantic correspondence, we introduce a video-side semantic projection function \(P_{sv}(\cdot )\) and a music-side semantic projection function \(P_{sm}(\cdot )\), which map the two modalities into a shared \(d_s\)-dimensional semantic embedding space:

$$\begin{aligned} \begin{aligned} \textbf{s}*{t}^{v}&= P*{sv} \left( \textbf{f}*{t}^{\textrm{cross}} \right) , \ \textbf{s}*{t}^{m}&= P_{sm} \left( \hat{\textbf{x}}_{0,t} \right) . \end{aligned} \end{aligned}$$

(11)

The projected representations satisfy

$$\begin{aligned} \textbf{s}*{t}^{v}, \textbf{s}*{t}^{m} \in \mathbb {R}^{d_s}, \end{aligned}$$

(12)

where \(\hat{\textbf{x}}_{0,t}\) denotes the local representation corresponding to temporal position t in the final generated music latent sequence. Based on the shared semantic space in Eq. (12), the semantic consistency loss is formulated as

$$\begin{aligned} \mathscr {L}_{\textrm{semantic}} = \frac{1}{T} \sum _{t=1}^{T} \left\Vert P_{sm} \left( \hat{\textbf{x}}_{0,t} \right) – P_{sv} \left( \textbf{f}_{t}^{\textrm{cross}} \right) \right\Vert _{2}^{2}. \end{aligned}$$

(13)

By minimizing the discrepancy between the projected semantic representation of the generated music and the cross-modal video representation produced by CMSC, this objective encourages the generated music to preserve semantic correspondence with the visual content and its associated multimodal context.

It is important to note that \(P_{sv}(\cdot )\) and \(P_{sm}(\cdot )\) are introduced solely to construct a shared semantic space for auxiliary cross-modal consistency learning. They are independent of the specific denoising parameterization employed within the latent diffusion model. Consequently, \(\mathscr {L}_{\textrm{semantic}}\) acts as an auxiliary regularization term on the overall conditional generation process rather than as a replacement for the latent diffusion mechanism itself.

To ensure that dynamic variations in the generated music respond coherently to continuous visual motion, FlowHarmony further establishes a temporal consistency constraint between music-latent dynamics and optical-flow variations.

Because the generated music representation and optical-flow features belong to different modalities, modality-specific temporal projection functions \(P_m(\cdot )\) and \(P_f(\cdot )\) are employed to map them into a shared \(d_{\textrm{temp}}\)-dimensional temporal embedding space:

$$\begin{aligned} \begin{aligned} \textbf{z}*{t}^{m}&= P_m \left( \hat{\textbf{x}}*{0,t} \right) , \ \textbf{z}*{t}^{f}&= P_f \left( \textbf{f}*{t}^{\textrm{flow}} \right) . \end{aligned} \end{aligned}$$

(14)

Here, the encoded optical-flow representation at temporal position t is obtained as

$$\begin{aligned} \textbf{f}_{t}^{\textrm{flow}} = E_{\textrm{flow}} \left( \textbf{F}_{t} \right) . \end{aligned}$$

(15)

where \(\textbf{F}*t\) denotes the optical-flow observation at temporal position t, and \(E*{\textrm{flow}}(\cdot )\) represents the corresponding motion encoder.

Rather than directly aligning the absolute values of heterogeneous representations, FlowHarmony compares their local temporal variations after projection into the shared temporal space. Specifically, the adjacent temporal variation of the generated music representation is defined as

$$\begin{aligned} \Delta \textbf{z}_{t}^{m} = \textbf{z}_{t}^{m} – \textbf{z}_{t-1}^{m}, \qquad t=2,\ldots ,T. \end{aligned}$$

(16)

while the corresponding variation of the visual motion representation is defined as

$$\begin{aligned} \Delta \textbf{z}_{t}^{f} = \textbf{z}_{t}^{f} – \textbf{z}_{t-1}^{f}, \qquad t=2,\ldots ,T. \end{aligned}$$

(17)

The temporal consistency loss is then formulated as

$$\begin{aligned} \mathscr {L}_{\textrm{temporal}} = \frac{1}{T-1} \sum _{t=2}^{T} \left\Vert \Delta \textbf{z}_{t}^{m} – \Delta \textbf{z}_{t}^{f} \right\Vert _{2}^{2}. \end{aligned}$$

(18)

This constraint compares the local variation trends of the generated music and visual motion within a shared temporal embedding space instead of directly matching heterogeneous raw features. It thereby encourages dynamic changes in the generated music to evolve in accordance with continuous motion patterns observed in the input video.

To further strengthen synchronization between musical beats and salient visual events, FlowHarmony exploits the visual rhythmic responses \(\textbf{b}_t\) produced by OF-BA to regularize the rhythmic structure of the generated music.

Let \(B(\cdot )\) denote a beat-response prediction module operating on the generated music latent representation. The predicted musical rhythmic response at temporal position t is defined as

$$\begin{aligned} \hat{\textbf{b}}_{t}^{m} = B \left( \hat{\textbf{x}}_{0,t} \right) . \end{aligned}$$

(19)

The rhythmic consistency loss is subsequently formulated as

$$\begin{aligned} \mathscr {L}_{\textrm{rhythm}} = \frac{1}{T} \sum _{t=1}^{T} \left\Vert \hat{\textbf{b}}_{t}^{m} – \textbf{b}_{t} \right\Vert _{2}^{2}. \end{aligned}$$

(20)

Here, \(\textbf{b}_t\) is constructed by OF-BA from optical-flow variations and scene-transition events and therefore characterizes the visual rhythmic response at the corresponding temporal position. By minimizing the discrepancy in Eq. (20), FlowHarmony explicitly encourages beat-related variations in the generated music to synchronize with salient visual motion and structural events in the video.

Combining the basic acoustic generation supervision with the semantic, temporal, and rhythmic cross-modal consistency constraints, the complete framework-level optimization objective of FlowHarmony is formulated as

$$\begin{aligned} \begin{aligned} \mathscr {L}*{\textrm{total}} ={}&\mathscr {L}*{\textrm{gen}} + \lambda _s \mathscr {L}*{\textrm{semantic}} + \lambda _t \mathscr {L}*{\textrm{temporal}} \&+ \lambda _r \mathscr {L}_{\textrm{rhythm}}, \end{aligned} \end{aligned}$$

(21)

where \(\lambda _s\), \(\lambda _t\), and \(\lambda _r\) denote the weighting coefficients associated with semantic, temporal, and rhythmic consistency, respectively.

The basic generation loss \(\mathscr {L}*{\textrm{gen}}\) exploits paired reference music to supervise the quality of the final generated output in observable acoustic spaces. The semantic consistency loss \(\mathscr {L}*{\textrm{semantic}}\) encourages correspondence between the generated music and the multimodal contextual semantics encoded from the video. The temporal consistency loss \(\mathscr {L}*{\textrm{temporal}}\) establishes a relationship between dynamic variations in the generated music and continuous visual motion. Finally, the rhythmic consistency loss \(\mathscr {L}*{\textrm{rhythm}}\) explicitly reinforces synchronization between musical rhythm and visually salient motion or scene-transition events.

Through the joint optimization of acoustic supervision and multi-level cross-modal consistency regularization, FlowHarmony learns an integrated generative mapping from video-conditioned multimodal representations to the music latent space and ultimately to the reconstructed audio signal. This hierarchical formulation enables the generated music to remain coherent with the input video not only in terms of global semantic content, but also with respect to fine-grained temporal evolution and visually induced rhythmic structure.

Multimodal modeling

To model the multi-level dynamic information of videos, we propose a multimodal information modeling approach. This method leverages multimodal inputs and dedicated feature extraction modules to construct structured and temporally aligned conditional representations, providing comprehensive information for downstream music generation.

In this approach, the model inputs comprise textual information, visual frame sequences, audio signals, and derived alignment features. Textual information includes global emotion labels, joint descriptions of the overall video content, and action- or event-level descriptions for individual shots. These textual inputs are encoded into high-dimensional semantic vectors using the pre-trained language-audio model CLAP32, providing both global semantic context and local semantic conditions.

Visual inputs consist of raw video frame sequences, which are mapped into a latent space via MAViL33, generating dense visual-semantic features. Inter-frame optical flow, computed from the pixel-wise motion between consecutive frames, captures action dynamics and is used to characterize motion patterns and rhythmic information within the video. Specifically, optical flow is estimated using the deep learning network RAFT, and each frame’s motion vectors are encoded as continuous temporal feature sequences to serve as motion references for music rhythm generation. Frame-level scene transition timestamps further annotate key visual cuts, enabling precise alignment between visual events and musical rhythm.

Audio inputs include raw waveforms and spectral features obtained via Short-Time Fourier Transform (STFT) and Mel filtering, capturing timbre and melodic information. Vocal tracks are transcribed into time-aligned text using automatic speech recognition (ASR), while accompaniment tracks are processed through a music understanding model to generate emotion labels, providing conditions for modeling overall thematic and emotional characteristics.

Rhythmic points are extracted from the audio via beat detection, and, in combination with video scene transitions, a transition-beat alignment feature matrix is constructed to achieve precise synchronization between visual events and musical rhythms. Through multi-level feature modeling, the global level provides overall thematic and emotional information, the shot level captures local semantics, actions, and temporal boundaries, and the frame level ensures precise dynamic temporal information. Finally, these features are fused within cross-modal attention modules or conditional diffusion models, providing structured and temporally aligned inputs to the generative model, ensuring that the produced music aligns with the video in terms of semantics, rhythm, and visual events.

Cross-modal synergistic constraint mechanism

The visual and optical-flow features are both organized along the temporal axis of the video and can therefore be aligned at the corresponding temporal positions. In contrast, the length L of the textual sequence generally differs from the number of video frames T. Instead of enforcing a rigid one-to-one correspondence between textual tokens and video frames, CMSC preserves the complete textual feature sequence and allows each video frame to adaptively retrieve the textual semantics that are most relevant to its current visual content through the subsequent attention operation. Compared with simple average pooling over textual features, this design reduces potential semantic information loss and enables different temporal locations in the video to attend to different textual descriptions.

After modality-specific feature projection, we further introduce a Cross-Modal Feature Attention (CFA) mechanism to explicitly model interactions among the visual, motion, and textual modalities. Specifically, the projected visual feature is employed as the query, enabling the current video frame to selectively retrieve complementary motion and textual information according to its visual content. For the t-th video frame, the query representation is defined as

$$\begin{aligned} Q_t = \tilde{f}_t^{\textrm{vid}} W_q, \end{aligned}$$

(22)

where \(W_q\) denotes the learnable query projection matrix.

To construct the cross-modal context, the projected optical-flow and textual features are first organized into two feature matrices:

$$\begin{aligned} \tilde{\textbf{F}}^{\textrm{flow}} = \begin{bmatrix} \tilde{f}_1^{\textrm{flow}} \\ \tilde{f}_2^{\textrm{flow}} \\ \vdots \\ \tilde{f}_T^{\textrm{flow}} \end{bmatrix} \in \mathbb {R}^{T \times d}, \end{aligned}$$

(23)

$$\begin{aligned} \tilde{\textbf{F}}^{\textrm{text}} = \begin{bmatrix} \tilde{f}_1^{\textrm{text}} \\ \tilde{f}_2^{\textrm{text}} \\ \vdots \\ \tilde{f}_L^{\textrm{text}} \end{bmatrix} \in \mathbb {R}^{L \times d}. \end{aligned}$$

(24)

The optical-flow and textual representations are then concatenated along the sequence dimension to construct a unified cross-modal context:

$$\begin{aligned} C = \begin{bmatrix} \tilde{\textbf{F}}^{\textrm{flow}} \\ \tilde{\textbf{F}}^{\textrm{text}} \end{bmatrix} \in \mathbb {R}^{(T+L)\times d}, \end{aligned}$$

(25)

where the concatenation is performed along the sequence dimension. Based on this cross-modal context, the key and value representations are obtained as

$$\begin{aligned} K = C W_k, \qquad V = C W_v, \end{aligned}$$

(26)

where \(W_k\) and \(W_v\) denote the learnable key and value projection matrices, respectively. Let the attention dimension be \(d_k\), and let \(W_q\), \(W_k\), and \(W_v\) satisfy

$$\begin{aligned} W_q, W_k, W_v \in \mathbb {R}^{d \times d_k}. \end{aligned}$$

(27)

Accordingly, \(Q_t \in \mathbb {R}^{1 \times d_k}\), while \(K,V \in \mathbb {R}^{(T+L)\times d_k}\). For each video time step t, the cross-modal attention weights are computed as

$$\begin{aligned} A_t = \operatorname {Softmax} \left( \frac{Q_t K^{\top }}{\sqrt{d_k}} \right) , \end{aligned}$$

(28)

where \(A_t \in \mathbb {R}^{1 \times (T+L)}\) represents the relevance scores between the current video frame and the elements of the cross-modal context. The value representations are subsequently aggregated according to these attention weights to obtain the cross-modal attention representation for the current frame:

$$\begin{aligned} h_t^{\textrm{att}} = A_t V. \end{aligned}$$

(29)

This operation enables CMSC to adaptively select complementary information from different modalities according to the content of the current video frame. For example, when substantial motion changes occur in the video, the visual query can assign larger attention weights to the relevant optical-flow representations. Conversely, when the visual content is strongly associated with particular scenes, objects, or affective semantics, the model can place greater emphasis on the corresponding textual representations. Therefore, rather than directly using concatenated heterogeneous features as the final fused representation, CFA explicitly models cross-modal dependencies and selectively aggregates information that is relevant to the current visual content while suppressing redundant or irrelevant cues.

To preserve the frame-level visual semantics while incorporating complementary cross-modal information, CMSC further combines the attention output with the projected visual representation through a residual connection:

$$\begin{aligned} f_t^{\textrm{cross}} = \tilde{f}_t^{\textrm{vid}} + h_t^{\textrm{att}} W_o, \end{aligned}$$

(30)

where \(W_o \in \mathbb {R}^{d_k \times d}\) denotes the learnable output projection matrix. The output projection maps the cross-modal attention representation from the \(d_k\)-dimensional attention space back to the unified d-dimensional embedding space, thereby enabling residual addition with the projected visual feature \(\tilde{f}_t^{\textrm{vid}}\). This residual fusion strategy allows the resulting representation to preserve the core visual semantics of the current frame while incorporating motion dynamics and textual semantics that are relevant to the corresponding visual content.

By applying the above operation to all video time steps, CMSC produces the complete cross-modal conditional sequence

$$\begin{aligned} \textbf{F}^{\textrm{cross}} = \begin{bmatrix} f_1^{\textrm{cross}} \\ f_2^{\textrm{cross}} \\ \vdots \\ f_T^{\textrm{cross}} \end{bmatrix} \in \mathbb {R}^{T \times d}. \end{aligned}$$

(31)

The resulting \(\textbf{F}^{\textrm{cross}}\) serves as the output of the CMSC module and provides a unified cross-modal conditional representation for subsequent music generation. Compared with using visual features alone, this representation not only preserves frame-level visual semantics but also explicitly incorporates video motion dynamics and high-level textual semantics, thereby providing a more comprehensive representation of the semantic content and temporal dynamics of the input video.

From an implementation perspece, CMSC can be summarized into four stages. First, visual, optical-flow, and textual features are independently extracted from their corresponding input modalities. Second, the three heterogeneous feature types are mapped into a unified tivd-dimensional cross-modal interaction space through modality-specific learnable linear projections. Third, the projected visual features are used as queries, while the projected optical-flow and textual features jointly construct the keys and values for CFA, enabling adaptive cross-modal information retrieval and aggregation. Finally, the attended cross-modal representation is mapped back to the unified embedding space through an output projection and fused with the projected visual representation via a residual connection, yielding the frame-level cross-modal representation \(\textbf{F}^{\textrm{cross}}\). Therefore, rather than simply concatenating multimodal features, CMSC dynamically selects the motion and textual information that is most relevant to the current visual content, thereby enabling fine-grained synergistic modeling of visual semantics, motion dynamics, and textual information (Fig. 2).

Fig. 2Fig. 2

Architecture of FlowHarmony with CMSC mechanism.

The temporal consistency loss is formulated as

Optical flow-guided beat aligner

As illustrated in Fig.  3, to achieve precise rhythmic alignment between the generated music and dynamic visual events in videos, especially under fast-paced scenarios, we introduce the OF-BA. This module leverages frame-level optical flow features and scene transition signals to predict the target music beat positions, which subsequently guide the latent diffusion music generator.

Fig. 3Fig. 3

Overview of the optical flow-guided beat aligner (OF-BA) module in a latent diffusion framework for video background music generation.

Given a video frame sequence \(\textbf{V} = \{v_1, \dots , v_T\}\), the corresponding optical flow features \(\textbf{F} = \{\textbf{F}_1, \dots , \textbf{F}_T\}\), and scene transition signals \(\textbf{S} = \{s_1, \dots , s_T\}\), OF-BA computes the frame-wise motion differences:

$$\begin{aligned} \Delta \textbf{F}_t = \textbf{F}_t – \textbf{F}_{t-1}, \quad t = 2, \dots , T \end{aligned}$$

(32)

These differences are normalized to generate frame-level rhythm sensitivity weights:

$$\begin{aligned} \alpha _t = \sigma \big (\Vert \Delta \textbf{F}_t\Vert _2\big ) \end{aligned}$$

(33)

where \(\sigma (\cdot )\) denotes the Sigmoid or other normalization function.

To emphasize beats at scene transitions, the weights are enhanced by the scene signals:

$$\begin{aligned} \tilde{\alpha }_t = \alpha _t + \beta s_t \end{aligned}$$

(34)

where \(\beta \) is a hyperparameter controlling the contribution of scene transitions to beat alignment.

The target beat position \(\textbf{b}_t\) for frame t is predicted via a lightweight feed-forward network:

$$\begin{aligned} \textbf{b}_t = \text {MLP}([\tilde{\alpha }_t, \textbf{b}_{t-1}]) \end{aligned}$$

(35)

where \([\cdot ,\cdot ]\) denotes concatenation and \(\textbf{b}_{t-1}\) is the beat of the previous frame to ensure smooth transitions.

Finally, during training, the predicted beats supervise the latent diffusion music generator through a rhythm loss:

$$\begin{aligned} \mathscr {L}_\text {rhythm} = \frac{1}{T} \sum _{t=1}^{T} \Vert \text {beat}(x_0^t) – \textbf{b}_t\Vert ^2 \end{aligned}$$

(36)

where \(x_0^t\) represents the generated music latent at frame t, and \(\text {beat}(\cdot )\) extracts the corresponding musical beat.

In summary, OF-BA enables precise frame-level alignment of music beats with video dynamics by integrating optical flow-based motion cues and scene transition signals. This module substantially enhances the dynamic expressiveness and temporal consistency of generated music, particularly in fast-paced visual scenarios.

Latent music diffusion

To ensure a high degree of consistency between video and music, we integrate a Latent Diffusion Model (LDM) with hierarchical video representations, utilizing the latent encoding of audio as a conditional signal. Specifically, we introduce a joint latent representation of audio and video throughout both the forward diffusion and reverse generation processes, enabling the synthesis of music that is rigorously aligned with the visual content.

In the forward diffusion phase, we process the latent encodings of both video and audio. The latent representation of the video is derived from a pre-trained visual encoder, while the audio latent encoding is generated by an audio encoder. These representations, \(z_{\text {video}}\) and \(z_{\text {audio}}\), serve as conditional inputs to the diffusion process. The diffusion mechanism progressively injects noise into the input, governed by a noise schedule hyperparameter \(\beta _t\). Given the latent variable \(z_{t-1}\) at step \(t-1\), the distribution of \(z_t\) at step t is defined as

$$\begin{aligned} q(z_t | z_{t-1}) = \mathscr {N}(z_t; \sqrt{1 – \beta _t} z_{t-1}, \beta _t I) \end{aligned}$$

(37)

where \(\beta _t \in [0, 1]\) controls the rate of noise application. By recursively substituting \(q(z_t | z_{t-1})\), the cumulative diffusion process is derived as

$$\begin{aligned} q(z_t | z_0) = \mathscr {N}(z_t; \sqrt{\bar{\alpha }_t} z_0, (1 – \bar{\alpha }_t) I) \end{aligned}$$

(38)

where \(\alpha _t = 1 – \beta _t\), and \(\bar{\alpha }_t = \prod _{s=1}^{t} \alpha _s\) represents the cumulative noise level at timestep t. The final state \(z_T \sim \mathscr {N}(0, I)\) indicates that at step T, the latent variable \(z_T\) approximates a standard isotropic Gaussian distribution.

In the reverse generation phase, we employ a Transformer-UNet (T-UNet) architecture to jointly optimize the latent representations of audio and video. The objective of the T-UNet is to estimate the noise and learn the reverse transition from the standard Gaussian distribution \(\mathscr {N}(0, I)\) to the target latent representation \(z_0\). The optimization goal is to minimize the error between the actual noise \(\epsilon \) and the predicted noise \(\epsilon _\theta \), defined by the objective function:

$$\begin{aligned} L = \mathbb {E}_{z_0, \epsilon \sim \mathscr {N}(0,1), t, c}\left[ \left\| \epsilon – \epsilon _\theta (z_t, t, c) \right\| ^2 \right] \end{aligned}$$

(39)

where \(\epsilon _\theta (z_t, t, c)\) is the noise predicted by the T-UNet, and c denotes the conditional signal, which encapsulates the latent encodings of both audio and video.

During the reverse process within the T-UNet, the latent encodings of audio \(z_{\text {audio}}\) and video \(z_{\text {video}}\) are provided as joint conditional signals. Ultimately, the prior \(z_0\) is reconstructed iteratively according to

$$\begin{aligned} p_\theta (z_{0:T} | c) = p(z_T) \prod _{t=1}^{T} p_\theta (z_{t-1} | z_t, c) \end{aligned}$$

(40)

where the conditional probability of the reverse transition, \(p_\theta (z_{t-1} | z_t, c)\), is modeled as

$$\begin{aligned} p_\theta (z_{t-1} | z_t, c) = \mathscr {N}(z_{t-1}; \mu _\theta (z_t, t, c), \sigma _t^2 I) \end{aligned}$$

(41)

Here, \(\mu _\theta \) represents the parameterized mean predicted by the network, and \(\sigma _t\) denotes the variance. Through this mechanism, the LDM synthesizes music that is synchronized with the video content, ensuring high consistency in rhythm, emotion, and visual narrative between the audio and video modalities.

In summary, by combining the Latent Diffusion Model with hierarchical video representations, we achieve precise cross-modal generation within the joint latent space of audio and video. This approach not only ensures synchronization between the music and the video but also significantly enhances the overall audiovisual immersion.