BaseStreamingHandler.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989
  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 { return _libraryItem; }
  199. }
  200. /// <summary>
  201. /// Gets or sets the iso mount.
  202. /// </summary>
  203. /// <value>The iso mount.</value>
  204. private IIsoMount IsoMount { get; set; }
  205. /// <summary>
  206. /// The _audio stream
  207. /// </summary>
  208. private MediaStream _audioStream;
  209. /// <summary>
  210. /// Gets the audio stream.
  211. /// </summary>
  212. /// <value>The audio stream.</value>
  213. protected MediaStream AudioStream
  214. {
  215. get { return _audioStream ?? (_audioStream = GetMediaStream(AudioStreamIndex, MediaStreamType.Audio)); }
  216. }
  217. /// <summary>
  218. /// The _video stream
  219. /// </summary>
  220. private MediaStream _videoStream;
  221. /// <summary>
  222. /// Gets the video stream.
  223. /// </summary>
  224. /// <value>The video stream.</value>
  225. protected MediaStream VideoStream
  226. {
  227. get
  228. {
  229. // No video streams here
  230. // Need to make this check to make sure we don't pickup embedded image streams (which are listed in the file as type video)
  231. if (LibraryItem is Audio)
  232. {
  233. return null;
  234. }
  235. return _videoStream ?? (_videoStream = GetMediaStream(VideoStreamIndex, MediaStreamType.Video));
  236. }
  237. }
  238. /// <summary>
  239. /// The subtitle stream
  240. /// </summary>
  241. private MediaStream _subtitleStream;
  242. /// <summary>
  243. /// Gets the subtitle stream.
  244. /// </summary>
  245. /// <value>The subtitle stream.</value>
  246. protected MediaStream SubtitleStream
  247. {
  248. get
  249. {
  250. // No subtitle streams here
  251. if (LibraryItem is Audio)
  252. {
  253. return null;
  254. }
  255. return _subtitleStream ?? (_subtitleStream = GetMediaStream(SubtitleStreamIndex, MediaStreamType.Subtitle, false));
  256. }
  257. }
  258. /// <summary>
  259. /// Determines which stream will be used for playback
  260. /// </summary>
  261. /// <param name="desiredIndex">Index of the desired.</param>
  262. /// <param name="type">The type.</param>
  263. /// <param name="returnFirstIfNoIndex">if set to <c>true</c> [return first if no index].</param>
  264. /// <returns>MediaStream.</returns>
  265. private MediaStream GetMediaStream(int? desiredIndex, MediaStreamType type, bool returnFirstIfNoIndex = true)
  266. {
  267. var streams = LibraryItem.MediaStreams.Where(s => s.Type == type).ToList();
  268. if (desiredIndex.HasValue)
  269. {
  270. var stream = streams.FirstOrDefault(s => s.Index == desiredIndex.Value);
  271. if (stream != null)
  272. {
  273. return stream;
  274. }
  275. }
  276. // Just return the first one
  277. return returnFirstIfNoIndex ? streams.FirstOrDefault() : null;
  278. }
  279. /// <summary>
  280. /// Gets the response info.
  281. /// </summary>
  282. /// <returns>Task{ResponseInfo}.</returns>
  283. protected override Task<ResponseInfo> GetResponseInfo()
  284. {
  285. var info = new ResponseInfo
  286. {
  287. ContentType = MimeTypes.GetMimeType(OutputFilePath),
  288. CompressResponse = false
  289. };
  290. return Task.FromResult(info);
  291. }
  292. /// <summary>
  293. /// Gets the client's desired audio bitrate
  294. /// </summary>
  295. /// <value>The audio bit rate.</value>
  296. protected int? AudioBitRate
  297. {
  298. get
  299. {
  300. var val = QueryString["AudioBitRate"];
  301. if (string.IsNullOrEmpty(val))
  302. {
  303. return null;
  304. }
  305. return int.Parse(val);
  306. }
  307. }
  308. /// <summary>
  309. /// Gets the client's desired video bitrate
  310. /// </summary>
  311. /// <value>The video bit rate.</value>
  312. protected int? VideoBitRate
  313. {
  314. get
  315. {
  316. var val = QueryString["VideoBitRate"];
  317. if (string.IsNullOrEmpty(val))
  318. {
  319. return null;
  320. }
  321. return int.Parse(val);
  322. }
  323. }
  324. /// <summary>
  325. /// Gets the desired audio stream index
  326. /// </summary>
  327. /// <value>The index of the audio stream.</value>
  328. private int? AudioStreamIndex
  329. {
  330. get
  331. {
  332. var val = QueryString["AudioStreamIndex"];
  333. if (string.IsNullOrEmpty(val))
  334. {
  335. return null;
  336. }
  337. return int.Parse(val);
  338. }
  339. }
  340. /// <summary>
  341. /// Gets the desired video stream index
  342. /// </summary>
  343. /// <value>The index of the video stream.</value>
  344. private int? VideoStreamIndex
  345. {
  346. get
  347. {
  348. var val = QueryString["VideoStreamIndex"];
  349. if (string.IsNullOrEmpty(val))
  350. {
  351. return null;
  352. }
  353. return int.Parse(val);
  354. }
  355. }
  356. /// <summary>
  357. /// Gets the desired subtitle stream index
  358. /// </summary>
  359. /// <value>The index of the subtitle stream.</value>
  360. private int? SubtitleStreamIndex
  361. {
  362. get
  363. {
  364. var val = QueryString["SubtitleStreamIndex"];
  365. if (string.IsNullOrEmpty(val))
  366. {
  367. return null;
  368. }
  369. return int.Parse(val);
  370. }
  371. }
  372. /// <summary>
  373. /// Gets the audio channels.
  374. /// </summary>
  375. /// <value>The audio channels.</value>
  376. public int? AudioChannels
  377. {
  378. get
  379. {
  380. var val = QueryString["audiochannels"];
  381. if (string.IsNullOrEmpty(val))
  382. {
  383. return null;
  384. }
  385. return int.Parse(val);
  386. }
  387. }
  388. /// <summary>
  389. /// Gets the audio sample rate.
  390. /// </summary>
  391. /// <value>The audio sample rate.</value>
  392. public int? AudioSampleRate
  393. {
  394. get
  395. {
  396. var val = QueryString["audiosamplerate"];
  397. if (string.IsNullOrEmpty(val))
  398. {
  399. return 44100;
  400. }
  401. return int.Parse(val);
  402. }
  403. }
  404. /// <summary>
  405. /// If we're going to put a fixed size on the command line, this will calculate it
  406. /// </summary>
  407. /// <param name="outputVideoCodec">The output video codec.</param>
  408. /// <returns>System.String.</returns>
  409. protected string GetOutputSizeParam(string outputVideoCodec)
  410. {
  411. // http://sonnati.wordpress.com/2012/10/19/ffmpeg-the-swiss-army-knife-of-internet-streaming-part-vi/
  412. var assSubtitleParam = string.Empty;
  413. if (SubtitleStream != null)
  414. {
  415. if (SubtitleStream.Codec.IndexOf("srt", StringComparison.OrdinalIgnoreCase) != -1 || SubtitleStream.Codec.IndexOf("subrip", StringComparison.OrdinalIgnoreCase) != -1)
  416. {
  417. assSubtitleParam = GetTextSubtitleParam(SubtitleStream);
  418. }
  419. }
  420. // If fixed dimensions were supplied
  421. if (Width.HasValue && Height.HasValue)
  422. {
  423. return string.Format(" -vf \"scale={0}:{1}{2}\"", Width.Value, Height.Value, assSubtitleParam);
  424. }
  425. var isH264Output = outputVideoCodec.Equals("libx264", StringComparison.OrdinalIgnoreCase);
  426. // If a fixed width was requested
  427. if (Width.HasValue)
  428. {
  429. return isH264Output ?
  430. string.Format(" -vf \"scale={0}:trunc(ow/a/2)*2{1}\"", Width.Value, assSubtitleParam) :
  431. string.Format(" -vf \"scale={0}:-1{1}\"", Width.Value, assSubtitleParam);
  432. }
  433. // If a max width was requested
  434. if (MaxWidth.HasValue && !MaxHeight.HasValue)
  435. {
  436. return isH264Output ?
  437. string.Format(" -vf \"scale=min(iw\\,{0}):trunc(ow/a/2)*2{1}\"", MaxWidth.Value, assSubtitleParam) :
  438. string.Format(" -vf \"scale=min(iw\\,{0}):-1{1}\"", MaxWidth.Value, assSubtitleParam);
  439. }
  440. // Need to perform calculations manually
  441. // Try to account for bad media info
  442. var currentHeight = VideoStream.Height ?? MaxHeight ?? Height ?? 0;
  443. var currentWidth = VideoStream.Width ?? MaxWidth ?? Width ?? 0;
  444. var outputSize = DrawingUtils.Resize(currentWidth, currentHeight, Width, Height, MaxWidth, MaxHeight);
  445. // If we're encoding with libx264, it can't handle odd numbered widths or heights, so we'll have to fix that
  446. if (isH264Output)
  447. {
  448. return string.Format(" -vf \"scale=trunc({0}/2)*2:trunc({1}/2)*2{2}\"", outputSize.Width, outputSize.Height, assSubtitleParam);
  449. }
  450. // Otherwise use -vf scale since ffmpeg will ensure internally that the aspect ratio is preserved
  451. return string.Format(" -vf \"scale={0}:-1{1}\"", Convert.ToInt32(outputSize.Width), assSubtitleParam);
  452. }
  453. /// <summary>
  454. /// Gets the text subtitle param.
  455. /// </summary>
  456. /// <param name="subtitleStream">The subtitle stream.</param>
  457. /// <returns>System.String.</returns>
  458. protected string GetTextSubtitleParam(MediaStream subtitleStream)
  459. {
  460. var path = subtitleStream.IsExternal ? GetConvertedAssPath(subtitleStream) : GetExtractedAssPath(subtitleStream);
  461. if (string.IsNullOrEmpty(path))
  462. {
  463. return string.Empty;
  464. }
  465. var param = string.Format(",ass={0}", path);
  466. var time = StartTimeTicks;
  467. if (time.HasValue)
  468. {
  469. var seconds = Convert.ToInt32(TimeSpan.FromTicks(time.Value).TotalSeconds);
  470. param += string.Format(",setpts=PTS-{0}/TB", seconds);
  471. }
  472. return param;
  473. }
  474. /// <summary>
  475. /// Gets the extracted ass path.
  476. /// </summary>
  477. /// <param name="subtitleStream">The subtitle stream.</param>
  478. /// <returns>System.String.</returns>
  479. private string GetExtractedAssPath(MediaStream subtitleStream)
  480. {
  481. var video = LibraryItem as Video;
  482. var path = Kernel.FFMpegManager.GetSubtitleCachePath(video, subtitleStream.Index, ".ass");
  483. if (!File.Exists(path))
  484. {
  485. var success = Kernel.FFMpegManager.ExtractTextSubtitle(video, subtitleStream.Index, path, CancellationToken.None).Result;
  486. if (!success)
  487. {
  488. return null;
  489. }
  490. }
  491. return path;
  492. }
  493. /// <summary>
  494. /// Gets the converted ass path.
  495. /// </summary>
  496. /// <param name="subtitleStream">The subtitle stream.</param>
  497. /// <returns>System.String.</returns>
  498. private string GetConvertedAssPath(MediaStream subtitleStream)
  499. {
  500. var video = LibraryItem as Video;
  501. var path = Kernel.FFMpegManager.GetSubtitleCachePath(video, subtitleStream.Index, ".ass");
  502. if (!File.Exists(path))
  503. {
  504. var success = Kernel.FFMpegManager.ConvertTextSubtitle(subtitleStream, path, CancellationToken.None).Result;
  505. if (!success)
  506. {
  507. return null;
  508. }
  509. }
  510. return path;
  511. }
  512. /// <summary>
  513. /// Gets the internal graphical subtitle param.
  514. /// </summary>
  515. /// <param name="subtitleStream">The subtitle stream.</param>
  516. /// <param name="videoCodec">The video codec.</param>
  517. /// <returns>System.String.</returns>
  518. protected string GetInternalGraphicalSubtitleParam(MediaStream subtitleStream, string videoCodec)
  519. {
  520. var outputSizeParam = string.Empty;
  521. // Add resolution params, if specified
  522. if (Width.HasValue || Height.HasValue || MaxHeight.HasValue || MaxWidth.HasValue)
  523. {
  524. outputSizeParam = GetOutputSizeParam(videoCodec).TrimEnd('"');
  525. outputSizeParam = "," + outputSizeParam.Substring(outputSizeParam.IndexOf("scale", StringComparison.OrdinalIgnoreCase));
  526. }
  527. 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);
  528. }
  529. /// <summary>
  530. /// Gets the fixed output video height, in pixels
  531. /// </summary>
  532. /// <value>The height.</value>
  533. protected int? Height
  534. {
  535. get
  536. {
  537. string val = QueryString["height"];
  538. if (string.IsNullOrEmpty(val))
  539. {
  540. return null;
  541. }
  542. return int.Parse(val);
  543. }
  544. }
  545. /// <summary>
  546. /// Gets the fixed output video width, in pixels
  547. /// </summary>
  548. /// <value>The width.</value>
  549. protected int? Width
  550. {
  551. get
  552. {
  553. string val = QueryString["width"];
  554. if (string.IsNullOrEmpty(val))
  555. {
  556. return null;
  557. }
  558. return int.Parse(val);
  559. }
  560. }
  561. /// <summary>
  562. /// Gets the maximum output video height, in pixels
  563. /// </summary>
  564. /// <value>The height of the max.</value>
  565. protected int? MaxHeight
  566. {
  567. get
  568. {
  569. string val = QueryString["maxheight"];
  570. if (string.IsNullOrEmpty(val))
  571. {
  572. return null;
  573. }
  574. return int.Parse(val);
  575. }
  576. }
  577. /// <summary>
  578. /// Gets the maximum output video width, in pixels
  579. /// </summary>
  580. /// <value>The width of the max.</value>
  581. protected int? MaxWidth
  582. {
  583. get
  584. {
  585. string val = QueryString["maxwidth"];
  586. if (string.IsNullOrEmpty(val))
  587. {
  588. return null;
  589. }
  590. return int.Parse(val);
  591. }
  592. }
  593. /// <summary>
  594. /// Gets the output video framerate
  595. /// </summary>
  596. /// <value>The max frame rate.</value>
  597. protected float? FrameRate
  598. {
  599. get
  600. {
  601. string val = QueryString["framerate"];
  602. if (string.IsNullOrEmpty(val))
  603. {
  604. return null;
  605. }
  606. return float.Parse(val);
  607. }
  608. }
  609. /// <summary>
  610. /// Gets the number of audio channels to specify on the command line
  611. /// </summary>
  612. /// <returns>System.Nullable{System.Int32}.</returns>
  613. protected int? GetSampleRateParam()
  614. {
  615. // If the user requested a max value
  616. if (AudioSampleRate.HasValue)
  617. {
  618. return AudioSampleRate.Value;
  619. }
  620. return null;
  621. }
  622. /// <summary>
  623. /// Gets the number of audio channels to specify on the command line
  624. /// </summary>
  625. /// <param name="audioCodec">The audio codec.</param>
  626. /// <returns>System.Nullable{System.Int32}.</returns>
  627. protected int? GetNumAudioChannelsParam(string audioCodec)
  628. {
  629. if (AudioStream.Channels > 2)
  630. {
  631. if (audioCodec.Equals("libvo_aacenc"))
  632. {
  633. // libvo_aacenc currently only supports two channel output
  634. return 2;
  635. }
  636. if (audioCodec.Equals("wmav2"))
  637. {
  638. // wmav2 currently only supports two channel output
  639. return 2;
  640. }
  641. }
  642. return GetNumAudioChannelsParam();
  643. }
  644. /// <summary>
  645. /// Gets the number of audio channels to specify on the command line
  646. /// </summary>
  647. /// <returns>System.Nullable{System.Int32}.</returns>
  648. protected int? GetNumAudioChannelsParam()
  649. {
  650. // If the user requested a max number of channels
  651. if (AudioChannels.HasValue)
  652. {
  653. return AudioChannels.Value;
  654. }
  655. return null;
  656. }
  657. /// <summary>
  658. /// Determines whether the specified stream is H264.
  659. /// </summary>
  660. /// <param name="stream">The stream.</param>
  661. /// <returns><c>true</c> if the specified stream is H264; otherwise, <c>false</c>.</returns>
  662. protected bool IsH264(MediaStream stream)
  663. {
  664. return stream.Codec.IndexOf("264", StringComparison.OrdinalIgnoreCase) != -1 ||
  665. stream.Codec.IndexOf("avc", StringComparison.OrdinalIgnoreCase) != -1;
  666. }
  667. /// <summary>
  668. /// Gets the name of the output audio codec
  669. /// </summary>
  670. /// <returns>System.String.</returns>
  671. protected string GetAudioCodec()
  672. {
  673. if (AudioCodec.HasValue)
  674. {
  675. if (AudioCodec == AudioCodecs.Aac)
  676. {
  677. return "libvo_aacenc";
  678. }
  679. if (AudioCodec == AudioCodecs.Mp3)
  680. {
  681. return "libmp3lame";
  682. }
  683. if (AudioCodec == AudioCodecs.Vorbis)
  684. {
  685. return "libvorbis";
  686. }
  687. if (AudioCodec == AudioCodecs.Wma)
  688. {
  689. return "wmav2";
  690. }
  691. }
  692. return "copy";
  693. }
  694. /// <summary>
  695. /// Gets the name of the output video codec
  696. /// </summary>
  697. /// <returns>System.String.</returns>
  698. protected string GetVideoCodec()
  699. {
  700. if (VideoCodec.HasValue)
  701. {
  702. if (VideoCodec == VideoCodecs.H264)
  703. {
  704. return "libx264";
  705. }
  706. if (VideoCodec == VideoCodecs.Vpx)
  707. {
  708. return "libvpx";
  709. }
  710. if (VideoCodec == VideoCodecs.Wmv)
  711. {
  712. return "wmv2";
  713. }
  714. if (VideoCodec == VideoCodecs.Theora)
  715. {
  716. return "libtheora";
  717. }
  718. }
  719. return "copy";
  720. }
  721. /// <summary>
  722. /// Gets the input argument.
  723. /// </summary>
  724. /// <param name="isoMount">The iso mount.</param>
  725. /// <returns>System.String.</returns>
  726. protected string GetInputArgument(IIsoMount isoMount)
  727. {
  728. return isoMount == null ?
  729. Kernel.FFMpegManager.GetInputArgument(LibraryItem) :
  730. Kernel.FFMpegManager.GetInputArgument(LibraryItem as Video, IsoMount);
  731. }
  732. /// <summary>
  733. /// Starts the FFMPEG.
  734. /// </summary>
  735. /// <param name="outputPath">The output path.</param>
  736. /// <returns>Task.</returns>
  737. protected async Task StartFFMpeg(string outputPath)
  738. {
  739. var video = LibraryItem as Video;
  740. //if (video != null && video.VideoType == VideoType.Iso &&
  741. // video.IsoType.HasValue && Kernel.IsoManager.CanMount(video.Path))
  742. //{
  743. // IsoMount = await Kernel.IsoManager.Mount(video.Path, CancellationToken.None).ConfigureAwait(false);
  744. //}
  745. var process = new Process
  746. {
  747. StartInfo = new ProcessStartInfo
  748. {
  749. CreateNoWindow = true,
  750. UseShellExecute = false,
  751. // Must consume both stdout and stderr or deadlocks may occur
  752. RedirectStandardOutput = true,
  753. RedirectStandardError = true,
  754. FileName = Kernel.FFMpegManager.FFMpegPath,
  755. WorkingDirectory = Path.GetDirectoryName(Kernel.FFMpegManager.FFMpegPath),
  756. Arguments = GetCommandLineArguments(outputPath, IsoMount),
  757. WindowStyle = ProcessWindowStyle.Hidden,
  758. ErrorDialog = false
  759. },
  760. EnableRaisingEvents = true
  761. };
  762. Plugin.Instance.OnTranscodeBeginning(outputPath, TranscodingJobType, process);
  763. //Logger.Info(process.StartInfo.FileName + " " + process.StartInfo.Arguments);
  764. var logFilePath = Path.Combine(Kernel.ApplicationPaths.LogDirectoryPath, "ffmpeg-" + Guid.NewGuid() + ".txt");
  765. // FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory.
  766. LogFileStream = new FileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous);
  767. process.Exited += OnFFMpegProcessExited;
  768. try
  769. {
  770. process.Start();
  771. }
  772. catch (Win32Exception ex)
  773. {
  774. //Logger.ErrorException("Error starting ffmpeg", ex);
  775. Plugin.Instance.OnTranscodeFailedToStart(outputPath, TranscodingJobType);
  776. process.Exited -= OnFFMpegProcessExited;
  777. LogFileStream.Dispose();
  778. throw;
  779. }
  780. // MUST read both stdout and stderr asynchronously or a deadlock may occurr
  781. process.BeginOutputReadLine();
  782. // Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback
  783. process.StandardError.BaseStream.CopyToAsync(LogFileStream);
  784. // Wait for the file to exist before proceeeding
  785. while (!File.Exists(outputPath))
  786. {
  787. await Task.Delay(100).ConfigureAwait(false);
  788. }
  789. }
  790. /// <summary>
  791. /// Processes the exited.
  792. /// </summary>
  793. /// <param name="sender">The sender.</param>
  794. /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
  795. protected void OnFFMpegProcessExited(object sender, EventArgs e)
  796. {
  797. if (IsoMount != null)
  798. {
  799. IsoMount.Dispose();
  800. IsoMount = null;
  801. }
  802. var outputFilePath = OutputFilePath;
  803. LogFileStream.Dispose();
  804. var process = (Process)sender;
  805. process.Exited -= OnFFMpegProcessExited;
  806. int? exitCode = null;
  807. try
  808. {
  809. exitCode = process.ExitCode;
  810. //Logger.Info("FFMpeg exited with code {0} for {1}", exitCode.Value, outputFilePath);
  811. }
  812. catch
  813. {
  814. //Logger.Info("FFMpeg exited with an error for {0}", outputFilePath);
  815. }
  816. process.Dispose();
  817. Plugin.Instance.OnTranscodingFinished(outputFilePath, TranscodingJobType);
  818. if (!exitCode.HasValue || exitCode.Value != 0)
  819. {
  820. //Logger.Info("Deleting partial stream file(s) {0}", outputFilePath);
  821. try
  822. {
  823. DeletePartialStreamFiles(outputFilePath);
  824. }
  825. catch (IOException ex)
  826. {
  827. //Logger.ErrorException("Error deleting partial stream file(s) {0}", ex, outputFilePath);
  828. }
  829. }
  830. else
  831. {
  832. //Logger.Info("FFMpeg completed and exited normally for {0}", outputFilePath);
  833. }
  834. }
  835. /// <summary>
  836. /// Deletes the partial stream files.
  837. /// </summary>
  838. /// <param name="outputFilePath">The output file path.</param>
  839. protected abstract void DeletePartialStreamFiles(string outputFilePath);
  840. }
  841. }