BaseStreamingHandler.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Common.Net;
  4. using MediaBrowser.Common.Net.Handlers;
  5. using MediaBrowser.Controller;
  6. using MediaBrowser.Controller.Entities;
  7. using MediaBrowser.Controller.Entities.Audio;
  8. using MediaBrowser.Controller.Library;
  9. using MediaBrowser.Model.Drawing;
  10. using MediaBrowser.Model.Dto;
  11. using MediaBrowser.Model.Entities;
  12. using System;
  13. using System.ComponentModel;
  14. using System.Diagnostics;
  15. using System.IO;
  16. using System.Linq;
  17. using System.Threading;
  18. using System.Threading.Tasks;
  19. namespace MediaBrowser.Api.Streaming
  20. {
  21. /// <summary>
  22. /// Represents a common base class for both progressive and hls streaming
  23. /// </summary>
  24. /// <typeparam name="TBaseItemType">The type of the T base item type.</typeparam>
  25. public abstract class BaseStreamingHandler<TBaseItemType> : BaseHandler<Kernel>
  26. where TBaseItemType : BaseItem, IHasMediaStreams, new()
  27. {
  28. /// <summary>
  29. /// Gets the command line arguments.
  30. /// </summary>
  31. /// <param name="outputPath">The output path.</param>
  32. /// <param name="isoMount">The iso mount.</param>
  33. /// <returns>System.String.</returns>
  34. protected abstract string GetCommandLineArguments(string outputPath, IIsoMount isoMount);
  35. /// <summary>
  36. /// Gets or sets the log file stream.
  37. /// </summary>
  38. /// <value>The log file stream.</value>
  39. protected Stream LogFileStream { get; set; }
  40. /// <summary>
  41. /// Gets the type of the transcoding job.
  42. /// </summary>
  43. /// <value>The type of the transcoding job.</value>
  44. protected abstract TranscodingJobType TranscodingJobType { get; }
  45. /// <summary>
  46. /// Gets the output file extension.
  47. /// </summary>
  48. /// <value>The output file extension.</value>
  49. protected string OutputFileExtension
  50. {
  51. get
  52. {
  53. return Path.GetExtension(HttpListenerContext.Request.Url.LocalPath);
  54. }
  55. }
  56. /// <summary>
  57. /// Gets the output file path.
  58. /// </summary>
  59. /// <value>The output file path.</value>
  60. protected string OutputFilePath
  61. {
  62. get
  63. {
  64. return Path.Combine(Kernel.ApplicationPaths.FFMpegStreamCachePath, GetCommandLineArguments("dummy\\dummy", null).GetMD5() + OutputFileExtension.ToLower());
  65. }
  66. }
  67. /// <summary>
  68. /// Gets the audio codec to endoce to.
  69. /// </summary>
  70. /// <value>The audio encoding format.</value>
  71. protected virtual AudioCodecs? AudioCodec
  72. {
  73. get
  74. {
  75. if (string.IsNullOrEmpty(QueryString["audioCodec"]))
  76. {
  77. return null;
  78. }
  79. return (AudioCodecs)Enum.Parse(typeof(AudioCodecs), QueryString["audioCodec"], true);
  80. }
  81. }
  82. /// <summary>
  83. /// Gets the video encoding codec.
  84. /// </summary>
  85. /// <value>The video codec.</value>
  86. protected VideoCodecs? VideoCodec
  87. {
  88. get
  89. {
  90. if (string.IsNullOrEmpty(QueryString["videoCodec"]))
  91. {
  92. return null;
  93. }
  94. return (VideoCodecs)Enum.Parse(typeof(VideoCodecs), QueryString["videoCodec"], true);
  95. }
  96. }
  97. /// <summary>
  98. /// Gets the time, in ticks, in which playback should start
  99. /// </summary>
  100. /// <value>The start time ticks.</value>
  101. protected long? StartTimeTicks
  102. {
  103. get
  104. {
  105. string val = QueryString["StartTimeTicks"];
  106. if (string.IsNullOrEmpty(val))
  107. {
  108. return null;
  109. }
  110. return long.Parse(val);
  111. }
  112. }
  113. /// <summary>
  114. /// The fast seek offset seconds
  115. /// </summary>
  116. private const int FastSeekOffsetSeconds = 1;
  117. /// <summary>
  118. /// Gets the fast seek command line parameter.
  119. /// </summary>
  120. /// <value>The fast seek command line parameter.</value>
  121. protected string FastSeekCommandLineParameter
  122. {
  123. get
  124. {
  125. var time = StartTimeTicks;
  126. if (time.HasValue)
  127. {
  128. var seconds = TimeSpan.FromTicks(time.Value).TotalSeconds - FastSeekOffsetSeconds;
  129. if (seconds > 0)
  130. {
  131. return string.Format("-ss {0}", seconds);
  132. }
  133. }
  134. return string.Empty;
  135. }
  136. }
  137. /// <summary>
  138. /// Gets the slow seek command line parameter.
  139. /// </summary>
  140. /// <value>The slow seek command line parameter.</value>
  141. protected string SlowSeekCommandLineParameter
  142. {
  143. get
  144. {
  145. var time = StartTimeTicks;
  146. if (time.HasValue)
  147. {
  148. if (TimeSpan.FromTicks(time.Value).TotalSeconds - FastSeekOffsetSeconds > 0)
  149. {
  150. return string.Format(" -ss {0}", FastSeekOffsetSeconds);
  151. }
  152. }
  153. return string.Empty;
  154. }
  155. }
  156. /// <summary>
  157. /// Gets the map args.
  158. /// </summary>
  159. /// <value>The map args.</value>
  160. protected virtual string MapArgs
  161. {
  162. get
  163. {
  164. var args = string.Empty;
  165. if (VideoStream != null)
  166. {
  167. args += string.Format("-map 0:{0}", VideoStream.Index);
  168. }
  169. else
  170. {
  171. args += "-map -0:v";
  172. }
  173. if (AudioStream != null)
  174. {
  175. args += string.Format(" -map 0:{0}", AudioStream.Index);
  176. }
  177. else
  178. {
  179. args += " -map -0:a";
  180. }
  181. if (SubtitleStream == null)
  182. {
  183. args += " -map -0:s";
  184. }
  185. return args;
  186. }
  187. }
  188. /// <summary>
  189. /// The _library item
  190. /// </summary>
  191. private TBaseItemType _libraryItem;
  192. /// <summary>
  193. /// Gets the library item that will be played, if any
  194. /// </summary>
  195. /// <value>The library item.</value>
  196. protected TBaseItemType LibraryItem
  197. {
  198. get
  199. {
  200. return _libraryItem ?? (_libraryItem = (TBaseItemType)DtoBuilder.GetItemByClientId(QueryString["id"]));
  201. }
  202. }
  203. /// <summary>
  204. /// Gets or sets the iso mount.
  205. /// </summary>
  206. /// <value>The iso mount.</value>
  207. private IIsoMount IsoMount { get; set; }
  208. /// <summary>
  209. /// The _audio stream
  210. /// </summary>
  211. private MediaStream _audioStream;
  212. /// <summary>
  213. /// Gets the audio stream.
  214. /// </summary>
  215. /// <value>The audio stream.</value>
  216. protected MediaStream AudioStream
  217. {
  218. get { return _audioStream ?? (_audioStream = GetMediaStream(AudioStreamIndex, MediaStreamType.Audio)); }
  219. }
  220. /// <summary>
  221. /// The _video stream
  222. /// </summary>
  223. private MediaStream _videoStream;
  224. /// <summary>
  225. /// Gets the video stream.
  226. /// </summary>
  227. /// <value>The video stream.</value>
  228. protected MediaStream VideoStream
  229. {
  230. get
  231. {
  232. // No video streams here
  233. // Need to make this check to make sure we don't pickup embedded image streams (which are listed in the file as type video)
  234. if (LibraryItem is Audio)
  235. {
  236. return null;
  237. }
  238. return _videoStream ?? (_videoStream = GetMediaStream(VideoStreamIndex, MediaStreamType.Video));
  239. }
  240. }
  241. /// <summary>
  242. /// The subtitle stream
  243. /// </summary>
  244. private MediaStream _subtitleStream;
  245. /// <summary>
  246. /// Gets the subtitle stream.
  247. /// </summary>
  248. /// <value>The subtitle stream.</value>
  249. protected MediaStream SubtitleStream
  250. {
  251. get
  252. {
  253. // No subtitle streams here
  254. if (LibraryItem is Audio)
  255. {
  256. return null;
  257. }
  258. return _subtitleStream ?? (_subtitleStream = GetMediaStream(SubtitleStreamIndex, MediaStreamType.Subtitle, false));
  259. }
  260. }
  261. /// <summary>
  262. /// Determines which stream will be used for playback
  263. /// </summary>
  264. /// <param name="desiredIndex">Index of the desired.</param>
  265. /// <param name="type">The type.</param>
  266. /// <param name="returnFirstIfNoIndex">if set to <c>true</c> [return first if no index].</param>
  267. /// <returns>MediaStream.</returns>
  268. private MediaStream GetMediaStream(int? desiredIndex, MediaStreamType type, bool returnFirstIfNoIndex = true)
  269. {
  270. var streams = LibraryItem.MediaStreams.Where(s => s.Type == type).ToList();
  271. if (desiredIndex.HasValue)
  272. {
  273. var stream = streams.FirstOrDefault(s => s.Index == desiredIndex.Value);
  274. if (stream != null)
  275. {
  276. return stream;
  277. }
  278. }
  279. // Just return the first one
  280. return returnFirstIfNoIndex ? streams.FirstOrDefault() : null;
  281. }
  282. /// <summary>
  283. /// Gets the response info.
  284. /// </summary>
  285. /// <returns>Task{ResponseInfo}.</returns>
  286. protected override Task<ResponseInfo> GetResponseInfo()
  287. {
  288. var info = new ResponseInfo
  289. {
  290. ContentType = MimeTypes.GetMimeType(OutputFilePath),
  291. CompressResponse = false
  292. };
  293. return Task.FromResult(info);
  294. }
  295. /// <summary>
  296. /// Gets the client's desired audio bitrate
  297. /// </summary>
  298. /// <value>The audio bit rate.</value>
  299. protected int? AudioBitRate
  300. {
  301. get
  302. {
  303. var val = QueryString["AudioBitRate"];
  304. if (string.IsNullOrEmpty(val))
  305. {
  306. return null;
  307. }
  308. return int.Parse(val);
  309. }
  310. }
  311. /// <summary>
  312. /// Gets the client's desired video bitrate
  313. /// </summary>
  314. /// <value>The video bit rate.</value>
  315. protected int? VideoBitRate
  316. {
  317. get
  318. {
  319. var val = QueryString["VideoBitRate"];
  320. if (string.IsNullOrEmpty(val))
  321. {
  322. return null;
  323. }
  324. return int.Parse(val);
  325. }
  326. }
  327. /// <summary>
  328. /// Gets the desired audio stream index
  329. /// </summary>
  330. /// <value>The index of the audio stream.</value>
  331. private int? AudioStreamIndex
  332. {
  333. get
  334. {
  335. var val = QueryString["AudioStreamIndex"];
  336. if (string.IsNullOrEmpty(val))
  337. {
  338. return null;
  339. }
  340. return int.Parse(val);
  341. }
  342. }
  343. /// <summary>
  344. /// Gets the desired video stream index
  345. /// </summary>
  346. /// <value>The index of the video stream.</value>
  347. private int? VideoStreamIndex
  348. {
  349. get
  350. {
  351. var val = QueryString["VideoStreamIndex"];
  352. if (string.IsNullOrEmpty(val))
  353. {
  354. return null;
  355. }
  356. return int.Parse(val);
  357. }
  358. }
  359. /// <summary>
  360. /// Gets the desired subtitle stream index
  361. /// </summary>
  362. /// <value>The index of the subtitle stream.</value>
  363. private int? SubtitleStreamIndex
  364. {
  365. get
  366. {
  367. var val = QueryString["SubtitleStreamIndex"];
  368. if (string.IsNullOrEmpty(val))
  369. {
  370. return null;
  371. }
  372. return int.Parse(val);
  373. }
  374. }
  375. /// <summary>
  376. /// Gets the audio channels.
  377. /// </summary>
  378. /// <value>The audio channels.</value>
  379. public int? AudioChannels
  380. {
  381. get
  382. {
  383. var val = QueryString["audiochannels"];
  384. if (string.IsNullOrEmpty(val))
  385. {
  386. return null;
  387. }
  388. return int.Parse(val);
  389. }
  390. }
  391. /// <summary>
  392. /// Gets the audio sample rate.
  393. /// </summary>
  394. /// <value>The audio sample rate.</value>
  395. public int? AudioSampleRate
  396. {
  397. get
  398. {
  399. var val = QueryString["audiosamplerate"];
  400. if (string.IsNullOrEmpty(val))
  401. {
  402. return 44100;
  403. }
  404. return int.Parse(val);
  405. }
  406. }
  407. /// <summary>
  408. /// If we're going to put a fixed size on the command line, this will calculate it
  409. /// </summary>
  410. /// <param name="outputVideoCodec">The output video codec.</param>
  411. /// <returns>System.String.</returns>
  412. protected string GetOutputSizeParam(string outputVideoCodec)
  413. {
  414. // http://sonnati.wordpress.com/2012/10/19/ffmpeg-the-swiss-army-knife-of-internet-streaming-part-vi/
  415. var assSubtitleParam = string.Empty;
  416. if (SubtitleStream != null)
  417. {
  418. if (SubtitleStream.Codec.IndexOf("srt", StringComparison.OrdinalIgnoreCase) != -1 || SubtitleStream.Codec.IndexOf("subrip", StringComparison.OrdinalIgnoreCase) != -1)
  419. {
  420. assSubtitleParam = GetTextSubtitleParam(SubtitleStream);
  421. }
  422. }
  423. // If fixed dimensions were supplied
  424. if (Width.HasValue && Height.HasValue)
  425. {
  426. return string.Format(" -vf \"scale={0}:{1}{2}\"", Width.Value, Height.Value, assSubtitleParam);
  427. }
  428. var isH264Output = outputVideoCodec.Equals("libx264", StringComparison.OrdinalIgnoreCase);
  429. // If a fixed width was requested
  430. if (Width.HasValue)
  431. {
  432. return isH264Output ?
  433. string.Format(" -vf \"scale={0}:trunc(ow/a/2)*2{1}\"", Width.Value, assSubtitleParam) :
  434. string.Format(" -vf \"scale={0}:-1{1}\"", Width.Value, assSubtitleParam);
  435. }
  436. // If a max width was requested
  437. if (MaxWidth.HasValue && !MaxHeight.HasValue)
  438. {
  439. return isH264Output ?
  440. string.Format(" -vf \"scale=min(iw\\,{0}):trunc(ow/a/2)*2{1}\"", MaxWidth.Value, assSubtitleParam) :
  441. string.Format(" -vf \"scale=min(iw\\,{0}):-1{1}\"", MaxWidth.Value, assSubtitleParam);
  442. }
  443. // Need to perform calculations manually
  444. // Try to account for bad media info
  445. var currentHeight = VideoStream.Height ?? MaxHeight ?? Height ?? 0;
  446. var currentWidth = VideoStream.Width ?? MaxWidth ?? Width ?? 0;
  447. var outputSize = DrawingUtils.Resize(currentWidth, currentHeight, Width, Height, MaxWidth, MaxHeight);
  448. // If we're encoding with libx264, it can't handle odd numbered widths or heights, so we'll have to fix that
  449. if (isH264Output)
  450. {
  451. return string.Format(" -vf \"scale=trunc({0}/2)*2:trunc({1}/2)*2{2}\"", outputSize.Width, outputSize.Height, assSubtitleParam);
  452. }
  453. // Otherwise use -vf scale since ffmpeg will ensure internally that the aspect ratio is preserved
  454. return string.Format(" -vf \"scale={0}:-1{1}\"", Convert.ToInt32(outputSize.Width), assSubtitleParam);
  455. }
  456. /// <summary>
  457. /// Gets the text subtitle param.
  458. /// </summary>
  459. /// <param name="subtitleStream">The subtitle stream.</param>
  460. /// <returns>System.String.</returns>
  461. protected string GetTextSubtitleParam(MediaStream subtitleStream)
  462. {
  463. var path = subtitleStream.IsExternal ? GetConvertedAssPath(subtitleStream) : GetExtractedAssPath(subtitleStream);
  464. if (string.IsNullOrEmpty(path))
  465. {
  466. return string.Empty;
  467. }
  468. var param = string.Format(",ass={0}", path);
  469. var time = StartTimeTicks;
  470. if (time.HasValue)
  471. {
  472. var seconds = Convert.ToInt32(TimeSpan.FromTicks(time.Value).TotalSeconds);
  473. param += string.Format(",setpts=PTS-{0}/TB", seconds);
  474. }
  475. return param;
  476. }
  477. /// <summary>
  478. /// Gets the extracted ass path.
  479. /// </summary>
  480. /// <param name="subtitleStream">The subtitle stream.</param>
  481. /// <returns>System.String.</returns>
  482. private string GetExtractedAssPath(MediaStream subtitleStream)
  483. {
  484. var video = LibraryItem as Video;
  485. var path = Kernel.FFMpegManager.GetSubtitleCachePath(video, subtitleStream.Index, ".ass");
  486. if (!File.Exists(path))
  487. {
  488. var success = Kernel.FFMpegManager.ExtractTextSubtitle(video, subtitleStream.Index, path, CancellationToken.None).Result;
  489. if (!success)
  490. {
  491. return null;
  492. }
  493. }
  494. return path;
  495. }
  496. /// <summary>
  497. /// Gets the converted ass path.
  498. /// </summary>
  499. /// <param name="subtitleStream">The subtitle stream.</param>
  500. /// <returns>System.String.</returns>
  501. private string GetConvertedAssPath(MediaStream subtitleStream)
  502. {
  503. var video = LibraryItem as Video;
  504. var path = Kernel.FFMpegManager.GetSubtitleCachePath(video, subtitleStream.Index, ".ass");
  505. if (!File.Exists(path))
  506. {
  507. var success = Kernel.FFMpegManager.ConvertTextSubtitle(subtitleStream, path, CancellationToken.None).Result;
  508. if (!success)
  509. {
  510. return null;
  511. }
  512. }
  513. return path;
  514. }
  515. /// <summary>
  516. /// Gets the internal graphical subtitle param.
  517. /// </summary>
  518. /// <param name="subtitleStream">The subtitle stream.</param>
  519. /// <param name="videoCodec">The video codec.</param>
  520. /// <returns>System.String.</returns>
  521. protected string GetInternalGraphicalSubtitleParam(MediaStream subtitleStream, string videoCodec)
  522. {
  523. var outputSizeParam = string.Empty;
  524. // Add resolution params, if specified
  525. if (Width.HasValue || Height.HasValue || MaxHeight.HasValue || MaxWidth.HasValue)
  526. {
  527. outputSizeParam = GetOutputSizeParam(videoCodec).TrimEnd('"');
  528. outputSizeParam = "," + outputSizeParam.Substring(outputSizeParam.IndexOf("scale", StringComparison.OrdinalIgnoreCase));
  529. }
  530. return string.Format(" -filter_complex \"[0:{0}]format=yuva444p,lut=u=128:v=128:y=gammaval(.3)[sub] ; [0:0] [sub] overlay{1}\"", subtitleStream.Index, outputSizeParam);
  531. }
  532. /// <summary>
  533. /// Gets the fixed output video height, in pixels
  534. /// </summary>
  535. /// <value>The height.</value>
  536. protected int? Height
  537. {
  538. get
  539. {
  540. string val = QueryString["height"];
  541. if (string.IsNullOrEmpty(val))
  542. {
  543. return null;
  544. }
  545. return int.Parse(val);
  546. }
  547. }
  548. /// <summary>
  549. /// Gets the fixed output video width, in pixels
  550. /// </summary>
  551. /// <value>The width.</value>
  552. protected int? Width
  553. {
  554. get
  555. {
  556. string val = QueryString["width"];
  557. if (string.IsNullOrEmpty(val))
  558. {
  559. return null;
  560. }
  561. return int.Parse(val);
  562. }
  563. }
  564. /// <summary>
  565. /// Gets the maximum output video height, in pixels
  566. /// </summary>
  567. /// <value>The height of the max.</value>
  568. protected int? MaxHeight
  569. {
  570. get
  571. {
  572. string val = QueryString["maxheight"];
  573. if (string.IsNullOrEmpty(val))
  574. {
  575. return null;
  576. }
  577. return int.Parse(val);
  578. }
  579. }
  580. /// <summary>
  581. /// Gets the maximum output video width, in pixels
  582. /// </summary>
  583. /// <value>The width of the max.</value>
  584. protected int? MaxWidth
  585. {
  586. get
  587. {
  588. string val = QueryString["maxwidth"];
  589. if (string.IsNullOrEmpty(val))
  590. {
  591. return null;
  592. }
  593. return int.Parse(val);
  594. }
  595. }
  596. /// <summary>
  597. /// Gets the output video framerate
  598. /// </summary>
  599. /// <value>The max frame rate.</value>
  600. protected float? FrameRate
  601. {
  602. get
  603. {
  604. string val = QueryString["framerate"];
  605. if (string.IsNullOrEmpty(val))
  606. {
  607. return null;
  608. }
  609. return float.Parse(val);
  610. }
  611. }
  612. /// <summary>
  613. /// Gets the number of audio channels to specify on the command line
  614. /// </summary>
  615. /// <returns>System.Nullable{System.Int32}.</returns>
  616. protected int? GetSampleRateParam()
  617. {
  618. // If the user requested a max value
  619. if (AudioSampleRate.HasValue)
  620. {
  621. return AudioSampleRate.Value;
  622. }
  623. return null;
  624. }
  625. /// <summary>
  626. /// Gets the number of audio channels to specify on the command line
  627. /// </summary>
  628. /// <param name="audioCodec">The audio codec.</param>
  629. /// <returns>System.Nullable{System.Int32}.</returns>
  630. protected int? GetNumAudioChannelsParam(string audioCodec)
  631. {
  632. if (AudioStream.Channels > 2)
  633. {
  634. if (audioCodec.Equals("libvo_aacenc"))
  635. {
  636. // libvo_aacenc currently only supports two channel output
  637. return 2;
  638. }
  639. if (audioCodec.Equals("wmav2"))
  640. {
  641. // wmav2 currently only supports two channel output
  642. return 2;
  643. }
  644. }
  645. return GetNumAudioChannelsParam();
  646. }
  647. /// <summary>
  648. /// Gets the number of audio channels to specify on the command line
  649. /// </summary>
  650. /// <returns>System.Nullable{System.Int32}.</returns>
  651. protected int? GetNumAudioChannelsParam()
  652. {
  653. // If the user requested a max number of channels
  654. if (AudioChannels.HasValue)
  655. {
  656. return AudioChannels.Value;
  657. }
  658. return null;
  659. }
  660. /// <summary>
  661. /// Determines whether the specified stream is H264.
  662. /// </summary>
  663. /// <param name="stream">The stream.</param>
  664. /// <returns><c>true</c> if the specified stream is H264; otherwise, <c>false</c>.</returns>
  665. protected bool IsH264(MediaStream stream)
  666. {
  667. return stream.Codec.IndexOf("264", StringComparison.OrdinalIgnoreCase) != -1 ||
  668. stream.Codec.IndexOf("avc", StringComparison.OrdinalIgnoreCase) != -1;
  669. }
  670. /// <summary>
  671. /// Gets the name of the output audio codec
  672. /// </summary>
  673. /// <returns>System.String.</returns>
  674. protected string GetAudioCodec()
  675. {
  676. if (AudioCodec.HasValue)
  677. {
  678. if (AudioCodec == AudioCodecs.Aac)
  679. {
  680. return "libvo_aacenc";
  681. }
  682. if (AudioCodec == AudioCodecs.Mp3)
  683. {
  684. return "libmp3lame";
  685. }
  686. if (AudioCodec == AudioCodecs.Vorbis)
  687. {
  688. return "libvorbis";
  689. }
  690. if (AudioCodec == AudioCodecs.Wma)
  691. {
  692. return "wmav2";
  693. }
  694. }
  695. return "copy";
  696. }
  697. /// <summary>
  698. /// Gets the name of the output video codec
  699. /// </summary>
  700. /// <returns>System.String.</returns>
  701. protected string GetVideoCodec()
  702. {
  703. if (VideoCodec.HasValue)
  704. {
  705. if (VideoCodec == VideoCodecs.H264)
  706. {
  707. return "libx264";
  708. }
  709. if (VideoCodec == VideoCodecs.Vpx)
  710. {
  711. return "libvpx";
  712. }
  713. if (VideoCodec == VideoCodecs.Wmv)
  714. {
  715. return "wmv2";
  716. }
  717. if (VideoCodec == VideoCodecs.Theora)
  718. {
  719. return "libtheora";
  720. }
  721. }
  722. return "copy";
  723. }
  724. /// <summary>
  725. /// Gets the input argument.
  726. /// </summary>
  727. /// <param name="isoMount">The iso mount.</param>
  728. /// <returns>System.String.</returns>
  729. protected string GetInputArgument(IIsoMount isoMount)
  730. {
  731. return isoMount == null ?
  732. Kernel.FFMpegManager.GetInputArgument(LibraryItem) :
  733. Kernel.FFMpegManager.GetInputArgument(LibraryItem as Video, IsoMount);
  734. }
  735. /// <summary>
  736. /// Starts the FFMPEG.
  737. /// </summary>
  738. /// <param name="outputPath">The output path.</param>
  739. /// <returns>Task.</returns>
  740. protected async Task StartFFMpeg(string outputPath)
  741. {
  742. var video = LibraryItem as Video;
  743. if (video != null && video.VideoType == VideoType.Iso &&
  744. video.IsoType.HasValue && Kernel.IsoManager.CanMount(video.Path))
  745. {
  746. IsoMount = await Kernel.IsoManager.Mount(video.Path, CancellationToken.None).ConfigureAwait(false);
  747. }
  748. var process = new Process
  749. {
  750. StartInfo = new ProcessStartInfo
  751. {
  752. CreateNoWindow = true,
  753. UseShellExecute = false,
  754. // Must consume both stdout and stderr or deadlocks may occur
  755. RedirectStandardOutput = true,
  756. RedirectStandardError = true,
  757. FileName = Kernel.FFMpegManager.FFMpegPath,
  758. WorkingDirectory = Path.GetDirectoryName(Kernel.FFMpegManager.FFMpegPath),
  759. Arguments = GetCommandLineArguments(outputPath, IsoMount),
  760. WindowStyle = ProcessWindowStyle.Hidden,
  761. ErrorDialog = false
  762. },
  763. EnableRaisingEvents = true
  764. };
  765. Plugin.Instance.OnTranscodeBeginning(outputPath, TranscodingJobType, process);
  766. Logger.Info(process.StartInfo.FileName + " " + process.StartInfo.Arguments);
  767. var logFilePath = Path.Combine(Kernel.ApplicationPaths.LogDirectoryPath, "ffmpeg-" + Guid.NewGuid() + ".txt");
  768. // FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory.
  769. LogFileStream = new FileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous);
  770. process.Exited += OnFFMpegProcessExited;
  771. try
  772. {
  773. process.Start();
  774. }
  775. catch (Win32Exception ex)
  776. {
  777. Logger.ErrorException("Error starting ffmpeg", ex);
  778. Plugin.Instance.OnTranscodeFailedToStart(outputPath, TranscodingJobType);
  779. process.Exited -= OnFFMpegProcessExited;
  780. LogFileStream.Dispose();
  781. throw;
  782. }
  783. // MUST read both stdout and stderr asynchronously or a deadlock may occurr
  784. process.BeginOutputReadLine();
  785. // Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback
  786. process.StandardError.BaseStream.CopyToAsync(LogFileStream);
  787. // Wait for the file to exist before proceeeding
  788. while (!File.Exists(outputPath))
  789. {
  790. await Task.Delay(100).ConfigureAwait(false);
  791. }
  792. }
  793. /// <summary>
  794. /// Processes the exited.
  795. /// </summary>
  796. /// <param name="sender">The sender.</param>
  797. /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
  798. protected void OnFFMpegProcessExited(object sender, EventArgs e)
  799. {
  800. if (IsoMount != null)
  801. {
  802. IsoMount.Dispose();
  803. IsoMount = null;
  804. }
  805. var outputFilePath = OutputFilePath;
  806. LogFileStream.Dispose();
  807. var process = (Process)sender;
  808. process.Exited -= OnFFMpegProcessExited;
  809. int? exitCode = null;
  810. try
  811. {
  812. exitCode = process.ExitCode;
  813. Logger.Info("FFMpeg exited with code {0} for {1}", exitCode.Value, outputFilePath);
  814. }
  815. catch
  816. {
  817. Logger.Info("FFMpeg exited with an error for {0}", outputFilePath);
  818. }
  819. process.Dispose();
  820. Plugin.Instance.OnTranscodingFinished(outputFilePath, TranscodingJobType);
  821. if (!exitCode.HasValue || exitCode.Value != 0)
  822. {
  823. Logger.Info("Deleting partial stream file(s) {0}", outputFilePath);
  824. try
  825. {
  826. DeletePartialStreamFiles(outputFilePath);
  827. }
  828. catch (IOException ex)
  829. {
  830. Logger.ErrorException("Error deleting partial stream file(s) {0}", ex, outputFilePath);
  831. }
  832. }
  833. else
  834. {
  835. Logger.Info("FFMpeg completed and exited normally for {0}", outputFilePath);
  836. }
  837. }
  838. /// <summary>
  839. /// Deletes the partial stream files.
  840. /// </summary>
  841. /// <param name="outputFilePath">The output file path.</param>
  842. protected abstract void DeletePartialStreamFiles(string outputFilePath);
  843. }
  844. }