Tmt5MediaPlayer.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. using MediaBrowser.Common.IO;
  2. using MediaBrowser.Model.Dto;
  3. using MediaBrowser.Model.Logging;
  4. using MediaBrowser.UI.Configuration;
  5. using MediaBrowser.UI.Playback;
  6. using MediaBrowser.UI.Playback.ExternalPlayer;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Collections.Specialized;
  10. using System.ComponentModel.Composition;
  11. using System.Diagnostics;
  12. using System.Globalization;
  13. using System.IO;
  14. using System.Threading.Tasks;
  15. namespace MediaBrowser.Plugins.Tmt5
  16. {
  17. /// <summary>
  18. /// Class GenericExternalPlayer
  19. /// </summary>
  20. [Export(typeof(BaseMediaPlayer))]
  21. public class Tmt5MediaPlayer : BaseExternalPlayer
  22. {
  23. [ImportingConstructor]
  24. public Tmt5MediaPlayer([Import("logger")] ILogger logger)
  25. : base(logger)
  26. {
  27. }
  28. /// <summary>
  29. /// Gets the name.
  30. /// </summary>
  31. /// <value>The name.</value>
  32. public override string Name
  33. {
  34. get { return "TMT5"; }
  35. }
  36. /// <summary>
  37. /// Gets a value indicating whether this instance can pause.
  38. /// </summary>
  39. /// <value><c>true</c> if this instance can pause; otherwise, <c>false</c>.</value>
  40. public override bool CanPause
  41. {
  42. get
  43. {
  44. return true;
  45. }
  46. }
  47. /// <summary>
  48. /// Gets a value indicating whether this instance can close automatically.
  49. /// </summary>
  50. /// <value><c>true</c> if this instance can close automatically; otherwise, <c>false</c>.</value>
  51. protected override bool CanCloseAutomatically
  52. {
  53. get
  54. {
  55. return true;
  56. }
  57. }
  58. /// <summary>
  59. /// Gets the play state directory.
  60. /// </summary>
  61. /// <value>The play state directory.</value>
  62. private string PlayStateDirectory
  63. {
  64. get
  65. {
  66. return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "ArcSoft");
  67. }
  68. }
  69. /// <summary>
  70. /// The _current position ticks
  71. /// </summary>
  72. private long? _currentPositionTicks;
  73. /// <summary>
  74. /// Gets the current position ticks.
  75. /// </summary>
  76. /// <value>The current position ticks.</value>
  77. public override long? CurrentPositionTicks
  78. {
  79. get
  80. {
  81. return _currentPositionTicks;
  82. }
  83. }
  84. /// <summary>
  85. /// The _current playlist index
  86. /// </summary>
  87. private int _currentPlaylistIndex;
  88. /// <summary>
  89. /// Gets the index of the current playlist.
  90. /// </summary>
  91. /// <value>The index of the current playlist.</value>
  92. public override int CurrentPlaylistIndex
  93. {
  94. get
  95. {
  96. return _currentPlaylistIndex;
  97. }
  98. }
  99. /// <summary>
  100. /// Gets or sets the status file watcher.
  101. /// </summary>
  102. /// <value>The status file watcher.</value>
  103. private FileSystemWatcher StatusFileWatcher { get; set; }
  104. /// <summary>
  105. /// Gets or sets a value indicating whether this instance has started playing.
  106. /// </summary>
  107. /// <value><c>true</c> if this instance has started playing; otherwise, <c>false</c>.</value>
  108. private bool HasStartedPlaying { get; set; }
  109. /// <summary>
  110. /// Gets or sets a value indicating whether this instance has stopped playing.
  111. /// </summary>
  112. /// <value><c>true</c> if this instance has stopped playing; otherwise, <c>false</c>.</value>
  113. private bool HasStoppedPlaying { get; set; }
  114. /// <summary>
  115. /// Determines whether this instance can play the specified item.
  116. /// </summary>
  117. /// <param name="item">The item.</param>
  118. /// <returns><c>true</c> if this instance can play the specified item; otherwise, <c>false</c>.</returns>
  119. public override bool CanPlay(BaseItemDto item)
  120. {
  121. return item.IsVideo || item.IsAudio;
  122. }
  123. /// <summary>
  124. /// Called when [player stopped internal].
  125. /// </summary>
  126. protected override void OnPlayerStoppedInternal()
  127. {
  128. DisposeFileSystemWatcher();
  129. HasStartedPlaying = false;
  130. HasStoppedPlaying = false;
  131. _currentPlaylistIndex = 0;
  132. _currentPositionTicks = 0;
  133. base.OnPlayerStoppedInternal();
  134. }
  135. /// <summary>
  136. /// Gets the command arguments.
  137. /// </summary>
  138. /// <param name="items">The items.</param>
  139. /// <param name="options">The options.</param>
  140. /// <param name="playerConfiguration">The player configuration.</param>
  141. /// <returns>System.String.</returns>
  142. protected override string GetCommandArguments(List<BaseItemDto> items, PlayOptions options, PlayerConfiguration playerConfiguration)
  143. {
  144. return "\"" + items[0].Path + "\"";
  145. }
  146. /// <summary>
  147. /// Called when [external player launched].
  148. /// </summary>
  149. protected override void OnExternalPlayerLaunched()
  150. {
  151. base.OnExternalPlayerLaunched();
  152. // If the playstate directory exists, start watching it
  153. if (Directory.Exists(PlayStateDirectory))
  154. {
  155. ReloadFileSystemWatcher();
  156. }
  157. }
  158. /// <summary>
  159. /// Pauses the internal.
  160. /// </summary>
  161. /// <returns>Task.</returns>
  162. protected override Task PauseInternal()
  163. {
  164. return SendCommandToMMC("-pause");
  165. }
  166. /// <summary>
  167. /// Uns the pause internal.
  168. /// </summary>
  169. /// <returns>Task.</returns>
  170. protected override Task UnPauseInternal()
  171. {
  172. return SendCommandToMMC("-play");
  173. }
  174. /// <summary>
  175. /// Stops the internal.
  176. /// </summary>
  177. /// <returns>Task.</returns>
  178. protected override Task StopInternal()
  179. {
  180. return SendCommandToMMC("-stop");
  181. }
  182. /// <summary>
  183. /// Closes the player.
  184. /// </summary>
  185. /// <returns>Task.</returns>
  186. protected Task ClosePlayer()
  187. {
  188. return SendCommandToMMC("-close");
  189. }
  190. /// <summary>
  191. /// Seeks the internal.
  192. /// </summary>
  193. /// <param name="positionTicks">The position ticks.</param>
  194. /// <returns>Task.</returns>
  195. /// <exception cref="System.InvalidOperationException">No media to seek to</exception>
  196. protected override Task SeekInternal(long positionTicks)
  197. {
  198. if (CurrentMedia == null)
  199. {
  200. throw new InvalidOperationException("No media to seek to");
  201. }
  202. if (CurrentMedia.Chapters == null)
  203. {
  204. throw new InvalidOperationException("TMT5 cannot seek without chapter information");
  205. }
  206. var chapterIndex = 0;
  207. for (var i = 0; i < CurrentMedia.Chapters.Count; i++)
  208. {
  209. if (CurrentMedia.Chapters[i].StartPositionTicks < positionTicks)
  210. {
  211. chapterIndex = i;
  212. }
  213. }
  214. return JumpToChapter(chapterIndex);
  215. }
  216. /// <summary>
  217. /// Jumps to chapter.
  218. /// </summary>
  219. /// <param name="chapter">The chapter.</param>
  220. /// <returns>Task.</returns>
  221. protected Task JumpToChapter(int chapter)
  222. {
  223. return SendCommandToMMC(" -chapter " + chapter);
  224. }
  225. /// <summary>
  226. /// Sends an arbitrary command to the TMT MMC console
  227. /// </summary>
  228. /// <param name="command">The command.</param>
  229. /// <returns>Task.</returns>
  230. protected Task SendCommandToMMC(string command)
  231. {
  232. return Task.Run(() =>
  233. {
  234. var directory = Path.GetDirectoryName(CurrentPlayerConfiguration.Command);
  235. var processInfo = new ProcessStartInfo
  236. {
  237. FileName = Path.Combine(directory, "MMCEDT5.exe"),
  238. Arguments = command,
  239. CreateNoWindow = true
  240. };
  241. Logger.Debug("{0} {1}", processInfo.FileName, processInfo.Arguments);
  242. using (var process = Process.Start(processInfo))
  243. {
  244. process.WaitForExit(2000);
  245. }
  246. });
  247. }
  248. /// <summary>
  249. /// Reloads the file system watcher.
  250. /// </summary>
  251. private void ReloadFileSystemWatcher()
  252. {
  253. DisposeFileSystemWatcher();
  254. Logger.Info("Watching TMT folder: " + PlayStateDirectory);
  255. StatusFileWatcher = new FileSystemWatcher(PlayStateDirectory, "*.set")
  256. {
  257. IncludeSubdirectories = true
  258. };
  259. // Need to include subdirectories since there are subfolders undearneath this with the TMT version #.
  260. StatusFileWatcher.Changed += StatusFileWatcher_Changed;
  261. StatusFileWatcher.EnableRaisingEvents = true;
  262. }
  263. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  264. /// <summary>
  265. /// Handles the Changed event of the StatusFileWatcher control.
  266. /// </summary>
  267. /// <param name="sender">The source of the event.</param>
  268. /// <param name="e">The <see cref="FileSystemEventArgs" /> instance containing the event data.</param>
  269. async void StatusFileWatcher_Changed(object sender, FileSystemEventArgs e)
  270. {
  271. Logger.Debug("TMT File Watcher reports change type {1} at {0}", e.FullPath, e.ChangeType);
  272. NameValueCollection values;
  273. try
  274. {
  275. values = FileSystem.ParseIniFile(e.FullPath);
  276. }
  277. catch (IOException)
  278. {
  279. // This can happen if the file is being written to at the exact moment we're trying to access it
  280. // Unfortunately we kind of have to just eat it
  281. return;
  282. }
  283. var tmtPlayState = values["State"];
  284. if (tmtPlayState.Equals("play", StringComparison.OrdinalIgnoreCase))
  285. {
  286. PlayState = PlayState.Playing;
  287. // Playback just started
  288. HasStartedPlaying = true;
  289. if (CurrentPlayOptions.StartPositionTicks > 0)
  290. {
  291. SeekInternal(CurrentPlayOptions.StartPositionTicks);
  292. }
  293. }
  294. else if (tmtPlayState.Equals("pause", StringComparison.OrdinalIgnoreCase))
  295. {
  296. PlayState = PlayState.Paused;
  297. }
  298. // If playback has previously started...
  299. // First notify the Progress event handler
  300. // Then check if playback has stopped
  301. if (HasStartedPlaying)
  302. {
  303. TimeSpan currentPosition;
  304. //TimeSpan.TryParse(values["TotalTime"], out currentDuration);
  305. if (TimeSpan.TryParse(values["CurTime"], UsCulture, out currentPosition))
  306. {
  307. _currentPositionTicks = currentPosition.Ticks;
  308. }
  309. _currentPlaylistIndex = 0;
  310. // Playback has stopped
  311. if (tmtPlayState.Equals("stop", StringComparison.OrdinalIgnoreCase))
  312. {
  313. Logger.Info("Playstate changed to stopped");
  314. if (!HasStoppedPlaying)
  315. {
  316. HasStoppedPlaying = true;
  317. DisposeFileSystemWatcher();
  318. await ClosePlayer().ConfigureAwait(false);
  319. }
  320. }
  321. }
  322. }
  323. /// <summary>
  324. /// Disposes the file system watcher.
  325. /// </summary>
  326. private void DisposeFileSystemWatcher()
  327. {
  328. if (StatusFileWatcher != null)
  329. {
  330. StatusFileWatcher.EnableRaisingEvents = false;
  331. StatusFileWatcher.Changed -= StatusFileWatcher_Changed;
  332. StatusFileWatcher.Dispose();
  333. StatusFileWatcher = null;
  334. }
  335. }
  336. /// <summary>
  337. /// Releases unmanaged and - optionally - managed resources.
  338. /// </summary>
  339. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  340. protected override void Dispose(bool dispose)
  341. {
  342. if (dispose)
  343. {
  344. DisposeFileSystemWatcher();
  345. }
  346. base.Dispose(dispose);
  347. }
  348. }
  349. }