generated from vignetteapp/dotnet-template
-
-
Notifications
You must be signed in to change notification settings - Fork 18
/
ResourceManager.cs
70 lines (60 loc) · 2.45 KB
/
ResourceManager.cs
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
// Copyright (c) homuler and The Vignette Authors
// This file is part of MediaPipe.NET.
// MediaPipe.NET is licensed under the MIT License. See LICENSE for details.
using System;
using Mediapipe.Net.External;
using Mediapipe.Net.Native;
namespace Mediapipe.Net.Util
{
/// <summary>
/// Class to manage MediaPipe resources, such as `.tflite` and `.pbtxt` files that it requests.
/// </summary>
/// <remarks>
/// There must not be more than one instance at the same time.
/// </remarks>
public unsafe abstract class ResourceManager
{
public delegate string PathResolver(string path);
/// <summary>
/// Resolves a path to a resource name.
/// If the resource name returned is different from the path, the <see cref="ResourceProvider" /> delegate will receive the resource name instead of the file path.
/// </summary>
public abstract PathResolver ResolvePath { get; }
/// <summary>
/// Reads a resource that MediaPipe requests.
/// </summary>
/// <param name="path">File path or name of the resource.</param>
/// <returns>Content of the MediaPipe resource as a byte array.</returns>
public delegate byte[] ResourceProvider(string path);
public abstract ResourceProvider ProvideResource { get; }
private static readonly object initLock = new object();
private static bool isInitialized = false;
public ResourceManager()
{
lock (initLock)
{
if (isInitialized)
throw new InvalidOperationException("ResourceManager can be initialized only once");
SafeNativeMethods.mp__SetCustomGlobalPathResolver__P(ResolvePath);
SafeNativeMethods.mp__SetCustomGlobalResourceProvider__P(provideResource);
isInitialized = true;
}
}
private bool provideResource(string path, IntPtr output)
{
try
{
byte[] bytes = ProvideResource(path);
StdString strOutput = new StdString(output, isOwner: false);
StdString strSpan = new StdString(bytes);
strOutput.Swap(strSpan);
return true;
}
catch (Exception ex)
{
Glog.Log(Glog.Severity.Error, $"Error while trying to provide resource '{path}': {ex}");
return false;
}
}
}
}