Skip to content

Commit

Permalink
done new Gif render
Browse files Browse the repository at this point in the history
  • Loading branch information
xupefei committed Jun 13, 2018
1 parent c13839c commit cc48d94
Show file tree
Hide file tree
Showing 7 changed files with 50 additions and 180 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright © 2017 Paddy Xu
// Copyright © 2018 Paddy Xu
//
// This file is part of QuickLook program.
//
Expand All @@ -17,42 +17,36 @@

using System;
using System.IO;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Threading;
using QuickLook.Common.Helpers;
using QuickLook.Plugin.ImageViewer.Exiv2;

namespace QuickLook.Plugin.ImageViewer.AnimatedImage
{
public class AnimatedImage : Image, IDisposable
{
private AnimationProvider _animation;
private bool _disposed;

public void Dispose()
{
BeginAnimation(AnimationFrameIndexProperty, null);
Source = null;
_animation = null;

_disposed = true;

Task.Delay(500).ContinueWith(t => ProcessHelper.PerformAggressiveGC());
_animation?.Dispose();
_animation = null;
}

private static void LoadFullImage(DependencyObject obj, DependencyPropertyChangedEventArgs ev)
{
if (!(obj is AnimatedImage instance))
return;

instance._animation = LoadFullImageCore((Uri) ev.NewValue);
instance._animation = LoadFullImageCore((Uri) ev.NewValue, instance.Dispatcher);
instance.BeginAnimation(AnimationFrameIndexProperty, instance._animation.Animator);
}

private static AnimationProvider LoadFullImageCore(Uri path)
private static AnimationProvider LoadFullImageCore(Uri path, Dispatcher uiDispatcher)
{
byte[] sign;
using (var reader =
Expand All @@ -64,7 +58,7 @@ private static AnimationProvider LoadFullImageCore(Uri path)
AnimationProvider provider = null;

if (sign[0] == 'G' && sign[1] == 'I' && sign[2] == 'F' && sign[3] == '8')
provider = new GIFAnimationProvider(path.LocalPath);
provider = new GifAnimationProvider(path.LocalPath, uiDispatcher);
//else if (sign[0] == 0x89 && sign[1] == 'P' && sign[2] == 'N' && sign[3] == 'G')
// provider = new APNGAnimationProvider();
//else
Expand Down Expand Up @@ -122,13 +116,9 @@ private static void AnimationFrameIndexChanged(DependencyObject obj, DependencyP
if (!(obj is AnimatedImage instance))
return;

new Task(() =>
{
var image = instance._animation.GetRenderedFrame((int) ev.NewValue);

instance.Dispatcher.BeginInvoke(
new Action(() => { instance.Source = image; }), DispatcherPriority.Loaded);
}).Start();
var image = instance._animation.GetRenderedFrame((int) ev.NewValue);
//if (!ReferenceEquals(instance.Source, image))
instance.Source = image;
}

#endregion DependencyProperty
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,23 +15,29 @@
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.

using System;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Threading;

namespace QuickLook.Plugin.ImageViewer.AnimatedImage
{
internal abstract class AnimationProvider
internal abstract class AnimationProvider : IDisposable
{
public AnimationProvider(string path)
protected AnimationProvider(string path, Dispatcher uiDispatcher)
{
Path = path;
Dispatcher = uiDispatcher;
}

public Dispatcher Dispatcher { get; }

public string Path { get; }

public Int32Animation Animator { get; protected set; }

public abstract DrawingImage GetRenderedFrame(int index);
public abstract void Dispose();

public abstract ImageSource GetRenderedFrame(int index);
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright © 2017 Paddy Xu
// Copyright © 2018 Paddy Xu
//
// This file is part of QuickLook program.
//
Expand All @@ -16,187 +16,60 @@
// along with this program. If not, see <http://www.gnu.org/licenses/>.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Drawing;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using QuickLook.Common.ExtensionMethods;

namespace QuickLook.Plugin.ImageViewer.AnimatedImage
{
internal class GIFAnimationProvider : AnimationProvider
internal class GifAnimationProvider : AnimationProvider
{
private readonly List<FrameInfo> _decodedFrames;
private readonly int _lastRenderedFrameIndex;
private readonly DrawingGroup renderedFrame;
private Bitmap _frame;
private BitmapSource _frameSource;
private bool _isPlaying;

public GIFAnimationProvider(string path) : base(path)
public GifAnimationProvider(string path, Dispatcher uiDispatcher) : base(path, uiDispatcher)
{
var decoder = new GifBitmapDecoder(new Uri(path), BitmapCreateOptions.PreservePixelFormat,
BitmapCacheOption.OnLoad);
_frame = (Bitmap) Image.FromFile(path);
_frameSource = _frame.ToBitmapSource();

_decodedFrames = new List<FrameInfo>(decoder.Frames.Count);
decoder.Frames.ForEach(f => _decodedFrames.Add(GetFrameInfo(f)));

renderedFrame = new DrawingGroup();
_lastRenderedFrameIndex = -1;

var delay = _decodedFrames[0].Delay.TotalMilliseconds;

Animator = new Int32Animation(0, decoder.Frames.Count - 1,
new Duration(TimeSpan.FromMilliseconds(delay * (decoder.Frames.Count - 1))))
Animator = new Int32Animation(0, 1, new Duration(TimeSpan.FromMilliseconds(50)))
{
RepeatBehavior = RepeatBehavior.Forever
};
}

public override DrawingImage GetRenderedFrame(int index)
public override void Dispose()
{
for (var i = _lastRenderedFrameIndex + 1; i < index; i++)
MakeFrame(renderedFrame, _decodedFrames[i], i > 0 ? _decodedFrames[i - 1] : null);
if (_frame == null)
return;

MakeFrame(
renderedFrame,
_decodedFrames[index],
index > 0 ? _decodedFrames[index - 1] : null);

var di=new DrawingImage(renderedFrame);
di.Freeze();
ImageAnimator.StopAnimate(_frame, OnFrameChanged);
_frame.Dispose();

return di;
_frame = null;
_frameSource = null;
}

#region private methods

private static void MakeFrame(
DrawingGroup renderedFrame,
FrameInfo currentFrame,
FrameInfo previousFrame)
public override ImageSource GetRenderedFrame(int index)
{
if (previousFrame == null)
renderedFrame.Children.Clear();
else
switch (previousFrame.DisposalMethod)
{
case FrameDisposalMethod.Unspecified:
case FrameDisposalMethod.Combine:
break;
case FrameDisposalMethod.RestorePrevious:
renderedFrame.Children.RemoveAt(renderedFrame.Children.Count - 1);
break;
case FrameDisposalMethod.RestoreBackground:
var bg = renderedFrame.Children.First();
renderedFrame.Children.Clear();
renderedFrame.Children.Add(bg);
break;
}

renderedFrame.Children.Add(new ImageDrawing(currentFrame.Frame, currentFrame.Rect));
}

private static FrameInfo GetFrameInfo(BitmapFrame frame)
{
var frameInfo = new FrameInfo
{
Frame = frame,
Delay = TimeSpan.FromMilliseconds(100),
DisposalMethod = FrameDisposalMethod.Unspecified,
Width = frame.PixelWidth,
Height = frame.PixelHeight,
Left = 0,
Top = 0
};

try
{
if (frame.Metadata is BitmapMetadata metadata)
{
const string delayQuery = "/grctlext/Delay";
const string disposalQuery = "/grctlext/Disposal";
const string widthQuery = "/imgdesc/Width";
const string heightQuery = "/imgdesc/Height";
const string leftQuery = "/imgdesc/Left";
const string topQuery = "/imgdesc/Top";

var delay = metadata.GetQueryOrNull<ushort>(delayQuery);
if (delay.HasValue)
frameInfo.Delay = TimeSpan.FromMilliseconds(10 * delay.Value);

var disposal = metadata.GetQueryOrNull<byte>(disposalQuery);
if (disposal.HasValue)
frameInfo.DisposalMethod = (FrameDisposalMethod) disposal.Value;

var width = metadata.GetQueryOrNull<ushort>(widthQuery);
if (width.HasValue)
frameInfo.Width = width.Value;

var height = metadata.GetQueryOrNull<ushort>(heightQuery);
if (height.HasValue)
frameInfo.Height = height.Value;

var left = metadata.GetQueryOrNull<ushort>(leftQuery);
if (left.HasValue)
frameInfo.Left = left.Value;

var top = metadata.GetQueryOrNull<ushort>(topQuery);
if (top.HasValue)
frameInfo.Top = top.Value;
}
}
catch (NotSupportedException)
if (!_isPlaying)
{
_isPlaying = true;
ImageAnimator.Animate(_frame, OnFrameChanged);
}

return frameInfo;
}

#endregion

#region structs

private class FrameInfo
{
public BitmapSource Frame { get; set; }
public FrameDisposalMethod DisposalMethod { get; set; }
public TimeSpan Delay { get; set; }
public Rect Rect => new Rect(Left, Top, Width, Height);

public double Width { private get; set; }
public double Height { private get; set; }
public double Left { private get; set; }
public double Top { private get; set; }
}

private enum FrameDisposalMethod
{
Unspecified = 0,
Combine = 1,
RestoreBackground = 2,
RestorePrevious = 3
return _frameSource;
}

#endregion
}

#region extensions

public static class Extensions
{
public static T? GetQueryOrNull<T>(this BitmapMetadata metadata, string query)
where T : struct
private void OnFrameChanged(object sender, EventArgs e)
{
if (metadata.ContainsQuery(query))
{
var value = metadata.GetQuery(query);
if (value != null)
return (T) value;
}

return null;
ImageAnimator.UpdateFrames();
_frameSource = _frame.ToBitmapSource();
}
}

#endregion
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright © 2017 Paddy Xu
// Copyright © 2018 Paddy Xu
//
// This file is part of QuickLook program.
//
Expand Down
3 changes: 2 additions & 1 deletion QuickLook.Plugin/QuickLook.Plugin.ImageViewer/Plugin.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright © 2017 Paddy Xu
// Copyright © 2018 Paddy Xu
//
// This file is part of QuickLook program.
//
Expand Down Expand Up @@ -84,6 +84,7 @@ public void View(string path, ContextObject context)

public void Cleanup()
{
_ip?.Dispose();
_ip = null;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@
</Compile>
<Compile Include="AnimatedImage\AnimatedImage.cs" />
<None Include="AnimatedImage\APNGAnimationProvider.cs" />
<Compile Include="AnimatedImage\GIFAnimationProvider.cs" />
<Compile Include="AnimatedImage\GifAnimationProvider.cs" />
<Compile Include="AnimatedImage\AnimationProvider.cs" />
<None Include="AnimatedImage\ImageMagickProvider.cs" />
<Compile Include="exiv2\Meta.cs" />
Expand Down
2 changes: 1 addition & 1 deletion QuickLook.sln.DotSettings
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
<s:Int64 x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/BLANK_LINES_AROUND_PROPERTY/@EntryValue">0</s:Int64>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/PLACE_ACCESSORHOLDER_ATTRIBUTE_ON_SAME_LINE_EX/@EntryValue">NEVER</s:String>
<s:String x:Key="/Default/CodeStyle/FileHeader/FileHeaderRegionName/@EntryValue"></s:String>
<s:String x:Key="/Default/CodeStyle/FileHeader/FileHeaderText/@EntryValue">Copyright © $CURRENT_YEAR$ $USER_NAME$&#xD;
<s:String x:Key="/Default/CodeStyle/FileHeader/FileHeaderText/@EntryValue">Copyright © $CURRENT_YEAR$ Paddy Xu&#xD;
&#xD;
This file is part of $SOLUTION$ program.&#xD;
&#xD;
Expand Down

0 comments on commit cc48d94

Please sign in to comment.