visualkit 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1356 @@
1
+ import logging
2
+ import math
3
+ import os
4
+
5
+ import cv2
6
+ import numpy as np
7
+
8
+ from visualkit.config import VideoConfig
9
+
10
+ # Configure logging
11
+ logging.basicConfig(level=logging.INFO)
12
+ logger = logging.getLogger(__name__)
13
+
14
+
15
+ class MediaElement:
16
+ def __init__(self, asset_path: str, duration: float, effect_type: str = "none"):
17
+ if not os.path.exists(asset_path):
18
+ raise FileNotFoundError(f"Media file not found: {asset_path}")
19
+ if duration <= 0:
20
+ raise ValueError("Duration must be positive")
21
+ self.asset_path = asset_path
22
+ self.duration = duration
23
+ self.effect_type = effect_type
24
+ self._cached_frame = None
25
+ self._last_timestamp = -1
26
+ self._last_effect_frame = None
27
+ self._cap = None # For video sources
28
+
29
+ @staticmethod
30
+ def get_available_effects():
31
+ """Return a list of all available effects"""
32
+ return [
33
+ "none",
34
+ "zoom",
35
+ "brightness",
36
+ "blur",
37
+ "pan_left",
38
+ "pan_right",
39
+ "pan_up",
40
+ "pan_down",
41
+ "zoom_out",
42
+ "rotate_clockwise",
43
+ "rotate_counterclockwise",
44
+ "shake",
45
+ "bounce",
46
+ "pulse",
47
+ "fade_in",
48
+ "fade_out",
49
+ "spiral",
50
+ # New effects
51
+ "swing",
52
+ "sway",
53
+ "elastic_zoom",
54
+ "rubber_band",
55
+ "zoom_bounce",
56
+ "zoom_elastic",
57
+ "ken_burns",
58
+ "float",
59
+ "drift",
60
+ "hover",
61
+ "wave",
62
+ "ripple",
63
+ ]
64
+
65
+ @staticmethod
66
+ def get_moving_effects():
67
+ """Return a list of effects that involve movement"""
68
+ return [
69
+ "none",
70
+ "zoom",
71
+ "pan_left",
72
+ "pan_right",
73
+ "pan_up",
74
+ "pan_down",
75
+ "zoom_out",
76
+ "rotate_clockwise",
77
+ "rotate_counterclockwise",
78
+ "shake",
79
+ "bounce",
80
+ "pulse",
81
+ "fade_in",
82
+ "fade_out",
83
+ "spiral",
84
+ "swing",
85
+ "sway",
86
+ "elastic_zoom",
87
+ "rubber_band",
88
+ "zoom_bounce",
89
+ "zoom_elastic",
90
+ "ken_burns",
91
+ "float",
92
+ "drift",
93
+ "hover",
94
+ "wave",
95
+ "ripple",
96
+ ]
97
+
98
+ def _scale_and_crop_internal(self, frame: np.ndarray, scale: float) -> np.ndarray:
99
+ """Internal method to scale frame without cropping to target dimensions"""
100
+ if scale <= 0:
101
+ scale = 1.0
102
+
103
+ h, w = frame.shape[:2]
104
+ new_h, new_w = int(h * scale), int(w * scale)
105
+
106
+ if new_h <= 0 or new_w <= 0:
107
+ return frame
108
+
109
+ return cv2.resize(frame, (new_w, new_h), interpolation=cv2.INTER_AREA)
110
+
111
+ def get_frame(self, timestamp: float, config: VideoConfig) -> np.ndarray:
112
+ try:
113
+ if self._cached_frame is None:
114
+ self._load_and_resize(config)
115
+ if (
116
+ self._last_effect_frame is None
117
+ or abs(timestamp - self._last_timestamp) > 0.01
118
+ ):
119
+ frame = self._cached_frame.copy()
120
+ if frame.shape[:2] != (
121
+ config.height,
122
+ config.width,
123
+ ): # Validate dimensions
124
+ frame = cv2.resize(
125
+ frame,
126
+ (config.width, config.height),
127
+ interpolation=cv2.INTER_AREA,
128
+ )
129
+ frame = self._apply_effect(frame, timestamp, config)
130
+ self._last_effect_frame = frame
131
+ self._last_timestamp = timestamp
132
+ return self._last_effect_frame.copy()
133
+ except Exception:
134
+ # logger.error(f"Error getting frame from {self.asset_path}: {e}")
135
+ return np.zeros((config.height, config.width, 3), dtype=np.uint8)
136
+
137
+ def _load_and_resize(self, config: VideoConfig):
138
+ option = config.resize_method.lower()
139
+ if option == "smart":
140
+ self._load_and_resize_fill_smart(config)
141
+ elif option == "adaptive":
142
+ self._load_and_resize_fill_adaptive(config)
143
+ elif option == "gradual":
144
+ self._load_and_resize_fill_gradual(config)
145
+ elif option == "aspect_ratio":
146
+ self._load_and_resize_with_aspect_ratio(config)
147
+ elif option == "fill":
148
+ self._load_and_resize_fill_direct(config)
149
+ else:
150
+ self._load_and_resize_with_aspect_ratio(config)
151
+
152
+ def _load_and_resize_fill_direct(self, config: VideoConfig):
153
+ """
154
+ Load and resize media to fill entire screen without preserving aspect ratio.
155
+ This is the most direct approach - simply stretch to fit target dimensions.
156
+ """
157
+ try:
158
+ if self.asset_path.lower().endswith((".jpg", ".jpeg", ".png", ".bmp")):
159
+ original_frame = cv2.imread(self.asset_path)
160
+ else:
161
+ if self._cap is None:
162
+ self._cap = cv2.VideoCapture(self.asset_path)
163
+ ret, original_frame = self._cap.read()
164
+ if not ret:
165
+ raise ValueError("Could not read video file")
166
+
167
+ if original_frame is None:
168
+ raise ValueError("Could not load media file")
169
+
170
+ # Create enlarged frame for movement effects (2.5x size)
171
+ enlarged_w = int(config.width * 2.5)
172
+ enlarged_h = int(config.height * 2.5)
173
+
174
+ # Simply resize to fill entire enlarged dimensions (may change aspect ratio)
175
+ self._cached_frame = cv2.resize(
176
+ original_frame, (enlarged_w, enlarged_h), interpolation=cv2.INTER_AREA
177
+ )
178
+
179
+ except Exception as e:
180
+ logger.error(f"Error loading media {self.asset_path}: {e}")
181
+ # Create enlarged black frame as fallback
182
+ enlarged_w = int(config.width * 2.5)
183
+ enlarged_h = int(config.height * 2.5)
184
+ self._cached_frame = np.zeros((enlarged_h, enlarged_w, 3), dtype=np.uint8)
185
+
186
+ def _load_and_resize_fill_smart(self, config: VideoConfig):
187
+ """
188
+ Load and resize image/video to fill the target dimensions with minimal stretching.
189
+ Uses smart cropping to remove less important areas before stretching.
190
+ """
191
+ try:
192
+ if self.asset_path.lower().endswith((".jpg", ".jpeg", ".png", ".bmp")):
193
+ original_frame = cv2.imread(self.asset_path)
194
+ else:
195
+ if self._cap is None:
196
+ self._cap = cv2.VideoCapture(self.asset_path)
197
+ ret, original_frame = self._cap.read()
198
+ if not ret:
199
+ raise ValueError("Could not read video file")
200
+
201
+ if original_frame is None:
202
+ raise ValueError("Could not load media file")
203
+
204
+ # Store original frame at higher resolution for movement effects
205
+ original_h, original_w = original_frame.shape[:2]
206
+
207
+ # Create enlarged frame for movement effects (2.5x size)
208
+ enlarged_w = int(config.width * 2.5)
209
+ enlarged_h = int(config.height * 2.5)
210
+
211
+ # Calculate aspect ratios
212
+ original_aspect = original_w / original_h
213
+ target_aspect = enlarged_w / enlarged_h
214
+
215
+ # Maximum allowed stretch factor to avoid extreme distortion
216
+ max_stretch_factor = 1.4
217
+
218
+ # Calculate what the dimensions would be if we just stretched
219
+ stretch_factor_w = enlarged_w / original_w
220
+ stretch_factor_h = enlarged_h / original_h
221
+ max_stretch = max(stretch_factor_w, stretch_factor_h)
222
+
223
+ if max_stretch <= max_stretch_factor:
224
+ # Stretching is acceptable, just resize directly
225
+ resized = cv2.resize(
226
+ original_frame,
227
+ (enlarged_w, enlarged_h),
228
+ interpolation=cv2.INTER_AREA,
229
+ )
230
+ self._cached_frame = resized
231
+ else:
232
+ # Need to crop first to reduce stretching
233
+ if original_aspect > target_aspect:
234
+ # Image is wider than target, crop width
235
+ # Calculate how much width we can afford to crop
236
+ ideal_crop_w = int(original_h * target_aspect)
237
+ min_crop_w = int(original_h * target_aspect / max_stretch_factor)
238
+
239
+ # Use smart cropping - prefer center crop but can adjust
240
+ crop_w = max(min_crop_w, min(ideal_crop_w, original_w))
241
+ crop_x = (original_w - crop_w) // 2
242
+
243
+ # Apply crop
244
+ cropped = original_frame[:, crop_x : crop_x + crop_w]
245
+ else:
246
+ # Image is taller than target, crop height
247
+ ideal_crop_h = int(original_w / target_aspect)
248
+ min_crop_h = int(original_w / target_aspect / max_stretch_factor)
249
+
250
+ # Use smart cropping - prefer center crop but can adjust
251
+ crop_h = max(min_crop_h, min(ideal_crop_h, original_h))
252
+ crop_y = (original_h - crop_h) // 2
253
+
254
+ # Apply crop
255
+ cropped = original_frame[crop_y : crop_y + crop_h, :]
256
+
257
+ # Now resize the cropped image
258
+ resized = cv2.resize(
259
+ cropped, (enlarged_w, enlarged_h), interpolation=cv2.INTER_AREA
260
+ )
261
+ self._cached_frame = resized
262
+
263
+ except Exception as e:
264
+ logger.error(f"Error loading media {self.asset_path}: {e}")
265
+ # Create enlarged black frame as fallback
266
+ enlarged_w = int(config.width * 2.5)
267
+ enlarged_h = int(config.height * 2.5)
268
+ self._cached_frame = np.zeros((enlarged_h, enlarged_w, 3), dtype=np.uint8)
269
+
270
+ def _load_and_resize_fill_adaptive(self, config: VideoConfig):
271
+ """
272
+ Load and resize with adaptive stretching - more stretching for minor differences,
273
+ less stretching for major aspect ratio differences.
274
+ """
275
+ try:
276
+ if self.asset_path.lower().endswith((".jpg", ".jpeg", ".png", ".bmp")):
277
+ original_frame = cv2.imread(self.asset_path)
278
+ else:
279
+ if self._cap is None:
280
+ self._cap = cv2.VideoCapture(self.asset_path)
281
+ ret, original_frame = self._cap.read()
282
+ if not ret:
283
+ raise ValueError("Could not read video file")
284
+
285
+ if original_frame is None:
286
+ raise ValueError("Could not load media file")
287
+
288
+ original_h, original_w = original_frame.shape[:2]
289
+
290
+ # Create enlarged frame for movement effects
291
+ enlarged_w = int(config.width * 2.5)
292
+ enlarged_h = int(config.height * 2.5)
293
+
294
+ # Calculate aspect ratios
295
+ original_aspect = original_w / original_h
296
+ target_aspect = enlarged_w / enlarged_h
297
+ aspect_ratio_diff = abs(original_aspect - target_aspect) / target_aspect
298
+
299
+ # Adaptive approach based on aspect ratio difference
300
+ if aspect_ratio_diff < 0.1:
301
+ # Very similar aspect ratios - just stretch
302
+ resized = cv2.resize(
303
+ original_frame,
304
+ (enlarged_w, enlarged_h),
305
+ interpolation=cv2.INTER_AREA,
306
+ )
307
+ self._cached_frame = resized
308
+
309
+ elif aspect_ratio_diff < 0.3:
310
+ # Moderate difference - slight crop + stretch
311
+ if original_aspect > target_aspect:
312
+ # Crop 15% from width
313
+ crop_w = int(original_w * 0.85)
314
+ crop_x = (original_w - crop_w) // 2
315
+ cropped = original_frame[:, crop_x : crop_x + crop_w]
316
+ else:
317
+ # Crop 15% from height
318
+ crop_h = int(original_h * 0.85)
319
+ crop_y = (original_h - crop_h) // 2
320
+ cropped = original_frame[crop_y : crop_y + crop_h, :]
321
+
322
+ resized = cv2.resize(
323
+ cropped, (enlarged_w, enlarged_h), interpolation=cv2.INTER_AREA
324
+ )
325
+ self._cached_frame = resized
326
+
327
+ else:
328
+ # Large difference - more aggressive cropping
329
+ if original_aspect > target_aspect:
330
+ # Crop to target aspect ratio + 20% margin
331
+ target_w = int(original_h * target_aspect * 1.2)
332
+ crop_w = min(target_w, original_w)
333
+ crop_x = (original_w - crop_w) // 2
334
+ cropped = original_frame[:, crop_x : crop_x + crop_w]
335
+ else:
336
+ # Crop to target aspect ratio + 20% margin
337
+ target_h = int(original_w / target_aspect * 1.2)
338
+ crop_h = min(target_h, original_h)
339
+ crop_y = (original_h - crop_h) // 2
340
+ cropped = original_frame[crop_y : crop_y + crop_h, :]
341
+
342
+ resized = cv2.resize(
343
+ cropped, (enlarged_w, enlarged_h), interpolation=cv2.INTER_AREA
344
+ )
345
+ self._cached_frame = resized
346
+
347
+ except Exception as e:
348
+ logger.error(f"Error loading media {self.asset_path}: {e}")
349
+ enlarged_w = int(config.width * 2.5)
350
+ enlarged_h = int(config.height * 2.5)
351
+ self._cached_frame = np.zeros((enlarged_h, enlarged_w, 3), dtype=np.uint8)
352
+
353
+ def _load_and_resize_fill_gradual(self, config: VideoConfig):
354
+ """
355
+ Load and resize with gradual stretching - combines cropping and stretching
356
+ in a balanced way to minimize visual distortion.
357
+ """
358
+ try:
359
+ if self.asset_path.lower().endswith((".jpg", ".jpeg", ".png", ".bmp")):
360
+ original_frame = cv2.imread(self.asset_path)
361
+ else:
362
+ if self._cap is None:
363
+ self._cap = cv2.VideoCapture(self.asset_path)
364
+ ret, original_frame = self._cap.read()
365
+ if not ret:
366
+ raise ValueError("Could not read video file")
367
+
368
+ if original_frame is None:
369
+ raise ValueError("Could not load media file")
370
+
371
+ original_h, original_w = original_frame.shape[:2]
372
+
373
+ # Create enlarged frame for movement effects
374
+ enlarged_w = int(config.width * 2.5)
375
+ enlarged_h = int(config.height * 2.5)
376
+
377
+ original_aspect = original_w / original_h
378
+ target_aspect = enlarged_w / enlarged_h
379
+
380
+ # Calculate intermediate dimensions that balance cropping and stretching
381
+ if original_aspect > target_aspect:
382
+ # Image is wider - crop some width and stretch the rest
383
+ crop_factor = 0.7 # Keep 70% of width difference
384
+ ideal_w = int(original_h * target_aspect)
385
+ crop_w = int(ideal_w + (original_w - ideal_w) * crop_factor)
386
+ crop_x = (original_w - crop_w) // 2
387
+
388
+ intermediate_frame = original_frame[:, crop_x : crop_x + crop_w]
389
+ else:
390
+ # Image is taller - crop some height and stretch the rest
391
+ crop_factor = 0.7 # Keep 70% of height difference
392
+ ideal_h = int(original_w / target_aspect)
393
+ crop_h = int(ideal_h + (original_h - ideal_h) * crop_factor)
394
+ crop_y = (original_h - crop_h) // 2
395
+
396
+ intermediate_frame = original_frame[crop_y : crop_y + crop_h, :]
397
+
398
+ # Resize the intermediate frame to final dimensions
399
+ resized = cv2.resize(
400
+ intermediate_frame,
401
+ (enlarged_w, enlarged_h),
402
+ interpolation=cv2.INTER_AREA,
403
+ )
404
+ self._cached_frame = resized
405
+
406
+ except Exception as e:
407
+ logger.error(f"Error loading media {self.asset_path}: {e}")
408
+ enlarged_w = int(config.width * 2.5)
409
+ enlarged_h = int(config.height * 2.5)
410
+ self._cached_frame = np.zeros((enlarged_h, enlarged_w, 3), dtype=np.uint8)
411
+
412
+ def _load_and_resize_with_aspect_ratio(self, config: VideoConfig):
413
+ try:
414
+ if self.asset_path.lower().endswith((".jpg", ".jpeg", ".png", ".bmp")):
415
+ original_frame = cv2.imread(self.asset_path)
416
+ else:
417
+ if self._cap is None:
418
+ self._cap = cv2.VideoCapture(self.asset_path)
419
+ ret, original_frame = self._cap.read()
420
+ if not ret:
421
+ raise ValueError("Could not read video file")
422
+ if original_frame is None:
423
+ raise ValueError("Could not load media file")
424
+
425
+ # Store original frame at higher resolution for movement effects
426
+ original_h, original_w = original_frame.shape[:2]
427
+ target_w, target_h = config.width, config.height
428
+
429
+ # Create a much larger frame for movement effects (2.5x size for better movement space) # noqa: E501
430
+ enlarged_w = int(target_w * 2.5)
431
+ enlarged_h = int(target_h * 2.5)
432
+
433
+ original_aspect = original_w / original_h
434
+ enlarged_aspect = enlarged_w / enlarged_h
435
+
436
+ if original_aspect > enlarged_aspect:
437
+ new_h = enlarged_h
438
+ new_w = int(enlarged_h * original_aspect)
439
+ else:
440
+ new_w = enlarged_w
441
+ new_h = int(enlarged_w / original_aspect)
442
+
443
+ resized = cv2.resize(
444
+ original_frame, (new_w, new_h), interpolation=cv2.INTER_AREA
445
+ )
446
+
447
+ # Center crop to enlarged size
448
+ y_offset = max(0, (new_h - enlarged_h) // 2)
449
+ x_offset = max(0, (new_w - enlarged_w) // 2)
450
+ cropped = resized[
451
+ y_offset : y_offset + enlarged_h, x_offset : x_offset + enlarged_w
452
+ ]
453
+
454
+ # Pad if needed
455
+ if cropped.shape[:2] != (enlarged_h, enlarged_w):
456
+ padded = np.zeros((enlarged_h, enlarged_w, 3), dtype=np.uint8)
457
+ y_start = (enlarged_h - cropped.shape[0]) // 2
458
+ x_start = (enlarged_w - cropped.shape[1]) // 2
459
+ padded[
460
+ y_start : y_start + cropped.shape[0],
461
+ x_start : x_start + cropped.shape[1],
462
+ ] = cropped
463
+ self._cached_frame = padded
464
+ else:
465
+ self._cached_frame = cropped
466
+
467
+ except Exception:
468
+ # logger.error(f"Error loading media {self.asset_path}: {e}")
469
+ # Create enlarged black frame
470
+ enlarged_w = int(config.width * 2.5)
471
+ enlarged_h = int(config.height * 2.5)
472
+ self._cached_frame = np.zeros((enlarged_h, enlarged_w, 3), dtype=np.uint8)
473
+
474
+ def _apply_effect(
475
+ self, frame: np.ndarray, timestamp: float, config: VideoConfig
476
+ ) -> np.ndarray:
477
+ """Apply the specified effect to the frame"""
478
+ if self.effect_type == "zoom":
479
+ return self._apply_zoom(frame, timestamp, config)
480
+ if self.effect_type == "brightness":
481
+ return self._apply_brightness(frame, timestamp, config)
482
+ if self.effect_type == "blur":
483
+ return self._apply_blur(frame, timestamp, config)
484
+ if self.effect_type == "pan_left":
485
+ return self._apply_pan_left(frame, timestamp, config)
486
+ if self.effect_type == "pan_right":
487
+ return self._apply_pan_right(frame, timestamp, config)
488
+ if self.effect_type == "pan_up":
489
+ return self._apply_pan_up(frame, timestamp, config)
490
+ if self.effect_type == "pan_down":
491
+ return self._apply_pan_down(frame, timestamp, config)
492
+ if self.effect_type == "zoom_out":
493
+ return self._apply_zoom_out(frame, timestamp, config)
494
+ if self.effect_type == "rotate_clockwise":
495
+ return self._apply_rotate_clockwise(frame, timestamp, config)
496
+ if self.effect_type == "rotate_counterclockwise":
497
+ return self._apply_rotate_counterclockwise(frame, timestamp, config)
498
+ if self.effect_type == "shake":
499
+ return self._apply_shake(frame, timestamp, config)
500
+ if self.effect_type == "bounce":
501
+ return self._apply_bounce(frame, timestamp, config)
502
+ if self.effect_type == "pulse":
503
+ return self._apply_pulse(frame, timestamp, config)
504
+ if self.effect_type == "fade_in":
505
+ return self._apply_fade_in(frame, timestamp, config)
506
+ if self.effect_type == "fade_out":
507
+ return self._apply_fade_out(frame, timestamp, config)
508
+ if self.effect_type == "spiral":
509
+ return self._apply_spiral(frame, timestamp, config)
510
+ # New effects
511
+ if self.effect_type == "swing":
512
+ return self._apply_swing(frame, timestamp, config)
513
+ if self.effect_type == "sway":
514
+ return self._apply_sway(frame, timestamp, config)
515
+ if self.effect_type == "elastic_zoom":
516
+ return self._apply_elastic_zoom(frame, timestamp, config)
517
+ if self.effect_type == "rubber_band":
518
+ return self._apply_rubber_band(frame, timestamp, config)
519
+ if self.effect_type == "zoom_bounce":
520
+ return self._apply_zoom_bounce(frame, timestamp, config)
521
+ if self.effect_type == "zoom_elastic":
522
+ return self._apply_zoom_elastic(frame, timestamp, config)
523
+ if self.effect_type == "ken_burns":
524
+ return self._apply_ken_burns(frame, timestamp, config)
525
+ if self.effect_type == "float":
526
+ return self._apply_float(frame, timestamp, config)
527
+ if self.effect_type == "drift":
528
+ return self._apply_drift(frame, timestamp, config)
529
+ if self.effect_type == "hover":
530
+ return self._apply_hover(frame, timestamp, config)
531
+ if self.effect_type == "wave":
532
+ return self._apply_wave(frame, timestamp, config)
533
+ if self.effect_type == "ripple":
534
+ return self._apply_ripple(frame, timestamp, config)
535
+ return self._crop_to_target(frame, config)
536
+
537
+ def _crop_to_target(self, frame: np.ndarray, config: VideoConfig) -> np.ndarray:
538
+ """Crop the frame to target dimensions"""
539
+ h, w = frame.shape[:2]
540
+ target_h, target_w = config.height, config.width
541
+
542
+ start_y = (h - target_h) // 2
543
+ start_x = (w - target_w) // 2
544
+
545
+ # Ensure we don't go out of bounds
546
+ start_y = max(0, min(start_y, h - target_h))
547
+ start_x = max(0, min(start_x, w - target_w))
548
+
549
+ cropped = frame[start_y : start_y + target_h, start_x : start_x + target_w]
550
+
551
+ if cropped.shape[:2] != (target_h, target_w):
552
+ cropped = cv2.resize(
553
+ cropped, (target_w, target_h), interpolation=cv2.INTER_AREA
554
+ )
555
+
556
+ return cropped
557
+
558
+ def _apply_pulse(
559
+ self, frame: np.ndarray, timestamp: float, config: VideoConfig
560
+ ) -> np.ndarray:
561
+ """Apply pulsing effect using sine wave scaling"""
562
+ # Create pulsing effect using sine wave
563
+ pulse_frequency = 2.0 # pulses per second
564
+ pulse_amplitude = 0.2 # how much to scale (20% variation)
565
+
566
+ # Calculate scale factor using sine wave
567
+ scale_variation = pulse_amplitude * math.sin(
568
+ timestamp * pulse_frequency * 2 * math.pi
569
+ )
570
+ scale = 1.0 + scale_variation
571
+
572
+ # Ensure scale doesn't go below a minimum value
573
+ scale = max(0.8, scale)
574
+
575
+ return self._scale_and_crop(frame, scale, config)
576
+
577
+ def _apply_zoom(
578
+ self, frame: np.ndarray, timestamp: float, config: VideoConfig
579
+ ) -> np.ndarray:
580
+ progress = min(1.0, timestamp / self.duration)
581
+ scale = 1.0 + (0.3 * progress)
582
+ return self._scale_and_crop(frame, scale, config)
583
+
584
+ def _apply_zoom_out(
585
+ self, frame: np.ndarray, timestamp: float, config: VideoConfig
586
+ ) -> np.ndarray:
587
+ progress = min(1.0, timestamp / self.duration)
588
+ scale = 1.3 - (0.3 * progress)
589
+ return self._scale_and_crop(frame, scale, config)
590
+
591
+ def _apply_brightness(
592
+ self, frame: np.ndarray, timestamp: float, config: VideoConfig
593
+ ) -> np.ndarray:
594
+ progress = min(1.0, timestamp / self.duration)
595
+ brightness = 30 * progress
596
+ frame_float = frame.astype(np.float32)
597
+ bright_frame = frame_float + brightness
598
+ result = np.clip(bright_frame, 0, 255).astype(np.uint8)
599
+ return self._crop_to_target(result, config)
600
+
601
+ def _apply_blur(
602
+ self, frame: np.ndarray, timestamp: float, config: VideoConfig
603
+ ) -> np.ndarray:
604
+ progress = min(1.0, timestamp / self.duration)
605
+ kernel_size = max(1, int(5 * progress))
606
+ if kernel_size % 2 == 0:
607
+ kernel_size += 1
608
+ result = cv2.GaussianBlur(frame, (kernel_size, kernel_size), 0)
609
+ return self._crop_to_target(result, config)
610
+
611
+ def _apply_pan_left(
612
+ self, frame: np.ndarray, timestamp: float, config: VideoConfig
613
+ ) -> np.ndarray:
614
+ progress = min(1.0, timestamp / self.duration)
615
+ h, w = frame.shape[:2]
616
+
617
+ # Calculate available movement space
618
+ max_x_movement = w - config.width
619
+ max_y_movement = h - config.height
620
+
621
+ # Check if we have enough space for pan effect
622
+ if (
623
+ max_x_movement < config.width * 0.3
624
+ ): # Need at least 30% of width for smooth pan
625
+ # Apply zoom to create more space
626
+ zoom_factor = 1.5
627
+ scaled_frame = self._scale_and_crop_internal(frame, zoom_factor)
628
+ h, w = scaled_frame.shape[:2]
629
+ max_x_movement = w - config.width
630
+ max_y_movement = h - config.height
631
+ frame = scaled_frame
632
+
633
+ # Pan from right to left (start at right edge, end at left edge)
634
+ x_offset = int(max_x_movement * (1 - progress))
635
+
636
+ # Center vertically
637
+ y_offset = max_y_movement // 2
638
+
639
+ # Ensure we don't go out of bounds
640
+ x_offset = max(0, min(x_offset, max_x_movement))
641
+ y_offset = max(0, min(y_offset, max_y_movement))
642
+
643
+ # Extract the target region
644
+ return frame[
645
+ y_offset : y_offset + config.height, x_offset : x_offset + config.width
646
+ ]
647
+
648
+ def _apply_pan_right(
649
+ self, frame: np.ndarray, timestamp: float, config: VideoConfig
650
+ ) -> np.ndarray:
651
+ progress = min(1.0, timestamp / self.duration)
652
+ h, w = frame.shape[:2]
653
+
654
+ # Calculate available movement space
655
+ max_x_movement = w - config.width
656
+ max_y_movement = h - config.height
657
+
658
+ # Check if we have enough space for pan effect
659
+ if (
660
+ max_x_movement < config.width * 0.3
661
+ ): # Need at least 30% of width for smooth pan
662
+ # Apply zoom to create more space
663
+ zoom_factor = 1.5
664
+ scaled_frame = self._scale_and_crop_internal(frame, zoom_factor)
665
+ h, w = scaled_frame.shape[:2]
666
+ max_x_movement = w - config.width
667
+ max_y_movement = h - config.height
668
+ frame = scaled_frame
669
+
670
+ # Pan from left to right (start at left edge, end at right edge)
671
+ x_offset = int(max_x_movement * progress)
672
+
673
+ # Center vertically
674
+ y_offset = max_y_movement // 2
675
+
676
+ # Ensure we don't go out of bounds
677
+ x_offset = max(0, min(x_offset, max_x_movement))
678
+ y_offset = max(0, min(y_offset, max_y_movement))
679
+
680
+ # Extract the target region
681
+ return frame[
682
+ y_offset : y_offset + config.height, x_offset : x_offset + config.width
683
+ ]
684
+
685
+ def _apply_pan_up(
686
+ self, frame: np.ndarray, timestamp: float, config: VideoConfig
687
+ ) -> np.ndarray:
688
+ progress = min(1.0, timestamp / self.duration)
689
+ h, w = frame.shape[:2]
690
+
691
+ # Calculate available movement space
692
+ max_x_movement = w - config.width
693
+ max_y_movement = h - config.height
694
+
695
+ # Check if we have enough space for pan effect
696
+ if (
697
+ max_y_movement < config.height * 0.3
698
+ ): # Need at least 30% of height for smooth pan
699
+ # Apply zoom to create more space
700
+ zoom_factor = 1.5
701
+ scaled_frame = self._scale_and_crop_internal(frame, zoom_factor)
702
+ h, w = scaled_frame.shape[:2]
703
+ max_x_movement = w - config.width
704
+ max_y_movement = h - config.height
705
+ frame = scaled_frame
706
+
707
+ # Pan from bottom to top (start at bottom edge, end at top edge)
708
+ y_offset = int(max_y_movement * (1 - progress))
709
+
710
+ # Center horizontally
711
+ x_offset = max_x_movement // 2
712
+
713
+ # Ensure we don't go out of bounds
714
+ y_offset = max(0, min(y_offset, max_y_movement))
715
+ x_offset = max(0, min(x_offset, max_x_movement))
716
+
717
+ # Extract the target region
718
+ return frame[
719
+ y_offset : y_offset + config.height, x_offset : x_offset + config.width
720
+ ]
721
+
722
+ def _apply_pan_down(
723
+ self, frame: np.ndarray, timestamp: float, config: VideoConfig
724
+ ) -> np.ndarray:
725
+ progress = min(1.0, timestamp / self.duration)
726
+ h, w = frame.shape[:2]
727
+
728
+ # Calculate available movement space
729
+ max_x_movement = w - config.width
730
+ max_y_movement = h - config.height
731
+
732
+ # Check if we have enough space for pan effect
733
+ if (
734
+ max_y_movement < config.height * 0.3
735
+ ): # Need at least 30% of height for smooth pan
736
+ # Apply zoom to create more space
737
+ zoom_factor = 1.5
738
+ scaled_frame = self._scale_and_crop_internal(frame, zoom_factor)
739
+ h, w = scaled_frame.shape[:2]
740
+ max_x_movement = w - config.width
741
+ max_y_movement = h - config.height
742
+ frame = scaled_frame
743
+
744
+ # Pan from top to bottom (start at top edge, end at bottom edge)
745
+ y_offset = int(max_y_movement * progress)
746
+
747
+ # Center horizontally
748
+ x_offset = max_x_movement // 2
749
+
750
+ # Ensure we don't go out of bounds
751
+ y_offset = max(0, min(y_offset, max_y_movement))
752
+ x_offset = max(0, min(x_offset, max_x_movement))
753
+
754
+ # Extract the target region
755
+ return frame[
756
+ y_offset : y_offset + config.height, x_offset : x_offset + config.width
757
+ ]
758
+
759
+ def _apply_rotate_clockwise(
760
+ self, frame: np.ndarray, timestamp: float, config: VideoConfig
761
+ ) -> np.ndarray:
762
+ progress = min(1.0, timestamp / self.duration)
763
+ angle = 15 * progress # Rotate up to 15 degrees
764
+ return self._rotate_and_crop(frame, angle, config)
765
+
766
+ def _apply_rotate_counterclockwise(
767
+ self, frame: np.ndarray, timestamp: float, config: VideoConfig
768
+ ) -> np.ndarray:
769
+ progress = min(1.0, timestamp / self.duration)
770
+ angle = -15 * progress # Rotate up to -15 degrees
771
+ return self._rotate_and_crop(frame, angle, config)
772
+
773
+ def _apply_shake(
774
+ self, frame: np.ndarray, timestamp: float, config: VideoConfig
775
+ ) -> np.ndarray:
776
+ # Create shake effect with random offsets
777
+ shake_intensity = 40 # Increased intensity for more visible shake
778
+ frequency = 25 # Shake frequency
779
+
780
+ # Use different frequencies for x and y to create more realistic shake
781
+ x_offset = int(shake_intensity * math.sin(timestamp * frequency))
782
+ y_offset = int(shake_intensity * math.cos(timestamp * frequency * 1.3))
783
+
784
+ h, w = frame.shape[:2]
785
+
786
+ # Calculate available movement space
787
+ max_x_movement = w - config.width
788
+ max_y_movement = h - config.height
789
+
790
+ # Check if we have enough space for shake effect
791
+ if max_x_movement < shake_intensity * 2 or max_y_movement < shake_intensity * 2:
792
+ # Apply zoom to create more space
793
+ zoom_factor = 1.3
794
+ scaled_frame = self._scale_and_crop_internal(frame, zoom_factor)
795
+ h, w = scaled_frame.shape[:2]
796
+ max_x_movement = w - config.width
797
+ max_y_movement = h - config.height
798
+ frame = scaled_frame
799
+
800
+ # Calculate center position
801
+ center_x = max_x_movement // 2
802
+ center_y = max_y_movement // 2
803
+
804
+ # Apply shake offset from center
805
+ start_x = center_x + x_offset
806
+ start_y = center_y + y_offset
807
+
808
+ # Ensure we don't go out of bounds
809
+ start_x = max(0, min(start_x, max_x_movement))
810
+ start_y = max(0, min(start_y, max_y_movement))
811
+
812
+ # Extract the shaken region
813
+ return frame[
814
+ start_y : start_y + config.height, start_x : start_x + config.width
815
+ ]
816
+
817
+ def _apply_bounce(
818
+ self, frame: np.ndarray, timestamp: float, config: VideoConfig
819
+ ) -> np.ndarray:
820
+ # Create bouncing effect using sine wave
821
+ bounce_height = 80 # Increased bounce height
822
+ bounce_frequency = 1.2 # bounces per second
823
+
824
+ # Use timestamp directly for continuous bouncing
825
+ bounce_offset = int(
826
+ bounce_height * abs(math.sin(timestamp * bounce_frequency * math.pi))
827
+ )
828
+
829
+ h, w = frame.shape[:2]
830
+
831
+ # Calculate available movement space
832
+ max_x_movement = w - config.width
833
+ max_y_movement = h - config.height
834
+
835
+ # Check if we have enough space for bounce effect
836
+ if max_y_movement < bounce_height * 2:
837
+ # Apply zoom to create more space
838
+ zoom_factor = 1.4
839
+ scaled_frame = self._scale_and_crop_internal(frame, zoom_factor)
840
+ h, w = scaled_frame.shape[:2]
841
+ max_x_movement = w - config.width
842
+ max_y_movement = h - config.height
843
+ frame = scaled_frame
844
+
845
+ # Calculate center position
846
+ center_x = max_x_movement // 2
847
+ center_y = max_y_movement // 2
848
+
849
+ # Apply bounce offset (moving up and down from center)
850
+ start_y = center_y - bounce_offset
851
+ start_x = center_x
852
+
853
+ # Ensure we don't go out of bounds
854
+ start_y = max(0, min(start_y, max_y_movement))
855
+ start_x = max(0, min(start_x, max_x_movement))
856
+
857
+ # Extract the bounced region
858
+ return frame[
859
+ start_y : start_y + config.height, start_x : start_x + config.width
860
+ ]
861
+
862
+ def _apply_fade_in(
863
+ self, frame: np.ndarray, timestamp: float, config: VideoConfig
864
+ ) -> np.ndarray:
865
+ progress = min(1.0, timestamp / self.duration)
866
+
867
+ # Create black background
868
+ result = np.zeros((config.height, config.width, 3), dtype=np.uint8)
869
+
870
+ # Get the frame portion
871
+ frame_cropped = self._crop_to_target(frame, config)
872
+
873
+ # Apply fade
874
+ alpha = progress
875
+ return cv2.addWeighted(result, 1 - alpha, frame_cropped, alpha, 0)
876
+
877
+ def _apply_fade_out(
878
+ self, frame: np.ndarray, timestamp: float, config: VideoConfig
879
+ ) -> np.ndarray:
880
+ progress = min(1.0, timestamp / self.duration)
881
+
882
+ # Create black background
883
+ result = np.zeros((config.height, config.width, 3), dtype=np.uint8)
884
+
885
+ # Get the frame portion
886
+ frame_cropped = self._crop_to_target(frame, config)
887
+
888
+ # Apply fade
889
+ alpha = 1 - progress
890
+ return cv2.addWeighted(result, 1 - alpha, frame_cropped, alpha, 0)
891
+
892
+ def _apply_spiral(
893
+ self, frame: np.ndarray, timestamp: float, config: VideoConfig
894
+ ) -> np.ndarray:
895
+ progress = min(1.0, timestamp / self.duration)
896
+
897
+ # Combine rotation with zoom
898
+ angle = 180 * progress
899
+ scale = 1.0 + 0.3 * progress
900
+
901
+ # Apply rotation first
902
+ rotated = self._rotate_frame(frame, angle)
903
+
904
+ # Then apply scale
905
+ return self._scale_and_crop(rotated, scale, config)
906
+
907
+ def _scale_and_crop(
908
+ self, frame: np.ndarray, scale: float, config: VideoConfig
909
+ ) -> np.ndarray:
910
+ """Scale frame and crop to target dimensions"""
911
+ if scale <= 0:
912
+ scale = 1.0
913
+
914
+ h, w = frame.shape[:2]
915
+ new_h, new_w = int(h * scale), int(w * scale)
916
+
917
+ if new_h <= 0 or new_w <= 0:
918
+ return self._crop_to_target(frame, config)
919
+
920
+ scaled = cv2.resize(frame, (new_w, new_h), interpolation=cv2.INTER_AREA)
921
+
922
+ # Crop to target size
923
+ start_y = max(0, (new_h - config.height) // 2)
924
+ start_x = max(0, (new_w - config.width) // 2)
925
+
926
+ end_y = min(new_h, start_y + config.height)
927
+ end_x = min(new_w, start_x + config.width)
928
+
929
+ cropped = scaled[start_y:end_y, start_x:end_x]
930
+
931
+ # Ensure exact dimensions
932
+ if cropped.shape[:2] != (config.height, config.width):
933
+ cropped = cv2.resize(
934
+ cropped, (config.width, config.height), interpolation=cv2.INTER_AREA
935
+ )
936
+
937
+ return cropped
938
+
939
+ def _rotate_frame(self, frame: np.ndarray, angle: float) -> np.ndarray:
940
+ """Rotate frame by given angle"""
941
+ h, w = frame.shape[:2]
942
+ center = (w // 2, h // 2)
943
+
944
+ # Get rotation matrix
945
+ rotation_matrix = cv2.getRotationMatrix2D(center, angle, 1.0)
946
+
947
+ # Apply rotation
948
+ return cv2.warpAffine(frame, rotation_matrix, (w, h))
949
+
950
+ def _rotate_and_crop(
951
+ self, frame: np.ndarray, angle: float, config: VideoConfig
952
+ ) -> np.ndarray:
953
+ """Rotate frame and crop to target dimensions"""
954
+ rotated = self._rotate_frame(frame, angle)
955
+ return self._crop_to_target(rotated, config)
956
+
957
+ # Swing/Pendulum Effects
958
+ def _apply_swing(
959
+ self, frame: np.ndarray, timestamp: float, config: VideoConfig
960
+ ) -> np.ndarray:
961
+ """Apply pendulum swing effect"""
962
+ swing_frequency = 0.8 # swings per second
963
+ swing_amplitude = 60 # maximum swing angle in pixels
964
+
965
+ # Calculate swing offset using sine wave
966
+ swing_offset = int(
967
+ swing_amplitude * math.sin(timestamp * swing_frequency * 2 * math.pi)
968
+ )
969
+
970
+ h, w = frame.shape[:2]
971
+ max_x_movement = w - config.width
972
+ max_y_movement = h - config.height
973
+
974
+ # Check if we have enough space for swing effect
975
+ if max_x_movement < swing_amplitude * 2:
976
+ zoom_factor = 1.4
977
+ scaled_frame = self._scale_and_crop_internal(frame, zoom_factor)
978
+ h, w = scaled_frame.shape[:2]
979
+ max_x_movement = w - config.width
980
+ max_y_movement = h - config.height
981
+ frame = scaled_frame
982
+
983
+ # Calculate center position and apply swing
984
+ center_x = max_x_movement // 2
985
+ center_y = max_y_movement // 2
986
+
987
+ start_x = center_x + swing_offset
988
+ start_y = center_y
989
+
990
+ # Ensure we don't go out of bounds
991
+ start_x = max(0, min(start_x, max_x_movement))
992
+ start_y = max(0, min(start_y, max_y_movement))
993
+
994
+ return frame[
995
+ start_y : start_y + config.height, start_x : start_x + config.width
996
+ ]
997
+
998
+ def _apply_sway(
999
+ self, frame: np.ndarray, timestamp: float, config: VideoConfig
1000
+ ) -> np.ndarray:
1001
+ """Apply gentle side-to-side sway effect"""
1002
+ sway_frequency = 0.3 # slower, more gentle movement
1003
+ sway_amplitude = 30 # gentler amplitude
1004
+
1005
+ # Calculate sway offset using sine wave
1006
+ sway_offset = int(
1007
+ sway_amplitude * math.sin(timestamp * sway_frequency * 2 * math.pi)
1008
+ )
1009
+
1010
+ h, w = frame.shape[:2]
1011
+ max_x_movement = w - config.width
1012
+ max_y_movement = h - config.height
1013
+
1014
+ # Check if we have enough space for sway effect
1015
+ if max_x_movement < sway_amplitude * 2:
1016
+ zoom_factor = 1.3
1017
+ scaled_frame = self._scale_and_crop_internal(frame, zoom_factor)
1018
+ h, w = scaled_frame.shape[:2]
1019
+ max_x_movement = w - config.width
1020
+ max_y_movement = h - config.height
1021
+ frame = scaled_frame
1022
+
1023
+ # Calculate center position and apply sway
1024
+ center_x = max_x_movement // 2
1025
+ center_y = max_y_movement // 2
1026
+
1027
+ start_x = center_x + sway_offset
1028
+ start_y = center_y
1029
+
1030
+ # Ensure we don't go out of bounds
1031
+ start_x = max(0, min(start_x, max_x_movement))
1032
+ start_y = max(0, min(start_y, max_y_movement))
1033
+
1034
+ return frame[
1035
+ start_y : start_y + config.height, start_x : start_x + config.width
1036
+ ]
1037
+
1038
+ # Elastic/Spring Effects
1039
+ def _apply_elastic_zoom(
1040
+ self, frame: np.ndarray, timestamp: float, config: VideoConfig
1041
+ ) -> np.ndarray:
1042
+ """Apply elastic zoom with overshoot and bounce"""
1043
+ progress = min(1.0, timestamp / self.duration)
1044
+
1045
+ if progress < 0.7:
1046
+ # Main zoom phase
1047
+ scale = 1.0 + (0.4 * progress / 0.7)
1048
+ else:
1049
+ # Elastic bounce phase
1050
+ elastic_progress = (progress - 0.7) / 0.3
1051
+ bounce = (
1052
+ 0.1
1053
+ * math.sin(elastic_progress * 4 * math.pi)
1054
+ * math.exp(-elastic_progress * 3)
1055
+ )
1056
+ scale = 1.4 + bounce
1057
+
1058
+ return self._scale_and_crop(frame, scale, config)
1059
+
1060
+ def _apply_rubber_band(
1061
+ self, frame: np.ndarray, timestamp: float, config: VideoConfig
1062
+ ) -> np.ndarray:
1063
+ """Apply rubber band stretching and snapping effect"""
1064
+ progress = min(1.0, timestamp / self.duration)
1065
+
1066
+ if progress < 0.5:
1067
+ # Stretch phase
1068
+ stretch_factor = progress * 2
1069
+ scale_x = 1.0 + (0.3 * stretch_factor)
1070
+ scale_y = 1.0 - (
1071
+ 0.15 * stretch_factor
1072
+ ) # Compress vertically while stretching horizontally
1073
+ else:
1074
+ # Snap back phase with overshoot
1075
+ snap_progress = (progress - 0.5) * 2
1076
+ overshoot = (
1077
+ 0.2
1078
+ * math.sin(snap_progress * 3 * math.pi)
1079
+ * math.exp(-snap_progress * 2)
1080
+ )
1081
+ scale_x = 1.3 - (0.3 * snap_progress) + overshoot
1082
+ scale_y = 0.85 + (0.15 * snap_progress) - overshoot * 0.5
1083
+
1084
+ # Apply non-uniform scaling
1085
+ h, w = frame.shape[:2]
1086
+ new_h = int(h * scale_y)
1087
+ new_w = int(w * scale_x)
1088
+
1089
+ if new_h > 0 and new_w > 0:
1090
+ scaled = cv2.resize(frame, (new_w, new_h), interpolation=cv2.INTER_AREA)
1091
+ return self._crop_to_target(scaled, config)
1092
+
1093
+ return self._crop_to_target(frame, config)
1094
+
1095
+ # Advanced Zoom Effects
1096
+ def _apply_zoom_bounce(
1097
+ self, frame: np.ndarray, timestamp: float, config: VideoConfig
1098
+ ) -> np.ndarray:
1099
+ """Apply zoom with bounce at the end"""
1100
+ progress = min(1.0, timestamp / self.duration)
1101
+
1102
+ if progress < 0.8:
1103
+ # Main zoom phase
1104
+ scale = 1.0 + (0.3 * progress / 0.8)
1105
+ else:
1106
+ # Bounce phase
1107
+ bounce_progress = (progress - 0.8) / 0.2
1108
+ bounce = (
1109
+ 0.1 * math.sin(bounce_progress * 2 * math.pi) * (1 - bounce_progress)
1110
+ )
1111
+ scale = 1.3 + bounce
1112
+
1113
+ return self._scale_and_crop(frame, scale, config)
1114
+
1115
+ def _apply_zoom_elastic(
1116
+ self, frame: np.ndarray, timestamp: float, config: VideoConfig
1117
+ ) -> np.ndarray:
1118
+ """Apply zoom with elastic overshoot"""
1119
+ progress = min(1.0, timestamp / self.duration)
1120
+
1121
+ # Elastic easing function
1122
+ if progress < 0.7:
1123
+ scale = 1.0 + (0.4 * progress / 0.7)
1124
+ else:
1125
+ elastic_progress = (progress - 0.7) / 0.3
1126
+ overshoot = (
1127
+ 0.15
1128
+ * math.sin(elastic_progress * 6 * math.pi)
1129
+ * math.exp(-elastic_progress * 4)
1130
+ )
1131
+ scale = 1.4 + overshoot
1132
+
1133
+ return self._scale_and_crop(frame, scale, config)
1134
+
1135
+ def _apply_ken_burns(
1136
+ self, frame: np.ndarray, timestamp: float, config: VideoConfig
1137
+ ) -> np.ndarray:
1138
+ """Apply classic Ken Burns effect (slow zoom + pan)"""
1139
+ progress = min(1.0, timestamp / self.duration)
1140
+
1141
+ # Slow zoom
1142
+ scale = 1.0 + (0.2 * progress)
1143
+
1144
+ # Slow pan (diagonal movement)
1145
+ h, w = frame.shape[:2]
1146
+
1147
+ # Apply scale first
1148
+ scaled = self._scale_and_crop_internal(frame, scale)
1149
+ sh, sw = scaled.shape[:2]
1150
+
1151
+ max_x_movement = sw - config.width
1152
+ max_y_movement = sh - config.height
1153
+
1154
+ # Pan diagonally from bottom-left to top-right
1155
+ x_offset = int(max_x_movement * progress * 0.3) # 30% of available movement
1156
+ y_offset = int(max_y_movement * (1 - progress * 0.3)) # Start from bottom
1157
+
1158
+ # Ensure we don't go out of bounds
1159
+ x_offset = max(0, min(x_offset, max_x_movement))
1160
+ y_offset = max(0, min(y_offset, max_y_movement))
1161
+
1162
+ return scaled[
1163
+ y_offset : y_offset + config.height, x_offset : x_offset + config.width
1164
+ ]
1165
+
1166
+ # Floating/Hovering Effects
1167
+ def _apply_float(
1168
+ self, frame: np.ndarray, timestamp: float, config: VideoConfig
1169
+ ) -> np.ndarray:
1170
+ """Apply gentle floating movement"""
1171
+ float_frequency = 0.5 # slow floating
1172
+ float_amplitude = 25 # gentle movement
1173
+
1174
+ # Calculate float offset using sine wave
1175
+ float_offset = int(
1176
+ float_amplitude * math.sin(timestamp * float_frequency * 2 * math.pi)
1177
+ )
1178
+
1179
+ h, w = frame.shape[:2]
1180
+ max_x_movement = w - config.width
1181
+ max_y_movement = h - config.height
1182
+
1183
+ # Check if we have enough space for float effect
1184
+ if max_y_movement < float_amplitude * 2:
1185
+ zoom_factor = 1.3
1186
+ scaled_frame = self._scale_and_crop_internal(frame, zoom_factor)
1187
+ h, w = scaled_frame.shape[:2]
1188
+ max_x_movement = w - config.width
1189
+ max_y_movement = h - config.height
1190
+ frame = scaled_frame
1191
+
1192
+ # Calculate center position and apply float
1193
+ center_x = max_x_movement // 2
1194
+ center_y = max_y_movement // 2
1195
+
1196
+ start_x = center_x
1197
+ start_y = center_y + float_offset
1198
+
1199
+ # Ensure we don't go out of bounds
1200
+ start_x = max(0, min(start_x, max_x_movement))
1201
+ start_y = max(0, min(start_y, max_y_movement))
1202
+
1203
+ return frame[
1204
+ start_y : start_y + config.height, start_x : start_x + config.width
1205
+ ]
1206
+
1207
+ def _apply_drift(
1208
+ self, frame: np.ndarray, timestamp: float, config: VideoConfig
1209
+ ) -> np.ndarray:
1210
+ """Apply slow diagonal drift movement"""
1211
+ progress = min(1.0, timestamp / self.duration)
1212
+
1213
+ h, w = frame.shape[:2]
1214
+ max_x_movement = w - config.width
1215
+ max_y_movement = h - config.height
1216
+
1217
+ # Check if we have enough space for drift effect
1218
+ if max_x_movement < config.width * 0.2 or max_y_movement < config.height * 0.2:
1219
+ zoom_factor = 1.4
1220
+ scaled_frame = self._scale_and_crop_internal(frame, zoom_factor)
1221
+ h, w = scaled_frame.shape[:2]
1222
+ max_x_movement = w - config.width
1223
+ max_y_movement = h - config.height
1224
+ frame = scaled_frame
1225
+
1226
+ # Drift diagonally from top-left to bottom-right
1227
+ x_offset = int(max_x_movement * progress * 0.6)
1228
+ y_offset = int(max_y_movement * progress * 0.6)
1229
+
1230
+ # Ensure we don't go out of bounds
1231
+ x_offset = max(0, min(x_offset, max_x_movement))
1232
+ y_offset = max(0, min(y_offset, max_y_movement))
1233
+
1234
+ return frame[
1235
+ y_offset : y_offset + config.height, x_offset : x_offset + config.width
1236
+ ]
1237
+
1238
+ def _apply_hover(
1239
+ self, frame: np.ndarray, timestamp: float, config: VideoConfig
1240
+ ) -> np.ndarray:
1241
+ """Apply small random hovering movements"""
1242
+ # Multiple sine waves for more organic movement
1243
+ hover_x = int(15 * math.sin(timestamp * 2.3) + 8 * math.sin(timestamp * 3.7))
1244
+ hover_y = int(12 * math.sin(timestamp * 1.8) + 6 * math.sin(timestamp * 4.2))
1245
+
1246
+ h, w = frame.shape[:2]
1247
+ max_x_movement = w - config.width
1248
+ max_y_movement = h - config.height
1249
+
1250
+ # Check if we have enough space for hover effect
1251
+ if max_x_movement < 50 or max_y_movement < 50:
1252
+ zoom_factor = 1.3
1253
+ scaled_frame = self._scale_and_crop_internal(frame, zoom_factor)
1254
+ h, w = scaled_frame.shape[:2]
1255
+ max_x_movement = w - config.width
1256
+ max_y_movement = h - config.height
1257
+ frame = scaled_frame
1258
+
1259
+ # Calculate center position and apply hover
1260
+ center_x = max_x_movement // 2
1261
+ center_y = max_y_movement // 2
1262
+
1263
+ start_x = center_x + hover_x
1264
+ start_y = center_y + hover_y
1265
+
1266
+ # Ensure we don't go out of bounds
1267
+ start_x = max(0, min(start_x, max_x_movement))
1268
+ start_y = max(0, min(start_y, max_y_movement))
1269
+
1270
+ return frame[
1271
+ start_y : start_y + config.height, start_x : start_x + config.width
1272
+ ]
1273
+
1274
+ # Wave/Ripple Effects
1275
+ def _apply_wave(
1276
+ self, frame: np.ndarray, timestamp: float, config: VideoConfig
1277
+ ) -> np.ndarray:
1278
+ """Apply wavy sinusoidal movement pattern"""
1279
+ wave_frequency = 1.2 # waves per second
1280
+ wave_amplitude_x = 40 # horizontal wave amplitude
1281
+ wave_amplitude_y = 25 # vertical wave amplitude
1282
+
1283
+ # Calculate wave offsets using different frequencies for x and y
1284
+ wave_x = int(
1285
+ wave_amplitude_x * math.sin(timestamp * wave_frequency * 2 * math.pi)
1286
+ )
1287
+ wave_y = int(
1288
+ wave_amplitude_y * math.sin(timestamp * wave_frequency * 1.5 * 2 * math.pi)
1289
+ )
1290
+
1291
+ h, w = frame.shape[:2]
1292
+ max_x_movement = w - config.width
1293
+ max_y_movement = h - config.height
1294
+
1295
+ # Check if we have enough space for wave effect
1296
+ if (
1297
+ max_x_movement < wave_amplitude_x * 2
1298
+ or max_y_movement < wave_amplitude_y * 2
1299
+ ):
1300
+ zoom_factor = 1.4
1301
+ scaled_frame = self._scale_and_crop_internal(frame, zoom_factor)
1302
+ h, w = scaled_frame.shape[:2]
1303
+ max_x_movement = w - config.width
1304
+ max_y_movement = h - config.height
1305
+ frame = scaled_frame
1306
+
1307
+ # Calculate center position and apply wave
1308
+ center_x = max_x_movement // 2
1309
+ center_y = max_y_movement // 2
1310
+
1311
+ start_x = center_x + wave_x
1312
+ start_y = center_y + wave_y
1313
+
1314
+ # Ensure we don't go out of bounds
1315
+ start_x = max(0, min(start_x, max_x_movement))
1316
+ start_y = max(0, min(start_y, max_y_movement))
1317
+
1318
+ return frame[
1319
+ start_y : start_y + config.height, start_x : start_x + config.width
1320
+ ]
1321
+
1322
+ def _apply_ripple(
1323
+ self, frame: np.ndarray, timestamp: float, config: VideoConfig
1324
+ ) -> np.ndarray:
1325
+ """Apply ripple-like expansion effect"""
1326
+ progress = min(1.0, timestamp / self.duration)
1327
+
1328
+ # Create ripple effect with oscillating scale
1329
+ ripple_frequency = 3.0 # ripples per duration
1330
+ ripple_amplitude = 0.1 # scale variation
1331
+
1332
+ # Base expansion
1333
+ base_scale = 1.0 + (0.2 * progress)
1334
+
1335
+ # Ripple oscillation
1336
+ ripple_offset = ripple_amplitude * math.sin(
1337
+ timestamp * ripple_frequency * 2 * math.pi
1338
+ )
1339
+
1340
+ # Fade out ripples over time
1341
+ ripple_fade = 1.0 - (progress * 0.5)
1342
+ ripple_offset *= ripple_fade
1343
+
1344
+ final_scale = base_scale + ripple_offset
1345
+
1346
+ # Ensure minimum scale
1347
+ final_scale = max(0.8, final_scale)
1348
+
1349
+ return self._scale_and_crop(frame, final_scale, config)
1350
+
1351
+ def cleanup(self):
1352
+ self._cached_frame = None
1353
+ self._last_effect_frame = None
1354
+ if self._cap is not None:
1355
+ self._cap.release()
1356
+ self._cap = None