Ffcc.cs 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567
  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. }
  889. /// <summary>
  890. /// Sets up AVFormatContext to be able from the memory buffer.
  891. /// </summary>
  892. protected unsafe void LoadFromRam(BufferData* bd)
  893. {
  894. _avioCtx = null;
  895. _avioCtxBufferSize = 4096;
  896. _avioCtxBuffer = (byte*)ffmpeg.av_malloc((ulong)_avioCtxBufferSize);
  897. if (_avioCtxBuffer == null)
  898. {
  899. CheckReturn(ffmpeg.AVERROR(ffmpeg.ENOMEM));
  900. return;
  901. }
  902. _rf = ReadPacket;
  903. _sf = Seek;
  904. _avioCtx = ffmpeg.avio_alloc_context(_avioCtxBuffer, _avioCtxBufferSize, 0, bd, _rf, null, _sf);
  905. if (_avioCtx == null)
  906. {
  907. CheckReturn(ffmpeg.AVERROR(ffmpeg.ENOMEM));
  908. return;
  909. }
  910. Decoder.Format->pb = _avioCtx;
  911. Open();
  912. }
  913. private static unsafe long Seek(void* opaque, long offset, int whence)
  914. {
  915. var bd = (BufferData*)opaque;
  916. return bd->Seek(offset, whence);
  917. }
  918. /// <summary>
  919. /// Load sound from MemoryStream into a SoundEffect
  920. /// </summary>
  921. /// <param name="decodedStream">Memory Stream containing sound data</param>
  922. private unsafe void LoadSoundFromStream(ref MemoryStream decodedStream)
  923. {
  924. if (DecodedMemoryStream.Length <= 0 || MediaType != AVMediaType.AVMEDIA_TYPE_AUDIO) return;
  925. if (!_useNAudio)
  926. {
  927. if (SoundEffect != null) return;
  928. SoundEffect = new SoundEffect(decodedStream.GetBuffer(), 0, (int) decodedStream.Length,
  929. ResampleFrame->sample_rate, (AudioChannels) ResampleFrame->channels, 0, 0);
  930. SoundEffectInstance = SoundEffect.CreateInstance();
  931. if (LoopStart >= 0)
  932. {
  933. SoundEffectInstance.IsLooped = true;
  934. }
  935. //doesn't throw an exception till you goto play it.
  936. }
  937. else
  938. RecorderOnDataAvailable(new WaveInEventArgs(decodedStream.GetBuffer(), (int)decodedStream.Length));
  939. }
  940. /// <summary>
  941. /// Copies byte[] data to a Pointer. So it can be used with ffmpeg.
  942. /// </summary>
  943. /// <param name="data">incoming data</param>
  944. /// <param name="length">size of data</param>
  945. //private void LoadFromRAM(byte[] data, int length)
  946. //{
  947. // _intPtr = Marshal.AllocHGlobal(length);
  948. // Marshal.Copy(data, 0, _intPtr, length);
  949. // LoadFromRAM(_intPtr, length);
  950. //}
  951. /// <summary>
  952. /// Add sound from byte[] to a Dynamic Sound Effect Instance, it can play while you give it more data.
  953. /// </summary>
  954. /// <param name="decodedStream">sound data</param>
  955. private unsafe void LoadSoundFromStream(ref byte[] buffer, int start, ref int length)
  956. {
  957. if (length > 0 && MediaType == AVMediaType.AVMEDIA_TYPE_AUDIO)
  958. {
  959. if (!_useNAudio)
  960. {
  961. if (DynamicSound == null)
  962. {
  963. //create instance here to set sample_rate and channels dynamically
  964. DynamicSound = new DynamicSoundEffectInstance(ResampleFrame->sample_rate, (AudioChannels)ResampleFrame->channels);
  965. }
  966. try
  967. {
  968. lock (_dynamicSoundEffectLock)
  969. DynamicSound.SubmitBuffer(buffer, start, length);
  970. }
  971. catch (ArgumentException)
  972. {
  973. //got error saying buffer was too small. makes no sense.
  974. }
  975. catch (Exception e)
  976. {
  977. if (e.GetType().Name == "SharpDXException")
  978. {
  979. //DynamicSound.Dispose();
  980. DynamicSound = null;
  981. if (!InitNaudio())
  982. {
  983. Mode = FfccMode.NotInit;
  984. State = FfccState.NoDLL;
  985. }
  986. else
  987. {
  988. LoadSoundFromStream(ref buffer, start, ref length);
  989. }
  990. }
  991. else
  992. e.Rethrow();
  993. }
  994. }
  995. else
  996. RecorderOnDataAvailable(new WaveInEventArgs(start > 0 ? buffer.Skip(start).ToArray() : buffer, length - start));
  997. }
  998. }
  999. /// <summary>
  1000. /// Load sound from memory stream by default.
  1001. /// </summary>
  1002. private void LoadSoundFromStream() => LoadSoundFromStream(ref _decodedMemoryStream);
  1003. /// <summary>
  1004. /// If looping seek back to LoopStart
  1005. /// </summary>
  1006. private unsafe void Loop()
  1007. {
  1008. if (LoopStart < 0 || Mode != FfccMode.StateMach) return;
  1009. //I didn't realize this didn't change the frame number to 0. it just appends the LoopStart pos to the current stream.
  1010. //So it is possible this could overflow when it's looped long enough to bring the current frame num to max value.
  1011. //Return = ffmpeg.avformat_seek_file(Decoder.Format, Decoder.StreamIndex, min, LoopStart, max, 0);
  1012. CheckReturn(ffmpeg.av_seek_frame(Decoder.Format, Decoder.StreamIndex, LoopStart, 0));
  1013. State = FfccState.Waiting;
  1014. }
  1015. /// <summary>
  1016. /// For use in threads runs Next till done. To keep audio buffer fed. Or really good timing
  1017. /// on video frames.
  1018. /// </summary>
  1019. private int NextInTask()
  1020. {
  1021. try
  1022. {
  1023. while (Mode == FfccMode.StateMach && !_cancellationToken.IsCancellationRequested && State != FfccState.Done && !IsDisposed)
  1024. {
  1025. lock (Decoder) //make the main thread wait if it accesses this class.
  1026. {
  1027. NextLoop();
  1028. }
  1029. if (!_useNAudio)
  1030. Thread.Sleep(NextAsyncSleep); //delay checks
  1031. }
  1032. }
  1033. //catch (ThreadAbortException)
  1034. //{
  1035. // disposeAll = true;//stop playing
  1036. //}
  1037. finally
  1038. {
  1039. Dispose(_cancellationToken.IsCancellationRequested); // dispose of everything except audio encase it's still playing.
  1040. }
  1041. #if _WINDOWS
  1042. if (_useNAudio)
  1043. {
  1044. while (!_cancellationToken.IsCancellationRequested && _nAudioOut != null && _nAudioOut.PlaybackState != PlaybackState.Stopped)
  1045. Thread.Sleep(NextAsyncSleep);
  1046. //try
  1047. //{
  1048. // if (nAudioOut != null)
  1049. // nAudioOut.Dispose();
  1050. // bufferedWaveProvider.ClearBuffer();
  1051. //}
  1052. //catch (InvalidOperationException)
  1053. ////{
  1054. // if (nAudioOut != null)
  1055. // Memory.MainThreadOnlyActions.Enqueue(nAudioOut.Dispose);
  1056. // Memory.MainThreadOnlyActions.Enqueue(bufferedWaveProvider.ClearBuffer);
  1057. // //doesn't like threads...
  1058. //}
  1059. }
  1060. #endif
  1061. return 0;
  1062. }
  1063. public void NextLoop()
  1064. {
  1065. while (!IsDisposed && !Ahead)
  1066. {
  1067. if (Next() < 0)
  1068. break;
  1069. }
  1070. }
  1071. /// <summary>
  1072. /// Opens filename and assigns FormatContext.
  1073. /// </summary>
  1074. private unsafe int Open()
  1075. {
  1076. if (!FileOpened)
  1077. {
  1078. fixed (AVFormatContext** tmp = &Decoder.Format)
  1079. {
  1080. Return = ffmpeg.avformat_open_input(tmp, DecodedFileName, null, null);
  1081. CheckReturn();
  1082. }
  1083. Return = ffmpeg.avformat_find_stream_info(Decoder.Format, null);
  1084. CheckReturn();
  1085. GetTags(ref Decoder.Format->metadata);
  1086. FileOpened = true;
  1087. }
  1088. return (FileOpened) ? 0 : -1;
  1089. }
  1090. /// <summary>
  1091. /// Finds the codec for the chosen stream
  1092. /// </summary>
  1093. private unsafe void PrepareCodec()
  1094. {
  1095. // find & open codec
  1096. fixed (AVCodec** tmp = &Decoder.Codec)
  1097. {
  1098. Return = ffmpeg.av_find_best_stream(Decoder.Format, MediaType, -1, -1, tmp, 0);
  1099. }
  1100. if (Return == ffmpeg.AVERROR_STREAM_NOT_FOUND && MediaType == AVMediaType.AVMEDIA_TYPE_AUDIO)
  1101. {
  1102. //Don't fail if no audio stream just be done.
  1103. State = FfccState.Done;
  1104. Mode = FfccMode.NotInit;
  1105. return;
  1106. }
  1107. CheckReturn();
  1108. Decoder.StreamIndex = Return;
  1109. GetTags(ref Decoder.Stream->metadata);
  1110. Decoder.CodecContext = ffmpeg.avcodec_alloc_context3(Decoder.Codec);
  1111. if (Decoder.CodecContext == null)
  1112. {
  1113. Die("Could not allocate codec context");
  1114. }
  1115. Return = ffmpeg.avcodec_parameters_to_context(Decoder.CodecContext, Decoder.Stream->codecpar);
  1116. CheckReturn();
  1117. fixed (AVDictionary** tmp = &_dict)
  1118. {
  1119. Return = ffmpeg.av_dict_set(tmp, "strict", "+experimental", 0);
  1120. CheckReturn();
  1121. Return = ffmpeg.avcodec_open2(Decoder.CodecContext, Decoder.Codec, tmp);
  1122. CheckReturn();
  1123. }
  1124. if (MediaType == AVMediaType.AVMEDIA_TYPE_AUDIO)
  1125. {
  1126. if (Decoder.CodecContext->channel_layout == 0)
  1127. {
  1128. if (Decoder.CodecContext->channels == 2)
  1129. {
  1130. Decoder.CodecContext->channel_layout = ffmpeg.AV_CH_LAYOUT_STEREO;
  1131. }
  1132. else if (Decoder.CodecContext->channels == 1)
  1133. {
  1134. Decoder.CodecContext->channel_layout = ffmpeg.AV_CH_LAYOUT_MONO;
  1135. }
  1136. else
  1137. {
  1138. Die("must set custom channel layout, is not stereo or mono");
  1139. }
  1140. }
  1141. }
  1142. }
  1143. private void PrepareProcess()
  1144. {
  1145. using (DecodedMemoryStream = new MemoryStream())
  1146. {
  1147. Process();
  1148. LoadSoundFromStream();
  1149. }
  1150. }
  1151. /// <summary>
  1152. /// PrepareResampler
  1153. /// </summary>
  1154. private unsafe void PrepareResampler()
  1155. {
  1156. if (MediaType != AVMediaType.AVMEDIA_TYPE_AUDIO)
  1157. {
  1158. return;
  1159. }
  1160. //resampler
  1161. ResampleFrame = ffmpeg.av_frame_alloc();
  1162. if (ResampleFrame == null)
  1163. {
  1164. Die("Error allocating the frame\n");
  1165. }
  1166. ResampleContext = ffmpeg.swr_alloc();
  1167. ffmpeg.av_opt_set_channel_layout(ResampleContext, "in_channel_layout", (long)Decoder.CodecContext->channel_layout, 0);
  1168. ffmpeg.av_opt_set_int(ResampleContext, "in_sample_rate", Decoder.CodecContext->sample_rate, 0);
  1169. ffmpeg.av_opt_set_sample_fmt(ResampleContext, "in_sample_fmt", Decoder.CodecContext->sample_fmt, 0);
  1170. ffmpeg.av_opt_set_channel_layout(ResampleContext, "out_channel_layout", (long)Decoder.CodecContext->channel_layout, 0);
  1171. ffmpeg.av_opt_set_sample_fmt(ResampleContext, "out_sample_fmt", AVSampleFormat.AV_SAMPLE_FMT_S16, 0);
  1172. ffmpeg.av_opt_set_int(ResampleContext, "out_sample_rate", Decoder.CodecContext->sample_rate, 0);
  1173. Return = ffmpeg.swr_init(ResampleContext);
  1174. if (Return < 0)
  1175. {
  1176. Die("swr_init");
  1177. }
  1178. Decoder.Frame->format = (int)Decoder.CodecContext->sample_fmt;
  1179. Decoder.Frame->channel_layout = Decoder.CodecContext->channel_layout;
  1180. Decoder.Frame->channels = Decoder.CodecContext->channels;
  1181. Decoder.Frame->sample_rate = Decoder.CodecContext->sample_rate;
  1182. ResampleFrame->nb_samples = Decoder.CodecContext->frame_size;
  1183. if (ResampleFrame->nb_samples == 0)
  1184. {
  1185. ResampleFrame->nb_samples = 32; //32, or 64, ADPCM require 32.
  1186. }
  1187. ResampleFrame->format = (int)AVSampleFormat.AV_SAMPLE_FMT_S16;
  1188. ResampleFrame->channel_layout = Decoder.CodecContext->channel_layout;
  1189. ResampleFrame->channels = Decoder.CodecContext->channels;
  1190. ResampleFrame->sample_rate = Decoder.CodecContext->sample_rate;
  1191. var convertedFrameBufferSize = ffmpeg.av_samples_get_buffer_size(null, ResampleFrame->channels,
  1192. ResampleFrame->nb_samples,
  1193. (AVSampleFormat)ResampleFrame->format, 0);
  1194. //ConvertedData = (byte*)Marshal.AllocHGlobal(convertedFrameBufferSize);
  1195. ConvertedData = new byte[convertedFrameBufferSize];
  1196. if (_useNAudio) InitNaudio();
  1197. }
  1198. /// <summary>
  1199. /// Setup scaler for drawing frames to bitmap.
  1200. /// </summary>
  1201. private unsafe void PrepareScaler()
  1202. {
  1203. if (MediaType != AVMediaType.AVMEDIA_TYPE_VIDEO)
  1204. {
  1205. return;
  1206. }
  1207. ScalerContext = ffmpeg.sws_getContext(
  1208. Decoder.CodecContext->width, Decoder.CodecContext->height, Decoder.CodecContext->pix_fmt,
  1209. Decoder.CodecContext->width, Decoder.CodecContext->height, AVPixelFormat.AV_PIX_FMT_RGBA,
  1210. ffmpeg.SWS_ACCURATE_RND, null, null, null);
  1211. Return = ffmpeg.sws_init_context(ScalerContext, null, null);
  1212. CheckReturn();
  1213. }
  1214. /// <summary>
  1215. /// Decodes, Resamples, Encodes
  1216. /// </summary>
  1217. /// <ref>https://stackoverflow.com/questions/32051847/c-ffmpeg-distorted-sound-when-converting-audio?rq=1#_=_</ref>
  1218. private unsafe void Process()
  1219. {
  1220. while (Decode(out var decodedFrame))
  1221. {
  1222. if (MediaType == AVMediaType.AVMEDIA_TYPE_VIDEO)
  1223. {
  1224. if (Mode == FfccMode.StateMach)
  1225. {
  1226. State = FfccState.Waiting;
  1227. break;
  1228. }
  1229. // do something with video here.
  1230. if (Mode == FfccMode.ProcessAll)
  1231. {
  1232. }
  1233. }
  1234. else if (MediaType == AVMediaType.AVMEDIA_TYPE_AUDIO)
  1235. {
  1236. Resample(ref decodedFrame);
  1237. if (Mode == FfccMode.StateMach && !Behind) //still behind stay here.
  1238. {
  1239. State = FfccState.Waiting;
  1240. break;
  1241. }
  1242. }
  1243. }
  1244. if (State != FfccState.Waiting)
  1245. {
  1246. State = FfccState.Done;
  1247. Timer.Stop();
  1248. Timer.Reset();
  1249. DecodeFlush(ref Decoder.CodecContext, ref *Decoder.Packet); //calling this twice was causing issues.
  1250. }
  1251. }
  1252. /// <summary>
  1253. /// </summary>
  1254. /// <param name="waveInEventArgs"></param>
  1255. /// <see cref="https://markheath.net/post/how-to-record-and-play-audio-at-same"/>
  1256. private void RecorderOnDataAvailable(WaveInEventArgs waveInEventArgs)
  1257. {
  1258. #if _WINDOWS
  1259. if (_bufferedWaveProvider == null)
  1260. InitNaudio();
  1261. if (_useNAudio)
  1262. _bufferedWaveProvider.AddSamples(waveInEventArgs.Buffer, 0, waveInEventArgs.BytesRecorded);
  1263. #endif
  1264. }
  1265. /// <summary>
  1266. /// Resample current frame, Save output data
  1267. /// </summary>
  1268. /// <param name="frame">Current Decoded Frame</param>
  1269. private unsafe void Resample(ref AVFrame frame)
  1270. {
  1271. // Convert
  1272. int outSamples;
  1273. fixed (byte** tmp = (byte*[])frame.data)
  1274. {
  1275. outSamples = ffmpeg.swr_convert(ResampleContext, null, 0, tmp, frame.nb_samples);
  1276. }
  1277. if (outSamples < 0)
  1278. {
  1279. Die("Could not convert");
  1280. }
  1281. for (; ; )
  1282. {
  1283. // ReSharper disable once CommentTypo
  1284. //https://ffmpeg.org/doxygen/3.2/group__lswr.html#ga97a8d5f6abe3bcdfb6072412f17285a4
  1285. CheckReturn(outSamples = ffmpeg.swr_get_out_samples(ResampleContext, 0));
  1286. // 32 was nb_samples but if too big would just not decode anything
  1287. if (outSamples < 32 * ResampleFrame->channels)
  1288. {
  1289. break;
  1290. }
  1291. //fixed (byte** tmp = &_convertedData)
  1292. fixed (byte* tmp = &_convertedData[0])
  1293. {
  1294. //https://ffmpeg.org/doxygen/3.2/group__lswr.html#gaa5bb6cab830146efa8c760fa66ee582a
  1295. CheckReturn(ffmpeg.swr_convert(ResampleContext, &tmp, ResampleFrame->nb_samples, null, 0));
  1296. }
  1297. var bufferSize = ffmpeg.av_samples_get_buffer_size(null,
  1298. ResampleFrame->channels,
  1299. ResampleFrame->nb_samples,
  1300. (AVSampleFormat)ResampleFrame->format,
  1301. 0);
  1302. // write to buffer
  1303. WriteToMs(ref _convertedData, 0, ref bufferSize);
  1304. }
  1305. }
  1306. /// <summary>
  1307. /// Run code depending on state
  1308. /// </summary>
  1309. /// <param name="state">Change the state to this</param>
  1310. /// <param name="ret">return this</param>
  1311. /// <returns>ret</returns>
  1312. private int Update(FfccState state = FfccState.Null, int ret = 0)
  1313. {
  1314. if (Mode == FfccMode.NotInit)
  1315. {
  1316. Die("Class not Init");
  1317. }
  1318. if (state == FfccState.NoDLL)
  1319. {
  1320. return -1;
  1321. }
  1322. if (state != FfccState.Null)
  1323. {
  1324. State = state;
  1325. }
  1326. do
  1327. {
  1328. switch (State)
  1329. {
  1330. case FfccState.Open:
  1331. State = FfccState.GetCodec;
  1332. if (0 < Open())
  1333. {
  1334. Die("Failed to Open");
  1335. }
  1336. break;
  1337. case FfccState.GetCodec:
  1338. State = FfccState.PrepareResampler;
  1339. PrepareCodec();
  1340. break;
  1341. case FfccState.PrepareResampler:
  1342. State = FfccState.PrepareScaler;
  1343. PrepareResampler();
  1344. break;
  1345. case FfccState.PrepareScaler:
  1346. State = FfccState.Read;
  1347. PrepareScaler();
  1348. break;
  1349. case FfccState.Read://Enters waiting state unless we want to process all now.
  1350. State = Mode == FfccMode.ProcessAll ? FfccState.ReadAll : FfccState.ReadOne;
  1351. //ReadOne here makes it grab one video frame and pre-caches audio to it's limit.
  1352. //Waiting here makes it wait till GetFrame() is called.
  1353. //ReadAll just processes the whole audio stream (memory leaky), not meant for video
  1354. //Currently video will just saves all the frames to bmp in temp folder on ReadAll.
  1355. break;
  1356. case FfccState.ReadAll:
  1357. State = FfccState.Done;
  1358. PrepareProcess();
  1359. break;
  1360. case FfccState.ReadOne:
  1361. PrepareProcess();
  1362. switch (State)
  1363. {
  1364. case FfccState.Waiting:
  1365. ret = 0;
  1366. break;
  1367. default:
  1368. ret = -1;
  1369. break;
  1370. }
  1371. break;
  1372. default:
  1373. State = FfccState.Done;
  1374. break;
  1375. }
  1376. }
  1377. while (!((Mode == FfccMode.ProcessAll && State == FfccState.Done) || (State == FfccState.Done || State == FfccState.Waiting)));
  1378. return ret;
  1379. }
  1380. private void WriteToMs(ref byte[] output, int start, ref int length)
  1381. {
  1382. if (Mode == FfccMode.StateMach)
  1383. {
  1384. LoadSoundFromStream(ref output, start, ref length);
  1385. }
  1386. else
  1387. {
  1388. DecodedMemoryStream.Write(output, start, length);
  1389. }
  1390. }
  1391. #endregion Methods
  1392. }
  1393. }