runarium 0.1.0

Generate animated videos from GPS running/cycling data with real-time statistics
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
use anyhow::Result;
use opencv::{core, imgproc, prelude::*};

use crate::{
  configs::RouteVideoConfig,
  types::{
    drawer_data::{PositionRect, Rect, SizeRect},
    fit_data::{LapData, RouteData},
  },
  utils::{
    converter::{
      convert_pace_to_sec, get_bounds, load_and_resize_image, pace_percentage,
      string_space,
    },
    creator::video_creator,
    element_drawer::Drawer,
    performance::processed,
    read_file::fit_reader,
  },
};

/// Generates an animated video of a running route with lap statistics overlay.
///
/// Creates a video showing progressive route drawing on a background image,
/// with real-time pace/distance info and a lap statistics panel.
///
/// # Arguments
/// * `route_scale` - Scale factor for route visualization (0.0-1.0 recommended)
/// * `offset_x_percent` - Horizontal offset as percentage of image width
/// * `offset_y_percent` - Vertical offset as percentage of image height
///
/// # Returns
/// * `Ok(())` - Video successfully created and saved
/// * `Err` - If FIT file reading, video encoding, or drawing operations fail
///
/// # Output
/// Creates `outputs/example.mp4` with:
/// - Animated route drawing (red line)
/// - Current position marker (green dot)
/// - Lap statistics panel (pace, heart rate, stride length)
/// - Real-time pace and distance overlay
pub fn progressive_route(
  route_scale: f64,
  offset_x_percent: f64,
  offset_y_percent: f64,
) -> Result<()> {
  // Read and extract data
  #[rustfmt::skip]
  let (route, lap) = fit_reader("source/example.fit")?;
  let RouteData {
    paces,
    gps_points: points,
    distances,
  } = route;
  let LapData {
    avg_heart_rate,
    enhanced_avg_speed,
    avg_step_length,
  } = lap;

  // Normalize coordinates
  #[rustfmt::skip]
  let (
    (lat_min, lat_max),
    (lon_min, lon_max)
  ) = get_bounds(&points);

  // Get background image
  let (bg_image, width, height) =
    load_and_resize_image("source/example.jpg", 1080)?;

  // Coordinate normalization to image space
  let to_px = |lat: f64, lon: f64| -> core::Point {
    let nx = if lon_max != lon_min {
      (lon - lon_min) / (lon_max - lon_min)
    } else {
      0.5
    };
    let ny = if lat_max != lat_min {
      (lat - lat_min) / (lat_max - lat_min)
    } else {
      0.5
    };

    let x = ((offset_x_percent + nx * route_scale) * width as f64) as i32;
    #[rustfmt::skip]
    let y = ((offset_y_percent + (1.0 - ny) * route_scale) * width as f64) as i32;
    core::Point::new(x, y)
  };

  // Initialized video generator
  #[rustfmt::skip]
  let pixel_points: Vec<core::Point> = points
    .iter()
    .map(|&(la, lo)| to_px(la, lo))
    .collect();
  let fps = (pixel_points.len() / 15) as f64;
  let output_file = "outputs/simple.mp4";
  let mut video = video_creator(width, height, fps, output_file)?;

  // Initialize frame
  // let mut path_frame = Mat::zeros(height, width, core::CV_8UC3)?.to_mat()?;
  let mut resized = Mat::default();
  imgproc::resize(
    &bg_image,
    &mut resized,
    core::Size::new(width, height),
    0.0,
    0.0,
    imgproc::INTER_LANCZOS4,
  )?;

  let mut path_frame = resized.clone();
  let drawer = Drawer::new(width, height);

  let font = crate::configs::video_config::Font::Simplex;
  let font_scale = 0.5;
  let thickness = 1;

  let pace_seconds: Vec<f32> = enhanced_avg_speed
    .iter()
    .map(|p| convert_pace_to_sec(p))
    .collect();

  let start_x = width / 2;
  let start_y = 100;
  let min_val = *pace_seconds
    .iter()
    .min_by(|a, b| a.total_cmp(b))
    .expect("Failed to find min pace");
  let min_denominator = (min_val / 30.0).floor() * 30.0;
  let bar_max_width = 200;

  // Create lap data
  drawer
    .header(
      &mut path_frame,
      start_x,
      start_y,
      font_scale,
      2,
      font,
    )
    .expect("Failed to draw header!");

  let green_color = drawer.color([0.0, 255.0, 0.0, 0.0]);
  let white_color = drawer.color([255.0, 255.0, 255.0, 0.0]);
  let size_of_speeds = enhanced_avg_speed.len();
  for (i, pace) in enhanced_avg_speed.iter().enumerate() {
    let size = drawer.text_size(pace, font_scale, thickness, font)?;
    let x = start_x - size.width / 2;
    let y = start_y + i as i32 * (size.height + 5);

    let pace_space = string_space(size_of_speeds, i + 1, pace);
    drawer
      .text(
        &mut path_frame,
        &pace_space,
        x,
        y,
        font_scale,
        thickness,
        font,
        white_color,
      )
      .expect("Failed to draw pace");

    let hr = &format!("{}", avg_heart_rate[i]);
    drawer
      .text(
        &mut path_frame,
        hr,
        x + 300,
        y,
        font_scale,
        thickness,
        font,
        white_color,
      )
      .expect("Failed to draw heart rate");

    let lenght_meters = avg_step_length[i] / 10.0;
    let stride_length = &format!("{}", lenght_meters);
    drawer
      .text(
        &mut path_frame,
        stride_length,
        x + 350,
        y,
        font_scale,
        thickness,
        font,
        white_color,
      )
      .expect("Failed to draw stride length");

    let percent = pace_percentage(min_denominator, pace_seconds[i]);
    let bar_width = (percent * bar_max_width as f32) as i32;
    let bar_height = size.height;
    let bar_x = x + size.width + 60;
    let bar_y = y - size.height;
    let rect = Rect {
      pos: PositionRect { x: bar_x, y: bar_y },
      size: SizeRect {
        width: bar_width,
        height: bar_height,
      },
    };
    drawer
      .rectangle(&mut path_frame, rect, green_color)
      .expect("Failed to draw bar");
  }

  // Create progressive route
  let red_color = drawer.color([0.0, 0.0, 255.0, 0.0]);
  for (i, point) in pixel_points.iter().enumerate() {
    if i > 0 {
      drawer.line(
        &mut path_frame,
        pixel_points[i - 1],
        *point,
        red_color,
      )?;
    }

    let mut current_frame = path_frame.clone();
    drawer.point(&mut current_frame, *point, green_color)?;

    if i < paces.len() && i < distances.len() {
      let pace_text = format!("Pace: {} min/km", paces[i]);
      let dist_text = format!("Dist: {:.2} km", distances[i] / 1000.0);
      let font_scale = 0.8;
      let thickness = 2;

      drawer.text_bar(
        &mut current_frame,
        &pace_text,
        &dist_text,
        font_scale,
        thickness,
        font,
      )?;
    }

    video.write(&current_frame)?;
    processed(i, pixel_points.clone());
  }

  video.release()?;
  println!(
    "✅ Video created: {} with {} points",
    output_file,
    pixel_points.len()
  );
  Ok(())
}

/// Generates an animated video with custom configuration.
///
/// This function provides full control over all aspects of the video generation
/// including colors, positioning, and what data to display.
///
/// # Arguments
/// * `config` - RouteVideoConfig containing all customization options
///
/// # Returns
/// * `Ok(())` - Video successfully created and saved
/// * `Err` - If FIT file reading, video encoding, or drawing operations fail
///
/// # Example
/// ```no_run
/// use runarium::video_config::RouteVideoConfig;
/// use runarium::generators::route_video::progressive_route_with_config;
///
/// let config = RouteVideoConfig::default();
/// progressive_route_with_config(config);
/// ```
pub fn progressive_route_with_config(config: RouteVideoConfig) -> Result<()> {
  // Read and extract data
  #[rustfmt::skip]
  let (route, lap) = fit_reader(&config.file_config.fit_file)?;
  let RouteData {
    paces,
    gps_points: points,
    distances,
  } = route;
  let LapData {
    avg_heart_rate,
    enhanced_avg_speed,
    avg_step_length,
  } = lap;

  // Normalize coordinates
  #[rustfmt::skip]
  let (
    (lat_min, lat_max),
    (lon_min, lon_max)
  ) = get_bounds(&points);

  // Get background image
  let (bg_image, width, height) = load_and_resize_image(
    &config.file_config.background_image,
    1080,
  )?;

  // Coordinate normalization to image space
  let to_px = |lat: f64, lon: f64| -> core::Point {
    let nx = if lon_max != lon_min {
      (lon - lon_min) / (lon_max - lon_min)
    } else {
      0.5
    };
    let ny = if lat_max != lat_min {
      (lat - lat_min) / (lat_max - lat_min)
    } else {
      0.5
    };

    let x = ((config.route_scale.offset_x_percent
      + nx * config.route_scale.scale)
      * width as f64) as i32;
    #[rustfmt::skip]
    let y = ((config.route_scale.offset_y_percent + (1.0 - ny) * config.route_scale.scale) * width as f64) as i32;
    core::Point::new(x, y)
  };

  // Initialized video generator
  #[rustfmt::skip]
  let pixel_points: Vec<core::Point> = points
    .iter()
    .map(|&(la, lo)| to_px(la, lo))
    .collect();
  let fps = (pixel_points.len() / 15) as f64;
  let mut video = video_creator(
    width,
    height,
    fps,
    &config.file_config.output_file,
  )?;

  // Initialize frame
  let mut resized = Mat::default();
  imgproc::resize(
    &bg_image,
    &mut resized,
    core::Size::new(width, height),
    0.0,
    0.0,
    imgproc::INTER_LANCZOS4,
  )?;

  let mut path_frame = resized.clone();
  let drawer = Drawer::new(width, height);

  let pace_seconds: Vec<f32> = enhanced_avg_speed
    .iter()
    .map(|p| convert_pace_to_sec(p))
    .collect();

  let start_x = (config.lap_data.position.0 * width as f64) as i32;
  let start_y = (config.lap_data.position.1 * height as f64) as i32;
  let min_val = *pace_seconds
    .iter()
    .min_by(|a, b| a.total_cmp(b))
    .expect("Failed to find min pace");
  let min_denominator = (min_val / 30.0).floor() * 30.0;

  // Create lap data
  if config.show_lap_data {
    drawer
      .header(
        &mut path_frame,
        start_x,
        start_y,
        config.lap_data.font_scale,
        2,
        config.lap_data.font,
      )
      .expect("Failed to draw header!");

    let text_color = drawer.color(config.lap_data.text_color.to_bgra());
    let bar_color = drawer.color(config.colors.lap_bars);
    let size_of_speeds = enhanced_avg_speed.len();

    for (i, pace) in enhanced_avg_speed.iter().enumerate() {
      let size = drawer.text_size(
        pace,
        config.lap_data.font_scale,
        config.lap_data.thickness,
        config.lap_data.font,
      )?;
      let x = start_x - size.width / 2;
      let y = start_y + i as i32 * (size.height + 5);

      // Draw pace
      let pace_space = string_space(size_of_speeds, i + 1, pace);
      drawer
        .text(
          &mut path_frame,
          &pace_space,
          x,
          y,
          config.lap_data.font_scale,
          config.lap_data.thickness,
          config.lap_data.font,
          text_color,
        )
        .expect("Failed to draw pace");

      // Draw heart rate if enabled
      if config.lap_data.show_heart_rate {
        let hr = &format!("{}", avg_heart_rate[i]);
        drawer
          .text(
            &mut path_frame,
            hr,
            x + 300,
            y,
            config.lap_data.font_scale,
            config.lap_data.thickness,
            config.lap_data.font,
            text_color,
          )
          .expect("Failed to draw heart rate");
      }

      // Draw stride length if enabled
      if config.lap_data.show_stride_length {
        let length_meters = avg_step_length[i] / 10.0;
        let stride_length = &format!("{}", length_meters);
        drawer
          .text(
            &mut path_frame,
            stride_length,
            x + 350,
            y,
            config.lap_data.font_scale,
            config.lap_data.thickness,
            config.lap_data.font,
            text_color,
          )
          .expect("Failed to draw stride length");
      }

      // Draw pace bars if enabled
      if config.lap_data.show_pace_bars {
        let percent = pace_percentage(min_denominator, pace_seconds[i]);
        let bar_width = (percent * 200.0) as i32;
        let bar_height = size.height;
        let bar_x = x + size.width + 60;
        let bar_y = y - size.height;
        let rect = Rect {
          pos: PositionRect { x: bar_x, y: bar_y },
          size: SizeRect {
            width: bar_width,
            height: bar_height,
          },
        };
        drawer
          .rectangle(&mut path_frame, rect, bar_color)
          .expect("Failed to draw bar");
      }
    }
  }

  // Create progressive route
  let route_color = drawer.color(config.colors.route_line);
  let position_color = drawer.color(config.colors.current_position);

  for (i, point) in pixel_points.iter().enumerate() {
    if config.show_route && i > 0 {
      drawer.line(
        &mut path_frame,
        pixel_points[i - 1],
        *point,
        route_color,
      )?;
    }

    let mut current_frame = path_frame.clone();
    if config.show_route {
      drawer.point(
        &mut current_frame,
        *point,
        position_color,
      )?;
    }

    // Draw pace and distance overlay if enabled
    if config.show_bottom_bar
      && i < paces.len()
      && i < distances.len()
      && (config.pace_dist.show_pace || config.pace_dist.show_distance)
    {
      let pace_text = if config.pace_dist.show_pace {
        format!("Pace: {} min/km", paces[i])
      } else {
        String::new()
      };

      let dist_text = if config.pace_dist.show_distance {
        format!("Dist: {:.2} km", distances[i] / 1000.0)
      } else {
        String::new()
      };

      drawer.text_bar(
        &mut current_frame,
        &pace_text,
        &dist_text,
        config.pace_dist.font_scale,
        config.pace_dist.thickness,
        config.pace_dist.font,
      )?;
    }

    video.write(&current_frame)?;
    processed(i, pixel_points.clone());
  }

  video.release()?;
  println!(
    "✅ Video created: {} with {} points",
    config.file_config.output_file,
    pixel_points.len()
  );
  Ok(())
}