Ffcc.cs 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568
  1. using System.ComponentModel;
  2. using System.Diagnostics;
  3. namespace OpenVIII.AV
  4. {
  5. using FFmpeg.AutoGen;
  6. using Microsoft.Xna.Framework.Audio;
  7. using Microsoft.Xna.Framework.Graphics;
  8. using NAudio.Wave;
  9. using NAudio.Wave.SampleProviders;
  10. using System;
  11. using System.Collections.Generic;
  12. using System.IO;
  13. using System.Linq;
  14. using System.Threading;
  15. using System.Threading.Tasks;
  16. /// <summary>
  17. /// Ffcc is a front end for processing Audio and Video using ffmpeg.autogen
  18. /// </summary>
  19. /// <remarks>
  20. /// Code bits mostly converted to c# from c++ It uses bits of code from FFMPEG examples and a-forge,
  21. /// FFMPEG.autogen, stack overflow
  22. /// </remarks>
  23. public abstract class Ffcc : IDisposable
  24. {
  25. protected static unsafe T Load<T>(BufferData* bufferData, byte[] headerData, int loopStart, FfccMode ffccMode, AVMediaType avType) where T : Ffcc, new()
  26. {
  27. if (bufferData == null) throw new ArgumentNullException(nameof(bufferData));
  28. if (!Enum.IsDefined(typeof(FfccMode), ffccMode))
  29. throw new InvalidEnumArgumentException(nameof(ffccMode), (int) ffccMode, typeof(FfccMode));
  30. if (!Enum.IsDefined(typeof(AVMediaType), avType))
  31. throw new InvalidEnumArgumentException(nameof(avType), (int) avType, typeof(AVMediaType));
  32. var r = new T();
  33. void play(BufferData* d)
  34. {
  35. r.LoadFromRam(d);
  36. r.Init(null, avType, ffccMode, loopStart);
  37. if (ffccMode != FfccMode.ProcessAll) return;
  38. ffmpeg.avformat_free_context(r.Decoder.Format);
  39. //ffmpeg.avio_context_free(&Decoder._format->pb); //CTD
  40. r.Decoder.Format = null;
  41. r.Dispose(false);
  42. }
  43. if (headerData != null)
  44. fixed (byte* tmp = &headerData[0])
  45. {
  46. lock (r.Decoder)
  47. {
  48. bufferData->SetHeader(tmp);
  49. play(bufferData);
  50. }
  51. }
  52. else
  53. play(bufferData);
  54. return r;
  55. }
  56. /// <summary>
  57. /// Opens filename and init class.
  58. /// </summary>
  59. protected static T Load<T>(string filename, AVMediaType mediaType = AVMediaType.AVMEDIA_TYPE_AUDIO, FfccMode mode = FfccMode.StateMach, int loopStart = -1) where T : Ffcc, new()
  60. {
  61. if (string.IsNullOrWhiteSpace(filename)) throw new ArgumentNullException(nameof(filename));
  62. if (!Enum.IsDefined(typeof(AVMediaType), mediaType))
  63. throw new InvalidEnumArgumentException(nameof(mediaType), (int) mediaType, typeof(AVMediaType));
  64. if (!Enum.IsDefined(typeof(FfccMode), mode))
  65. throw new InvalidEnumArgumentException(nameof(mode), (int) mode, typeof(FfccMode));
  66. var r = new T();
  67. r.Init(filename, mediaType, mode, loopStart);
  68. if (mode == FfccMode.ProcessAll)
  69. r.Dispose(false);
  70. return r;
  71. }
  72. #region Fields
  73. /// <summary>
  74. /// If you have sound skipping increase this number and it'll go away. might decrease sync or
  75. /// increase memory load The goal is to keep the dynamic sound effect interface fed. If it plays
  76. /// the audio before you give it more, then you get sound skips.
  77. /// </summary>
  78. /// <value>The goal buffer Count.</value>
  79. /// <remarks>
  80. /// Will want to be as low as possible without sound skipping. 91.875 is 1 second of audio at
  81. /// 44100 hz @ 15 fps; 99.9001 is 1 second of audio at 48000 hz @ 15 fps;
  82. /// </remarks>
  83. private const int GoalBufferCount = 100;
  84. /// <summary>
  85. /// NextAsync sleeps when filling buffer. If set too high buffer will empty before filling it again.
  86. /// </summary>
  87. private const int NextAsyncSleep = 10;
  88. /// <summary>
  89. /// on exception this is turned to true and will force fallback to naudio when monogame isn't working.
  90. /// </summary>
  91. private static bool _useNAudio;
  92. private readonly object _dynamicSoundEffectLock = new object();
  93. private readonly unsafe AVDictionary* _dict;
  94. private unsafe AVIOContext* _avioCtx;
  95. private unsafe byte* _avioCtxBuffer;
  96. private int _avioCtxBufferSize;
  97. private byte[] _convertedData;
  98. //private byte* _convertedData;
  99. private MemoryStream _decodedMemoryStream;
  100. private bool _frameSkip = true;
  101. //private IntPtr _intPtr;
  102. private int _loopStart;
  103. private CancellationToken _cancellationToken = new CancellationToken();
  104. #if _WINDOWS
  105. private BufferedWaveProvider _bufferedWaveProvider;
  106. /// <summary>
  107. /// Wave out for naudio only works in windows.
  108. /// </summary>
  109. /// <see cref="https://markheath.net/post/how-to-record-and-play-audio-at-same"/>
  110. private DirectSoundOut _nAudioOut;
  111. /// <summary>
  112. /// DirectSound requires VolumeSampleProvider to change volume.
  113. /// </summary>
  114. private VolumeSampleProvider _volumeSampleProvider;
  115. /// <summary>
  116. /// Required by naudio to pan the sound.
  117. /// </summary>
  118. private PanningSampleProvider _panningSampleProvider;
  119. #endif
  120. private avio_alloc_context_read_packet _rf;
  121. private avio_alloc_context_seek _sf;
  122. private CancellationTokenSource _sourceToken;
  123. private Task _task;
  124. private DynamicSoundEffectInstance _dynamicSound;
  125. #endregion Fields
  126. #region Destructors
  127. ~Ffcc()
  128. {
  129. Dispose(false);
  130. }
  131. #endregion Destructors
  132. #region Enums
  133. public enum FfccMode
  134. {
  135. /// <summary>
  136. /// Processes entire file at once and does something with output
  137. /// </summary>
  138. ProcessAll,
  139. /// <summary>
  140. /// State machine, functions in this call update to update current state. And update
  141. /// decides what to do next.
  142. /// </summary>
  143. StateMach,
  144. /// <summary>
  145. /// Not Init some error happened that prevented the class from working
  146. /// </summary>
  147. NotInit
  148. }
  149. public enum FfccState
  150. {
  151. Open,
  152. /// <summary>
  153. /// Waiting for request for next frame
  154. /// </summary>
  155. Waiting,
  156. /// <summary>
  157. /// Read all the data
  158. /// </summary>
  159. ReadAll,
  160. /// <summary>
  161. /// Done reading file nothing more can be done
  162. /// </summary>
  163. Done,
  164. /// <summary>
  165. /// Don't change state just pass ret value.
  166. /// </summary>
  167. Null,
  168. /// <summary>
  169. /// Get packet of data containing frames
  170. /// </summary>
  171. ReadOne,
  172. /// <summary>
  173. /// Missing DLL required to function
  174. /// </summary>
  175. NoDLL,
  176. /// <summary>
  177. /// Gets stream and Codec
  178. /// </summary>
  179. GetCodec,
  180. /// <summary>
  181. /// Prepares Scaler for Video stream
  182. /// </summary>
  183. PrepareScaler,
  184. /// <summary>
  185. /// Start Reading
  186. /// </summary>
  187. Read,
  188. /// <summary>
  189. /// Prepares Resampler for Audio stream
  190. /// </summary>
  191. PrepareResampler
  192. }
  193. #endregion Enums
  194. #region Properties
  195. /// <summary>
  196. /// Are you ahead of target frame
  197. /// </summary>
  198. /// <returns>true if ahead</returns>
  199. public bool Ahead
  200. {
  201. get
  202. {
  203. if (Decoder.StreamIndex == -1 || Mode != FfccMode.StateMach) return true;
  204. if (MediaType == AVMediaType.AVMEDIA_TYPE_AUDIO)
  205. {
  206. if (DynamicSound != null)
  207. {
  208. return DynamicSound.PendingBufferCount > GoalBufferCount;
  209. }
  210. #if _WINDOWS
  211. if (_useNAudio)
  212. {
  213. return _bufferedWaveProvider.BufferedDuration.TotalSeconds > _bufferedWaveProvider.BufferDuration.TotalSeconds - 1;
  214. }
  215. #endif
  216. }
  217. else if (Timer.IsRunning)
  218. {
  219. return CurrentFrameNum > ExpectedFrame;
  220. }
  221. return true;
  222. }
  223. }
  224. /// <summary>
  225. /// Are you behind target frame
  226. /// </summary>
  227. /// <returns>true if behind</returns>
  228. public bool Behind => !Ahead && !Current;
  229. /// <summary>
  230. /// Are you on target frame
  231. /// </summary>
  232. /// <returns>true if correct frame</returns>
  233. public unsafe bool Current
  234. {
  235. get
  236. {
  237. if (Decoder.StreamIndex != -1 && Mode == FfccMode.StateMach)
  238. {
  239. if (MediaType == AVMediaType.AVMEDIA_TYPE_AUDIO)
  240. {
  241. if (DynamicSound != null)
  242. {
  243. return DynamicSound.PendingBufferCount == GoalBufferCount;
  244. }
  245. #if _WINDOWS
  246. if (_useNAudio)
  247. {
  248. return Math.Abs(_bufferedWaveProvider.BufferedDuration.TotalSeconds - (_bufferedWaveProvider.BufferDuration.TotalSeconds - 1)) < float.Epsilon;
  249. }
  250. #endif
  251. Die($"{Decoder.CodecContext->sample_rate} is currently unsupported");
  252. }
  253. else if (Timer.IsRunning)
  254. {
  255. return CurrentFrameNum == ExpectedFrame;
  256. }
  257. }
  258. return false;
  259. }
  260. }
  261. /// <summary>
  262. /// Path and filename of file.
  263. /// </summary>
  264. public string DecodedFileName { get; set; }
  265. /// <summary>
  266. /// Dynamic Sound Effect Interface for class allows control out of class. Mode must be in STATE_MACH
  267. /// </summary>
  268. public DynamicSoundEffectInstance DynamicSound
  269. {
  270. get => _dynamicSound; private set
  271. {
  272. lock (_dynamicSoundEffectLock)
  273. _dynamicSound = value;
  274. }
  275. }
  276. /// <summary>
  277. /// True if file is open.
  278. /// </summary>
  279. public bool FileOpened { get; set; }
  280. /// <summary>
  281. /// returns Frames per second or if that is 0. it will return the Time_Base ratio. This is
  282. /// the fundamental unit of time (in seconds) in terms of which frame timestamps are
  283. /// represented. In many cases the audio files time base is the same as the sample rate.
  284. /// example 1/44100. video files audio stream might be 1/100 or 1/1000. these can make for
  285. /// large durations.
  286. /// </summary>
  287. public unsafe double FPS
  288. {
  289. get
  290. {
  291. var r = FPSVideo;
  292. if (Math.Abs(r) > double.Epsilon)
  293. {
  294. return r;
  295. }
  296. if (MediaType == AVMediaType.AVMEDIA_TYPE_AUDIO && Decoder.CodecContext != null && Decoder.CodecContext->framerate.den != 0)
  297. {
  298. return Decoder.CodecContext->framerate.num / (double)Decoder.CodecContext->framerate.den;
  299. }
  300. if (Decoder.Stream != null && Decoder.Stream->time_base.den != 0)
  301. {
  302. return Decoder.Stream->time_base.num / (double)Decoder.Stream->time_base.den; // returns the time_base
  303. }
  304. return 0;
  305. }
  306. }
  307. /// <summary>
  308. /// When getting video frames if behind it goes to next frame. disabled for debugging purposes.
  309. /// </summary>
  310. public bool FrameSkip { get => MediaType == AVMediaType.AVMEDIA_TYPE_VIDEO && _frameSkip; set => _frameSkip = value; }
  311. /// <summary>
  312. /// Is the class disposed of. If true calling Dispose() does nothing.
  313. /// </summary>
  314. public bool IsDisposed { get; private set; }
  315. /// <summary>
  316. /// Sample Count that loop starts from.
  317. /// </summary>
  318. public int LoopStart { get => _loopStart; set => _loopStart = value; }
  319. /// <summary>
  320. /// Current media type being processed.
  321. /// </summary>
  322. public AVMediaType MediaType { get; set; }
  323. /// <summary>
  324. /// Metadata container for tags.
  325. /// </summary>
  326. public Dictionary<string, string> Metadata { get; } = new Dictionary<string, string>();
  327. /// <summary>
  328. /// SoundEffect for class allows control out of class. Mode must be in PROCESS_ALL
  329. /// </summary>
  330. public SoundEffect SoundEffect { get; set; }
  331. /// <summary>
  332. /// SoundEffectInterface for class. allows for more control than just playing the above sound effect.
  333. /// </summary>
  334. public SoundEffectInstance SoundEffectInstance { get; set; }
  335. /// <summary>
  336. /// Stopwatch tracks the time audio has played so video can sync or loops can be looped.
  337. /// </summary>
  338. public Stopwatch Timer { get; } = new Stopwatch();
  339. /// <summary>
  340. /// if there is no stream it returns false. only checked when trying to process audio
  341. /// </summary>
  342. private bool AudioEnabled => Decoder.StreamIndex >= 0;
  343. //private byte* ConvertedData { get => _convertedData; set => _convertedData = value; }
  344. private byte[] ConvertedData { get => _convertedData; set => _convertedData = value; }
  345. /// <summary>
  346. /// Current frame number
  347. /// </summary>
  348. /// <returns>Current frame number or -1 on error</returns>
  349. public unsafe int CurrentFrameNum => Decoder.CodecContext != null ? Decoder.CodecContext->frame_number : -1;
  350. /// <summary>
  351. /// MemoryStream of Audio after decoding and resampling to compatible format.
  352. /// </summary>
  353. private MemoryStream DecodedMemoryStream { get => _decodedMemoryStream; set => _decodedMemoryStream = value; }
  354. /// <summary>
  355. /// Holder of variables for Decoder
  356. /// </summary>
  357. protected FfccVariableGroup Decoder { get; set; } = new FfccVariableGroup();
  358. /// <summary>
  359. /// Based on timer and FPS determines what the current frame is.
  360. /// </summary>
  361. /// <returns>Expected Frame Number</returns>
  362. private int ExpectedFrame => Timer.IsRunning ? (int)Math.Round(Timer.ElapsedMilliseconds * (FPS / 1000)) : 0;
  363. /// <summary>
  364. /// FPS of the video stream.
  365. /// </summary>
  366. private unsafe double FPSVideo
  367. {
  368. get
  369. {
  370. Return = ffmpeg.av_find_best_stream(Decoder.Format, AVMediaType.AVMEDIA_TYPE_VIDEO, -1, -1, null, 0);
  371. if (Return < 0)
  372. {
  373. return 0;
  374. }
  375. if (Decoder.Format->streams[Return]->codec->framerate.den > 0)
  376. {
  377. return (double)Decoder.Format->streams[Return]->codec->framerate.num / Decoder.Format->streams[Return]->codec->framerate.den;
  378. }
  379. return 0;
  380. }
  381. }
  382. /// <summary>
  383. /// Mode that ffcc is running in.
  384. /// </summary>
  385. private FfccMode Mode { get; set; }
  386. /// <summary>
  387. /// Resample Context
  388. /// </summary>
  389. private unsafe SwrContext* ResampleContext { get; set; }
  390. /// <summary>
  391. /// Frame used by resampler
  392. /// </summary>
  393. private unsafe AVFrame* ResampleFrame { get; set; }
  394. /// <summary>
  395. /// Most ffmpeg functions return an integer. If the value is less than 0 it is an error
  396. /// usually. Sometimes data is passed and then it will be greater than 0.
  397. /// </summary>
  398. private int Return { get; set; }
  399. /// <summary>
  400. /// SWS Context
  401. /// </summary>
  402. private unsafe SwsContext* ScalerContext { get; set; }
  403. /// <summary>
  404. /// State ffcc is in.
  405. /// </summary>
  406. private FfccState State { get; set; }
  407. #endregion Properties
  408. #region Methods
  409. /// <summary>
  410. /// Dispose of all leaky variables.
  411. /// </summary>
  412. public void Dispose() => Dispose(true);
  413. /// <summary>
  414. /// Attempts to get 1 frame of Video, or refill Audio buffer.
  415. /// </summary>
  416. /// <returns>Returns -1 if missing stream or returns AVERROR or returns 0 if no problem.</returns>
  417. public int Next()
  418. {
  419. //if stream doesn't exist or stream is done, end
  420. if (Decoder.StreamIndex == -1 || State == FfccState.Done)
  421. {
  422. return -1;
  423. }
  424. // read next frame(s)
  425. return Update(FfccState.ReadOne);
  426. }
  427. /// <summary>
  428. /// Start playing Sound or Start FPS timer for Video
  429. /// </summary>
  430. /// <param name="volume">
  431. /// Volume, ranging from 0.0 (silence) to 1.0 (full volume). Volume during playback is scaled
  432. /// by SoundEffect.MasterVolume.
  433. /// </param>
  434. /// <param name="pitch">
  435. /// Pitch adjustment, ranging from -1.0 (down an octave) to 0.0 (no change) to 1.0 (up an octave).
  436. /// </param>
  437. /// <param name="pan">
  438. /// Panning, ranging from -1.0 (left speaker) to 0.0 (centered), 1.0 (right speaker).
  439. /// </param>
  440. public void Play(float volume = 1.0f, float pitch = 0.0f, float pan = 0.0f) // there are some videos without sound meh.
  441. {
  442. if (Decoder != null && Decoder.StreamIndex > -1)
  443. {
  444. if (!Timer.IsRunning && Mode == FfccMode.StateMach && MediaType == AVMediaType.AVMEDIA_TYPE_VIDEO)
  445. {
  446. Timer.Start();
  447. }
  448. if (!_useNAudio)
  449. {
  450. if (DynamicSound != null && !DynamicSound.IsDisposed && AudioEnabled)
  451. {
  452. lock (_dynamicSoundEffectLock)
  453. {
  454. DynamicSound.Volume = volume;
  455. DynamicSound.Pitch = pitch;
  456. DynamicSound.Pan = pan;
  457. DynamicSound.Play();
  458. }
  459. }
  460. if (SoundEffect != null && !SoundEffect.IsDisposed && AudioEnabled)
  461. {
  462. SoundEffectInstance.Volume = volume;
  463. SoundEffectInstance.Pitch = pitch;
  464. SoundEffectInstance.Pan = pan;
  465. try
  466. {
  467. SoundEffectInstance.Play();
  468. }
  469. catch (Exception e)
  470. {
  471. if (e.GetType().Name == "SharpDXException")
  472. {
  473. Mode = FfccMode.NotInit;
  474. State = FfccState.NoDLL;
  475. SoundEffectInstance = null;
  476. SoundEffect = null;
  477. // if it gets here I can't extract the sound from the SoundEffect but
  478. // I can turn on nAudio and next sound will work
  479. _useNAudio = true;
  480. }
  481. else
  482. e.Rethrow();
  483. }
  484. }
  485. }
  486. #if _WINDOWS
  487. else if (_bufferedWaveProvider != null && _nAudioOut != null)
  488. {
  489. _volumeSampleProvider.Volume = volume;
  490. if (_panningSampleProvider != null) // panning requires mono sound so it's null if it wasn't 1 channel.
  491. _panningSampleProvider.Pan = pan;
  492. // i'll leave out pitch unless it's needed. there is a provider for it but sounds
  493. // like it might do more than we need.
  494. _nAudioOut.Play();
  495. }
  496. #endif
  497. }
  498. }
  499. /// <summary>
  500. /// Same as Play but with a task. Thread is terminated on Stop() or Dispose().
  501. /// </summary>
  502. public void PlayInTask(float volume = 1.0f, float pitch = 0.0f, float pan = 0.0f)
  503. {
  504. if (MediaType == AVMediaType.AVMEDIA_TYPE_AUDIO)
  505. {
  506. if (_sourceToken == null)
  507. _sourceToken = new CancellationTokenSource();
  508. Play(volume, pitch, pan);
  509. _task = new Task<int>(NextInTask);
  510. _task.Start();
  511. }
  512. else
  513. Play(volume, pitch, pan);
  514. }
  515. /// <summary>
  516. /// Stop playing Sound or Stop the FPS timer for Video , and Dispose of Variables
  517. /// </summary>
  518. public async void Stop()
  519. {
  520. if (Timer.IsRunning)
  521. {
  522. Timer.Stop();
  523. Timer.Reset();
  524. }
  525. if (!_useNAudio)
  526. {
  527. if (DynamicSound != null && !DynamicSound.IsDisposed)
  528. {
  529. lock (_dynamicSoundEffectLock)
  530. {
  531. if (AudioEnabled)
  532. {
  533. try
  534. {
  535. DynamicSound?.Stop();
  536. }
  537. catch (NullReferenceException)
  538. {
  539. }
  540. }
  541. DynamicSound.Dispose();
  542. }
  543. DynamicSound = null;
  544. }
  545. if (SoundEffectInstance != null && !SoundEffectInstance.IsDisposed)
  546. {
  547. if (AudioEnabled)
  548. {
  549. SoundEffectInstance.Stop();
  550. }
  551. SoundEffectInstance.Dispose();
  552. }
  553. if (SoundEffect != null && !SoundEffect.IsDisposed)
  554. {
  555. SoundEffect.Dispose();
  556. }
  557. }
  558. #if _WINDOWS
  559. else if (_bufferedWaveProvider != null && _nAudioOut != null)
  560. {
  561. _nAudioOut.Stop();
  562. try
  563. {
  564. _nAudioOut.Dispose();
  565. _bufferedWaveProvider.ClearBuffer();
  566. }
  567. catch (InvalidOperationException)
  568. {
  569. // naudio can't be disposed of if not in original thread.
  570. }
  571. }
  572. #endif
  573. if (_task != null)
  574. {
  575. _sourceToken.Cancel();
  576. await _task;
  577. }
  578. }
  579. /// <summary>
  580. /// Converts Frame to Texture with correct colors pace
  581. /// </summary>
  582. /// <returns>Texture2D</returns>
  583. public unsafe Texture2D Texture2D()
  584. {
  585. lock (Decoder)
  586. {
  587. var frameTex = new Texture2D(Memory.SpriteBatch.GraphicsDevice, Decoder.CodecContext->width, Decoder.CodecContext->height, false, SurfaceFormat.Color);
  588. const int bpp = 4;
  589. var texBuffer = new byte[Decoder.CodecContext->width * Decoder.CodecContext->height * bpp];
  590. fixed (byte* ptr = &texBuffer[0])
  591. {
  592. byte*[] srcData = { ptr, null, null, null };
  593. int[] srcLineSize = { Decoder.CodecContext->width * bpp, 0, 0, 0 };
  594. // convert video frame to the RGB data
  595. ffmpeg.sws_scale(ScalerContext, Decoder.Frame->data, Decoder.Frame->linesize, 0, Decoder.CodecContext->height, srcData, srcLineSize);
  596. }
  597. frameTex.SetData(texBuffer);
  598. return frameTex;
  599. }
  600. }
  601. protected virtual void Dispose(bool disposing)
  602. {
  603. if (Decoder != null)
  604. {
  605. lock (Decoder)
  606. { dis(); }
  607. }
  608. else dis();
  609. void dis()
  610. {
  611. if (disposing)
  612. {
  613. Stop();
  614. }
  615. if (!IsDisposed)
  616. {
  617. if (_task != null)
  618. {
  619. if (_task.IsCompleted)
  620. _task.Dispose();
  621. else
  622. Memory.FfccLeftOverTask.Add(_task);
  623. _task = null;
  624. }
  625. State = FfccState.Done;
  626. Mode = FfccMode.NotInit;
  627. // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
  628. // TODO: set large fields to null.
  629. DecodedMemoryStream?.Dispose();
  630. if (ConvertedData != null)
  631. {
  632. //Marshal.FreeHGlobal((IntPtr)ConvertedData);
  633. }
  634. //if (_intPtr != null)
  635. //{
  636. // Marshal.FreeHGlobal(_intPtr);
  637. //}
  638. unsafe
  639. {
  640. ffmpeg.sws_freeContext(ScalerContext);
  641. if (ResampleContext != null)
  642. {
  643. ffmpeg.swr_close(ResampleContext);
  644. var pResampleContext = ResampleContext;
  645. ffmpeg.swr_free(&pResampleContext);
  646. }
  647. ffmpeg.av_frame_unref(ResampleFrame);
  648. ffmpeg.av_free(ResampleFrame);
  649. if (_avioCtx != null)
  650. {
  651. //ffmpeg.avio_close(avio_ctx); //CTD
  652. ffmpeg.av_free(_avioCtx);
  653. }
  654. }
  655. //if (avio_ctx_buffer != null)
  656. // ffmpeg.av_freep(avio_ctx_buffer); //throws exception
  657. // set to true to prevent multiple disposing
  658. IsDisposed = true;
  659. //GC.Collect(); // don't know if this really does much. was trying to make sure the memory i'm watching is what is really there.
  660. }
  661. else
  662. {
  663. #if _WINDOWS
  664. if (_nAudioOut != null && _useNAudio)
  665. {
  666. _nAudioOut.Dispose();
  667. _nAudioOut = null;
  668. _bufferedWaveProvider.ClearBuffer();
  669. }
  670. #endif
  671. if (_sourceToken != null)
  672. {
  673. _sourceToken.Dispose();
  674. _sourceToken = null;
  675. }
  676. if (Decoder == null) return;
  677. Decoder.Dispose();
  678. Decoder = null;
  679. }
  680. }
  681. }
  682. /// <summary>
  683. /// Flush the Decoder context and packet
  684. /// </summary>
  685. /// <param name="codecContext">Decoder Codec Context</param>
  686. /// <param name="packet">Decoder Packet</param>
  687. /// <returns>0 on success, less than 0 on error</returns>
  688. private static unsafe void DecodeFlush(ref AVCodecContext* codecContext, ref AVPacket packet)
  689. {
  690. packet.data = null;
  691. packet.size = 0;
  692. fixed (AVPacket* tmpPacket = &packet)
  693. {
  694. CheckReturn(ffmpeg.avcodec_send_packet(codecContext, tmpPacket));
  695. }
  696. }
  697. /// <summary>
  698. /// throw new exception
  699. /// </summary>
  700. /// <param name="v">string of message</param>
  701. private static void Die(string v) => throw new Exception(v.Trim('\0'));
  702. /// <summary>
  703. /// For reading data from a memory pointer as if it's a file.
  704. /// </summary>
  705. /// <param name="opaque">incoming data</param>
  706. /// <param name="buf">outgoing data</param>
  707. /// <param name="bufSize">outgoing buffer size</param>
  708. /// <returns>Total bytes read, or EOF</returns>
  709. private static unsafe int ReadPacket(void* opaque, byte* buf, int bufSize)
  710. {
  711. var bd = (BufferData*)opaque;
  712. return bd->Read(buf, bufSize);
  713. }
  714. /// <summary>
  715. /// Converts FFMPEG error codes into a string.
  716. /// </summary>
  717. private static unsafe string AvError(int ret)
  718. {
  719. const ulong bufferSize = 256;
  720. var buffer = new byte[bufferSize];
  721. fixed (byte* ptr = &buffer[0])
  722. {
  723. ffmpeg.av_strerror(ret, ptr, bufferSize);
  724. }
  725. return System.Text.Encoding.UTF8.GetString(buffer).Trim('\0');
  726. }
  727. /// <summary>
  728. /// Throws exception if Ret is less than 0
  729. /// </summary>
  730. private void CheckReturn()
  731. {
  732. CheckReturn(Return);
  733. }
  734. private static void CheckReturn(int returnVal)
  735. {
  736. switch (returnVal)
  737. {
  738. case ffmpeg.AVERROR_OUTPUT_CHANGED:
  739. Die($"The swr_context output ch_layout, sample_rate, sample_fmt must match out frame! {returnVal} - {AvError(returnVal)}");
  740. break;
  741. case ffmpeg.AVERROR_INPUT_CHANGED:
  742. Die($"The swr_context input ch_layout, sample_rate, sample_fmt must match in frame! {returnVal} - {AvError(returnVal)}");
  743. break;
  744. default:
  745. if (returnVal < 0)
  746. {
  747. Die($"{returnVal} - {AvError(returnVal)}");
  748. }
  749. break;
  750. }
  751. }
  752. /// <summary>
  753. /// Decode the next frame.
  754. /// </summary>
  755. /// <param name="frame">Current Decoded Frame</param>
  756. /// <returns>false if EOF, or true if grabbed frame</returns>
  757. private unsafe bool Decode(out AVFrame frame)
  758. {
  759. do
  760. {
  761. //need this extra receive frame for when decoding audio with >1 frame per packet
  762. Return = ffmpeg.avcodec_receive_frame(Decoder.CodecContext, Decoder.Frame);
  763. if (Return == ffmpeg.AVERROR(ffmpeg.EAGAIN))
  764. {
  765. do
  766. {
  767. do
  768. {
  769. //make sure packet is unref before getting a new one.
  770. ffmpeg.av_packet_unref(Decoder.Packet);
  771. //Debug.WriteLine("Getting Packet");
  772. Return = ffmpeg.av_read_frame(Decoder.Format, Decoder.Packet);
  773. if (Return == ffmpeg.AVERROR_EOF)
  774. {
  775. goto EOF;
  776. }
  777. CheckReturn();
  778. }
  779. //check for correct stream.
  780. while (Decoder.Packet->stream_index != Decoder.StreamIndex);
  781. Return = ffmpeg.avcodec_send_packet(Decoder.CodecContext, Decoder.Packet);
  782. ffmpeg.av_packet_unref(Decoder.Packet);
  783. CheckReturn();
  784. Return = ffmpeg.avcodec_receive_frame(Decoder.CodecContext, Decoder.Frame);
  785. }
  786. while (Return == ffmpeg.AVERROR(ffmpeg.EAGAIN));
  787. CheckReturn();
  788. }
  789. else if (Return == ffmpeg.AVERROR_EOF)
  790. {
  791. goto EOF;
  792. }
  793. else
  794. {
  795. CheckReturn();
  796. }
  797. }
  798. //check for frame skip, if enabled check if behind.
  799. while (FrameSkip && Behind);
  800. frame = *Decoder.Frame;
  801. return true;
  802. //end of file, check for loop and end.
  803. //TODO: add LoopEnd and LOOPLength support https://github.com/FFT-Hackers/vgmstream/commit/b332e5cf5cc9e3469cbbab226836083d8377ce61
  804. EOF:
  805. Loop();
  806. frame = *Decoder.Frame;
  807. return false;
  808. }
  809. /// <summary>
  810. /// reads the tags from metadata
  811. /// </summary>
  812. /// <param name="metadata">metadata from format or stream</param>
  813. private unsafe void GetTags(ref AVDictionary* metadata)
  814. {
  815. AVDictionaryEntry* tag = null;
  816. while ((tag = ffmpeg.av_dict_get(metadata, "", tag, ffmpeg.AV_DICT_IGNORE_SUFFIX)) != null)
  817. {
  818. var key = "";
  819. var val = "";
  820. for (var i = 0; tag->value[i] != 0; i++)
  821. {
  822. val += (char)tag->value[i];
  823. }
  824. for (var i = 0; tag->key[i] != 0; i++)
  825. {
  826. key += (char)tag->key[i];
  827. }
  828. Metadata[key.Trim().ToUpper()] = val;
  829. Memory.Log.WriteLine($"{key} = {val}");
  830. if (key.Trim().IndexOf("LoopStart", StringComparison.OrdinalIgnoreCase) >= 0)
  831. {
  832. if (int.TryParse(val, out _loopStart)) continue;
  833. _loopStart = 0;
  834. Memory.Log.WriteLine($"Failed Parse {key} = {val}");
  835. }
  836. else if (key.Trim().IndexOf("LoopEnd", StringComparison.OrdinalIgnoreCase) >= 0)
  837. {
  838. if (!int.TryParse(val, out var _))
  839. Memory.Log.WriteLine($"Failed Parse {key} = {val}");
  840. }
  841. else if (key.Trim().IndexOf("LoopLength", StringComparison.OrdinalIgnoreCase) >= 0)
  842. {
  843. if (!int.TryParse(val, out var _))
  844. Memory.Log.WriteLine($"Failed Parse {key} = {val}");
  845. }
  846. }
  847. }
  848. /// <summary>
  849. /// Opens filename and init class.
  850. /// </summary>
  851. protected void Init(string filename, AVMediaType mediaType = AVMediaType.AVMEDIA_TYPE_AUDIO, FfccMode mode = FfccMode.StateMach, int loopStart = -1)
  852. {
  853. if (!Enum.IsDefined(typeof(FfccMode), mode))
  854. throw new InvalidEnumArgumentException(nameof(mode), (int) mode, typeof(FfccMode));
  855. if (!Enum.IsDefined(typeof(AVMediaType), mediaType))
  856. throw new InvalidEnumArgumentException(nameof(mediaType), (int) mediaType, typeof(AVMediaType));
  857. ffmpeg.av_log_set_level(ffmpeg.AV_LOG_PANIC);
  858. LoopStart = loopStart;
  859. State = FfccState.Open;
  860. Mode = mode;
  861. DecodedFileName = filename;
  862. MediaType = mediaType;
  863. Return = -1;
  864. ConvertedData = null;
  865. Update();
  866. }
  867. private unsafe bool InitNaudio()
  868. {
  869. #if _WINDOWS
  870. if (Extended.IsLinux) return false;
  871. _bufferedWaveProvider = new BufferedWaveProvider(
  872. new WaveFormat(ResampleFrame->sample_rate, ResampleFrame->channels))
  873. {
  874. DiscardOnBufferOverflow = false
  875. };
  876. _volumeSampleProvider = new VolumeSampleProvider(_bufferedWaveProvider.ToSampleProvider());
  877. _nAudioOut = new DirectSoundOut();
  878. if (ResampleFrame->channels == 1)
  879. {
  880. _panningSampleProvider = new PanningSampleProvider(_volumeSampleProvider);
  881. _nAudioOut.Init(_panningSampleProvider);
  882. }
  883. else
  884. _nAudioOut.Init(_volumeSampleProvider);
  885. _useNAudio = true;
  886. return true;
  887. #endif
  888. return true;
  889. }
  890. /// <summary>
  891. /// Sets up AVFormatContext to be able from the memory buffer.
  892. /// </summary>
  893. protected unsafe void LoadFromRam(BufferData* bd)
  894. {
  895. _avioCtx = null;
  896. _avioCtxBufferSize = 4096;
  897. _avioCtxBuffer = (byte*)ffmpeg.av_malloc((ulong)_avioCtxBufferSize);
  898. if (_avioCtxBuffer == null)
  899. {
  900. CheckReturn(ffmpeg.AVERROR(ffmpeg.ENOMEM));
  901. return;
  902. }
  903. _rf = ReadPacket;
  904. _sf = Seek;
  905. _avioCtx = ffmpeg.avio_alloc_context(_avioCtxBuffer, _avioCtxBufferSize, 0, bd, _rf, null, _sf);
  906. if (_avioCtx == null)
  907. {
  908. CheckReturn(ffmpeg.AVERROR(ffmpeg.ENOMEM));
  909. return;
  910. }
  911. Decoder.Format->pb = _avioCtx;
  912. Open();
  913. }
  914. private static unsafe long Seek(void* opaque, long offset, int whence)
  915. {
  916. var bd = (BufferData*)opaque;
  917. return bd->Seek(offset, whence);
  918. }
  919. /// <summary>
  920. /// Load sound from MemoryStream into a SoundEffect
  921. /// </summary>
  922. /// <param name="decodedStream">Memory Stream containing sound data</param>
  923. private unsafe void LoadSoundFromStream(ref MemoryStream decodedStream)
  924. {
  925. if (DecodedMemoryStream.Length <= 0 || MediaType != AVMediaType.AVMEDIA_TYPE_AUDIO) return;
  926. if (!_useNAudio)
  927. {
  928. if (SoundEffect != null) return;
  929. SoundEffect = new SoundEffect(decodedStream.GetBuffer(), 0, (int) decodedStream.Length,
  930. ResampleFrame->sample_rate, (AudioChannels) ResampleFrame->channels, 0, 0);
  931. SoundEffectInstance = SoundEffect.CreateInstance();
  932. if (LoopStart >= 0)
  933. {
  934. SoundEffectInstance.IsLooped = true;
  935. }
  936. //doesn't throw an exception till you goto play it.
  937. }
  938. else
  939. RecorderOnDataAvailable(new WaveInEventArgs(decodedStream.GetBuffer(), (int)decodedStream.Length));
  940. }
  941. /// <summary>
  942. /// Copies byte[] data to a Pointer. So it can be used with ffmpeg.
  943. /// </summary>
  944. /// <param name="data">incoming data</param>
  945. /// <param name="length">size of data</param>
  946. //private void LoadFromRAM(byte[] data, int length)
  947. //{
  948. // _intPtr = Marshal.AllocHGlobal(length);
  949. // Marshal.Copy(data, 0, _intPtr, length);
  950. // LoadFromRAM(_intPtr, length);
  951. //}
  952. /// <summary>
  953. /// Add sound from byte[] to a Dynamic Sound Effect Instance, it can play while you give it more data.
  954. /// </summary>
  955. /// <param name="decodedStream">sound data</param>
  956. private unsafe void LoadSoundFromStream(ref byte[] buffer, int start, ref int length)
  957. {
  958. if (length > 0 && MediaType == AVMediaType.AVMEDIA_TYPE_AUDIO)
  959. {
  960. if (!_useNAudio)
  961. {
  962. if (DynamicSound == null)
  963. {
  964. //create instance here to set sample_rate and channels dynamically
  965. DynamicSound = new DynamicSoundEffectInstance(ResampleFrame->sample_rate, (AudioChannels)ResampleFrame->channels);
  966. }
  967. try
  968. {
  969. lock (_dynamicSoundEffectLock)
  970. DynamicSound.SubmitBuffer(buffer, start, length);
  971. }
  972. catch (ArgumentException)
  973. {
  974. //got error saying buffer was too small. makes no sense.
  975. }
  976. catch (Exception e)
  977. {
  978. if (e.GetType().Name == "SharpDXException")
  979. {
  980. //DynamicSound.Dispose();
  981. DynamicSound = null;
  982. if (!InitNaudio())
  983. {
  984. Mode = FfccMode.NotInit;
  985. State = FfccState.NoDLL;
  986. }
  987. else
  988. {
  989. LoadSoundFromStream(ref buffer, start, ref length);
  990. }
  991. }
  992. else
  993. e.Rethrow();
  994. }
  995. }
  996. else
  997. RecorderOnDataAvailable(new WaveInEventArgs(start > 0 ? buffer.Skip(start).ToArray() : buffer, length - start));
  998. }
  999. }
  1000. /// <summary>
  1001. /// Load sound from memory stream by default.
  1002. /// </summary>
  1003. private void LoadSoundFromStream() => LoadSoundFromStream(ref _decodedMemoryStream);
  1004. /// <summary>
  1005. /// If looping seek back to LoopStart
  1006. /// </summary>
  1007. private unsafe void Loop()
  1008. {
  1009. if (LoopStart < 0 || Mode != FfccMode.StateMach) return;
  1010. //I didn't realize this didn't change the frame number to 0. it just appends the LoopStart pos to the current stream.
  1011. //So it is possible this could overflow when it's looped long enough to bring the current frame num to max value.
  1012. //Return = ffmpeg.avformat_seek_file(Decoder.Format, Decoder.StreamIndex, min, LoopStart, max, 0);
  1013. CheckReturn(ffmpeg.av_seek_frame(Decoder.Format, Decoder.StreamIndex, LoopStart, 0));
  1014. State = FfccState.Waiting;
  1015. }
  1016. /// <summary>
  1017. /// For use in threads runs Next till done. To keep audio buffer fed. Or really good timing
  1018. /// on video frames.
  1019. /// </summary>
  1020. private int NextInTask()
  1021. {
  1022. try
  1023. {
  1024. while (Mode == FfccMode.StateMach && !_cancellationToken.IsCancellationRequested && State != FfccState.Done && !IsDisposed)
  1025. {
  1026. lock (Decoder) //make the main thread wait if it accesses this class.
  1027. {
  1028. NextLoop();
  1029. }
  1030. if (!_useNAudio)
  1031. Thread.Sleep(NextAsyncSleep); //delay checks
  1032. }
  1033. }
  1034. //catch (ThreadAbortException)
  1035. //{
  1036. // disposeAll = true;//stop playing
  1037. //}
  1038. finally
  1039. {
  1040. Dispose(_cancellationToken.IsCancellationRequested); // dispose of everything except audio encase it's still playing.
  1041. }
  1042. #if _WINDOWS
  1043. if (_useNAudio)
  1044. {
  1045. while (!_cancellationToken.IsCancellationRequested && _nAudioOut != null && _nAudioOut.PlaybackState != PlaybackState.Stopped)
  1046. Thread.Sleep(NextAsyncSleep);
  1047. //try
  1048. //{
  1049. // if (nAudioOut != null)
  1050. // nAudioOut.Dispose();
  1051. // bufferedWaveProvider.ClearBuffer();
  1052. //}
  1053. //catch (InvalidOperationException)
  1054. ////{
  1055. // if (nAudioOut != null)
  1056. // Memory.MainThreadOnlyActions.Enqueue(nAudioOut.Dispose);
  1057. // Memory.MainThreadOnlyActions.Enqueue(bufferedWaveProvider.ClearBuffer);
  1058. // //doesn't like threads...
  1059. //}
  1060. }
  1061. #endif
  1062. return 0;
  1063. }
  1064. public void NextLoop()
  1065. {
  1066. while (!IsDisposed && !Ahead)
  1067. {
  1068. if (Next() < 0)
  1069. break;
  1070. }
  1071. }
  1072. /// <summary>
  1073. /// Opens filename and assigns FormatContext.
  1074. /// </summary>
  1075. private unsafe int Open()
  1076. {
  1077. if (!FileOpened)
  1078. {
  1079. fixed (AVFormatContext** tmp = &Decoder.Format)
  1080. {
  1081. Return = ffmpeg.avformat_open_input(tmp, DecodedFileName, null, null);
  1082. CheckReturn();
  1083. }
  1084. Return = ffmpeg.avformat_find_stream_info(Decoder.Format, null);
  1085. CheckReturn();
  1086. GetTags(ref Decoder.Format->metadata);
  1087. FileOpened = true;
  1088. }
  1089. return (FileOpened) ? 0 : -1;
  1090. }
  1091. /// <summary>
  1092. /// Finds the codec for the chosen stream
  1093. /// </summary>
  1094. private unsafe void PrepareCodec()
  1095. {
  1096. // find & open codec
  1097. fixed (AVCodec** tmp = &Decoder.Codec)
  1098. {
  1099. Return = ffmpeg.av_find_best_stream(Decoder.Format, MediaType, -1, -1, tmp, 0);
  1100. }
  1101. if (Return == ffmpeg.AVERROR_STREAM_NOT_FOUND && MediaType == AVMediaType.AVMEDIA_TYPE_AUDIO)
  1102. {
  1103. //Don't fail if no audio stream just be done.
  1104. State = FfccState.Done;
  1105. Mode = FfccMode.NotInit;
  1106. return;
  1107. }
  1108. CheckReturn();
  1109. Decoder.StreamIndex = Return;
  1110. GetTags(ref Decoder.Stream->metadata);
  1111. Decoder.CodecContext = ffmpeg.avcodec_alloc_context3(Decoder.Codec);
  1112. if (Decoder.CodecContext == null)
  1113. {
  1114. Die("Could not allocate codec context");
  1115. }
  1116. Return = ffmpeg.avcodec_parameters_to_context(Decoder.CodecContext, Decoder.Stream->codecpar);
  1117. CheckReturn();
  1118. fixed (AVDictionary** tmp = &_dict)
  1119. {
  1120. Return = ffmpeg.av_dict_set(tmp, "strict", "+experimental", 0);
  1121. CheckReturn();
  1122. Return = ffmpeg.avcodec_open2(Decoder.CodecContext, Decoder.Codec, tmp);
  1123. CheckReturn();
  1124. }
  1125. if (MediaType == AVMediaType.AVMEDIA_TYPE_AUDIO)
  1126. {
  1127. if (Decoder.CodecContext->channel_layout == 0)
  1128. {
  1129. if (Decoder.CodecContext->channels == 2)
  1130. {
  1131. Decoder.CodecContext->channel_layout = ffmpeg.AV_CH_LAYOUT_STEREO;
  1132. }
  1133. else if (Decoder.CodecContext->channels == 1)
  1134. {
  1135. Decoder.CodecContext->channel_layout = ffmpeg.AV_CH_LAYOUT_MONO;
  1136. }
  1137. else
  1138. {
  1139. Die("must set custom channel layout, is not stereo or mono");
  1140. }
  1141. }
  1142. }
  1143. }
  1144. private void PrepareProcess()
  1145. {
  1146. using (DecodedMemoryStream = new MemoryStream())
  1147. {
  1148. Process();
  1149. LoadSoundFromStream();
  1150. }
  1151. }
  1152. /// <summary>
  1153. /// PrepareResampler
  1154. /// </summary>
  1155. private unsafe void PrepareResampler()
  1156. {
  1157. if (MediaType != AVMediaType.AVMEDIA_TYPE_AUDIO)
  1158. {
  1159. return;
  1160. }
  1161. //resampler
  1162. ResampleFrame = ffmpeg.av_frame_alloc();
  1163. if (ResampleFrame == null)
  1164. {
  1165. Die("Error allocating the frame\n");
  1166. }
  1167. ResampleContext = ffmpeg.swr_alloc();
  1168. ffmpeg.av_opt_set_channel_layout(ResampleContext, "in_channel_layout", (long)Decoder.CodecContext->channel_layout, 0);
  1169. ffmpeg.av_opt_set_int(ResampleContext, "in_sample_rate", Decoder.CodecContext->sample_rate, 0);
  1170. ffmpeg.av_opt_set_sample_fmt(ResampleContext, "in_sample_fmt", Decoder.CodecContext->sample_fmt, 0);
  1171. ffmpeg.av_opt_set_channel_layout(ResampleContext, "out_channel_layout", (long)Decoder.CodecContext->channel_layout, 0);
  1172. ffmpeg.av_opt_set_sample_fmt(ResampleContext, "out_sample_fmt", AVSampleFormat.AV_SAMPLE_FMT_S16, 0);
  1173. ffmpeg.av_opt_set_int(ResampleContext, "out_sample_rate", Decoder.CodecContext->sample_rate, 0);
  1174. Return = ffmpeg.swr_init(ResampleContext);
  1175. if (Return < 0)
  1176. {
  1177. Die("swr_init");
  1178. }
  1179. Decoder.Frame->format = (int)Decoder.CodecContext->sample_fmt;
  1180. Decoder.Frame->channel_layout = Decoder.CodecContext->channel_layout;
  1181. Decoder.Frame->channels = Decoder.CodecContext->channels;
  1182. Decoder.Frame->sample_rate = Decoder.CodecContext->sample_rate;
  1183. ResampleFrame->nb_samples = Decoder.CodecContext->frame_size;
  1184. if (ResampleFrame->nb_samples == 0)
  1185. {
  1186. ResampleFrame->nb_samples = 32; //32, or 64, ADPCM require 32.
  1187. }
  1188. ResampleFrame->format = (int)AVSampleFormat.AV_SAMPLE_FMT_S16;
  1189. ResampleFrame->channel_layout = Decoder.CodecContext->channel_layout;
  1190. ResampleFrame->channels = Decoder.CodecContext->channels;
  1191. ResampleFrame->sample_rate = Decoder.CodecContext->sample_rate;
  1192. var convertedFrameBufferSize = ffmpeg.av_samples_get_buffer_size(null, ResampleFrame->channels,
  1193. ResampleFrame->nb_samples,
  1194. (AVSampleFormat)ResampleFrame->format, 0);
  1195. //ConvertedData = (byte*)Marshal.AllocHGlobal(convertedFrameBufferSize);
  1196. ConvertedData = new byte[convertedFrameBufferSize];
  1197. if (_useNAudio) InitNaudio();
  1198. }
  1199. /// <summary>
  1200. /// Setup scaler for drawing frames to bitmap.
  1201. /// </summary>
  1202. private unsafe void PrepareScaler()
  1203. {
  1204. if (MediaType != AVMediaType.AVMEDIA_TYPE_VIDEO)
  1205. {
  1206. return;
  1207. }
  1208. ScalerContext = ffmpeg.sws_getContext(
  1209. Decoder.CodecContext->width, Decoder.CodecContext->height, Decoder.CodecContext->pix_fmt,
  1210. Decoder.CodecContext->width, Decoder.CodecContext->height, AVPixelFormat.AV_PIX_FMT_RGBA,
  1211. ffmpeg.SWS_ACCURATE_RND, null, null, null);
  1212. Return = ffmpeg.sws_init_context(ScalerContext, null, null);
  1213. CheckReturn();
  1214. }
  1215. /// <summary>
  1216. /// Decodes, Resamples, Encodes
  1217. /// </summary>
  1218. /// <ref>https://stackoverflow.com/questions/32051847/c-ffmpeg-distorted-sound-when-converting-audio?rq=1#_=_</ref>
  1219. private unsafe void Process()
  1220. {
  1221. while (Decode(out var decodedFrame))
  1222. {
  1223. if (MediaType == AVMediaType.AVMEDIA_TYPE_VIDEO)
  1224. {
  1225. if (Mode == FfccMode.StateMach)
  1226. {
  1227. State = FfccState.Waiting;
  1228. break;
  1229. }
  1230. // do something with video here.
  1231. if (Mode == FfccMode.ProcessAll)
  1232. {
  1233. }
  1234. }
  1235. else if (MediaType == AVMediaType.AVMEDIA_TYPE_AUDIO)
  1236. {
  1237. Resample(ref decodedFrame);
  1238. if (Mode == FfccMode.StateMach && !Behind) //still behind stay here.
  1239. {
  1240. State = FfccState.Waiting;
  1241. break;
  1242. }
  1243. }
  1244. }
  1245. if (State != FfccState.Waiting)
  1246. {
  1247. State = FfccState.Done;
  1248. Timer.Stop();
  1249. Timer.Reset();
  1250. DecodeFlush(ref Decoder.CodecContext, ref *Decoder.Packet); //calling this twice was causing issues.
  1251. }
  1252. }
  1253. /// <summary>
  1254. /// </summary>
  1255. /// <param name="waveInEventArgs"></param>
  1256. /// <see cref="https://markheath.net/post/how-to-record-and-play-audio-at-same"/>
  1257. private void RecorderOnDataAvailable(WaveInEventArgs waveInEventArgs)
  1258. {
  1259. #if _WINDOWS
  1260. if (_bufferedWaveProvider == null)
  1261. InitNaudio();
  1262. if (_useNAudio)
  1263. _bufferedWaveProvider.AddSamples(waveInEventArgs.Buffer, 0, waveInEventArgs.BytesRecorded);
  1264. #endif
  1265. }
  1266. /// <summary>
  1267. /// Resample current frame, Save output data
  1268. /// </summary>
  1269. /// <param name="frame">Current Decoded Frame</param>
  1270. private unsafe void Resample(ref AVFrame frame)
  1271. {
  1272. // Convert
  1273. int outSamples;
  1274. fixed (byte** tmp = (byte*[])frame.data)
  1275. {
  1276. outSamples = ffmpeg.swr_convert(ResampleContext, null, 0, tmp, frame.nb_samples);
  1277. }
  1278. if (outSamples < 0)
  1279. {
  1280. Die("Could not convert");
  1281. }
  1282. for (; ; )
  1283. {
  1284. // ReSharper disable once CommentTypo
  1285. //https://ffmpeg.org/doxygen/3.2/group__lswr.html#ga97a8d5f6abe3bcdfb6072412f17285a4
  1286. CheckReturn(outSamples = ffmpeg.swr_get_out_samples(ResampleContext, 0));
  1287. // 32 was nb_samples but if too big would just not decode anything
  1288. if (outSamples < 32 * ResampleFrame->channels)
  1289. {
  1290. break;
  1291. }
  1292. //fixed (byte** tmp = &_convertedData)
  1293. fixed (byte* tmp = &_convertedData[0])
  1294. {
  1295. //https://ffmpeg.org/doxygen/3.2/group__lswr.html#gaa5bb6cab830146efa8c760fa66ee582a
  1296. CheckReturn(ffmpeg.swr_convert(ResampleContext, &tmp, ResampleFrame->nb_samples, null, 0));
  1297. }
  1298. var bufferSize = ffmpeg.av_samples_get_buffer_size(null,
  1299. ResampleFrame->channels,
  1300. ResampleFrame->nb_samples,
  1301. (AVSampleFormat)ResampleFrame->format,
  1302. 0);
  1303. // write to buffer
  1304. WriteToMs(ref _convertedData, 0, ref bufferSize);
  1305. }
  1306. }
  1307. /// <summary>
  1308. /// Run code depending on state
  1309. /// </summary>
  1310. /// <param name="state">Change the state to this</param>
  1311. /// <param name="ret">return this</param>
  1312. /// <returns>ret</returns>
  1313. private int Update(FfccState state = FfccState.Null, int ret = 0)
  1314. {
  1315. if (Mode == FfccMode.NotInit)
  1316. {
  1317. Die("Class not Init");
  1318. }
  1319. if (state == FfccState.NoDLL)
  1320. {
  1321. return -1;
  1322. }
  1323. if (state != FfccState.Null)
  1324. {
  1325. State = state;
  1326. }
  1327. do
  1328. {
  1329. switch (State)
  1330. {
  1331. case FfccState.Open:
  1332. State = FfccState.GetCodec;
  1333. if (0 < Open())
  1334. {
  1335. Die("Failed to Open");
  1336. }
  1337. break;
  1338. case FfccState.GetCodec:
  1339. State = FfccState.PrepareResampler;
  1340. PrepareCodec();
  1341. break;
  1342. case FfccState.PrepareResampler:
  1343. State = FfccState.PrepareScaler;
  1344. PrepareResampler();
  1345. break;
  1346. case FfccState.PrepareScaler:
  1347. State = FfccState.Read;
  1348. PrepareScaler();
  1349. break;
  1350. case FfccState.Read://Enters waiting state unless we want to process all now.
  1351. State = Mode == FfccMode.ProcessAll ? FfccState.ReadAll : FfccState.ReadOne;
  1352. //ReadOne here makes it grab one video frame and pre-caches audio to it's limit.
  1353. //Waiting here makes it wait till GetFrame() is called.
  1354. //ReadAll just processes the whole audio stream (memory leaky), not meant for video
  1355. //Currently video will just saves all the frames to bmp in temp folder on ReadAll.
  1356. break;
  1357. case FfccState.ReadAll:
  1358. State = FfccState.Done;
  1359. PrepareProcess();
  1360. break;
  1361. case FfccState.ReadOne:
  1362. PrepareProcess();
  1363. switch (State)
  1364. {
  1365. case FfccState.Waiting:
  1366. ret = 0;
  1367. break;
  1368. default:
  1369. ret = -1;
  1370. break;
  1371. }
  1372. break;
  1373. default:
  1374. State = FfccState.Done;
  1375. break;
  1376. }
  1377. }
  1378. while (!((Mode == FfccMode.ProcessAll && State == FfccState.Done) || (State == FfccState.Done || State == FfccState.Waiting)));
  1379. return ret;
  1380. }
  1381. private void WriteToMs(ref byte[] output, int start, ref int length)
  1382. {
  1383. if (Mode == FfccMode.StateMach)
  1384. {
  1385. LoadSoundFromStream(ref output, start, ref length);
  1386. }
  1387. else
  1388. {
  1389. DecodedMemoryStream.Write(output, start, length);
  1390. }
  1391. }
  1392. #endregion Methods
  1393. }
  1394. }