-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathBassCdBehaviour.cs
363 lines (322 loc) · 13.3 KB
/
BassCdBehaviour.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
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
using FoxDb;
using FoxDb.Interfaces;
using FoxTunes.Interfaces;
using ManagedBass.Cd;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
namespace FoxTunes
{
[ComponentPriority(ComponentPriorityAttribute.LOW)]
public class BassCdBehaviour : StandardBehaviour, IConfigurableComponent, IInvocableComponent, IDisposable
{
public const string OPEN_CD = "FFFF";
public static string Location
{
get
{
return Path.GetDirectoryName(typeof(BassCdBehaviour).Assembly.Location);
}
}
public BassCdBehaviour()
{
BassLoader.AddPath(Path.Combine(Location, Environment.Is64BitProcess ? "x64" : "x86", BassLoader.DIRECTORY_NAME_ADDON));
BassLoader.AddPath(Path.Combine(Location, Environment.Is64BitProcess ? "x64" : "x86", "bass_gapless_cd.dll"));
}
public ICore Core { get; private set; }
public IPlaylistManager PlaylistManager { get; private set; }
public IBackgroundTaskEmitter BackgroundTaskEmitter { get; private set; }
public IConfiguration Configuration { get; private set; }
public IBassOutput Output { get; private set; }
public CdDoorMonitor DoorMonitor { get; private set; }
public IBassStreamPipelineFactory BassStreamPipelineFactory { get; private set; }
private bool _Enabled { get; set; }
public bool Enabled
{
get
{
return this._Enabled;
}
set
{
this._Enabled = value;
Logger.Write(this, LogLevel.Debug, "Enabled = {0}", this.Enabled);
}
}
private bool _CdLookup { get; set; }
public bool CdLookup
{
get
{
return this._CdLookup;
}
private set
{
this._CdLookup = value;
Logger.Write(this, LogLevel.Debug, "CD Lookup = {0}", this.CdLookup);
}
}
private IEnumerable<string> _CdLookupHosts { get; set; }
public IEnumerable<string> CdLookupHosts
{
get
{
return this._CdLookupHosts;
}
private set
{
this._CdLookupHosts = value;
if (value != null)
{
foreach (var cdLookupHost in value)
{
Logger.Write(this, LogLevel.Debug, "CD Lookup Host = {0}", cdLookupHost);
}
}
}
}
public override void InitializeComponent(ICore core)
{
this.Core = core;
this.Output = core.Components.Output as IBassOutput;
this.PlaylistManager = core.Managers.Playlist;
this.BackgroundTaskEmitter = core.Components.BackgroundTaskEmitter;
this.DoorMonitor = ComponentRegistry.Instance.GetComponent<CdDoorMonitor>();
if (this.DoorMonitor != null)
{
this.DoorMonitor.StateChanged += this.OnStateChanged;
}
this.Configuration = core.Components.Configuration;
this.Configuration.GetElement<BooleanConfigurationElement>(
BassCdStreamProviderBehaviourConfiguration.SECTION,
BassCdStreamProviderBehaviourConfiguration.ENABLED_ELEMENT
).ConnectValue(value => this.Enabled = value);
this.Configuration.GetElement<BooleanConfigurationElement>(
BassCdStreamProviderBehaviourConfiguration.SECTION,
BassCdStreamProviderBehaviourConfiguration.LOOKUP_ELEMENT
).ConnectValue(value => this.CdLookup = value);
this.Configuration.GetElement<TextConfigurationElement>(
BassCdStreamProviderBehaviourConfiguration.SECTION,
BassCdStreamProviderBehaviourConfiguration.LOOKUP_HOST_ELEMENT
).ConnectValue(value =>
{
if (!string.IsNullOrEmpty(value))
{
this.CdLookupHosts = value.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
}
else
{
this.CdLookupHosts = BassCdStreamProviderBehaviourConfiguration.GetLookupHosts();
}
});
this.BassStreamPipelineFactory = ComponentRegistry.Instance.GetComponent<IBassStreamPipelineFactory>();
if (this.BassStreamPipelineFactory != null)
{
this.BassStreamPipelineFactory.CreatingPipeline += this.OnCreatingPipeline;
}
base.InitializeComponent(core);
}
protected virtual void OnCreatingPipeline(object sender, CreatingPipelineEventArgs e)
{
if (!this.Enabled)
{
return;
}
var drive = default(int);
var id = default(string);
var track = default(int);
if (!CdUtils.ParseUrl(e.Stream.FileName, out drive, out id, out track))
{
return;
}
if (e.Input != null)
{
Logger.Write(this, LogLevel.Debug, "Overriding the default pipeline input: {0}", e.Input.GetType().Name);
e.Input.Dispose();
}
e.Input = new BassCdStreamInput(this, drive, e.Pipeline, e.Stream.Flags);
e.Input.InitializeComponent(this.Core);
}
protected virtual void OnStateChanged(object sender, EventArgs e)
{
if (this.Output.IsStarted && this.DoorMonitor.State == CdDoorState.Open)
{
Logger.Write(this, LogLevel.Debug, "CD door was opened, shutting down the output.");
this.Output.Shutdown();
}
}
public IEnumerable<ConfigurationSection> GetConfigurationSections()
{
return BassCdStreamProviderBehaviourConfiguration.GetConfigurationSections();
}
public IEnumerable<string> InvocationCategories
{
get
{
yield return InvocationComponent.CATEGORY_PLAYLIST;
}
}
public IEnumerable<IInvocationComponent> Invocations
{
get
{
if (this.Enabled)
{
foreach (var drive in CdUtils.GetDrives())
{
yield return new InvocationComponent(InvocationComponent.CATEGORY_PLAYLIST, OPEN_CD, drive, path: Strings.BassCdStreamProviderBehaviour_Path);
}
}
}
}
public Task InvokeAsync(IInvocationComponent component)
{
switch (component.Id)
{
case OPEN_CD:
var drive = CdUtils.GetDrive(component.Name);
if (drive == CdUtils.NO_DRIVE)
{
break;
}
return this.OpenCd(drive);
}
#if NET40
return TaskEx.FromResult(false);
#else
return Task.CompletedTask;
#endif
}
public Task OpenCd(int drive)
{
return this.OpenCd(this.PlaylistManager.SelectedPlaylist, drive);
}
public async Task OpenCd(Playlist playlist, int drive)
{
using (var task = new AddCdToPlaylistTask(playlist, drive, this.CdLookup, this.CdLookupHosts))
{
task.InitializeComponent(this.Core);
await this.BackgroundTaskEmitter.Send(task).ConfigureAwait(false);
await task.Run().ConfigureAwait(false);
}
}
public bool IsDisposed { get; private set; }
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (this.IsDisposed || !disposing)
{
return;
}
this.OnDisposing();
this.IsDisposed = true;
}
protected virtual void OnDisposing()
{
if (this.BassStreamPipelineFactory != null)
{
this.BassStreamPipelineFactory.CreatingPipeline -= this.OnCreatingPipeline;
}
}
~BassCdBehaviour()
{
Logger.Write(this, LogLevel.Error, "Component was not disposed: {0}", this.GetType().Name);
try
{
this.Dispose(true);
}
catch
{
//Nothing can be done, never throw on GC thread.
}
}
private class AddCdToPlaylistTask : PlaylistTaskBase
{
public AddCdToPlaylistTask(Playlist playlist, int drive, bool cdLookup, IEnumerable<string> cdLookupHosts) : base(playlist)
{
this.Drive = drive;
this.CdLookup = cdLookup;
this.CdLookupHosts = cdLookupHosts;
}
public override bool Visible
{
get
{
return true;
}
}
public int Drive { get; private set; }
public bool CdLookup { get; private set; }
public IEnumerable<string> CdLookupHosts { get; private set; }
public IPlaylistManager PlaylistManager { get; private set; }
public IPlaylistBrowser PlaylistBrowser { get; private set; }
public CdPlaylistItemFactory Factory { get; private set; }
public override void InitializeComponent(ICore core)
{
this.PlaylistManager = core.Managers.Playlist;
this.PlaylistBrowser = core.Components.PlaylistBrowser;
this.Factory = new CdPlaylistItemFactory(this.Drive, this.CdLookup, this.CdLookupHosts, this.Visible);
this.Factory.InitializeComponent(core);
base.InitializeComponent(core);
}
protected override async Task OnRun()
{
this.Name = "Opening CD";
try
{
if (!BassCd.IsReady(this.Drive))
{
throw new InvalidOperationException("Drive is not ready.");
}
var playlist = this.PlaylistManager.SelectedPlaylist;
var playlistItems = default(PlaylistItem[]);
await this.WithSubTask(this.Factory, async () => playlistItems = await this.Factory.Create(CancellationToken.None).ConfigureAwait(false)).ConfigureAwait(false);
using (var task = new SingletonReentrantTask(this, ComponentSlots.Database, SingletonReentrantTask.PRIORITY_HIGH, async cancellationToken =>
{
//Always append for now.
this.Sequence = this.PlaylistBrowser.GetInsertIndex(this.PlaylistManager.SelectedPlaylist);
await this.AddPlaylistItems(playlist, playlistItems).ConfigureAwait(false);
await this.ShiftItems(QueryOperator.GreaterOrEqual, this.Sequence, this.Offset).ConfigureAwait(false);
await this.SetPlaylistItemsStatus(PlaylistItemStatus.None).ConfigureAwait(false);
}))
{
await task.Run().ConfigureAwait(false);
}
}
finally
{
//Ignoring result on purpose.
BassCd.Release(this.Drive);
}
await this.SignalEmitter.Send(new Signal(this, CommonSignals.PlaylistUpdated, new PlaylistUpdatedSignalState(this.Playlist, DataSignalType.Updated))).ConfigureAwait(false);
}
private async Task AddPlaylistItems(Playlist playlist, IEnumerable<PlaylistItem> playlistItems)
{
using (var transaction = this.Database.BeginTransaction(this.Database.PreferredIsolationLevel))
{
var set = this.Database.Set<PlaylistItem>(transaction);
var position = 0;
foreach (var playlistItem in playlistItems)
{
Logger.Write(this, LogLevel.Debug, "Adding file to playlist: {0}", playlistItem.FileName);
playlistItem.Playlist_Id = playlist.Id;
playlistItem.Sequence = this.Sequence + position;
playlistItem.Status = PlaylistItemStatus.Import;
await set.AddAsync(playlistItem).ConfigureAwait(false);
position++;
}
this.Offset += position;
if (transaction.HasTransaction)
{
transaction.Commit();
}
}
}
}
}
}