Debian Codegraph @

src/images/castlevideos.pas

raw
1 {
2 Copyright 2008-2023 Michalis Kamburelis.
3
4 This file is part of "Castle Game Engine".
5
6 "Castle Game Engine" is free software; see the file COPYING.txt,
7 included in this distribution, for details about the copyright.
8
9 "Castle Game Engine" is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 ----------------------------------------------------------------------------
14 }
15
16 { Video (movie) data (TVideo and helpers). }
17 unit CastleVideos;
18
19 {$I castleconf.inc}
20
21 interface
22
23 uses SysUtils, Generics.Collections,
24 CastleImages, CastleTimeUtils;
25
26 type
27 EInvalidFadeFrames = class(Exception);
28 ECannotOpenFirstVideoFrame = class(Exception);
29
30 { Video.
31
32 It can load movie from a sequence of image files.
33 With the help of ffmpeg, it can also load any normal movie file format,
34 like avi (compressed by anything ffmpeg can handle), OggTheora and
35 many others. ffmpeg really handles probably everything you will
36 ever want.
37
38 Video is stored simply as a sequence of uncompressed images in memory.
39 This is not good for real movies, so don't even try to open
40 any real, 2 hour, full dvd resolution movie --- loading will
41 take hours and you will clog your memory. This class is @italic(not)
42 supposed to be used in a real movie player.
43
44 However, this simple storage is perfect to load a short movie
45 for some effect in a game, for example a simple movie with flames
46 or smoke to be shown as texture in your 3D game.
47 Memory and loading time is acceptable then,
48 and you want to prepare all your textures before the game starts anyway
49 (for a 3D game, there's no time to decode some movie format while
50 playing...).
51
52 See example program
53 @code(examples/images_videos/simple_video_editor/)
54 in our engine for example of a simple movie player/editor implemented on top
55 of this class. }
56 TVideo = class
57 private
58 FItems: array of TCastleImage;
59 function GetItems(Index: Integer): TCastleImage;
60 private
61 FLoaded: boolean;
62 FTimeLoop: boolean;
63 FTimeBackwards: boolean;
64 FFramesPerSecond: Single;
65 public
66 constructor Create;
67 destructor Destroy; override;
68
69 { Loaded video properties.
70 Use these only when @link(Loaded) is @true.
71
72 Time is supposed to be in seconds. (Actually, we don't care;
73 but when the movie file says to play "25 frames per second", then
74 we will make 25 frames per this Time unit. So you probably
75 want to count the Time in seconds too.)
76
77 @link(Count) is always >= 1 when the video is loaded.
78 That is, we don't allow videos with zero frames (I don't
79 know if any movie format allows this.)
80
81 @groupBegin }
82 function Count: Integer;
83 property Items [Index: Integer]: TCastleImage read GetItems;
84 function Width: Cardinal;
85 function Height: Cardinal;
86 function IndexFromTime(const Time: TFloatTime): Integer;
87 function ImageFromTime(const Time: TFloatTime): TCastleImage;
88 { @groupEnd }
89
90 { Duration of the video. In seconds (or, more precisely, in the
91 same time units as for ImageFromTime and other methods).
92
93 Note that this doesn't count the "backwards" running time,
94 so it ignores TimeBackwards and TimeLoop values.
95
96 Use this only when @link(Loaded). }
97 function TimeDuration: Single;
98
99 { Number of frames per second for this video.
100
101 For formats with varying frame-rate (although we do not support
102 any such format right now), this will be just average frame-rate.
103 The idea is that this property is just to show the user, so (s)he
104 can judge the quality of the video. }
105 property FramesPerSecond: Single read FFramesPerSecond;
106
107 { Loads video from file or URL.
108
109 URL is downloaded using CastleDownload unit.
110 As always, if you all you care about is loading normal files, then just pass
111 a normal filename (absolute or relative to the current directory)
112 as the URL parameter.
113
114 Supported video formats:
115
116 @unorderedList(
117
118 @item(We recognize video URLs by extension, and then try
119 to load them through ffmpeg. So ffmpeg must be available
120 on $PATH for this. See castle-model-viewer docs for some links.
121
122 Internally, for now we just use ffmpeg to decompose the video to
123 single images, and then proceed to load this image sequence.
124 So this takes some time and drains memory for longer movies,
125 and it's not supposed to be really used to load longer movies.
126
127 Of course, this may get improved (and some simple video formats
128 may be handled without ffmpeg dependency) in the future,
129 if the need arises. For now, it's enough for me --- all I want
130 is to load some simple texture movies (like smoke or fire
131 or dense fog animations) to use as billboards in games.
132 For such short movies, loading time and memory use are acceptable.)
133
134 @item(We can also load a sequence of images with a URL
135 like image@@counter(1).png.
136
137 We use @link(FormatNameCounter) to recognize URLs with
138 @code(@@counter(*)) macro. If URL contains @code(@@counter(*)) macro,
139 then we try to load image sequence starting from counter equal 0
140 or (if that doesn't exist) from counter equal 1.
141 This way your image sequence numbering can start from 0 or from 1,
142 and it will work in any case.
143
144 If URL doesn't contain @code(@@counter(*)) macro,
145 then we just load a single image (and treat it as a movie with only one frame).
146
147 Note that this allows you to have alpha channel for the video.
148 Since we just load the sequence of images, they can have
149 alpha channel just like any still image (e.g. PNG) can have it.
150 So your animated texture of fire / smoke
151 etc. will be rendered will all the features of alpha channel
152 (blending or alha testing, depending on alpha channel type).
153 I don't know if any video file format supports any kind of
154 alpha channel, so using image sequence may be actually your
155 only choice for videos with alpha channel.)
156 )
157
158 Parameters ResizeToX, ResizeToY allow you to resize video frames.
159 If one of them is non-zero, the appropriate video size (width and/or
160 height) will be resized. Resizing quality is controlled by
161 Interpolation parameter. }
162 procedure LoadFromFile(const Url: String;
163 const ResizeToX: Cardinal = 0;
164 const ResizeToY: Cardinal = 0;
165 const Interpolation: TResizeInterpolation = riBilinear;
166 const LoadOptions: TLoadImageOptions = []);
167
168 { Save video to file (or image sequence).
169
170 Handled formats: just like LoadFromFile. Also, just like LoadFromFile,
171 we need ffmpeg on $PATH to save to any single-file movie format. }
172 procedure SaveToFile(const Url: String);
173
174 procedure Resize(const ResizeToX, ResizeToY: Cardinal;
175 const Interpolation: TResizeInterpolation = riBilinear);
176
177 { Release all resources allocated by @link(LoadFromFile).
178 @link(Loaded) property changes to @false after calling this.
179
180 It's safe to call this even if @link(Loaded) is already @false --- then
181 this will do nothing. }
182 procedure Close;
183
184 property Loaded: boolean read FLoaded;
185
186 { Play the video in a never-ending loop.
187
188 If @true then IndexFromTime and ImageFromTime will return information
189 that causes the video to be played in an infinite loop.
190 This cooperates with TimeBackwards:
191 If TimeBackwards is also @true, then each loop step will play
192 video once forward, and once backward --- infinitely.
193
194 It's Ok to change the value of this property at any time
195 (even when video is not yet loaded), since this doesn't really
196 cause any internal recalculation. It only affects what
197 *FromTime methods return. }
198 property TimeLoop: boolean read FTimeLoop write FTimeLoop default false;
199
200 { Play the video backwards after playing it forward.
201
202 This cooperates with TimeLoop. If this is @true and TimeLoop = @false,
203 video will be played once forward, once backward, and then stop.
204 If this is @true and TimeLoop = also @true, then the video
205 will be played forward, then backward, infinitely.
206
207 It's Ok to change the value of this property at any time
208 (even when video is not yet loaded), since this doesn't really
209 cause any internal recalculation. It only affects what
210 *FromTime methods return. }
211 property TimeBackwards: boolean
212 read FTimeBackwards write FTimeBackwards default false;
213
214 { Mix the video with itself played backwards,
215 to force the video to play seamless in a loop.
216
217 This edits the loaded video, such that every frame becomes a mix
218 between itself and the corresponding frame from the second half
219 of the video. This forces any
220 movie to become seamless when played in a loop.
221
222 After this, the movie frames count is halved and TimeBackwards
223 is set to @true. This is to conserve memory (and running time of
224 this function), since there's no point in keeping both halves of the
225 movie anymore --- they are identical (except reversed in time)
226 after such operation.
227
228 @italic(Unfortunately, this doesn't look perfect, human eye can easily
229 notice the extreme time points (in the middle and at the end),
230 when objects in the video reverse their directions etc.
231 So the video is seamless, and it's a better trick than just setting
232 TimeBackwards := true, but it still doesn't really look good.) }
233 procedure MixWithSelfBackwards;
234
235 { Edit the video beginning to fade with the video ending,
236 thus forcing the video to play seamless in a loop.
237
238 The idea is to take out last FadeFrames from the video
239 (FadeFrames must be >= 0 and <= Count div 2). And then mix
240 the beginning of the video, such that the beginning FadeFrames
241 frames gradually fade from the original end of video to original
242 begin of the video.
243
244 Video must be loaded when using this.
245
246 @raises(EInvalidFadeFrames When FadeFrames is wrong.) }
247 procedure FadeWithSelf(FadeFrames: Cardinal);
248
249 { Similar to IndexFromTime, this is a class method that calculates
250 frame index using the same algorithm. (Actually, IndexFromTime
251 just calls this, but this is implementation detail...).
252
253 The idea is that you can reuse the same algorithm in cases when
254 you somehow have the video data but do not have an instance
255 of TVideo class.
256
257 In particular, this public for TGLVideo.IndexFromTime,
258 TGLVideo.GLTextureFromTime methods. }
259 class function FrameIndexFromTime(const Time: TFloatTime;
260 const ACount: Integer;
261 const AFramesPerSecond: Single;
262 const ATimeLoop, ATimeBackwards: boolean): Integer;
263
264 { Alpha channel type of loaded video.
265 See TCastleImage.AlphaChannel for precise meaning of this.
266 Currently based on the first video image, so it's fast although
267 in some cases possibly inaccurate. }
268 function AlphaChannel(
269 const AlphaTolerance: Byte = DefaultAlphaTolerance): TAlphaChannel;
270
271 procedure FlipHorizontal;
272 procedure FlipVertical;
273 end;
274
275 { A cache of loaded videos.
276
277 The idea is that instead of creating TVideo instance and calling
278 TVideo.LoadFromFile, you instead call
279 @code(Video := Cache.Video_IncReference(...)).
280 Later, instead of freeing this video, call
281 @code(Video_DecReference(Video)). From your point of view, things
282 will work the same. But if you expect to load many videos from the
283 same URL, then you will get a great speed and memory saving,
284 because video will only be actually loaded once. This may happen
285 e.g. if you have a VRML / X3D file with lots of MovieTexture nodes
286 with the same urls.
287
288 Notes:
289
290 @unorderedList(
291 @item(All passed here URLs must be absolute.)
292
293 @item(Note that in case of problems with loading,
294 Video_IncReference may raise an exception, just like normal
295 TVideo.LoadFromFile. In this case it's guaranteed that no reference will
296 be incremented, of course. If Video_IncReference returns
297 in a normal way, then it will return something non-@nil for sure.)
298
299 @item(Video_DecReference alwas sets Video to @nil, like FreeAndNil.)
300
301 @item(All videos handled here are always loaded.
302 So Video_IncReference always returns TVideo with TVideo.Loaded = @true.
303 And you are forbidden from closing this video by TVideo.Close
304 yourself.)
305 )
306
307 Note that before destroying this object you must free all videos,
308 i.e. call Video_DecReference for all videos allocated by
309 Video_IncReference. @italic(This class is not a lousy way
310 of avoiding memory leaks) --- it would be a bad idea, because it would
311 cause sloppy programming, where memory is unnecessarily allocated for
312 a long time. In fact, this class asserts in destructor that no videos
313 are in cache anymore, so if you compiled with assertions enabled,
314 this class does the job of memory-leak detector. }
315 TVideosCache = class
316 private
317 type
318 TCachedVideo = class
319 References: Cardinal;
320 Url: String;
321 LoadOptions: TLoadImageOptions;
322 Video: TVideo;
323 AlphaChannel: TAlphaChannel;
324 end;
325 TCachedVideoList = {$ifdef FPC}specialize{$endif} TObjectList<TCachedVideo>;
326 var
327 CachedVideos: TCachedVideoList;
328 FOnEmpty: TProcedure;
329 protected
330 { If cache is empty, calls OnEmpty. Note that OnEmpty may destroy current
331 instance, so call CheckEmpty only when you finished processing
332 --- Self may be invalid afterwards. }
333 procedure CheckEmpty;
334 public
335 constructor Create;
336 destructor Destroy; override;
337
338 function Video_IncReference(const Url: String;
339 out AlphaChannel: TAlphaChannel;
340 const LoadOptions: TLoadImageOptions = []): TVideo;
341 procedure Video_DecReference(var Video: TVideo);
342
343 function Empty: boolean; virtual;
344
345 { Called when cache becomes empty. This is only for internal usage
346 by X3DNodes unit for now. }
347 property OnEmpty: TProcedure read FOnEmpty write FOnEmpty;
348 end;
349
350 { Does given MIME type looks like a video file extension
351 that can be handled (encoded or decoded) by ffmpeg.
352
353 FfmpegOutput = @true means that you want to encode this video
354 (use this as output of ffmpeg). FfmpegOutput = @false means you
355 want to decode the video, that is use this as an input to ffmpeg. }
356 function FfmpegVideoMimeType(const MimeType: string;
357 const FfmpegOutput: boolean): boolean;
358
359 { Returns full path to ffmpeg-compatible executable.
360
361 When not found:
362 @unorderedList(
363 @item If ExceptionOnError then we raise an exception.
364 @item If not ExceptionOnError then we simply return ''.
365 ) }
366 function FfmpegExecutable(const ExceptionOnError: boolean): string;
367
368 { Execute ffmpeg. 1st parameter must not be ''.
369 It should usually be calculated by FfmpegExecutable. }
370 procedure FfmpegExecute(const Executable: string;
371 const Parameters: array of string);
372
373 var
374 { When @true, then we will load animated GIFs using ffmpeg.
375 Otherwise, we load GIF using TCastleImage as a single (not animated) image.
376
377 TODO: When the TFPReaderGif from FPC will support reading all GIF frames,
378 then this variable will be ignored, and we will always read all GIF frames
379 inside @link(TVideo), @link(TGLVideo2D), @link(TGLVideo3D),
380 and ffmpeg will not be necessary to read GIF animations.
381
382 Use @link(TCastleImage) if you want to always load GIF as static image
383 (first frame, if case of animated GIF).
384 }
385 LoadAnimatedGifs: boolean = false;
386
387 { Maximum number of video frames to read, for TVideo.LoadFromFile.
388
389 This prevents using up all the memory by accidentally trying to read
390 a long movie. Remember that our current implementation is @bold(not)
391 suited for long movies, it will load very slowly and consume a lot of memory.
392 See https://castle-engine.io/x3d_implementation_texturing.php
393 notes about MovieTexture.
394
395 By default this is equal to 1 minute, for 25 frames-per-second movie.
396 Even this can eat 2 GB for 640 x 350 resolution. }
397 MaximumVideoLength: Cardinal = 1 * 60 * 25;
398
399 { Log video cache events. Allows to see how the cache performs,
400 and also how long it takes to load videos (useful, as some videos may
401 be already lengthy).
402
403 Meaningful only if you initialized log (see CastleLog unit) by InitializeLog first. }
404 LogVideosCache: boolean = false;
405
406 const
407 DefaultFramesPerSecond = 25.0;
408
409 implementation
410
411 uses Classes,
412 {$ifndef FPC} {$ifdef MSWINDOWS} Windows, ShellApi, {$endif} {$endif}
413 Math,
414 CastleClassUtils, CastleUtils, CastleStringUtils,
415 CastleLog, CastleFilesUtils, CastleTextureImages,
416 CastleDownload, CastleUriUtils, CastleFindFiles;
417
418 { TVideo --------------------------------------------------------------------- }
419
420 constructor TVideo.Create;
421 begin
422 inherited;
423 FLoaded := false;
424 { This is just constant for now }
425 FFramesPerSecond := DefaultFramesPerSecond;
426 end;
427
428 destructor TVideo.Destroy;
429 begin
430 Close;
431 inherited;
432 end;
433
434 function TVideo.Count: Integer;
435 begin
436 Assert(Loaded);
437 Result := High(FItems) + 1;
438 end;
439
440 function TVideo.GetItems(Index: Integer): TCastleImage;
441 begin
442 Assert(Loaded);
443 Result := FItems[Index];
444 end;
445
446 class function TVideo.FrameIndexFromTime(const Time: TFloatTime;
447 const ACount: Integer;
448 const AFramesPerSecond: Single;
449 const ATimeLoop, ATimeBackwards: boolean): Integer;
450 var
451 DivResult: SmallInt;
452 ModResult: Word;
453 begin
454 Result := Floor(Time * AFramesPerSecond);
455
456 DivUnsignedMod(Result, ACount, DivResult, ModResult);
457
458 if ATimeLoop then
459 begin
460 if ATimeBackwards and Odd(DivResult) then
461 Result := ACount - 1 - ModResult else
462 Result := ModResult;
463 end else
464 begin
465 if ATimeBackwards then
466 begin
467 if (DivResult < 0) or (DivResult > 1) then
468 Result := 0 else
469 if DivResult = 1 then
470 Result := ACount - 1 - ModResult;
471 { else DivResult = 0, so Result is already correct }
472 end else
473 begin
474 if DivResult < 0 then
475 Result := 0 else
476 if DivResult > 0 then
477 Result := ACount - 1;
478 end;
479 end;
480 end;
481
482 function TVideo.IndexFromTime(const Time: TFloatTime): Integer;
483 begin
484 Assert(Loaded);
485 Result := FrameIndexFromTime(Time, Count, FramesPerSecond,
486 TimeLoop, TimeBackwards);
487 end;
488
489 function TVideo.ImageFromTime(const Time: TFloatTime): TCastleImage;
490 begin
491 Result := FItems[IndexFromTime(Time)];
492 end;
493
494 function TVideo.TimeDuration: Single;
495 begin
496 { Use Count, not High(FItems) (Count = High(FItems) + 1).
497 Reason: we want the last frame to be treated as well as the others. }
498 Result := Count / FramesPerSecond;
499 end;
500
501 procedure TVideo.Close;
502 var
503 I: Integer;
504 begin
505 for I := 0 to High(FItems) do
506 FreeAndNil(FItems[I]);
507 SetLength(FItems, 0);
508 FLoaded := false;
509 end;
510
511 procedure TVideo.Resize(const ResizeToX, ResizeToY: Cardinal;
512 const Interpolation: TResizeInterpolation = riBilinear);
513 var
514 I: Integer;
515 begin
516 for I := 0 to High(FItems) do
517 FItems[I].Resize(ResizeToX, ResizeToY, Interpolation);
518 end;
519
520 procedure TVideo.LoadFromFile(const Url: String;
521 const ResizeToX: Cardinal = 0;
522 const ResizeToY: Cardinal = 0;
523 const Interpolation: TResizeInterpolation = riBilinear;
524 const LoadOptions: TLoadImageOptions = []);
525
526 function LoadSingleImage(const Url: String): TCastleImage;
527 begin
528 Result := CastleImages.LoadImage(Url, TextureImageClasses,
529 ResizeToX, ResizeToY, Interpolation, LoadOptions);
530 end;
531
532 { Load from an image sequence (possibly just a single image).
533 When RemoveLoadedTempImages, we will remove the loaded image files,
534 in this case the URL @italic(must) be a filename. }
535 procedure LoadFromImages(const Url: String;
536 RemoveLoadedTempImages: boolean);
537
538 { Load movie frame number Index. Returns if success. }
539 function LoadFrame(const Index: Cardinal): boolean;
540 var
541 UrlComplete: string;
542 NewItem: TCastleImage;
543 begin
544 UrlComplete := FormatNameCounter(Url, Index, false);
545
546 try
547 { LoadImage will raise an exception
548 for invalid / not existing / not readable image file / url.
549 Don't increase FItems before NewItem is successfully loaded. }
550 NewItem := LoadSingleImage(UrlComplete);
551 except
552 Exit(false);
553 end;
554
555 SetLength(FItems, Length(FItems) + 1);
556 FItems[High(FItems)] := NewItem;
557
558 if RemoveLoadedTempImages then
559 CheckDeleteFile(UrlComplete, true);
560
561 Result := true;
562 end;
563
564 var
565 Index, ReplacementsDone: Cardinal;
566 SingleFrame: TCastleImage;
567 begin
568 FormatNameCounter(Url, 0, false, ReplacementsDone);
569 if ReplacementsDone > 0 then
570 begin
571 { Try to load frame 0. Ignore failure (it means movie starts at frame 1). }
572 LoadFrame(0);
573
574 Index := 1;
575 while LoadFrame(Index) and
576 (Length(FItems) < MaximumVideoLength) do
577 Inc(Index);
578
579 if Length(FItems) = 0 then
580 raise ECannotOpenFirstVideoFrame.CreateFmt('First video image ("%s" or "%s") cannot be loaded (not found, or not supported image format). Cannot load the video',
581 [FormatNameCounter(Url, 0, false),
582 FormatNameCounter(Url, 1, false)]);
583 end else
584 begin
585 SingleFrame := LoadSingleImage(Url);
586 SetLength(FItems, 1);
587 FItems[0] := SingleFrame;
588
589 { when RemoveLoadedTempImages, we know URL is a filename and can be safely
590 passed to CheckDeleteFile }
591 if RemoveLoadedTempImages then
592 CheckDeleteFile(Url, true);
593 end;
594 end;
595
596 { Load a single video file from an URL. }
597 procedure LoadFromFfmpeg(const Url: String);
598 var
599 MovieFileName: string;
600 MovieFileNameTemporary: boolean;
601 TemporaryImagesPrefix, FfmpegTemporaryImagesPattern, OurTemporaryImagesPattern: string;
602 Executable: string;
603 S: TStream;
604 begin
605 Executable := FfmpegExecutable(true);
606
607 { initialize TemporaryImagesPrefix, TemporaryImagesPattern }
608 TemporaryImagesPrefix := GetTempFileNamePrefix;
609 FfmpegTemporaryImagesPattern := TemporaryImagesPrefix + '%d.png';
610 OurTemporaryImagesPattern := TemporaryImagesPrefix + '@counter(1).png';
611
612 MovieFileName := UriToFilenameSafe(Url);
613 MovieFileNameTemporary := false;
614
615 { If URL isn't a local file (maybe it's http, maybe data URI) then
616 download it ourselves to a temporary file.
617
618 We don't let ffmpeg to download video. Although ffmpeg can handle
619 http URLs, but then progress of download is not visible using
620 our progress (OTOH, it is streamed and converted during downloading).
621 Most important: ffmpeg can't handle data URI (we could not even
622 pass such long strings on the command-line). }
623 if MovieFileName = '' then
624 begin
625 MovieFileName := GetTempFileNameCheck;
626 MovieFileNameTemporary := true;
627 S := Download(Url);
628 try
629 StreamSaveToFile(S, MovieFileName);
630 finally FreeAndNil(S) end;
631 end;
632
633 try
634 FfmpegExecute(Executable, [ '-i', MovieFileName, '-y', '-qscale', '1',
635 '-vframes', IntToStr(MaximumVideoLength),
636 '-f', 'image2', FfmpegTemporaryImagesPattern ]);
637 finally
638 if MovieFileNameTemporary then
639 CheckDeleteFile(MovieFileName, true);
640 end;
641
642 LoadFromImages(OurTemporaryImagesPattern, true);
643 end;
644
645 begin
646 Close;
647
648 if FfmpegVideoMimeType(UriMimeType(Url), true) then
649 LoadFromFfmpeg(Url)
650 else
651 LoadFromImages(Url, false);
652
653 FLoaded := true;
654 end;
655
656 procedure TVideo.SaveToFile(const Url: String);
657
658 procedure SaveToImages(const Url: String);
659 var
660 Index, ReplacementsDone: Cardinal;
661 S: string;
662 begin
663 FormatNameCounter(Url, 0, true, ReplacementsDone);
664 if ReplacementsDone > 0 then
665 begin
666 { Note that Index is 1-based, that's how FormatNameCounter
667 works for LoadFromFile and ffmpeg, so also here. }
668 for Index := 1 to Count do
669 begin
670 S := FormatNameCounter(Url, Index, true);
671 SaveImage(FItems[Index - 1], S);
672 end;
673 end else
674 begin
675 { single image file --- suitable only if video has exactly one frame }
676 if Count <> 1 then
677 raise Exception.CreateFmt('Single image URL detected ("%s"), but saved video doesn''t have exactly one frame (it has %d frames). Cannot save',
678 [UriDisplay(Url), Count]);
679
680 SaveImage(FItems[0], Url);
681 end;
682 end;
683
684 procedure RemoveTemporaryImages(const FileName: string);
685 var
686 Index, ReplacementsDone: Cardinal;
687 S: string;
688 begin
689 WritelnLog('Removing temporary image files "' + FileName + '" ...');
690 FormatNameCounter(FileName, 0, true, ReplacementsDone);
691 if ReplacementsDone > 0 then
692 begin
693 for Index := 1 to Count do
694 begin
695 S := FormatNameCounter(FileName, Index, true);
696 if not DeleteFile(PChar(S)) then
697 WritelnWarning('Video', Format('Cannot delete temporary file "%s"', [S]));
698 end;
699 end else
700 begin
701 if not DeleteFile(PChar(FileName)) then
702 WritelnWarning('Video', Format('Cannot delete temporary file "%s"', [FileName]));
703 end;
704 WritelnLog('Done removing temporary image files.');
705 end;
706
707 procedure SaveToFfmpeg(const FileName: string);
708 var
709 TemporaryImagesPrefix, TemporaryImagesPattern: string;
710 Executable: string;
711 begin
712 Executable := FindExe('ffmpeg');
713
714 if Executable = '' then
715 begin
716 raise Exception.Create('You must have "ffmpeg" program from ' +
717 '[http://ffmpeg.mplayerhq.hu/] installed and available on $PATH to be able to ' +
718 'save movie files');
719 end else
720 begin
721 { initialize TemporaryImagesPrefix, TemporaryImagesPattern }
722 TemporaryImagesPrefix := GetTempFileNamePrefix;
723 TemporaryImagesPattern := TemporaryImagesPrefix + '%d.png';
724
725 SaveToImages(TemporaryImagesPattern);
726
727 { ffmpeg call will output some things on stdout anyway.
728 So it's Ok that we also output something, stdout is required
729 by ffmpeg anyway... }
730
731 WritelnLog('FFMpeg found, executing...');
732 WritelnLog(Executable + ' -f image2 -i "' + TemporaryImagesPattern +
733 '" -y -qscale 1 "' + FileName + '"');
734
735 {$if defined(FPC)}
736 ExecuteProcess(Executable,
737 ['-f', 'image2', '-i', TemporaryImagesPattern, '-y', '-qscale', '1', FileName]);
738 {$elseif defined(MSWINDOWS)}
739 ShellExecute(
740 0,
741 'open',
742 PChar(Executable),
743 PChar('-f image2 -i ' + TemporaryImagesPattern + '-y -qscale 1 ' + FileName),
744 nil,
745 SW_SHOW);
746 {$else}
747 raise Exception.Create('TODO: Executing ffmpeg on Delphi/non-Windows not implemented');
748 {$endif}
749
750 RemoveTemporaryImages(TemporaryImagesPattern);
751 end;
752 end;
753
754 begin
755 Assert(Loaded);
756
757 if FfmpegVideoMimeType(UriMimeType(Url), false) then
758 SaveToFfmpeg(Url) else
759 SaveToImages(UriToFilenameSafe(Url));
760 end;
761
762 function TVideo.Width: Cardinal;
763 begin
764 Assert(Loaded);
765 Result := Items[0].Width;
766 end;
767
768 function TVideo.Height: Cardinal;
769 begin
770 Assert(Loaded);
771 Result := Items[0].Height;
772 end;
773
774 procedure TVideo.MixWithSelfBackwards;
775 var
776 I, NewCount: Integer;
777 begin
778 Assert(Loaded);
779
780 for I := 0 to Count div 2 do
781 begin
782 Items[I].LerpWith(0.5, Items[Count - 1 - I]);
783 end;
784
785 { shrink count to half }
786 NewCount := (Count div 2) + (Count mod 2);
787 for I := NewCount to Count - 1 do
788 begin
789 FreeAndNil(FItems[I]);
790 end;
791 SetLength(FItems, NewCount);
792
793 TimeBackwards := true;
794 end;
795
796 procedure TVideo.FadeWithSelf(FadeFrames: Cardinal);
797 var
798 I, NewCount: Integer;
799 begin
800 Assert(Loaded);
801
802 if FadeFrames > Cardinal(Count) div 2 then
803 raise EInvalidFadeFrames.CreateFmt('FadeFrames for FadeWithSelf too large: are %d, but frames count div 2 = %s',
804 [FadeFrames, Count div 2]);
805
806 for I := 0 to FadeFrames - 1 do
807 begin
808 Items[I].LerpWith(1 - I / FadeFrames, Items[Count - FadeFrames + I]);
809 end;
810
811 NewCount := Count - FadeFrames;
812 for I := NewCount to Count - 1 do
813 begin
814 FreeAndNil(FItems[I]);
815 end;
816 SetLength(FItems, NewCount);
817 end;
818
819 function TVideo.AlphaChannel(
820 const AlphaTolerance: Byte): TAlphaChannel;
821 begin
822 Assert(Loaded);
823 Result := Items[0].AlphaChannel(AlphaTolerance);
824 end;
825
826 procedure TVideo.FlipHorizontal;
827 var
828 I: Integer;
829 begin
830 for I := 0 to Count - 1 do
831 Items[I].FlipHorizontal;
832 end;
833
834 procedure TVideo.FlipVertical;
835 var
836 I: Integer;
837 begin
838 for I := 0 to Count - 1 do
839 Items[I].FlipVertical;
840 end;
841
842 { TVideosCache --------------------------------------------------------------- }
843
844 constructor TVideosCache.Create;
845 begin
846 inherited;
847 CachedVideos := TCachedVideoList.Create;
848 end;
849
850 destructor TVideosCache.Destroy;
851 begin
852 if CachedVideos <> nil then
853 begin
854 Assert(CachedVideos.Count = 0, ' Some references to videos still exist ' +
855 'when freeing TVideosCache');
856 FreeAndNil(CachedVideos);
857 end;
858 inherited;
859 end;
860
861 function TVideosCache.Video_IncReference(const Url: String;
862 out AlphaChannel: TAlphaChannel;
863 const LoadOptions: TLoadImageOptions): TVideo;
864 var
865 I: Integer;
866 C: TCachedVideo;
867 Start: TProcessTimerResult;
868 S: string;
869 begin
870 for I := 0 to CachedVideos.Count - 1 do
871 begin
872 C := CachedVideos[I];
873 if (C.Url = Url) and
874 (C.LoadOptions = LoadOptions) then
875 begin
876 Inc(C.References);
877 AlphaChannel := C.AlphaChannel;
878
879 if LogVideosCache then
880 WritelnLog('++', 'Video %s : %d', [UriDisplay(Url), C.References]);
881
882 Exit(C.Video);
883 end;
884 end;
885
886 { Initialize Result first, before calling CachedVideos.Add.
887 That's because in case TVideo.LoadFromFile raises exception,
888 we don't want to add video to cache (because caller would have
889 no way to call Video_DecReference later). }
890
891 if LogVideosCache then
892 Start := ProcessTimer;
893
894 Result := TVideo.Create;
895 try
896 Result.LoadFromFile(Url, 0, 0, riBilinear, LoadOptions);
897 except
898 FreeAndNil(Result);
899 raise;
900 end;
901
902 C := TCachedVideo.Create;
903 CachedVideos.Add(C);
904 C.References := 1;
905 C.Url := Url;
906 C.LoadOptions := LoadOptions;
907 C.Video := Result;
908 C.AlphaChannel := Result.AlphaChannel;
909 AlphaChannel := C.AlphaChannel;
910
911 if LogVideosCache then
912 begin
913 S := Format('Video %s : 1. Loading time: %f',
914 [UriDisplay(Url), ProcessTimerSeconds(ProcessTimer, Start)]);
915 if AlphaChannel <> acNone then
916 S := S + '. Detected as simple yes/no ("test") alpha channel: ' +
917 BoolToStr(AlphaChannel = acTest, true);
918 WritelnLog('++', S);
919 end;
920 end;
921
922 procedure TVideosCache.Video_DecReference(var Video: TVideo);
923 var
924 I: Integer;
925 C: TCachedVideo;
926 begin
927 for I := 0 to CachedVideos.Count - 1 do
928 begin
929 C := CachedVideos[I];
930 if C.Video = Video then
931 begin
932 if LogVideosCache then
933 WritelnLog('--', 'Video %s : %d', [C.Url, C.References - 1]);
934
935 Video := nil;
936
937 if C.References = 1 then
938 begin
939 FreeAndNil(C.Video);
940 CachedVideos.Delete(I);
941 CheckEmpty;
942 end else
943 Dec(C.References);
944
945 Exit;
946 end;
947 end;
948
949 raise EInternalError.CreateFmt(
950 'TVideosCache.Video_DecReference: no reference found for video %s',
951 [PointerToStr(Video)]);
952 end;
953
954 function TVideosCache.Empty: boolean;
955 begin
956 Result := (CachedVideos.Count = 0);
957 end;
958
959 procedure TVideosCache.CheckEmpty;
960 begin
961 { Check Assigned(OnEmpty) first, as it's usually not assigned. }
962 if Assigned(OnEmpty) and Empty then
963 OnEmpty();
964 end;
965
966 { non-object routines -------------------------------------------------------- }
967
968 function FfmpegVideoMimeType(const MimeType: string;
969 const FfmpegOutput: boolean): boolean;
970 begin
971 { For now we ignore FfmpegOutput, all formats below are good
972 for both input and output. (Actually, MIME (always from file extension now)
973 specifies only "container" data type, not actual encoding,
974 so there's no guarentee, but potentially it's all possible.)
975 See "ffmpeg -formats". }
976 Result :=
977 (LoadAnimatedGifs and (MimeType = 'image/gif')) or
978 (MimeType = 'video/x-msvideo') or
979 (MimeType = 'video/mpeg') or
980 (MimeType = 'video/ogg') or
981 (MimeType = 'video/quicktime') or
982 (MimeType = 'video/x-flv') or
983 (MimeType = 'application/x-shockwave-flash') or
984 (MimeType = 'video/mp4');
985 end;
986
987 function FfmpegExecutable(const ExceptionOnError: boolean): string;
988 const
989 SFfmpegNotFound = 'You must have "ffmpeg" from [http://www.ffmpeg.org/] ' +
990 '(or "avconv" from [http://www.libav.org/]) ' +
991 'installed and available on $PATH to be able to load movie files';
992 begin
993 Result := FindExe('ffmpeg');
994 if Result = '' then
995 Result := FindExe('avconv');
996 if (Result = '') and ExceptionOnError then
997 raise Exception.Create(SFfmpegNotFound);
998 end;
999
1000 procedure FfmpegExecute(const Executable: string;
1001 const Parameters: array of string);
1002 var
1003 S, Parameter: string;
1004 begin
1005 WritelnLog('FFMpeg found, executing...');
1006 { Only for the sake of logging we glue Parameters together.
1007 For actual execution, we pass Parameters as an array, which is *much*
1008 safer (no need to worry whether Parameter contains " inside etc.) }
1009 {$ifdef FPC}
1010 S := Executable;
1011 {$else}
1012 S := '';
1013 {$endif}
1014 for Parameter in Parameters do
1015 begin
1016 S := S + ' ';
1017 if Pos(' ', Parameter) <> 0 then
1018 S := S + '"' + Parameter + '"'
1019 else
1020 S := S + Parameter;
1021 end;
1022 WritelnLog(S);
1023
1024 {$if defined(FPC)}
1025 ExecuteProcess(Executable, Parameters);
1026 {$elseif defined(MSWINDOWS)}
1027 ShellExecute(
1028 0,
1029 'open',
1030 PChar(Executable),
1031 PChar(S),
1032 nil,
1033 SW_SHOW);
1034 {$else}
1035 raise Exception.Create('TODO: Executing ffmpeg on Delphi/non-Windows not implemented');
1036 {$endif}
1037 end;
1038
1039 end.