MediaPlayerCtrl.cs 96 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354
  1. using UnityEngine;
  2. using System.Runtime.InteropServices;
  3. using System;
  4. using System.IO;
  5. using System.Collections;
  6. using System.Collections.Generic;
  7. using UnityEngine.UI;
  8. #if !UNITY_WEBPLAYER && !UNITY_WEBGL && !UNITY_WP8 && !UNITY_WP8_1
  9. using FFmpeg.AutoGen;
  10. using System.Threading;
  11. #endif
  12. #if UNITY_EDITOR || UNITY_STANDALONE
  13. public unsafe class MediaPlayerCtrl : MonoBehaviour {
  14. #else
  15. public class MediaPlayerCtrl : MonoBehaviour
  16. {
  17. #endif
  18. public string m_strFileName;
  19. public GameObject[] m_TargetMaterial = null;
  20. private Texture2D m_VideoTexture = null;
  21. private Texture2D m_VideoTextureDummy = null;
  22. private Texture2D m_VideoTextureY;
  23. private Texture2D m_VideoTextureU;
  24. private Texture2D m_VideoTextureV;
  25. private Texture2D m_VideoTextureDummyY;
  26. private Texture2D m_VideoTextureDummyU;
  27. private Texture2D m_VideoTextureDummyV;
  28. private MEDIAPLAYER_STATE m_CurrentState;
  29. private int m_iCurrentSeekPosition;
  30. private float m_fVolume = 1.0f;
  31. private int m_iWidth;
  32. private int m_iHeight;
  33. private float m_fSpeed = 1.0f;
  34. public bool m_bFullScreen = false;//Please use only in FullScreen prefab.
  35. public bool m_bSupportRockchip = true; //Using a device support Rochchip or Low-end devices
  36. //(Reason 1 : Not directly play in StreamingAssets)
  37. //(Reason 2 : Video buffer is RGB565 only supported)
  38. public bool m_bPC_FastMode = false;
  39. public delegate void VideoEnd();
  40. public delegate void VideoReady();
  41. public delegate void VideoError(MEDIAPLAYER_ERROR errorCode, MEDIAPLAYER_ERROR errorCodeExtra);
  42. public delegate void VideoFirstFrameReady();
  43. public delegate void VideoResize ();
  44. public VideoResize OnResize;
  45. public VideoReady OnReady;
  46. public VideoEnd OnEnd;
  47. public VideoError OnVideoError;
  48. public VideoFirstFrameReady OnVideoFirstFrameReady;
  49. private IntPtr m_texPtr;
  50. private IntPtr m_texPtrY;
  51. private IntPtr m_texPtrU;
  52. private IntPtr m_texPtrV;
  53. public Shader m_shaderYUV;
  54. #if UNITY_IPHONE || UNITY_TVOS
  55. private int m_iPauseFrame;
  56. #endif
  57. #if UNITY_ANDROID && !UNITY_EDITOR && (UNITY_5 || UNITY_5_3_OR_NEWER)
  58. [DllImport ("BlueDoveMediaRender")]
  59. private static extern void InitNDK();
  60. #if UNITY_5_2 || UNITY_5_3_OR_NEWER
  61. [DllImport ("BlueDoveMediaRender")]
  62. private static extern IntPtr EasyMovieTextureRender();
  63. #endif
  64. #endif
  65. #if (UNITY_STANDALONE_WIN || UNITY_EDITOR_WIN) && !UNITY_EDITOR_OSX
  66. [DllImport ("EasyMovieTexture")]
  67. private static extern int SetTexture();
  68. [DllImport ("EasyMovieTexture")]
  69. private static extern void ReleaseTexture(int iID);
  70. [DllImport ("EasyMovieTexture")]
  71. private static extern void SetTextureFromUnity(int iID,System.IntPtr texture,System.IntPtr textureY,System.IntPtr textureU,System.IntPtr textureV, int w, int h,byte[] data);
  72. [DllImport("EasyMovieTexture")]
  73. private static extern IntPtr GetRenderEventFunc();
  74. #endif
  75. #if (UNITY_STANDALONE_OSX || UNITY_EDITOR_OSX )
  76. [DllImport ("EasyMovieTextureRender")]
  77. private static extern int SetTexture();
  78. [DllImport ("EasyMovieTextureRender")]
  79. private static extern void ReleaseTexture(int iID);
  80. [DllImport ("EasyMovieTextureRender")]
  81. private static extern void SetTextureFromUnity(int iID,System.IntPtr texture,System.IntPtr textureY,System.IntPtr textureU,System.IntPtr textureV, int w, int h,byte[] data);
  82. [DllImport("EasyMovieTextureRender")]
  83. private static extern IntPtr GetRenderEventFunc();
  84. #endif
  85. private int m_iAndroidMgrID;
  86. private bool m_bIsFirstFrameReady;
  87. public enum MEDIAPLAYER_ERROR
  88. {
  89. MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK = 200,
  90. MEDIA_ERROR_IO = -1004,
  91. MEDIA_ERROR_MALFORMED = -1007,
  92. MEDIA_ERROR_TIMED_OUT = -110,
  93. MEDIA_ERROR_UNSUPPORTED = -1010,
  94. MEDIA_ERROR_SERVER_DIED = 100,
  95. MEDIA_ERROR_UNKNOWN = 1
  96. }
  97. public enum MEDIAPLAYER_STATE
  98. {
  99. NOT_READY = 0,
  100. READY = 1,
  101. END = 2,
  102. PLAYING = 3,
  103. PAUSED = 4,
  104. STOPPED = 5,
  105. ERROR = 6
  106. }
  107. public enum MEDIA_SCALE
  108. {
  109. SCALE_X_TO_Y = 0,
  110. SCALE_X_TO_Z = 1,
  111. SCALE_Y_TO_X = 2,
  112. SCALE_Y_TO_Z = 3,
  113. SCALE_Z_TO_X = 4,
  114. SCALE_Z_TO_Y = 5,
  115. SCALE_X_TO_Y_2 = 6,
  116. }
  117. bool m_bFirst = false;
  118. public MEDIA_SCALE m_ScaleValue;
  119. public GameObject[] m_objResize = null;
  120. public bool m_bLoop = false;
  121. public bool m_bAutoPlay = true;
  122. private bool m_bStop = false;
  123. private bool m_bInit = false;
  124. #if !UNITY_WEBPLAYER && !UNITY_WEBGL && !UNITY_WP8 && !UNITY_WP8_1
  125. static MediaPlayerCtrl()
  126. {
  127. #if UNITY_EDITOR
  128. String currentPath = Environment.GetEnvironmentVariable ("PATH", EnvironmentVariableTarget.Process);
  129. String dllPath = Environment.CurrentDirectory + Path.DirectorySeparatorChar + "Assets" + Path.DirectorySeparatorChar + "Plugins";
  130. if (currentPath.Contains (dllPath) == false) {
  131. Environment.SetEnvironmentVariable ("PATH", currentPath + Path.PathSeparator + dllPath, EnvironmentVariableTarget.Process);
  132. }
  133. dllPath = Environment.CurrentDirectory + Path.DirectorySeparatorChar + "Assets" + Path.DirectorySeparatorChar + "Plugins" + Path.DirectorySeparatorChar + "x64";
  134. if (currentPath.Contains (dllPath) == false) {
  135. Environment.SetEnvironmentVariable ("PATH", currentPath + Path.PathSeparator + dllPath, EnvironmentVariableTarget.Process);
  136. }
  137. dllPath = Environment.CurrentDirectory + Path.DirectorySeparatorChar + "Assets" + Path.DirectorySeparatorChar + "Plugins" + Path.DirectorySeparatorChar + "x86";
  138. if (currentPath.Contains (dllPath) == false) {
  139. Environment.SetEnvironmentVariable ("PATH", currentPath + Path.PathSeparator + dllPath, EnvironmentVariableTarget.Process);
  140. }
  141. #endif
  142. }
  143. void Awake()
  144. {
  145. #if UNITY_STANDALONE
  146. String currentPath = Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Process);
  147. String dllPath = Application.dataPath + Path.DirectorySeparatorChar + "Plugins";
  148. if(currentPath.Contains(dllPath) == false)
  149. {
  150. Environment.SetEnvironmentVariable("PATH", currentPath + Path.PathSeparator + dllPath, EnvironmentVariableTarget.Process);
  151. }
  152. #endif
  153. if (SystemInfo.deviceModel.Contains("rockchip"))
  154. {
  155. m_bSupportRockchip = true;
  156. }
  157. else
  158. {
  159. m_bSupportRockchip = false;
  160. }
  161. #if UNITY_IPHONE || UNITY_TVOS || UNITY_EDITOR || UNITY_STANDALONE
  162. if(m_TargetMaterial!=null)
  163. {
  164. for( int iIndex = 0; iIndex < m_TargetMaterial.Length; iIndex++)
  165. {
  166. if( m_TargetMaterial[iIndex] != null)
  167. {
  168. if(m_TargetMaterial[iIndex].GetComponent<MeshFilter>() != null)
  169. {
  170. Vector2 [] vec2UVs= m_TargetMaterial[iIndex].GetComponent<MeshFilter>().mesh.uv;
  171. for(int i = 0; i < vec2UVs.Length; i++)
  172. {
  173. vec2UVs[i] = new Vector2(vec2UVs[i].x, 1.0f -vec2UVs[i].y);
  174. }
  175. m_TargetMaterial[iIndex].GetComponent<MeshFilter>().mesh.uv = vec2UVs;
  176. }
  177. if(m_TargetMaterial[iIndex].GetComponent<RawImage>() != null)
  178. {
  179. m_TargetMaterial[iIndex].GetComponent<RawImage>().uvRect = new Rect(0,1,1,-1);
  180. }
  181. }
  182. }
  183. }
  184. #endif
  185. #if UNITY_STANDALONE || UNITY_EDITOR
  186. //RegisterDebugCallback(new DebugCallback(DebugMethod));
  187. //threadVideo = new Thread(ThreadUpdate);
  188. //threadVideo.Start();
  189. #endif
  190. #if UNITY_ANDROID && !UNITY_EDITOR
  191. #if UNITY_5 || UNITY_5_3_OR_NEWER
  192. if( SystemInfo.graphicsMultiThreaded == true)
  193. InitNDK();
  194. #endif
  195. m_iAndroidMgrID = Call_InitNDK();
  196. #endif
  197. Call_SetUnityActivity();
  198. }
  199. // Use this for initialization
  200. void Start()
  201. {
  202. #if UNITY_ANDROID
  203. if (Application.dataPath.Contains(".obb")) {
  204. Call_SetSplitOBB(true,Application.dataPath);
  205. }
  206. else
  207. {
  208. Call_SetSplitOBB(false, null);
  209. }
  210. #endif
  211. m_bInit = true;
  212. }
  213. void OnApplicationQuit()
  214. {
  215. //if (System.IO.Directory.Exists(Application.persistentDataPath + "/Data") == true)
  216. // System.IO.Directory.Delete(Application.persistentDataPath + "/Data", true);
  217. }
  218. bool m_bCheckFBO = false;
  219. void OnDisable()
  220. {
  221. if (GetCurrentState() == MEDIAPLAYER_STATE.PLAYING)
  222. {
  223. Pause();
  224. }
  225. }
  226. void OnEnable()
  227. {
  228. if (GetCurrentState() == MEDIAPLAYER_STATE.PAUSED)
  229. {
  230. Play();
  231. }
  232. }
  233. void Update()
  234. {
  235. if (string.IsNullOrEmpty(m_strFileName))
  236. {
  237. return;
  238. }
  239. if (checkNewActions)
  240. {
  241. checkNewActions = false;
  242. CheckThreading ();
  243. }
  244. if (m_bFirst == false)
  245. {
  246. string strName = m_strFileName.Trim();
  247. #if UNITY_IPHONE || UNITY_TVOS
  248. /*if (strName.StartsWith("http",StringComparison.OrdinalIgnoreCase))
  249. {
  250. StartCoroutine( DownloadStreamingVideoAndLoad(strName) );
  251. }
  252. else*/
  253. {
  254. Call_Load(strName,0);
  255. }
  256. #elif UNITY_ANDROID
  257. if(m_bSupportRockchip)
  258. {
  259. Call_SetRockchip(m_bSupportRockchip);
  260. if(strName.Contains("://"))
  261. {
  262. Call_Load(strName,0);
  263. }
  264. else
  265. {
  266. //Call_Load(strName,0);
  267. StartCoroutine( CopyStreamingAssetVideoAndLoad(strName));
  268. }
  269. }
  270. else
  271. {
  272. Call_Load(strName,0);
  273. }
  274. #elif UNITY_STANDALONE
  275. Call_Load(strName,0);
  276. #endif
  277. Call_SetLooping(m_bLoop);
  278. m_bFirst = true;
  279. }
  280. if (m_CurrentState == MEDIAPLAYER_STATE.PLAYING || m_CurrentState == MEDIAPLAYER_STATE.PAUSED)
  281. {
  282. if (m_bCheckFBO == false) {
  283. if (Call_GetVideoWidth () <= 0 || Call_GetVideoHeight () <= 0) {
  284. return;
  285. }
  286. m_iWidth = Call_GetVideoWidth ();
  287. m_iHeight = Call_GetVideoHeight ();
  288. Resize ();
  289. if (m_VideoTexture != null) {
  290. //Destroy(m_VideoTexture);
  291. if (m_VideoTextureDummy != null) {
  292. Destroy (m_VideoTextureDummy);
  293. m_VideoTextureDummy = null;
  294. }
  295. m_VideoTextureDummy = m_VideoTexture;
  296. m_VideoTexture = null;
  297. }
  298. if (m_VideoTextureY != null) {
  299. if (m_VideoTextureDummyY != null) {
  300. Destroy (m_VideoTextureDummyY);
  301. m_VideoTextureDummyY = null;
  302. }
  303. m_VideoTextureDummyY = m_VideoTextureY;
  304. m_VideoTextureY = null;
  305. }
  306. if (m_VideoTextureU != null) {
  307. if (m_VideoTextureDummyU != null) {
  308. Destroy (m_VideoTextureDummyU);
  309. m_VideoTextureDummyU = null;
  310. }
  311. m_VideoTextureDummyU = m_VideoTextureU;
  312. m_VideoTextureU = null;
  313. }
  314. if (m_VideoTextureV != null) {
  315. if (m_VideoTextureDummyV != null) {
  316. Destroy (m_VideoTextureDummyV);
  317. m_VideoTextureDummyV = null;
  318. }
  319. m_VideoTextureDummyV = m_VideoTextureV;
  320. m_VideoTextureV = null;
  321. }
  322. #if UNITY_ANDROID || UNITY_EDITOR || UNITY_STANDALONE
  323. #if UNITY_EDITOR || UNITY_STANDALONE
  324. if(m_bPC_FastMode == true)
  325. {
  326. m_VideoTextureY = new Texture2D (Call_GetVideoWidth (), Call_GetVideoHeight (), TextureFormat.Alpha8, false);
  327. m_VideoTextureU = new Texture2D (Call_GetVideoWidth () / 2, Call_GetVideoHeight () / 2, TextureFormat.Alpha8, false);
  328. m_VideoTextureV = new Texture2D (Call_GetVideoWidth () / 2, Call_GetVideoHeight () / 2, TextureFormat.Alpha8, false);
  329. m_VideoTextureY.filterMode = FilterMode.Bilinear;
  330. m_VideoTextureY.wrapMode = TextureWrapMode.Clamp;
  331. m_VideoTextureU.filterMode = FilterMode.Bilinear;
  332. m_VideoTextureU.wrapMode = TextureWrapMode.Clamp;
  333. m_VideoTextureV.filterMode = FilterMode.Bilinear;
  334. m_VideoTextureV.wrapMode = TextureWrapMode.Clamp;
  335. }
  336. else
  337. {
  338. if (m_bSupportRockchip) {
  339. m_VideoTexture = new Texture2D (Call_GetVideoWidth (), Call_GetVideoHeight (), TextureFormat.RGB565, false);
  340. } else {
  341. m_VideoTexture = new Texture2D (Call_GetVideoWidth (), Call_GetVideoHeight (), TextureFormat.RGBA32, false);
  342. }
  343. m_VideoTexture.filterMode = FilterMode.Bilinear;
  344. m_VideoTexture.wrapMode = TextureWrapMode.Clamp;
  345. }
  346. if(m_bPC_FastMode == true)
  347. {
  348. m_texPtrY = m_VideoTextureY.GetNativeTexturePtr ();
  349. m_texPtrU = m_VideoTextureU.GetNativeTexturePtr ();
  350. m_texPtrV = m_VideoTextureV.GetNativeTexturePtr ();
  351. }
  352. else
  353. {
  354. m_texPtr = m_VideoTexture.GetNativeTexturePtr ();
  355. }
  356. #else
  357. if (m_bSupportRockchip) {
  358. m_VideoTexture = new Texture2D (Call_GetVideoWidth (), Call_GetVideoHeight (), TextureFormat.RGB565, false);
  359. } else {
  360. m_VideoTexture = new Texture2D (Call_GetVideoWidth (), Call_GetVideoHeight (), TextureFormat.RGBA32, false);
  361. }
  362. m_VideoTexture.filterMode = FilterMode.Bilinear;
  363. m_VideoTexture.wrapMode = TextureWrapMode.Clamp;
  364. m_texPtr = m_VideoTexture.GetNativeTexturePtr ();
  365. #endif
  366. #if UNITY_5_2 || UNITY_5_3_OR_NEWER
  367. Call_SetUnityTexture((int)m_texPtr);
  368. #else
  369. Call_SetUnityTexture (m_VideoTexture.GetNativeTextureID ());
  370. #endif
  371. #endif
  372. Call_SetWindowSize ();
  373. m_bCheckFBO = true;
  374. if (OnResize != null)
  375. OnResize ();
  376. } else {
  377. if (Call_GetVideoWidth () != m_iWidth || Call_GetVideoHeight () != m_iHeight) {
  378. m_iWidth = Call_GetVideoWidth ();
  379. m_iHeight = Call_GetVideoHeight ();
  380. if (OnResize != null)
  381. OnResize ();
  382. ResizeTexture ();
  383. }
  384. }
  385. Call_UpdateVideoTexture();
  386. m_iCurrentSeekPosition = Call_GetSeekPosition();
  387. }
  388. if (m_CurrentState != Call_GetStatus())
  389. {
  390. m_CurrentState = Call_GetStatus();
  391. if (m_CurrentState == MEDIAPLAYER_STATE.READY)
  392. {
  393. if (OnReady != null)
  394. OnReady();
  395. if (m_bAutoPlay)
  396. Call_Play(0);
  397. if (m_bReadyPlay) {
  398. Call_Play(0);
  399. m_bReadyPlay = false;
  400. }
  401. SetVolume(m_fVolume);
  402. }
  403. else if (m_CurrentState == MEDIAPLAYER_STATE.END)
  404. {
  405. if (OnEnd != null)
  406. OnEnd();
  407. if (m_bLoop == true)
  408. {
  409. Call_Play(0);
  410. }
  411. }
  412. else if (m_CurrentState == MEDIAPLAYER_STATE.ERROR)
  413. {
  414. OnError((MEDIAPLAYER_ERROR)Call_GetError(), (MEDIAPLAYER_ERROR)Call_GetErrorExtra());
  415. }
  416. }
  417. GL.InvalidateState ();
  418. }
  419. public void DeleteVideoTexture()
  420. {
  421. if (m_VideoTextureDummy != null)
  422. {
  423. Destroy(m_VideoTextureDummy);
  424. m_VideoTextureDummy = null;
  425. }
  426. if (m_VideoTexture != null)
  427. {
  428. Destroy(m_VideoTexture);
  429. m_VideoTexture = null;
  430. }
  431. if (m_VideoTextureDummyY != null)
  432. {
  433. Destroy(m_VideoTextureDummyY);
  434. m_VideoTextureDummyY = null;
  435. }
  436. if (m_VideoTextureY != null)
  437. {
  438. Destroy(m_VideoTextureY);
  439. m_VideoTextureY = null;
  440. }
  441. if (m_VideoTextureDummyU != null)
  442. {
  443. Destroy(m_VideoTextureDummyU);
  444. m_VideoTextureDummyU = null;
  445. }
  446. if (m_VideoTextureU != null)
  447. {
  448. Destroy(m_VideoTextureU);
  449. m_VideoTextureU = null;
  450. }
  451. if (m_VideoTextureDummyV != null)
  452. {
  453. Destroy(m_VideoTextureDummyV);
  454. m_VideoTextureDummyV = null;
  455. }
  456. if (m_VideoTextureV != null)
  457. {
  458. Destroy(m_VideoTextureV);
  459. m_VideoTextureV = null;
  460. }
  461. }
  462. public void ResizeTexture()
  463. {
  464. Debug.Log ("ResizeTexture " + m_iWidth + " " + m_iHeight);
  465. if (m_iWidth == 0 || m_iHeight == 0)
  466. return;
  467. if (m_VideoTexture != null) {
  468. //Destroy(m_VideoTexture);
  469. if (m_VideoTextureDummy != null) {
  470. Destroy (m_VideoTextureDummy);
  471. m_VideoTextureDummy = null;
  472. }
  473. m_VideoTextureDummy = m_VideoTexture;
  474. m_VideoTexture = null;
  475. }
  476. if (m_VideoTextureY != null) {
  477. if (m_VideoTextureDummyY != null) {
  478. Destroy (m_VideoTextureDummyY);
  479. m_VideoTextureDummyY = null;
  480. }
  481. m_VideoTextureDummyY = m_VideoTextureY;
  482. m_VideoTextureY = null;
  483. }
  484. if (m_VideoTextureU != null) {
  485. if (m_VideoTextureDummyU != null) {
  486. Destroy (m_VideoTextureDummyU);
  487. m_VideoTextureDummyU = null;
  488. }
  489. m_VideoTextureDummyU = m_VideoTextureU;
  490. m_VideoTextureU = null;
  491. }
  492. if (m_VideoTextureV != null) {
  493. if (m_VideoTextureDummyV != null) {
  494. Destroy (m_VideoTextureDummyV);
  495. m_VideoTextureDummyV = null;
  496. }
  497. m_VideoTextureDummyV = m_VideoTextureV;
  498. m_VideoTextureV = null;
  499. }
  500. #if UNITY_IPHONE && !UNITY_EDITOR
  501. _videoTexture =null;
  502. bFirstIOS = true;
  503. #endif
  504. #if UNITY_ANDROID || UNITY_EDITOR || UNITY_STANDALONE
  505. #if UNITY_EDITOR || UNITY_STANDALONE
  506. if(m_bPC_FastMode == true)
  507. {
  508. m_VideoTextureY = new Texture2D (Call_GetVideoWidth (), Call_GetVideoHeight (), TextureFormat.Alpha8, false);
  509. m_VideoTextureU = new Texture2D (Call_GetVideoWidth () / 2, Call_GetVideoHeight () / 2, TextureFormat.Alpha8, false);
  510. m_VideoTextureV = new Texture2D (Call_GetVideoWidth () / 2, Call_GetVideoHeight () / 2, TextureFormat.Alpha8, false);
  511. }
  512. else
  513. {
  514. if (m_bSupportRockchip) {
  515. m_VideoTexture = new Texture2D (Call_GetVideoWidth (), Call_GetVideoHeight (), TextureFormat.RGB565, false);
  516. } else {
  517. m_VideoTexture = new Texture2D (Call_GetVideoWidth (), Call_GetVideoHeight (), TextureFormat.RGBA32, false);
  518. }
  519. }
  520. m_VideoTexture.filterMode = FilterMode.Bilinear;
  521. m_VideoTexture.wrapMode = TextureWrapMode.Clamp;
  522. if(m_bPC_FastMode == true)
  523. {
  524. m_texPtrY = m_VideoTextureY.GetNativeTexturePtr ();
  525. m_texPtrU = m_VideoTextureU.GetNativeTexturePtr ();
  526. m_texPtrV = m_VideoTextureV.GetNativeTexturePtr ();
  527. }
  528. else
  529. {
  530. m_texPtr = m_VideoTexture.GetNativeTexturePtr ();
  531. }
  532. #else
  533. if (m_bSupportRockchip) {
  534. m_VideoTexture = new Texture2D (Call_GetVideoWidth (), Call_GetVideoHeight (), TextureFormat.RGB565, false);
  535. } else {
  536. m_VideoTexture = new Texture2D (Call_GetVideoWidth (), Call_GetVideoHeight (), TextureFormat.RGBA32, false);
  537. }
  538. m_VideoTexture.filterMode = FilterMode.Bilinear;
  539. m_VideoTexture.wrapMode = TextureWrapMode.Clamp;
  540. m_texPtr = m_VideoTexture.GetNativeTexturePtr ();
  541. #endif
  542. #if UNITY_5_2 || UNITY_5_3_OR_NEWER
  543. Call_SetUnityTexture((int)m_texPtr);
  544. #else
  545. Call_SetUnityTexture (m_VideoTexture.GetNativeTextureID ());
  546. #endif
  547. #endif
  548. Call_SetWindowSize ();
  549. }
  550. public void Resize()
  551. {
  552. if (m_CurrentState != MEDIAPLAYER_STATE.PLAYING)
  553. return;
  554. if (Call_GetVideoWidth() <= 0 || Call_GetVideoHeight() <= 0)
  555. {
  556. return;
  557. }
  558. if (m_objResize != null)
  559. {
  560. int iScreenWidth = Screen.width;
  561. int iScreenHeight = Screen.height;
  562. float fRatioScreen = (float)iScreenHeight / (float)iScreenWidth;
  563. int iWidth = Call_GetVideoWidth();
  564. int iHeight = Call_GetVideoHeight();
  565. float fRatio = (float)iHeight / (float)iWidth;
  566. float fRatioResult = fRatioScreen / fRatio;
  567. for (int i = 0; i < m_objResize.Length; i++)
  568. {
  569. if (m_objResize[i] == null)
  570. continue;
  571. if (m_bFullScreen)
  572. {
  573. m_objResize[i].transform.localScale = new Vector3(20.0f / fRatioScreen, 20.0f / fRatioScreen, 1.0f);
  574. if (fRatio < 1.0f)
  575. {
  576. if (fRatioScreen < 1.0f)
  577. {
  578. if (fRatio > fRatioScreen)
  579. {
  580. m_objResize[i].transform.localScale *= fRatioResult;
  581. }
  582. }
  583. m_ScaleValue = MEDIA_SCALE.SCALE_X_TO_Y;
  584. }
  585. else
  586. {
  587. if (fRatioScreen > 1.0f) {
  588. if (fRatio >= fRatioScreen) {
  589. m_objResize [i].transform.localScale *= fRatioResult;
  590. }
  591. } else {
  592. m_objResize [i].transform.localScale *= fRatioResult;
  593. }
  594. m_ScaleValue = MEDIA_SCALE.SCALE_X_TO_Y;
  595. }
  596. }
  597. if (m_ScaleValue == MEDIA_SCALE.SCALE_X_TO_Y)
  598. {
  599. m_objResize[i].transform.localScale
  600. = new Vector3(m_objResize[i].transform.localScale.x
  601. , m_objResize[i].transform.localScale.x * fRatio
  602. , m_objResize[i].transform.localScale.z);
  603. }
  604. else if (m_ScaleValue == MEDIA_SCALE.SCALE_X_TO_Y_2)
  605. {
  606. m_objResize[i].transform.localScale
  607. = new Vector3(m_objResize[i].transform.localScale.x
  608. , m_objResize[i].transform.localScale.x * fRatio / 2.0f
  609. , m_objResize[i].transform.localScale.z);
  610. }
  611. else if (m_ScaleValue == MEDIA_SCALE.SCALE_X_TO_Z)
  612. {
  613. m_objResize[i].transform.localScale
  614. = new Vector3(m_objResize[i].transform.localScale.x
  615. , m_objResize[i].transform.localScale.y
  616. , m_objResize[i].transform.localScale.x * fRatio);
  617. }
  618. else if (m_ScaleValue == MEDIA_SCALE.SCALE_Y_TO_X)
  619. {
  620. m_objResize[i].transform.localScale
  621. = new Vector3(m_objResize[i].transform.localScale.y / fRatio
  622. , m_objResize[i].transform.localScale.y
  623. , m_objResize[i].transform.localScale.z);
  624. }
  625. else if (m_ScaleValue == MEDIA_SCALE.SCALE_Y_TO_Z)
  626. {
  627. m_objResize[i].transform.localScale
  628. = new Vector3(m_objResize[i].transform.localScale.x
  629. , m_objResize[i].transform.localScale.y
  630. , m_objResize[i].transform.localScale.y / fRatio);
  631. }
  632. else if (m_ScaleValue == MEDIA_SCALE.SCALE_Z_TO_X)
  633. {
  634. m_objResize[i].transform.localScale
  635. = new Vector3(m_objResize[i].transform.localScale.z * fRatio
  636. , m_objResize[i].transform.localScale.y
  637. , m_objResize[i].transform.localScale.z);
  638. }
  639. else if (m_ScaleValue == MEDIA_SCALE.SCALE_Z_TO_Y)
  640. {
  641. m_objResize[i].transform.localScale
  642. = new Vector3(m_objResize[i].transform.localScale.x
  643. , m_objResize[i].transform.localScale.z * fRatio
  644. , m_objResize[i].transform.localScale.z);
  645. }
  646. else
  647. {
  648. m_objResize[i].transform.localScale
  649. = new Vector3(m_objResize[i].transform.localScale.x, m_objResize[i].transform.localScale.y, m_objResize[i].transform.localScale.z);
  650. }
  651. }
  652. }
  653. }
  654. //The error code is the following sites related documents.
  655. //http://developer.android.com/reference/android/media/MediaPlayer.OnErrorListener.html
  656. void OnError(MEDIAPLAYER_ERROR iCode, MEDIAPLAYER_ERROR iCodeExtra)
  657. {
  658. string strError = "";
  659. switch (iCode)
  660. {
  661. case MEDIAPLAYER_ERROR.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
  662. strError = "MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK";
  663. break;
  664. case MEDIAPLAYER_ERROR.MEDIA_ERROR_SERVER_DIED:
  665. strError = "MEDIA_ERROR_SERVER_DIED";
  666. break;
  667. case MEDIAPLAYER_ERROR.MEDIA_ERROR_UNKNOWN:
  668. strError = "MEDIA_ERROR_UNKNOWN";
  669. break;
  670. default:
  671. strError = "Unknown error " + iCode;
  672. break;
  673. }
  674. strError += " ";
  675. switch (iCodeExtra)
  676. {
  677. case MEDIAPLAYER_ERROR.MEDIA_ERROR_IO:
  678. strError += "MEDIA_ERROR_IO";
  679. break;
  680. case MEDIAPLAYER_ERROR.MEDIA_ERROR_MALFORMED:
  681. strError += "MEDIA_ERROR_MALFORMED";
  682. break;
  683. case MEDIAPLAYER_ERROR.MEDIA_ERROR_TIMED_OUT:
  684. strError += "MEDIA_ERROR_TIMED_OUT";
  685. break;
  686. case MEDIAPLAYER_ERROR.MEDIA_ERROR_UNSUPPORTED:
  687. strError += "MEDIA_ERROR_UNSUPPORTED";
  688. break;
  689. default:
  690. strError = "Unknown error " + iCode;
  691. break;
  692. }
  693. Debug.LogError(strError);
  694. if (OnVideoError != null)
  695. {
  696. OnVideoError(iCode, iCodeExtra);
  697. }
  698. }
  699. void OnDestroy()
  700. {
  701. #if UNITY_ANDROID
  702. //Call_Reset();
  703. #endif
  704. Call_UnLoad();
  705. DeleteVideoTexture ();
  706. Call_Destroy();
  707. }
  708. bool m_bPause = false;
  709. void OnApplicationPause(bool bPause)
  710. {
  711. Debug.Log("ApplicationPause : " + bPause);
  712. if (bPause == true)
  713. {
  714. if (m_CurrentState == MEDIAPLAYER_STATE.PAUSED)
  715. {
  716. m_bPause = true;
  717. }
  718. #if (UNITY_IPHONE || UNITY_TVOS) && !UNITY_EDITOR
  719. if (m_CurrentState == MEDIAPLAYER_STATE.PLAYING)
  720. {
  721. m_iPauseFrame = m_iCurrentSeekPosition;
  722. Stop();
  723. //Pause();
  724. }
  725. else
  726. {
  727. m_iPauseFrame = 0;
  728. }
  729. #else
  730. Call_Pause();
  731. #endif
  732. }
  733. else
  734. {
  735. #if ( UNITY_IPHONE || UNITY_TVOS )&& !UNITY_EDITOR
  736. if (m_iPauseFrame != 0)
  737. {
  738. m_bStop = false;
  739. Call_Play(m_iPauseFrame);
  740. //Call_Play();
  741. //Call_RePlay();
  742. }
  743. #else
  744. Call_RePlay();
  745. #endif
  746. if (m_bPause == true)
  747. {
  748. Call_Pause();
  749. m_bPause = false;
  750. }
  751. }
  752. }
  753. public MEDIAPLAYER_STATE GetCurrentState()
  754. {
  755. return m_CurrentState;
  756. }
  757. public Texture2D GetVideoTexture()
  758. {
  759. return m_VideoTexture;
  760. }
  761. bool m_bReadyPlay = false;
  762. public void Play()
  763. {
  764. if (m_bStop == true)
  765. {
  766. SeekTo(0);
  767. Call_Play(0);
  768. m_bStop = false;
  769. }
  770. if (m_CurrentState == MEDIAPLAYER_STATE.PAUSED)
  771. {
  772. Call_RePlay ();
  773. }
  774. else if (m_CurrentState == MEDIAPLAYER_STATE.READY || m_CurrentState == MEDIAPLAYER_STATE.STOPPED || m_CurrentState == MEDIAPLAYER_STATE.END)
  775. {
  776. Call_Play (0);
  777. }
  778. else if (m_CurrentState == MEDIAPLAYER_STATE.NOT_READY)
  779. {
  780. m_bReadyPlay = true;
  781. }
  782. }
  783. public void Stop()
  784. {
  785. if (m_CurrentState == MEDIAPLAYER_STATE.PLAYING)
  786. Call_Pause();
  787. m_bStop = true;
  788. m_CurrentState = MEDIAPLAYER_STATE.STOPPED;
  789. m_iCurrentSeekPosition = 0;
  790. }
  791. public void Pause()
  792. {
  793. if (m_CurrentState == MEDIAPLAYER_STATE.PLAYING)
  794. {
  795. Call_Pause();
  796. m_CurrentState = MEDIAPLAYER_STATE.PAUSED;
  797. }
  798. }
  799. public void Load(string strFileName)
  800. {
  801. if (GetCurrentState() != MEDIAPLAYER_STATE.NOT_READY)
  802. UnLoad();
  803. m_bReadyPlay = false;
  804. m_bIsFirstFrameReady = false;
  805. m_bFirst = false;
  806. m_bCheckFBO = false;
  807. m_strFileName = strFileName;
  808. if (m_bInit == false)
  809. return;
  810. m_CurrentState = MEDIAPLAYER_STATE.NOT_READY;
  811. }
  812. public void SetVolume(float fVolume)
  813. {
  814. if (m_CurrentState == MEDIAPLAYER_STATE.PLAYING || m_CurrentState == MEDIAPLAYER_STATE.PAUSED || m_CurrentState == MEDIAPLAYER_STATE.END || m_CurrentState == MEDIAPLAYER_STATE.READY || m_CurrentState == MEDIAPLAYER_STATE.STOPPED)
  815. {
  816. m_fVolume = fVolume;
  817. Call_SetVolume(fVolume);
  818. }
  819. }
  820. //return milisecond
  821. public int GetSeekPosition()
  822. {
  823. if (m_CurrentState == MEDIAPLAYER_STATE.PLAYING || m_CurrentState == MEDIAPLAYER_STATE.PAUSED || m_CurrentState == MEDIAPLAYER_STATE.END)
  824. return m_iCurrentSeekPosition;
  825. else
  826. return 0;
  827. }
  828. public void SeekTo(int iSeek)
  829. {
  830. if (m_CurrentState == MEDIAPLAYER_STATE.PLAYING || m_CurrentState == MEDIAPLAYER_STATE.READY || m_CurrentState == MEDIAPLAYER_STATE.PAUSED || m_CurrentState == MEDIAPLAYER_STATE.END || m_CurrentState == MEDIAPLAYER_STATE.STOPPED)
  831. Call_SetSeekPosition(iSeek);
  832. }
  833. /// <summary>
  834. /// Sets the speed.
  835. /// Experimental API( PC&iOS support, support from Android version 6.0 or later)
  836. /// </summary>
  837. /// <param name="fSpeed">video playback speed.</param>
  838. public void SetSpeed(float fSpeed)
  839. {
  840. if (m_CurrentState == MEDIAPLAYER_STATE.PLAYING || m_CurrentState == MEDIAPLAYER_STATE.READY || m_CurrentState == MEDIAPLAYER_STATE.PAUSED || m_CurrentState == MEDIAPLAYER_STATE.END || m_CurrentState == MEDIAPLAYER_STATE.STOPPED) {
  841. m_fSpeed = fSpeed;
  842. Call_SetSpeed (fSpeed);
  843. }
  844. }
  845. //Gets the duration of the file.
  846. //Returns
  847. //the duration in milliseconds, if no duration is available (for example, if streaming live content), -1 is returned.
  848. public int GetDuration()
  849. {
  850. if (m_CurrentState == MEDIAPLAYER_STATE.PLAYING || m_CurrentState == MEDIAPLAYER_STATE.PAUSED || m_CurrentState == MEDIAPLAYER_STATE.END || m_CurrentState == MEDIAPLAYER_STATE.READY || m_CurrentState == MEDIAPLAYER_STATE.STOPPED)
  851. return Call_GetDuration();
  852. else
  853. return 0;
  854. }
  855. public float GetSeekBarValue()
  856. {
  857. if (m_CurrentState == MEDIAPLAYER_STATE.PLAYING || m_CurrentState == MEDIAPLAYER_STATE.PAUSED || m_CurrentState == MEDIAPLAYER_STATE.END || m_CurrentState == MEDIAPLAYER_STATE.READY || m_CurrentState == MEDIAPLAYER_STATE.STOPPED)
  858. {
  859. if (GetDuration () == 0) {
  860. return 0;
  861. }
  862. return (float)GetSeekPosition() / (float)GetDuration() ;
  863. }
  864. else
  865. return 0;
  866. }
  867. public void SetSeekBarValue(float fValue)
  868. {
  869. if (m_CurrentState == MEDIAPLAYER_STATE.PLAYING || m_CurrentState == MEDIAPLAYER_STATE.PAUSED || m_CurrentState == MEDIAPLAYER_STATE.END || m_CurrentState == MEDIAPLAYER_STATE.READY || m_CurrentState == MEDIAPLAYER_STATE.STOPPED)
  870. {
  871. if (GetDuration () == 0) {
  872. return;
  873. }
  874. SeekTo( (int)((float)GetDuration() * fValue) );
  875. }
  876. else
  877. return;
  878. }
  879. //Get update status in buffering a media stream received through progressive HTTP download.
  880. //The received buffering percentage indicates how much of the content has been buffered or played.
  881. //For example a buffering update of 80 percent when half the content has already been played indicates that the next 30 percent of the content to play has been buffered.
  882. //the percentage (0-100) of the content that has been buffered or played thus far
  883. public int GetCurrentSeekPercent()
  884. {
  885. if (m_CurrentState == MEDIAPLAYER_STATE.PLAYING || m_CurrentState == MEDIAPLAYER_STATE.PAUSED || m_CurrentState == MEDIAPLAYER_STATE.END || m_CurrentState == MEDIAPLAYER_STATE.READY)
  886. return Call_GetCurrentSeekPercent();
  887. else
  888. return 0;
  889. }
  890. public int GetVideoWidth()
  891. {
  892. return Call_GetVideoWidth();
  893. }
  894. public int GetVideoHeight()
  895. {
  896. return Call_GetVideoHeight();
  897. }
  898. public void UnLoad()
  899. {
  900. m_bCheckFBO = false;
  901. #if UNITY_ANDROID
  902. //Call_Reset();
  903. #endif
  904. Call_UnLoad();
  905. m_CurrentState = MEDIAPLAYER_STATE.NOT_READY;
  906. }
  907. public void SelectSoundTrack(int iIndex)
  908. {
  909. Call_SelectSoundTrack(iIndex);
  910. }
  911. public int[] GetSoundTrack()
  912. {
  913. return Call_GetSoundTrack();
  914. }
  915. #if !UNITY_EDITOR && !UNITY_STANDALONE && !UNITY_WEBGL
  916. #if UNITY_ANDROID
  917. private AndroidJavaObject javaObj = null;
  918. private AndroidJavaObject GetJavaObject()
  919. {
  920. if (javaObj == null)
  921. {
  922. javaObj = new AndroidJavaObject("com.EasyMovieTexture.EasyMovieTexture");
  923. }
  924. return javaObj;
  925. }
  926. private void Call_Destroy()
  927. {
  928. #if UNITY_5 || UNITY_5_3_OR_NEWER
  929. if( SystemInfo.graphicsMultiThreaded == true)
  930. {
  931. #if UNITY_5_2 || UNITY_5_3_OR_NEWER
  932. GL.IssuePluginEvent(EasyMovieTextureRender(), 5 + m_iAndroidMgrID * 10 + 7000);
  933. #else
  934. GL.IssuePluginEvent(5 + m_iAndroidMgrID * 10 + 7000);
  935. #endif
  936. }
  937. else
  938. {
  939. GetJavaObject().Call("Destroy");
  940. }
  941. #else
  942. GetJavaObject().Call("Destroy");
  943. #endif
  944. }
  945. private void Call_UnLoad()
  946. {
  947. #if UNITY_5 || UNITY_5_3_OR_NEWER
  948. if( SystemInfo.graphicsMultiThreaded == true)
  949. {
  950. #if UNITY_5_2 || UNITY_5_3_OR_NEWER
  951. GL.IssuePluginEvent(EasyMovieTextureRender(), 4 + m_iAndroidMgrID * 10 + 7000);
  952. #else
  953. GL.IssuePluginEvent(4 + m_iAndroidMgrID * 10 + 7000);
  954. #endif
  955. }
  956. else
  957. {
  958. GetJavaObject().Call("UnLoad");
  959. }
  960. #else
  961. GetJavaObject().Call("UnLoad");
  962. #endif
  963. }
  964. private bool Call_Load(string strFileName, int iSeek)
  965. {
  966. #if UNITY_5 || UNITY_5_3_OR_NEWER
  967. if( SystemInfo.graphicsMultiThreaded == true)
  968. {
  969. GetJavaObject().Call("NDK_SetFileName", strFileName);
  970. #if UNITY_5_2 || UNITY_5_3_OR_NEWER
  971. GL.IssuePluginEvent(EasyMovieTextureRender(), 1 + m_iAndroidMgrID * 10 + 7000);
  972. #else
  973. GL.IssuePluginEvent(1+ m_iAndroidMgrID * 10 + 7000);
  974. #endif
  975. Call_SetNotReady();
  976. return true;
  977. }
  978. else
  979. {
  980. GetJavaObject().Call("NDK_SetFileName", strFileName);
  981. if (GetJavaObject().Call<bool>("Load"))
  982. {
  983. return true;
  984. }
  985. else
  986. {
  987. OnError(MEDIAPLAYER_ERROR.MEDIA_ERROR_UNKNOWN, MEDIAPLAYER_ERROR.MEDIA_ERROR_UNKNOWN);
  988. return false;
  989. }
  990. }
  991. #else
  992. GetJavaObject().Call("NDK_SetFileName", strFileName);
  993. if (GetJavaObject().Call<bool>("Load"))
  994. {
  995. return true;
  996. }
  997. else
  998. {
  999. OnError(MEDIAPLAYER_ERROR.MEDIA_ERROR_UNKNOWN, MEDIAPLAYER_ERROR.MEDIA_ERROR_UNKNOWN);
  1000. return false;
  1001. }
  1002. #endif
  1003. }
  1004. private void Call_UpdateVideoTexture()
  1005. {
  1006. if( Call_IsUpdateFrame() == false)
  1007. return;
  1008. if(m_VideoTextureDummy != null)
  1009. {
  1010. Destroy(m_VideoTextureDummy);
  1011. m_VideoTextureDummy = null;
  1012. }
  1013. for( int i = 0; i < m_TargetMaterial.Length; i++)
  1014. {
  1015. if(m_TargetMaterial[i])
  1016. {
  1017. if(m_TargetMaterial[i].GetComponent<MeshRenderer>()!= null)
  1018. {
  1019. if(m_TargetMaterial[i].GetComponent<MeshRenderer>().material.mainTexture != m_VideoTexture)
  1020. {
  1021. m_TargetMaterial[i].GetComponent<MeshRenderer>().material.mainTexture = m_VideoTexture;
  1022. }
  1023. }
  1024. if(m_TargetMaterial[i].GetComponent<RawImage>()!= null)
  1025. {
  1026. if(m_TargetMaterial[i].GetComponent<RawImage>().texture != m_VideoTexture)
  1027. {
  1028. m_TargetMaterial[i].GetComponent<RawImage>().texture = m_VideoTexture;
  1029. }
  1030. }
  1031. }
  1032. }
  1033. #if UNITY_5 || UNITY_5_3_OR_NEWER
  1034. if( SystemInfo.graphicsMultiThreaded == true)
  1035. {
  1036. #if UNITY_5_2 || UNITY_5_3_OR_NEWER
  1037. GL.IssuePluginEvent(EasyMovieTextureRender(), 3 + m_iAndroidMgrID * 10 + 7000);
  1038. #else
  1039. GL.IssuePluginEvent(3+ m_iAndroidMgrID * 10 + 7000);
  1040. #endif
  1041. }
  1042. else
  1043. {
  1044. GetJavaObject().Call("UpdateVideoTexture");
  1045. }
  1046. #else
  1047. GetJavaObject().Call("UpdateVideoTexture");
  1048. #endif
  1049. if (!m_bIsFirstFrameReady)
  1050. {
  1051. m_bIsFirstFrameReady = true;
  1052. if (OnVideoFirstFrameReady != null)
  1053. {
  1054. OnVideoFirstFrameReady();
  1055. //OnVideoFirstFrameReady = null;
  1056. }
  1057. }
  1058. }
  1059. private void Call_SetVolume(float fVolume)
  1060. {
  1061. GetJavaObject().Call("SetVolume",fVolume);
  1062. }
  1063. private void Call_SetSeekPosition(int iSeek)
  1064. {
  1065. GetJavaObject().Call("SetSeekPosition",iSeek);
  1066. }
  1067. private int Call_GetSeekPosition()
  1068. {
  1069. return GetJavaObject().Call<int>("GetSeekPosition");
  1070. }
  1071. private void Call_Play(int iSeek)
  1072. {
  1073. GetJavaObject().Call("Play",iSeek);
  1074. }
  1075. private void Call_Reset()
  1076. {
  1077. GetJavaObject().Call("Reset");
  1078. }
  1079. private void Call_Stop()
  1080. {
  1081. GetJavaObject().Call("Stop");
  1082. }
  1083. private void Call_RePlay()
  1084. {
  1085. GetJavaObject().Call("RePlay");
  1086. }
  1087. private void Call_Pause()
  1088. {
  1089. GetJavaObject().Call("Pause");
  1090. }
  1091. private int Call_InitNDK()
  1092. {
  1093. return GetJavaObject().Call<int>("InitNative",GetJavaObject());
  1094. }
  1095. private int Call_GetVideoWidth()
  1096. {
  1097. return GetJavaObject().Call<int>("GetVideoWidth");
  1098. }
  1099. private int Call_GetVideoHeight()
  1100. {
  1101. return GetJavaObject().Call<int>("GetVideoHeight");
  1102. }
  1103. private bool Call_IsUpdateFrame()
  1104. {
  1105. return GetJavaObject().Call<bool>("IsUpdateFrame");
  1106. }
  1107. private void Call_SetUnityTexture(int iTextureID)
  1108. {
  1109. GetJavaObject().Call("SetUnityTexture",iTextureID);
  1110. }
  1111. private void Call_SetWindowSize()
  1112. {
  1113. #if UNITY_5 || UNITY_5_3_OR_NEWER
  1114. if( SystemInfo.graphicsMultiThreaded == true)
  1115. {
  1116. #if UNITY_5_2 || UNITY_5_3_OR_NEWER
  1117. GL.IssuePluginEvent(EasyMovieTextureRender(), 2 + m_iAndroidMgrID * 10 + 7000);
  1118. #else
  1119. GL.IssuePluginEvent(2+ m_iAndroidMgrID * 10 + 7000);
  1120. #endif
  1121. }
  1122. else
  1123. {
  1124. GetJavaObject().Call("SetWindowSize");
  1125. }
  1126. #else
  1127. GetJavaObject().Call("SetWindowSize");
  1128. #endif
  1129. }
  1130. private void Call_SetLooping(bool bLoop)
  1131. {
  1132. GetJavaObject().Call("SetLooping",bLoop);
  1133. }
  1134. private void Call_SetRockchip(bool bValue)
  1135. {
  1136. GetJavaObject().Call("SetRockchip",bValue);
  1137. }
  1138. private int Call_GetDuration()
  1139. {
  1140. return GetJavaObject().Call<int>("GetDuration");
  1141. }
  1142. private int Call_GetCurrentSeekPercent()
  1143. {
  1144. return GetJavaObject().Call<int>("GetCurrentSeekPercent");
  1145. }
  1146. private int Call_GetError()
  1147. {
  1148. return GetJavaObject().Call<int>("GetError");
  1149. }
  1150. private void Call_SetSplitOBB(bool bValue, string strOBBName)
  1151. {
  1152. GetJavaObject().Call("SetSplitOBB",bValue,strOBBName);
  1153. }
  1154. private int Call_GetErrorExtra()
  1155. {
  1156. return GetJavaObject().Call<int>("GetErrorExtra");
  1157. }
  1158. private void Call_SetUnityActivity()
  1159. {
  1160. AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
  1161. AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
  1162. GetJavaObject().Call("SetUnityActivity", jo);
  1163. #if UNITY_5 || UNITY_5_3_OR_NEWER
  1164. if( SystemInfo.graphicsMultiThreaded == true)
  1165. {
  1166. #if UNITY_5_2 || UNITY_5_3_OR_NEWER
  1167. GL.IssuePluginEvent(EasyMovieTextureRender(), 0 + m_iAndroidMgrID * 10 + 7000);
  1168. #else
  1169. GL.IssuePluginEvent(0+ m_iAndroidMgrID * 10 + 7000);
  1170. #endif
  1171. }
  1172. else
  1173. {
  1174. Call_InitJniManager();
  1175. }
  1176. #else
  1177. Call_InitJniManager();
  1178. #endif
  1179. }
  1180. private void Call_SetNotReady()
  1181. {
  1182. GetJavaObject().Call("SetNotReady");
  1183. }
  1184. private void Call_InitJniManager()
  1185. {
  1186. GetJavaObject().Call("InitJniManager");
  1187. }
  1188. private void Call_SetSpeed(float fSpeed)
  1189. {
  1190. using (AndroidJavaClass buildVersion = new AndroidJavaClass("android.os.Build$VERSION"))
  1191. {
  1192. int sdkVersion = buildVersion.GetStatic<int>("SDK_INT");
  1193. if(sdkVersion >= 23 ) //Android 6.0
  1194. {
  1195. GetJavaObject().Call("SetSpeed",fSpeed);
  1196. }
  1197. }
  1198. }
  1199. private MEDIAPLAYER_STATE Call_GetStatus()
  1200. {
  1201. return (MEDIAPLAYER_STATE)GetJavaObject().Call<int>("GetStatus");
  1202. }
  1203. private void Call_SelectSoundTrack(int iIndex)
  1204. {
  1205. GetJavaObject().Call("SelectTrack",iIndex);
  1206. }
  1207. private int[] Call_GetSoundTrack()
  1208. {
  1209. return GetJavaObject().Call<int []>("GetSoundTrack");
  1210. }
  1211. #elif UNITY_IPHONE || UNITY_TVOS
  1212. [DllImport("__Internal")]
  1213. private static extern int VideoPlayerPluginCreateInstance();
  1214. [DllImport("__Internal")]
  1215. private static extern void VideoPlayerPluginDestroyInstance(int iID);
  1216. [DllImport("__Internal")]
  1217. private static extern bool VideoPlayerPluginCanOutputToTexture(string videoURL);
  1218. [DllImport("__Internal")]
  1219. private static extern void VideoPlayerPluginSetLoop(int iID, bool bLoop);
  1220. [DllImport("__Internal")]
  1221. private static extern void VideoPlayerPluginSetVolume(int iID, float fVolume);
  1222. [DllImport("__Internal")]
  1223. private static extern bool VideoPlayerPluginPlayerReady(int iID);
  1224. [DllImport("__Internal")]
  1225. private static extern float VideoPlayerPluginDurationSeconds(int iID);
  1226. [DllImport("__Internal")]
  1227. private static extern void VideoPlayerPluginExtents(int iID,ref int width, ref int height);
  1228. [DllImport("__Internal")]
  1229. private static extern IntPtr VideoPlayerPluginCurFrameTexture(int iID);
  1230. [DllImport("__Internal")]
  1231. private static extern void VideoPlayerPluginLoadVideo(int iID,string videoURL);
  1232. [DllImport("__Internal")]
  1233. private static extern void VideoPlayerPluginPlayVideo(int iID);
  1234. [DllImport("__Internal")]
  1235. private static extern void VideoPlayerPluginPauseVideo(int iID);
  1236. [DllImport("__Internal")]
  1237. private static extern void VideoPlayerPluginResumeVideo(int iID);
  1238. [DllImport("__Internal")]
  1239. private static extern void VideoPlayerPluginRewindVideo(int iID);
  1240. [DllImport("__Internal")]
  1241. private static extern void VideoPlayerPluginSeekToVideo(int iID,float time);
  1242. [DllImport("__Internal")]
  1243. private static extern float VideoPlayerPluginCurTimeSeconds(int iID);
  1244. [DllImport("__Internal")]
  1245. private static extern bool VideoPlayerPluginIsPlaying(int iID);
  1246. [DllImport("__Internal")]
  1247. private static extern void VideoPlayerPluginStopVideo(int iID);
  1248. [DllImport("__Internal")]
  1249. private static extern bool VideoPlayerPluginFinish(int iID);
  1250. [DllImport("__Internal")]
  1251. private static extern bool VideoPlayerPluginError(int iID);
  1252. [DllImport("__Internal")]
  1253. private static extern void VideoPlayerPluginSetTexture(int iID,int iTextureID);
  1254. [DllImport("__Internal")]
  1255. private static extern void VideoPlayerPluginSetSpeed(int iID,float fSpeed);
  1256. [DllImport("__Internal")]
  1257. private static extern void VideoPlayerPluginSetAudioTrack(int iID,int trackID);
  1258. [DllImport("__Internal")]
  1259. private static extern int VideoPlayerPluginGetAudioTrack(int iID);
  1260. [DllImport("__Internal")]
  1261. private static extern int VideoPlayerPluginGetCurrentSeekPercent(int iID);
  1262. int m_iID = -1;
  1263. /// <summary>
  1264. /// ???????????????true??????? /// </summary>
  1265. public bool ready
  1266. {
  1267. get
  1268. {
  1269. return VideoPlayerPluginPlayerReady(m_iID);
  1270. }
  1271. }
  1272. /// <summary>
  1273. ///
  1274. /// </summary>
  1275. public float duration
  1276. {
  1277. get
  1278. {
  1279. return VideoPlayerPluginDurationSeconds(m_iID);
  1280. }
  1281. }
  1282. public float currentTime
  1283. {
  1284. get
  1285. {
  1286. return VideoPlayerPluginCurTimeSeconds(m_iID);
  1287. }
  1288. }
  1289. public bool isPlaying
  1290. {
  1291. get
  1292. {
  1293. return VideoPlayerPluginIsPlaying(m_iID);
  1294. }
  1295. }
  1296. public Vector2 videoSize
  1297. {
  1298. get
  1299. {
  1300. int width = 0, height = 0;
  1301. VideoPlayerPluginExtents(m_iID,ref width, ref height);
  1302. return new Vector2(width, height);
  1303. }
  1304. }
  1305. private Texture2D _videoTexture;
  1306. public Texture2D videoTexture
  1307. {
  1308. get
  1309. {
  1310. IntPtr nativeTex = ready ? VideoPlayerPluginCurFrameTexture(m_iID) : (IntPtr)0;
  1311. if (nativeTex != (IntPtr)0)
  1312. {
  1313. if (_videoTexture == null)
  1314. {
  1315. #if UNITY_5 || UNITY_5_3_OR_NEWER
  1316. if(SystemInfo.graphicsDeviceType == UnityEngine.Rendering.GraphicsDeviceType.Metal)
  1317. _videoTexture = new Texture2D (Call_GetVideoWidth (), Call_GetVideoHeight (), TextureFormat.RGBA32, false);
  1318. else
  1319. _videoTexture = Texture2D.CreateExternalTexture((int)videoSize.x, (int)videoSize.y, TextureFormat.RGBA32,
  1320. false, false, (IntPtr)nativeTex);
  1321. #else
  1322. _videoTexture = Texture2D.CreateExternalTexture((int)videoSize.x, (int)videoSize.y, TextureFormat.RGBA32,
  1323. false, false, (IntPtr)nativeTex);
  1324. #endif
  1325. _videoTexture.filterMode = FilterMode.Bilinear;
  1326. _videoTexture.wrapMode = TextureWrapMode.Clamp;
  1327. }
  1328. _videoTexture.UpdateExternalTexture((IntPtr)nativeTex);
  1329. }
  1330. /* else
  1331. {
  1332. if(_videoTexture != null)
  1333. {
  1334. Destroy(_videoTexture);
  1335. }
  1336. _videoTexture = null;
  1337. }*/
  1338. return _videoTexture;
  1339. }
  1340. }
  1341. private void Call_Destroy()
  1342. {
  1343. VideoPlayerPluginDestroyInstance(m_iID);
  1344. if(_videoTexture != null)
  1345. Destroy(_videoTexture);
  1346. _videoTexture = null;
  1347. m_iID = -1;
  1348. }
  1349. private void Call_UnLoad()
  1350. {
  1351. VideoPlayerPluginStopVideo(m_iID);
  1352. VideoPlayerPluginDestroyInstance(m_iID);
  1353. }
  1354. private bool Call_Load(string strFileName, int iSeek)
  1355. {
  1356. if( m_iID == -1)
  1357. {
  1358. Call_SetUnityActivity();
  1359. }
  1360. bFirstIOS = true;
  1361. /*if(_videoTexture != null)
  1362. {
  1363. Destroy(_videoTexture);
  1364. }*/
  1365. _videoTexture = null;
  1366. if (VideoPlayerPluginCanOutputToTexture(strFileName))
  1367. {
  1368. VideoPlayerPluginLoadVideo(m_iID,strFileName);
  1369. }
  1370. return true;
  1371. }
  1372. bool bFirstIOS = false;
  1373. private void Call_UpdateVideoTexture()
  1374. {
  1375. if( m_CurrentState == MEDIAPLAYER_STATE.PLAYING || m_CurrentState == MEDIAPLAYER_STATE.PAUSED)
  1376. {
  1377. if( videoTexture == null)
  1378. return;
  1379. if(bFirstIOS == true)
  1380. {
  1381. bFirstIOS = false;
  1382. return;
  1383. }
  1384. if(bFirstIOS == false)
  1385. {
  1386. for( int i = 0; i < m_TargetMaterial.Length; i++)
  1387. {
  1388. if(m_TargetMaterial[i])
  1389. {
  1390. if(m_TargetMaterial[i].GetComponent<MeshRenderer>() != null)
  1391. m_TargetMaterial[i].GetComponent<MeshRenderer>().material.mainTexture = _videoTexture;
  1392. }
  1393. if(m_TargetMaterial[i])
  1394. {
  1395. if(m_TargetMaterial[i].GetComponent<RawImage>() != null)
  1396. m_TargetMaterial[i].GetComponent<RawImage>().texture= _videoTexture;
  1397. }
  1398. }
  1399. if(m_VideoTextureDummy != null)
  1400. {
  1401. Destroy(m_VideoTextureDummy);
  1402. m_VideoTextureDummy = null;
  1403. }
  1404. }
  1405. m_VideoTexture = _videoTexture;
  1406. }
  1407. if (!m_bIsFirstFrameReady)
  1408. {
  1409. m_bIsFirstFrameReady = true;
  1410. if (OnVideoFirstFrameReady != null)
  1411. {
  1412. OnVideoFirstFrameReady();
  1413. //OnVideoFirstFrameReady = null;
  1414. }
  1415. }
  1416. }
  1417. private void Call_SetVolume(float fVolume)
  1418. {
  1419. VideoPlayerPluginSetVolume(m_iID, fVolume);
  1420. }
  1421. private void Call_SetSeekPosition(int iSeek)
  1422. {
  1423. float fSeek = (float)iSeek / 1000.0f;
  1424. VideoPlayerPluginSeekToVideo(m_iID,fSeek);
  1425. }
  1426. private int Call_GetSeekPosition()
  1427. {
  1428. float fSeek = VideoPlayerPluginCurTimeSeconds(m_iID);
  1429. return (int)(fSeek * 1000.0f);
  1430. }
  1431. private void Call_Play(int iSeek)
  1432. {
  1433. float fSeek = (float)iSeek / 1000.0f;
  1434. if( isPlaying == true )
  1435. {
  1436. VideoPlayerPluginSeekToVideo(m_iID,fSeek);
  1437. }
  1438. else
  1439. {
  1440. if( m_CurrentState != MEDIAPLAYER_STATE.READY)
  1441. VideoPlayerPluginSeekToVideo(m_iID,fSeek);
  1442. VideoPlayerPluginPlayVideo(m_iID);
  1443. }
  1444. if( m_CurrentState == MEDIAPLAYER_STATE.STOPPED)
  1445. m_CurrentState = MEDIAPLAYER_STATE.PLAYING;
  1446. }
  1447. private void Call_Reset()
  1448. {
  1449. }
  1450. private void Call_Stop()
  1451. {
  1452. VideoPlayerPluginStopVideo(m_iID);
  1453. }
  1454. private void Call_RePlay()
  1455. {
  1456. VideoPlayerPluginResumeVideo(m_iID);
  1457. m_CurrentState = MEDIAPLAYER_STATE.PLAYING;
  1458. }
  1459. private void Call_Pause()
  1460. {
  1461. m_CurrentState = MEDIAPLAYER_STATE.PAUSED;
  1462. VideoPlayerPluginPauseVideo(m_iID);
  1463. }
  1464. private int Call_GetVideoWidth()
  1465. {
  1466. return (int)videoSize.x;
  1467. }
  1468. private int Call_GetVideoHeight()
  1469. {
  1470. return (int)videoSize.y;
  1471. }
  1472. private void Call_SetUnityTexture(int iTextureID)
  1473. {
  1474. VideoPlayerPluginSetTexture(m_iID,iTextureID);
  1475. }
  1476. private void Call_SetWindowSize()
  1477. {
  1478. }
  1479. private void Call_SetLooping(bool bLoop)
  1480. {
  1481. VideoPlayerPluginSetLoop(m_iID, bLoop);
  1482. }
  1483. public void Call_SetUnityActivity()
  1484. {
  1485. m_iID = VideoPlayerPluginCreateInstance();
  1486. }
  1487. private int Call_GetError()
  1488. {
  1489. return 0;
  1490. }
  1491. private int Call_GetErrorExtra()
  1492. {
  1493. return 0;
  1494. }
  1495. private int Call_GetDuration()
  1496. {
  1497. return (int)(duration * 1000);
  1498. }
  1499. private int Call_GetCurrentSeekPercent()
  1500. {
  1501. return VideoPlayerPluginGetCurrentSeekPercent(m_iID);
  1502. }
  1503. private void Call_SetSpeed(float fSpeed)
  1504. {
  1505. VideoPlayerPluginSetSpeed(m_iID,fSpeed);
  1506. }
  1507. private MEDIAPLAYER_STATE Call_GetStatus()
  1508. {
  1509. if( VideoPlayerPluginFinish(m_iID) )
  1510. {
  1511. return MEDIAPLAYER_STATE.END;
  1512. }
  1513. if( VideoPlayerPluginError(m_iID) )
  1514. {
  1515. return MEDIAPLAYER_STATE.ERROR;
  1516. }
  1517. if( m_CurrentState == MEDIAPLAYER_STATE.PAUSED || m_CurrentState == MEDIAPLAYER_STATE.STOPPED)
  1518. {
  1519. return m_CurrentState;
  1520. }
  1521. else if(isPlaying)
  1522. {
  1523. return MEDIAPLAYER_STATE.PLAYING;
  1524. }
  1525. else if(ready)
  1526. {
  1527. return MEDIAPLAYER_STATE.READY;
  1528. }
  1529. return m_CurrentState;
  1530. }
  1531. private void Call_SelectSoundTrack(int iIndex)
  1532. {
  1533. VideoPlayerPluginSetAudioTrack(m_iID,iIndex);
  1534. }
  1535. private int[] Call_GetSoundTrack()
  1536. {
  1537. if(VideoPlayerPluginGetAudioTrack(m_iID) !=0)
  1538. {
  1539. int [] info = new int[VideoPlayerPluginGetAudioTrack(m_iID)];
  1540. for(int i =0; i < info.Length; i++)
  1541. {
  1542. info[i] = i;
  1543. }
  1544. return info;
  1545. }
  1546. else
  1547. {
  1548. return null;
  1549. }
  1550. }
  1551. #endif
  1552. #else
  1553. AVFrame* pConvertedFrame = null;
  1554. sbyte* pConvertedFrameBuffer = null;
  1555. SwsContext* pConvertContext = null;
  1556. AVCodecContext* pCodecContext = null;
  1557. AVCodecContext* pAudioCodecContext = null;
  1558. AVFrame* pDecodedFrame = null;
  1559. AVFrame* pDecodedAudioFrame = null;
  1560. AVFormatContext* pFormatContext = null;
  1561. AVPacket* pPacket = null;
  1562. AVStream* pStream = null;
  1563. AVStream* pStreamAudio = null;
  1564. Queue<IntPtr> m_queuePacketVideo;
  1565. Queue<IntPtr> m_queuePacketSound;
  1566. int iStreamAudioIndex;
  1567. int iStreamIndex;
  1568. AudioClip audioClip;
  1569. AudioSource audioSource;
  1570. long iSoundCount = 0;
  1571. int iInitCount = 0;
  1572. double pts;
  1573. bool bVideoFirstFrameReady = false;
  1574. int m_iID;
  1575. private void Call_Destroy()
  1576. {
  1577. if (loader != null) {
  1578. while (loader.IsAlive == true) {
  1579. loader.Abort ();
  1580. }
  1581. loader = null;
  1582. }
  1583. if( threadVideo != null)
  1584. {
  1585. while(threadVideo.IsAlive == true)
  1586. {
  1587. threadVideo.Abort();
  1588. }
  1589. threadVideo = null;
  1590. }
  1591. ffmpeg.avformat_network_deinit ();
  1592. ReleaseTexture (m_iID);
  1593. }
  1594. private void Call_UnLoad()
  1595. {
  1596. m_CurrentState = MEDIAPLAYER_STATE.NOT_READY;
  1597. m_bSetTextureFirst = false;
  1598. if (loader != null) {
  1599. while (loader.IsAlive == true) {
  1600. loader.Abort ();
  1601. }
  1602. loader = null;
  1603. }
  1604. if( threadVideo != null)
  1605. {
  1606. while(threadVideo.IsAlive == true)
  1607. {
  1608. threadVideo.Abort();
  1609. }
  1610. threadVideo = null;
  1611. }
  1612. if (listAudio != null)
  1613. {
  1614. listAudio.Clear();
  1615. listAudio = null;
  1616. }
  1617. if (listVideo != null)
  1618. {
  1619. listVideo.Clear();
  1620. listVideo = null;
  1621. }
  1622. if (listAudioPts != null)
  1623. {
  1624. listAudioPts.Clear();
  1625. listAudioPts = null;
  1626. }
  1627. if (listAudioPtsTime != null)
  1628. {
  1629. listAudioPtsTime.Clear();
  1630. listAudioPtsTime = null;
  1631. }
  1632. if (listVideoPts != null)
  1633. {
  1634. listVideoPts.Clear();
  1635. listVideoPts = null;
  1636. }
  1637. fCurrentSeekTime = 0.0f;
  1638. fLastFrameTime = 0.0f;
  1639. if (pPacket != null)
  1640. {
  1641. ffmpeg.av_free_packet(pPacket);
  1642. Marshal.FreeCoTaskMem((IntPtr)pPacket);
  1643. pPacket = null;
  1644. }
  1645. int iCount = m_queuePacketVideo.Count;
  1646. for (int i = 0; i < iCount; i++)
  1647. {
  1648. if (m_queuePacketVideo.Count > 0)
  1649. pPacket = (AVPacket*)m_queuePacketVideo.Dequeue();
  1650. if (pPacket != null)
  1651. {
  1652. ffmpeg.av_free_packet(pPacket);
  1653. Marshal.FreeCoTaskMem((IntPtr)pPacket);
  1654. pPacket = null;
  1655. }
  1656. }
  1657. iCount = m_queuePacketSound.Count;
  1658. for (int i = 0; i < iCount; i++)
  1659. {
  1660. if (m_queuePacketSound.Count > 0)
  1661. pPacket = (AVPacket*)m_queuePacketSound.Dequeue();
  1662. if (pPacket != null)
  1663. {
  1664. ffmpeg.av_free_packet(pPacket);
  1665. Marshal.FreeCoTaskMem((IntPtr)pPacket);
  1666. pPacket = null;
  1667. }
  1668. }
  1669. if (pConvertedFrame != null)
  1670. {
  1671. ffmpeg.av_free(pConvertedFrame);
  1672. pConvertedFrame = null;
  1673. }
  1674. if(pConvertedFrameBuffer != null)
  1675. {
  1676. ffmpeg.av_free(pConvertedFrameBuffer);
  1677. pConvertedFrameBuffer = null;
  1678. }
  1679. if(pConvertContext != null)
  1680. {
  1681. ffmpeg.sws_freeContext(pConvertContext);
  1682. pConvertContext = null;
  1683. }
  1684. if(pDecodedFrame != null)
  1685. {
  1686. ffmpeg.av_free(pDecodedFrame);
  1687. pDecodedFrame = null;
  1688. }
  1689. if (pDecodedAudioFrame != null)
  1690. ffmpeg.av_free (pDecodedAudioFrame);
  1691. pDecodedAudioFrame = null;
  1692. if(pCodecContext != null)
  1693. ffmpeg.avcodec_close(pCodecContext);
  1694. pCodecContext = null;
  1695. if (pAudioCodecContext != null)
  1696. ffmpeg.avcodec_close (pAudioCodecContext);
  1697. pAudioCodecContext = null;
  1698. if (pFormatContext != null) {
  1699. AVFormatContext* ppFormatContext = pFormatContext;
  1700. ffmpeg.avformat_close_input (&ppFormatContext);
  1701. }
  1702. pFormatContext = null;
  1703. if (audioSource != null) {
  1704. audioSource.Stop();
  1705. }
  1706. if ( audioClip != null)
  1707. {
  1708. Destroy (audioClip);
  1709. audioClip = null;
  1710. }
  1711. }
  1712. Thread loader = null;
  1713. private unsafe bool Call_Load(string strFileName, int iSeek)
  1714. {
  1715. if(m_queuePacketVideo == null)
  1716. m_queuePacketVideo = new Queue<IntPtr>();
  1717. if (m_queuePacketSound == null)
  1718. m_queuePacketSound = new Queue<IntPtr>();
  1719. fCurrentSeekTime = 0.0f;
  1720. fLastFrameTime = 0.0f;
  1721. iSoundCount = 0;
  1722. iInitCount= 0;
  1723. bSeekTo = true;
  1724. bEnd = false;
  1725. bEndCheck = false;
  1726. if (audioSource != null) {
  1727. audioSource.Stop();
  1728. audioSource.time = 0.0f;
  1729. }
  1730. if ( audioClip != null)
  1731. {
  1732. Destroy (audioClip);
  1733. audioClip = null;
  1734. }
  1735. pFormatContext = ffmpeg.avformat_alloc_context();
  1736. if( strFileName.Contains("://") == false)
  1737. {
  1738. strFileName = Application.streamingAssetsPath + "/" + strFileName;
  1739. Debug.Log(strFileName);
  1740. }
  1741. else if( strFileName.Contains("file://") == true)
  1742. {
  1743. strFileName = strFileName.Replace("file://", "");
  1744. }
  1745. loader = new Thread ( () => {
  1746. AVFormatContext* ppFomatContext = null;
  1747. if (ffmpeg.avformat_open_input(&ppFomatContext, strFileName, null, null) != 0)
  1748. {
  1749. pFormatContext = null;
  1750. m_CurrentState = MEDIAPLAYER_STATE.ERROR;
  1751. Debug.Log("Could not open file");
  1752. throw new ApplicationException(@"Could not open file");
  1753. }
  1754. //ffmpeg.av_dict_free(&opts);
  1755. pFormatContext = ppFomatContext;
  1756. if (ffmpeg.avformat_find_stream_info(pFormatContext, null) != 0)
  1757. {
  1758. m_CurrentState = MEDIAPLAYER_STATE.ERROR;
  1759. Debug.Log("Could not find stream info");
  1760. throw new ApplicationException(@"Could not find stream info");
  1761. }
  1762. AddActionForUnityMainThread( () => {
  1763. LoadVideoPart2 ();
  1764. });
  1765. });
  1766. loader.Priority = System.Threading.ThreadPriority.AboveNormal;
  1767. loader.IsBackground = true;
  1768. loader.Start ();
  1769. return true;
  1770. }
  1771. void LoadVideoPart2 ()
  1772. {
  1773. pStream = null;
  1774. pStreamAudio = null;
  1775. bool bFindVideo = false;
  1776. bool bFindAudio = false;
  1777. for (var i = 0; i < (pFormatContext)->nb_streams; i++)
  1778. {
  1779. if ((pFormatContext)->streams[i]->codec->codec_type == AVMediaType.AVMEDIA_TYPE_VIDEO)
  1780. {
  1781. if(bFindVideo == false)
  1782. {
  1783. bFindVideo = true;
  1784. pStream = (pFormatContext)->streams[i];
  1785. iStreamIndex = i;
  1786. Debug.Log("Video" + iStreamIndex);
  1787. }
  1788. }
  1789. else if((pFormatContext)->streams[i]->codec->codec_type == AVMediaType.AVMEDIA_TYPE_AUDIO)
  1790. {
  1791. if (bFindAudio == false)
  1792. {
  1793. bFindAudio = true;
  1794. pStreamAudio = (pFormatContext)->streams[i];
  1795. iStreamAudioIndex = i;
  1796. }
  1797. }
  1798. }
  1799. if (pStream == null)
  1800. {
  1801. m_CurrentState = MEDIAPLAYER_STATE.ERROR;
  1802. Debug.Log("Could not found video stream");
  1803. throw new ApplicationException(@"Could not found video stream");
  1804. }
  1805. if (pStreamAudio == null)
  1806. {
  1807. //m_CurrentState = MEDIAPLAYER_STATE.ERROR;
  1808. Debug.Log("Could not found Audio stream" + bFindAudio);
  1809. //throw new ApplicationException(@"Could not found audio stream");
  1810. }
  1811. var codecContext = *pStream->codec;
  1812. m_iWidth = codecContext.width;
  1813. m_iHeight = codecContext.height;
  1814. var sourcePixFmt = codecContext.pix_fmt;
  1815. var codecId = codecContext.codec_id;
  1816. var convertToPixFmt = AVPixelFormat.AV_PIX_FMT_RGBA;
  1817. #if UNITY_5
  1818. if( SystemInfo.graphicsDeviceType == UnityEngine.Rendering.GraphicsDeviceType.Direct3D9)
  1819. {
  1820. convertToPixFmt = AVPixelFormat.AV_PIX_FMT_BGRA;
  1821. }
  1822. #endif
  1823. pConvertContext = ffmpeg.sws_getContext(m_iWidth, m_iHeight, sourcePixFmt,
  1824. m_iWidth, m_iHeight, convertToPixFmt,
  1825. ffmpeg.SWS_FAST_BILINEAR, null, null, null);
  1826. if (pConvertContext == null)
  1827. {
  1828. m_CurrentState = MEDIAPLAYER_STATE.ERROR;
  1829. Debug.Log("Could not initialize the conversion context");
  1830. throw new ApplicationException(@"Could not initialize the conversion context");
  1831. }
  1832. //pConvertedFrame = ffmpeg.avcodec_alloc_frame();
  1833. pConvertedFrame = ffmpeg.av_frame_alloc();
  1834. var convertedFrameBufferSize = ffmpeg.avpicture_get_size(convertToPixFmt, m_iWidth, m_iHeight);
  1835. pConvertedFrameBuffer = (sbyte*)ffmpeg.av_malloc((ulong)convertedFrameBufferSize);
  1836. AVPicture* tempPicture = (AVPicture*)pConvertedFrame;
  1837. ffmpeg.avpicture_fill(tempPicture , pConvertedFrameBuffer, convertToPixFmt, m_iWidth, m_iHeight);
  1838. var pCodec = ffmpeg.avcodec_find_decoder(codecId);
  1839. if (pCodec == null)
  1840. {
  1841. m_CurrentState = MEDIAPLAYER_STATE.ERROR;
  1842. Debug.Log("Unsupported codec");
  1843. throw new ApplicationException(@"Unsupported codec");
  1844. }
  1845. pCodecContext = pStream->codec;
  1846. pCodecContext->hwaccel = ff_find_hwaccel(pCodecContext->codec_id ,sourcePixFmt);
  1847. //if ((pCodec->capabilities & ffmpeg.AV_CODEC_CAP_TRUNCATED) == ffmpeg.AV_CODEC_CAP_TRUNCATED)
  1848. {
  1849. //pCodecContext->flags = ffmpeg.AV_CODEC_FLAG_TRUNCATED;
  1850. }
  1851. if (ffmpeg.avcodec_open2(pCodecContext, pCodec, null) < 0)
  1852. {
  1853. m_CurrentState = MEDIAPLAYER_STATE.ERROR;
  1854. Debug.Log("Could not open codec");
  1855. throw new ApplicationException(@"Could not open codec");
  1856. }
  1857. if(pStreamAudio != null)
  1858. {
  1859. var codecAudioContext = *pStreamAudio->codec;
  1860. var pAudioCodec = ffmpeg.avcodec_find_decoder(codecAudioContext.codec_id);
  1861. if (pAudioCodec == null) {
  1862. m_CurrentState = MEDIAPLAYER_STATE.ERROR;
  1863. Debug.Log("Unsupported codec");
  1864. throw new ApplicationException(@"Unsupported codec");
  1865. }
  1866. pAudioCodecContext = pStreamAudio->codec;
  1867. ///> Initialize Codec Context as Decoder
  1868. if (ffmpeg.avcodec_open2(pAudioCodecContext, pAudioCodec, null) < 0) {
  1869. m_CurrentState = MEDIAPLAYER_STATE.ERROR;
  1870. Debug.Log("Could not open codec");
  1871. throw new ApplicationException(@"Could not open codec");
  1872. }
  1873. }
  1874. pDecodedFrame = ffmpeg.av_frame_alloc();
  1875. pDecodedAudioFrame = ffmpeg.av_frame_alloc();
  1876. listAudio = new List<float[]>();
  1877. listVideo = new Queue<byte[]>();
  1878. listAudioPts = new List<double>();
  1879. listAudioPtsTime = new List<double>();
  1880. listVideoPts = new Queue<float>();
  1881. if( m_strFileName.StartsWith("rtsp",StringComparison.OrdinalIgnoreCase) == true)
  1882. {
  1883. }
  1884. else
  1885. {
  1886. action = Interrupt1;
  1887. //pFormatContext->interrupt_callback.callback = Marshal.GetFunctionPointerForDelegate(action);
  1888. }
  1889. bVideoFirstFrameReady = false;
  1890. threadVideo = new Thread(ThreadUpdate);
  1891. threadVideo.IsBackground = true;
  1892. threadVideo.Start();
  1893. if (m_bAutoPlay == true)
  1894. {
  1895. if( OnReady != null)
  1896. OnReady();
  1897. m_CurrentState = MEDIAPLAYER_STATE.PLAYING;
  1898. }
  1899. else
  1900. {
  1901. m_CurrentState = MEDIAPLAYER_STATE.READY;
  1902. if( OnReady != null)
  1903. OnReady();
  1904. }
  1905. loader = null;
  1906. }
  1907. AVHWAccel *ff_find_hwaccel( AVCodecID codec_id, AVPixelFormat pix_fmt)
  1908. {
  1909. AVHWAccel *hwaccel=null;
  1910. while((hwaccel= ffmpeg.av_hwaccel_next(hwaccel))!=null){
  1911. if ( hwaccel->id == codec_id
  1912. && hwaccel->pix_fmt == pix_fmt)
  1913. return hwaccel;
  1914. }
  1915. return null;
  1916. }
  1917. public delegate void VideoInterrupt();
  1918. VideoInterrupt action = null;
  1919. bool bInterrupt = false;
  1920. public void Interrupt1()
  1921. {
  1922. pFormatContext->interrupt_callback.callback = (IntPtr)null;
  1923. bInterrupt = true;
  1924. //Debug.Log ("Interrupt1");
  1925. //Call_Pause ();
  1926. }
  1927. static double av_q2d(AVRational a){
  1928. return a.num / (double) a.den;
  1929. }
  1930. float fLastFrameTime = 0.0f;
  1931. float fCurrentSeekTime = 0.0f;
  1932. float[] fAudioData;
  1933. bool bEnd = false;
  1934. Thread threadVideo;
  1935. List<float[]> listAudio;
  1936. Queue<byte[]> listVideo;
  1937. List<double> listAudioPts;
  1938. List<double> listAudioPtsTime;
  1939. Queue<float> listVideoPts;
  1940. private static void DebugMethod(string message)
  1941. {
  1942. Debug.Log("EasyMovieTexture: " + message);
  1943. }
  1944. private void ThreadUpdate()
  1945. {
  1946. /*lock (listVideo)
  1947. {
  1948. if (listVideo != null)
  1949. {
  1950. listVideo.Clear();
  1951. }
  1952. }
  1953. lock (listVideoPts)
  1954. {
  1955. if (listVideoPts != null)
  1956. {
  1957. listVideoPts.Clear();
  1958. }
  1959. }*/
  1960. while (true)
  1961. {
  1962. if (m_CurrentState == MEDIAPLAYER_STATE.ERROR)
  1963. break;
  1964. if (listVideo != null)
  1965. {
  1966. if (m_queuePacketVideo.Count < 200)
  1967. ReadPacket();
  1968. while (listVideo.Count >10 || bEnd == true )
  1969. {
  1970. if (m_queuePacketVideo.Count < 200)
  1971. {
  1972. ReadPacket();
  1973. }
  1974. UpdateSound();
  1975. Thread.Sleep(5);
  1976. }
  1977. }
  1978. UpdateVideo();
  1979. UpdateSound();
  1980. Thread.Sleep(1);
  1981. //Thread.Sleep(5);
  1982. }
  1983. }
  1984. bool bBuffering = true;
  1985. bool bEndCheck = false;
  1986. private void ReadPacket()
  1987. {
  1988. AVPacket* Packet = (AVPacket*)Marshal.AllocCoTaskMem(sizeof(AVPacket));
  1989. ffmpeg.av_init_packet(Packet);
  1990. int ret = ffmpeg.av_read_frame(pFormatContext, Packet);
  1991. if (ret < 0)
  1992. {
  1993. if (ret == -541478725)
  1994. {
  1995. bEndCheck = true;
  1996. if (listVideo.Count < 3)
  1997. {
  1998. bEnd = true;
  1999. if (Packet != null)
  2000. {
  2001. ffmpeg.av_free_packet(Packet);
  2002. Marshal.FreeCoTaskMem((IntPtr)Packet);
  2003. Packet = null;
  2004. }
  2005. //threadVideo.Abort();
  2006. return;
  2007. }
  2008. }
  2009. else
  2010. {
  2011. if (Packet != null)
  2012. {
  2013. ffmpeg.av_free_packet(Packet);
  2014. Marshal.FreeCoTaskMem((IntPtr)Packet);
  2015. Packet = null;
  2016. }
  2017. //throw new ApplicationException(@"Could not read frame");
  2018. Debug.Log("Could not read frame");
  2019. }
  2020. }
  2021. else
  2022. {
  2023. if (Packet->stream_index == iStreamIndex)
  2024. {
  2025. lock(m_queuePacketVideo)
  2026. {
  2027. m_queuePacketVideo.Enqueue((IntPtr)Packet);
  2028. }
  2029. }
  2030. else
  2031. {
  2032. lock (m_queuePacketSound)
  2033. {
  2034. m_queuePacketSound.Enqueue((IntPtr)Packet);
  2035. }
  2036. }
  2037. }
  2038. if (bEndCheck == true)
  2039. {
  2040. if (listVideo.Count < 3)
  2041. {
  2042. Debug.Log("End");
  2043. bEnd = true;
  2044. if (Packet != null)
  2045. {
  2046. ffmpeg.av_free_packet(Packet);
  2047. Marshal.FreeCoTaskMem((IntPtr)Packet);
  2048. Packet = null;
  2049. }
  2050. //threadVideo.Abort();
  2051. bEndCheck = false;
  2052. return;
  2053. }
  2054. }
  2055. }
  2056. private void UpdateSound()
  2057. {
  2058. var gotSound = 0;
  2059. if (m_CurrentState != MEDIAPLAYER_STATE.PAUSED)
  2060. {
  2061. if (m_queuePacketSound.Count > 0)
  2062. pPacket = (AVPacket*)m_queuePacketSound.Dequeue();
  2063. if (pPacket != null)
  2064. {
  2065. if (pStreamAudio != null)
  2066. {
  2067. if (pPacket->stream_index == iStreamAudioIndex)
  2068. {
  2069. int iAudioLen = ffmpeg.avcodec_decode_audio4(pAudioCodecContext, pDecodedAudioFrame, &gotSound, pPacket);
  2070. if (iAudioLen >= 0)
  2071. {
  2072. if (gotSound == 1)
  2073. {
  2074. int iDataSize = ffmpeg.av_samples_get_buffer_size(null, pAudioCodecContext->channels, pDecodedAudioFrame->nb_samples, pAudioCodecContext->sample_fmt, 1);
  2075. int iDataSize2 = ffmpeg.av_samples_get_buffer_size(null, pAudioCodecContext->channels, pDecodedAudioFrame->nb_samples, AVSampleFormat.AV_SAMPLE_FMT_FLT, 1);
  2076. //if( pAudioCodecContext->sample_fmt != AVSampleFormat.AV_SAMPLE_FMT_FLT)
  2077. {
  2078. //for(int i = 0; i < pAudioCodecContext->channels; i++)
  2079. {
  2080. sbyte* outData = (sbyte*)Marshal.AllocCoTaskMem(iDataSize2 * sizeof(sbyte)); ;
  2081. SwrContext* pAudioCvtContext = null;
  2082. if (pAudioCodecContext->channel_layout == 0)
  2083. {
  2084. long layout = ffmpeg.av_get_default_channel_layout(pAudioCodecContext->channels);
  2085. pAudioCvtContext = ffmpeg.swr_alloc_set_opts(null, (long)layout, AVSampleFormat.AV_SAMPLE_FMT_FLT, pAudioCodecContext->sample_rate
  2086. , (long)layout, pAudioCodecContext->sample_fmt, pAudioCodecContext->sample_rate, 0, (void*)0);
  2087. }
  2088. else
  2089. {
  2090. pAudioCvtContext = ffmpeg.swr_alloc_set_opts(null, (long)pAudioCodecContext->channel_layout, AVSampleFormat.AV_SAMPLE_FMT_FLT, pAudioCodecContext->sample_rate
  2091. , (long)pAudioCodecContext->channel_layout, pAudioCodecContext->sample_fmt, pAudioCodecContext->sample_rate, 0, (void*)0);
  2092. }
  2093. int error = 0;
  2094. if ((error = ffmpeg.swr_init(pAudioCvtContext)) < 0)
  2095. {
  2096. Debug.Log("error " + error);
  2097. }
  2098. ffmpeg.swr_convert(pAudioCvtContext, &outData, iDataSize2, pDecodedAudioFrame->extended_data, pDecodedAudioFrame->nb_samples);
  2099. sbyte* soundFrameAddress = outData;
  2100. var soundBufferPtr = new IntPtr(soundFrameAddress);
  2101. byte[] buffer = new byte[iDataSize2];
  2102. Marshal.Copy(soundBufferPtr, buffer, 0, iDataSize2);
  2103. if ((ulong)pPacket->dts != ffmpeg.AV_NOPTS_VALUE)
  2104. {
  2105. pts = ffmpeg.av_frame_get_best_effort_timestamp(pDecodedAudioFrame);
  2106. }
  2107. else
  2108. {
  2109. pts = 0;
  2110. }
  2111. pts *= av_q2d(pStreamAudio->time_base);
  2112. if (bSeekTo == true)
  2113. {
  2114. double value = pts * (double)pDecodedAudioFrame->sample_rate;
  2115. //Debug.Log(value + " " + pts + " " + GetDuration() + " " + pDecodedAudioFrame->pkt_duration);
  2116. iSoundCount = (long)value;
  2117. fCurrentSeekTime = (float)pts;
  2118. fLastFrameTime = fCurrentSeekTime;
  2119. bSeekTo = false;
  2120. }
  2121. //Debug.Log(pts);
  2122. while (pts > 300.0f * (iInitCount + 1))
  2123. {
  2124. Debug.Log("777");
  2125. iSoundCount -= (long)(300.0 * (double)pDecodedAudioFrame->sample_rate);
  2126. // Debug.Log(iSoundCount);
  2127. iInitCount++; ;
  2128. }
  2129. //Debug.Log ("sound " + iSoundCount);
  2130. //Debug.Log (pDecodedAudioFrame->pkt_dts + " " +pDecodedAudioFrame->pkt_duration + " " + pDecodedAudioFrame->pkt_pos + " " + pDecodedAudioFrame->pkt_pts + " " + pts);
  2131. fAudioData = new float[buffer.Length / 4];
  2132. Buffer.BlockCopy(buffer, 0, fAudioData, 0, buffer.Length);
  2133. lock (listAudio)
  2134. {
  2135. listAudio.Add(fAudioData);
  2136. lock (listAudioPts)
  2137. {
  2138. lock (listAudioPtsTime)
  2139. {
  2140. iSoundCount += iDataSize2 / 4 / pDecodedAudioFrame->channels;
  2141. listAudioPts.Add(iSoundCount);
  2142. listAudioPtsTime.Add(pts);
  2143. }
  2144. }
  2145. }
  2146. //Debug.Log ( iDataSize + " "+ pts + " " + pAudioCodecContext->sample_rate + " " + pDecodedAudioFrame->sample_rate + " "+ pDecodedAudioFrame->nb_samples + " " + pDecodedAudioFrame->pkt_pts + " " + pDecodedAudioFrame->pkt_pos);
  2147. //Debug.Log ("sound decode time " + pts);
  2148. //audioClip.SetData(fAudioData,(int)(pAudioCodecContext->sample_rate * pts ) );
  2149. //audioClip.SetData(fAudioData,(int)(pDecodedAudioFrame->pkt_pts ) );
  2150. ffmpeg.swr_free(&pAudioCvtContext);
  2151. Marshal.FreeCoTaskMem((IntPtr)outData);
  2152. }
  2153. }
  2154. }
  2155. }
  2156. }
  2157. }
  2158. }
  2159. if (pPacket != null)
  2160. {
  2161. ffmpeg.av_free_packet(pPacket);
  2162. Marshal.FreeCoTaskMem((IntPtr)pPacket);
  2163. pPacket = null;
  2164. }
  2165. }
  2166. }
  2167. private void UpdateVideo()
  2168. {
  2169. var gotPicture = 0;
  2170. if(m_queuePacketVideo.Count < 3)
  2171. {
  2172. bBuffering = true;
  2173. }
  2174. if(m_queuePacketVideo.Count > 100 || bEndCheck == true)
  2175. {
  2176. bBuffering = false;
  2177. }
  2178. if(bBuffering == true)
  2179. {
  2180. return;
  2181. }
  2182. if ( m_CurrentState != MEDIAPLAYER_STATE.PAUSED)
  2183. {
  2184. if(m_queuePacketVideo.Count > 0)
  2185. pPacket = (AVPacket*)m_queuePacketVideo.Dequeue();
  2186. if (pPacket != null)
  2187. {
  2188. if (pPacket->stream_index == iStreamIndex) {
  2189. var size = ffmpeg.avcodec_decode_video2 (pCodecContext, pDecodedFrame, &gotPicture, pPacket);
  2190. if (size < 0) {
  2191. //throw new ApplicationException (string.Format (@"Error while decoding frame "));
  2192. Debug.Log("Error while decoding frame");
  2193. return;
  2194. }
  2195. if ((ulong)pPacket->dts != ffmpeg.AV_NOPTS_VALUE) {
  2196. pts = ffmpeg.av_frame_get_best_effort_timestamp (pDecodedFrame);
  2197. } else {
  2198. pts = 0;
  2199. }
  2200. pts *= av_q2d (pStream->time_base);
  2201. if (gotPicture == 1) {
  2202. if (pts > 0) {
  2203. if (listVideo.Count > 5)
  2204. {
  2205. if (!m_bIsFirstFrameReady) {
  2206. //Debug.Log("FistReady" + listVideo.Count);
  2207. m_bIsFirstFrameReady = true;
  2208. bVideoFirstFrameReady = true;
  2209. }
  2210. }
  2211. }
  2212. //Debug.Log ("Video " + pts);
  2213. //fLastFrameTime = (float)pts;
  2214. sbyte** src = &pDecodedFrame->data0;
  2215. sbyte** dst = &pConvertedFrame->data0;
  2216. int* srcStride = pDecodedFrame->linesize;
  2217. int* dstStride = pConvertedFrame->linesize;
  2218. int iLineSize = srcStride[0] ;
  2219. int iLineSize1 = srcStride[1] ;
  2220. int iLineSize2 = srcStride[2] ;
  2221. if (m_bPC_FastMode == true) {
  2222. int iVideoSize = m_iWidth * m_iHeight + (2 * m_iWidth / 2 * m_iHeight / 2);
  2223. byte[] buffer = new byte[iVideoSize];
  2224. if (iLineSize != m_iWidth) {
  2225. sbyte* convertedFrameAddress;
  2226. IntPtr imageBufferPtr;
  2227. for (int i = 0; i < m_iHeight; i++) {
  2228. convertedFrameAddress = pDecodedFrame->data0 + iLineSize * i;
  2229. imageBufferPtr = new IntPtr (convertedFrameAddress);
  2230. Marshal.Copy(imageBufferPtr,buffer ,m_iWidth * i,m_iWidth );
  2231. }
  2232. for (int i = 0; i < m_iHeight / 2; i++) {
  2233. convertedFrameAddress = pDecodedFrame->data1 + iLineSize1 * i;
  2234. imageBufferPtr = new IntPtr (convertedFrameAddress);
  2235. Marshal.Copy(imageBufferPtr,buffer,m_iWidth * m_iHeight + m_iWidth / 2 * i ,m_iWidth / 2);
  2236. convertedFrameAddress = pDecodedFrame->data2 + iLineSize2 * i;
  2237. imageBufferPtr = new IntPtr (convertedFrameAddress);
  2238. Marshal.Copy(imageBufferPtr ,buffer,m_iWidth * m_iHeight+m_iWidth / 2 * m_iHeight / 2 + m_iWidth / 2 * i,m_iWidth / 2 );
  2239. }
  2240. } else {
  2241. sbyte* convertedFrameAddress = pDecodedFrame->data0;
  2242. var imageBufferPtr = new IntPtr (convertedFrameAddress);
  2243. Marshal.Copy(imageBufferPtr,buffer,0,m_iWidth * m_iHeight);
  2244. convertedFrameAddress = pDecodedFrame->data1;
  2245. imageBufferPtr = new IntPtr (convertedFrameAddress);
  2246. Marshal.Copy(imageBufferPtr,buffer,m_iWidth * m_iHeight,m_iWidth / 2 * m_iHeight / 2);
  2247. convertedFrameAddress = pDecodedFrame->data2;
  2248. imageBufferPtr = new IntPtr (convertedFrameAddress);
  2249. Marshal.Copy(imageBufferPtr,buffer,m_iWidth * m_iHeight+m_iWidth / 2 * m_iHeight / 2,m_iWidth / 2 * m_iHeight / 2);
  2250. }
  2251. lock (listVideo)
  2252. {
  2253. listVideo.Enqueue(buffer);
  2254. lock (listVideoPts)
  2255. {
  2256. listVideoPts.Enqueue((float)pts);
  2257. }
  2258. }
  2259. } else {
  2260. ffmpeg.sws_scale (pConvertContext, src, srcStride, 0, m_iHeight, dst, dstStride);
  2261. sbyte* convertedFrameAddress = pConvertedFrame->data0;
  2262. var imageBufferPtr = new IntPtr (convertedFrameAddress);
  2263. byte[] buffer = new byte[4* m_iWidth *m_iHeight];
  2264. Marshal.Copy(imageBufferPtr,buffer,0,4* m_iWidth *m_iHeight);
  2265. lock (listVideo)
  2266. {
  2267. listVideo.Enqueue(buffer);
  2268. lock (listVideoPts)
  2269. {
  2270. listVideoPts.Enqueue((float)pts);
  2271. }
  2272. }
  2273. }
  2274. }
  2275. }
  2276. }
  2277. if (pPacket != null)
  2278. {
  2279. ffmpeg.av_free_packet(pPacket);
  2280. Marshal.FreeCoTaskMem((IntPtr)pPacket);
  2281. pPacket = null;
  2282. }
  2283. }
  2284. }
  2285. int iSoundBufferCount = 0;
  2286. /*void OnAudioSetPosition(int newPosition)
  2287. {
  2288. //Debug.Log (newPosition);
  2289. //Debug.Log("Pts" + listAudioPtsTime[0]);
  2290. }*/
  2291. void OnAudioRead(float[] data)
  2292. {
  2293. //Debug.Log (listAudio.Count);
  2294. if (listAudio.Count < 3)
  2295. {
  2296. return;
  2297. }
  2298. //Debug.Log (data.Length + " " + listAudio[1].Length);
  2299. if (iSoundBufferCount == 0) {
  2300. iSoundBufferCount = listAudio[0].Length;
  2301. }
  2302. if (iSoundBufferCount < data.Length) {
  2303. Array.Copy (listAudio [0], listAudio [0].Length - iSoundBufferCount, data, 0, iSoundBufferCount);
  2304. //Debug.Log (iSoundBufferCount + " " + data.Length + " " + listAudio [1].Length);
  2305. if ((data.Length - iSoundBufferCount) > listAudio [1].Length) {
  2306. Array.Copy (listAudio [1], 0, data, 0, listAudio [1].Length);
  2307. Array.Copy (listAudio [2], 0, data, iSoundBufferCount + listAudio [1].Length, data.Length - iSoundBufferCount - listAudio [1].Length);
  2308. iSoundBufferCount = listAudio[2].Length - (data.Length - iSoundBufferCount - listAudio [1].Length);
  2309. listAudio.RemoveAt (0);
  2310. listAudioPts.RemoveAt (0);
  2311. listAudioPtsTime.RemoveAt (0);
  2312. } else {
  2313. Array.Copy (listAudio [1], 0, data, iSoundBufferCount, data.Length - iSoundBufferCount);
  2314. iSoundBufferCount = listAudio[1].Length - (data.Length - iSoundBufferCount);
  2315. }
  2316. listAudio.RemoveAt (0);
  2317. listAudioPts.RemoveAt (0);
  2318. listAudioPtsTime.RemoveAt (0);
  2319. } else {
  2320. Array.Copy (listAudio [0], listAudio [0].Length - iSoundBufferCount, data,0, data.Length);
  2321. iSoundBufferCount -= data.Length;
  2322. }
  2323. if (iSoundBufferCount == 0) {
  2324. listAudio.RemoveAt (0);
  2325. listAudioPts.RemoveAt (0);
  2326. listAudioPtsTime.RemoveAt (0);
  2327. iSoundBufferCount = listAudio[0].Length;
  2328. }
  2329. }
  2330. private int m_LastAudioPartSetted = -1;
  2331. Material material = null;
  2332. bool m_bSetTextureFirst = false;
  2333. private void Call_UpdateVideoTexture()
  2334. {
  2335. if (bEnd == true && listVideo.Count == 0 )
  2336. {
  2337. m_CurrentState = MEDIAPLAYER_STATE.END;
  2338. if (OnEnd != null)
  2339. {
  2340. OnEnd();
  2341. //return;
  2342. }
  2343. if (m_bLoop == true)
  2344. {
  2345. Destroy (audioClip);
  2346. audioClip = null;
  2347. Load (m_strFileName);
  2348. bEnd = false;
  2349. return;
  2350. }
  2351. bEnd = false;
  2352. return;
  2353. }
  2354. if (bInterrupt == true)
  2355. {
  2356. if (audioSource != null)
  2357. {
  2358. audioSource.Pause();
  2359. }
  2360. }
  2361. else
  2362. {
  2363. if (audioSource != null && m_CurrentState == MEDIAPLAYER_STATE.PLAYING && m_bIsFirstFrameReady == true)
  2364. {
  2365. if( audioSource.isPlaying == false/* && audioSource.time > 0.02f*/)
  2366. audioSource.Play();
  2367. }
  2368. }
  2369. if (threadVideo == null && m_CurrentState != MEDIAPLAYER_STATE.END && m_CurrentState != MEDIAPLAYER_STATE.NOT_READY && m_CurrentState != MEDIAPLAYER_STATE.ERROR)
  2370. {
  2371. threadVideo = new Thread(ThreadUpdate);
  2372. threadVideo.IsBackground = true;
  2373. threadVideo.Start();
  2374. }
  2375. if ( m_CurrentState == MEDIAPLAYER_STATE.PLAYING && m_bIsFirstFrameReady == true && bInterrupt == false )
  2376. {
  2377. if( bBuffering == true)
  2378. {
  2379. if (audioSource != null)
  2380. audioSource.Pause();
  2381. }
  2382. if (listVideo.Count > 0 && bBuffering == false)
  2383. {
  2384. fCurrentSeekTime += Time.deltaTime * m_fSpeed;
  2385. }
  2386. }
  2387. //Debug.Log("last " + fLastFrameTime + " " + fCurrentSeekTime + " " + listVideo.Count);
  2388. if( fLastFrameTime > fCurrentSeekTime - 0.2f )
  2389. {
  2390. for (int i = 0; i < listAudio.Count; i++)
  2391. {
  2392. if( listAudioPtsTime.Count > i)
  2393. {
  2394. if(audioSource == null && (int)((float)pAudioCodecContext->sample_rate * ((float)listAudioPtsTime[i] + ((float)Call_GetDuration() / 1000.0f))) > 0)
  2395. {
  2396. audioSource = gameObject.AddComponent<AudioSource>();
  2397. audioSource.volume = m_fVolume;
  2398. }
  2399. }
  2400. if(audioClip == null && audioSource != null )
  2401. {
  2402. /*if ((float)Call_GetDuration() <= 0)
  2403. {
  2404. audioClip = AudioClip.Create("videoAudio",(int)((float)pAudioCodecContext->sample_rate * ((float)listAudioPtsTime[i] + 300.0f)),pAudioCodecContext->channels,pAudioCodecContext->sample_rate,true,OnAudioRead);
  2405. }
  2406. else*/
  2407. {
  2408. #if UNITY_5
  2409. audioClip = AudioClip.Create("videoAudio",(int)((float)pAudioCodecContext->sample_rate * 300.0f),pAudioCodecContext->channels,pAudioCodecContext->sample_rate,false);
  2410. #else
  2411. audioClip = AudioClip.Create("videoAudio",(int)((float)pAudioCodecContext->sample_rate * 300.0f),pAudioCodecContext->channels,pAudioCodecContext->sample_rate,false,false);
  2412. #endif
  2413. }
  2414. audioSource.clip = audioClip;
  2415. }
  2416. if (audioSource != null && Call_GetDuration() >0)
  2417. {
  2418. if( listAudioPts.Count > i)
  2419. {
  2420. if (listAudioPts [i] >= 0) {
  2421. {
  2422. /*if( listAudioPts[i] > (int)((float)pAudioCodecContext->sample_rate * ((float)listAudioPtsTime[i] + ((float)Call_GetDuration() / 1000.0f))))
  2423. {
  2424. audioClip.SetData(listAudio[i],(int)(((double)pAudioCodecContext->sample_rate) * listAudioPtsTime[i] ) );
  2425. }
  2426. else*/
  2427. {
  2428. //Debug.Log(audioSource.time + " " + (float)listAudioPtsTime[i] + " " +listAudioPts [i] +" " + fLastFrameTime + " " + listAudio[i].Length);
  2429. audioClip.SetData(listAudio[i],(int)(listAudioPts[i] % (pAudioCodecContext->sample_rate * 300.0f)) );
  2430. // audioClip.SetData(listAudio[i], (int)(listAudioPtsTime[i] % 300.0 * (double)pAudioCodecContext->sample_rate));
  2431. }
  2432. }
  2433. }
  2434. }
  2435. }
  2436. }
  2437. if (audioSource != null && audioSource.isPlaying && Call_GetDuration() >0) {
  2438. listAudio.Clear();
  2439. listAudioPts.Clear();
  2440. listAudioPtsTime.Clear();
  2441. }
  2442. }
  2443. else
  2444. {
  2445. //do
  2446. {
  2447. #if (UNITY_5_2 || UNITY_5_3_OR_NEWER)
  2448. if( listVideo.Count > 0)
  2449. {
  2450. if (m_bPC_FastMode == true)
  2451. {
  2452. if (SystemInfo.graphicsDeviceType == UnityEngine.Rendering.GraphicsDeviceType.Direct3D11)
  2453. {
  2454. m_texPtrY = m_VideoTextureY.GetNativeTexturePtr();
  2455. m_texPtrU = m_VideoTextureU.GetNativeTexturePtr();
  2456. m_texPtrV = m_VideoTextureV.GetNativeTexturePtr();
  2457. }
  2458. SetTextureFromUnity (m_iID,(IntPtr)0,m_texPtrY,m_texPtrU,m_texPtrV, m_iWidth, m_iHeight, listVideo.Dequeue());
  2459. if (SystemInfo.graphicsDeviceType == UnityEngine.Rendering.GraphicsDeviceType.Metal)
  2460. {
  2461. GL.IssuePluginEvent(GetRenderEventFunc(), 8000 + m_iID);
  2462. }
  2463. else
  2464. {
  2465. GL.IssuePluginEvent(GetRenderEventFunc(), 7000 + m_iID);
  2466. }
  2467. }
  2468. else
  2469. {
  2470. if (SystemInfo.graphicsDeviceType == UnityEngine.Rendering.GraphicsDeviceType.Direct3D11)
  2471. {
  2472. m_texPtr = m_VideoTexture.GetNativeTexturePtr();
  2473. }
  2474. SetTextureFromUnity (m_iID,m_texPtr,(IntPtr)0,(IntPtr)0,(IntPtr)0, m_iWidth, m_iHeight, listVideo.Dequeue());
  2475. if (SystemInfo.graphicsDeviceType == UnityEngine.Rendering.GraphicsDeviceType.Metal)
  2476. {
  2477. GL.IssuePluginEvent(GetRenderEventFunc(), 8000 + m_iID);
  2478. }
  2479. else
  2480. {
  2481. GL.IssuePluginEvent(GetRenderEventFunc(), 7000 + m_iID);
  2482. }
  2483. }
  2484. }
  2485. if( listVideoPts.Count > 0)
  2486. {
  2487. float fpts = listVideoPts.Dequeue();
  2488. if (fpts > fCurrentSeekTime + 2.0f)
  2489. {
  2490. fCurrentSeekTime = fpts;
  2491. double value = pts * (double)pDecodedAudioFrame->sample_rate;
  2492. //Debug.Log(value + " " + pts + " " + GetDuration() + " " + pDecodedAudioFrame->pkt_duration);
  2493. iSoundCount = (long)value;
  2494. }
  2495. //Debug.Log(fpts + " " + audioSource.time);
  2496. /* if (fpts > fCurrentSeekTime)
  2497. {
  2498. fCurrentSeekTime = fpts;
  2499. }*/
  2500. if (fLastFrameTime == 0)
  2501. {
  2502. {
  2503. if(fpts<0)
  2504. {
  2505. fLastFrameTime = 0;
  2506. }
  2507. else
  2508. {
  2509. fCurrentSeekTime = fpts;
  2510. fLastFrameTime = fpts;
  2511. }
  2512. if( audioSource != null && Call_GetDuration() >0 )
  2513. {
  2514. audioSource.time = fLastFrameTime%300.0f;
  2515. }
  2516. }
  2517. }
  2518. else
  2519. {
  2520. if(fpts<=0)
  2521. fLastFrameTime = fCurrentSeekTime - 0.05f;
  2522. else
  2523. fLastFrameTime = fpts;
  2524. }
  2525. }
  2526. if( audioSource != null && Call_GetDuration() > 0)
  2527. {
  2528. if( audioSource.time - fLastFrameTime%300.0f > 0.1f)
  2529. {
  2530. //Debug.Log("sync1 " + audioSource.time + " " + fLastFrameTime);
  2531. audioSource.time = fLastFrameTime%300.0f;
  2532. }
  2533. else if( audioSource.time - fLastFrameTime%300.0f < -0.1f)
  2534. {
  2535. //Debug.Log("sync2");
  2536. audioSource.time = fLastFrameTime%300.0f;
  2537. }
  2538. }
  2539. #else
  2540. //var imageBufferPtr = new IntPtr (convertedFrameAddress);
  2541. if( listVideo.Count > 0)
  2542. {
  2543. m_VideoTexture.LoadRawTextureData(listVideo.Dequeue());
  2544. m_VideoTexture.Apply();
  2545. }
  2546. if( listVideoPts.Count > 0)
  2547. {
  2548. float fpts = listVideoPts.Dequeue();
  2549. if(fLastFrameTime == 0)
  2550. {
  2551. if( fpts > fCurrentSeekTime)
  2552. {
  2553. fLastFrameTime = fCurrentSeekTime;
  2554. }
  2555. }
  2556. else
  2557. {
  2558. fLastFrameTime = fpts;
  2559. }
  2560. }
  2561. if( audioSource != null)
  2562. {
  2563. /*if( audioSource.time - fLastFrameTime > 0)
  2564. {
  2565. //Debug.Log("sync1");
  2566. audioSource.time = fLastFrameTime;
  2567. }
  2568. else if( audioSource.time - fLastFrameTime < -0.2f)
  2569. {
  2570. //Debug.Log("sync2");
  2571. audioSource.time = fLastFrameTime;
  2572. }*/
  2573. }
  2574. #endif
  2575. if (m_bSetTextureFirst == false)
  2576. {
  2577. m_bSetTextureFirst = true;
  2578. if (m_shaderYUV == null)
  2579. {
  2580. m_shaderYUV = Shader.Find("Unlit/Unlit_YUV");
  2581. }
  2582. if (material == null)
  2583. {
  2584. material = new Material(m_shaderYUV);
  2585. }
  2586. if (m_TargetMaterial != null)
  2587. {
  2588. for (int i = 0; i < m_TargetMaterial.Length; i++)
  2589. {
  2590. if (m_TargetMaterial[i] == null)
  2591. continue;
  2592. if (m_TargetMaterial[i].GetComponent<MeshRenderer>() != null)
  2593. {
  2594. if (m_TargetMaterial[i].GetComponent<MeshRenderer>().material.mainTexture != m_VideoTexture)
  2595. {
  2596. m_TargetMaterial[i].GetComponent<MeshRenderer>().material.mainTexture = m_VideoTexture;
  2597. }
  2598. }
  2599. if (m_bPC_FastMode == true)
  2600. {
  2601. if (m_TargetMaterial[i].GetComponent<MeshRenderer>() != null)
  2602. {
  2603. material.mainTextureScale = m_TargetMaterial[i].GetComponent<MeshRenderer>().material.mainTextureScale;
  2604. material.mainTextureOffset = m_TargetMaterial[i].GetComponent<MeshRenderer>().material.mainTextureOffset;
  2605. m_TargetMaterial[i].GetComponent<MeshRenderer>().material = material;
  2606. if (m_TargetMaterial[i].GetComponent<MeshRenderer>().material.GetTexture("_Y") != m_VideoTextureY)
  2607. {
  2608. m_TargetMaterial[i].GetComponent<MeshRenderer>().material.SetTexture("_Y", m_VideoTextureY);
  2609. }
  2610. if (m_TargetMaterial[i].GetComponent<MeshRenderer>().material.GetTexture("_U") != m_VideoTextureU)
  2611. {
  2612. m_TargetMaterial[i].GetComponent<MeshRenderer>().material.SetTexture("_U", m_VideoTextureU);
  2613. }
  2614. if (m_TargetMaterial[i].GetComponent<MeshRenderer>().material.GetTexture("_V") != m_VideoTextureV)
  2615. {
  2616. m_TargetMaterial[i].GetComponent<MeshRenderer>().material.SetTexture("_V", m_VideoTextureV);
  2617. }
  2618. }
  2619. }
  2620. if (m_TargetMaterial[i].GetComponent<RawImage>() != null)
  2621. {
  2622. if (m_TargetMaterial[i].GetComponent<RawImage>().texture != m_VideoTexture)
  2623. {
  2624. m_TargetMaterial[i].GetComponent<RawImage>().texture = m_VideoTexture;
  2625. }
  2626. }
  2627. if (m_bPC_FastMode == true)
  2628. {
  2629. if (m_TargetMaterial[i].GetComponent<RawImage>() != null)
  2630. {
  2631. m_TargetMaterial[i].GetComponent<RawImage>().material = material;
  2632. if (m_TargetMaterial[i].GetComponent<RawImage>().material.GetTexture("_Y") != m_VideoTextureY)
  2633. {
  2634. m_TargetMaterial[i].GetComponent<RawImage>().material.SetTexture("_Y", m_VideoTextureY);
  2635. }
  2636. if (m_TargetMaterial[i].GetComponent<RawImage>().material.GetTexture("_U") != m_VideoTextureU)
  2637. {
  2638. m_TargetMaterial[i].GetComponent<RawImage>().material.SetTexture("_U", m_VideoTextureU);
  2639. }
  2640. if (m_TargetMaterial[i].GetComponent<RawImage>().material.GetTexture("_V") != m_VideoTextureV)
  2641. {
  2642. m_TargetMaterial[i].GetComponent<RawImage>().material.SetTexture("_V", m_VideoTextureV);
  2643. }
  2644. }
  2645. }
  2646. }
  2647. }
  2648. }
  2649. if (bVideoFirstFrameReady == true) {
  2650. if (OnVideoFirstFrameReady != null) {
  2651. OnVideoFirstFrameReady ();
  2652. bVideoFirstFrameReady = false;
  2653. }
  2654. if (listAudio.Count > 0)
  2655. {
  2656. if (audioSource == null /*&& (int)((float)pAudioCodecContext->sample_rate * ((float)listAudioPtsTime[i] + ((float)Call_GetDuration() / 1000.0f))) > 0*/)
  2657. {
  2658. audioSource = gameObject.AddComponent<AudioSource>();
  2659. }
  2660. if (audioClip == null && audioSource != null)
  2661. {
  2662. /*if ((float)Call_GetDuration() <= 0)
  2663. {
  2664. audioClip = AudioClip.Create("videoAudio",(int)((float)pAudioCodecContext->sample_rate * ((float)listAudioPtsTime[i] + 300.0f)),pAudioCodecContext->channels,pAudioCodecContext->sample_rate,true,OnAudioRead);
  2665. }
  2666. else*/
  2667. {
  2668. /*if (Call_GetDuration () > 1500000) {
  2669. audioClip = AudioClip.Create("videoAudio",(int)((float)pAudioCodecContext->sample_rate * ((float)listAudioPtsTime[i] + 10.0f)),pAudioCodecContext->channels,pAudioCodecContext->sample_rate,false);
  2670. }
  2671. else{
  2672. audioClip = AudioClip.Create("videoAudio",(int)((float)pAudioCodecContext->sample_rate * ((float)listAudioPtsTime[i] + 300.0f)),pAudioCodecContext->channels,pAudioCodecContext->sample_rate,false);
  2673. }*/
  2674. #if UNITY_5
  2675. audioClip = AudioClip.Create("videoAudio", (int)((float)pAudioCodecContext->sample_rate * 300.0f), pAudioCodecContext->channels, pAudioCodecContext->sample_rate, false);
  2676. #else
  2677. audioClip = AudioClip.Create("videoAudio",(int)((float)pAudioCodecContext->sample_rate * 300.0f),pAudioCodecContext->channels,pAudioCodecContext->sample_rate,false,false);
  2678. #endif
  2679. }
  2680. audioSource.clip = audioClip;
  2681. //audioSource.Play();
  2682. //AudioSource.PlayClipAtPoint(audioClip,new Vector3(0,0,0));
  2683. }
  2684. }
  2685. // Just to be sure I guess - don't know what migh happen if I seek in video etc...
  2686. if (m_LastAudioPartSetted > listAudio.Count)
  2687. {
  2688. m_LastAudioPartSetted = -1;
  2689. }
  2690. // using m_LastAudioPartSetted - 1 again to be sure - what if the last part of audio gets updated/appended? IDK...
  2691. for (int i = Math.Max(0, m_LastAudioPartSetted - 1); i < listAudio.Count; i++) {
  2692. m_LastAudioPartSetted = i;
  2693. if (audioSource != null && Call_GetDuration() >0 || Call_GetDuration() == 0) {
  2694. if (listAudioPts.Count > i) {
  2695. if (listAudioPts [i] >= 0) {
  2696. {
  2697. /*if (listAudioPts [i] > (int)((float)pAudioCodecContext->sample_rate * ((float)listAudioPtsTime [i] + ((float)Call_GetDuration () / 1000.0f)))) {
  2698. audioClip.SetData (listAudio [i], (int)(((double)pAudioCodecContext->sample_rate) * listAudioPtsTime [i]));
  2699. } else*/ {
  2700. //Debug.Log(audioSource.time + " " + (float)listAudioPtsTime[i] + " " +listAudioPts [i] +" " + fLastFrameTime + " " + listAudio[i].Length);
  2701. audioClip.SetData(listAudio[i],(int)(listAudioPts[i] % (pAudioCodecContext->sample_rate * 300.0f)) );
  2702. }
  2703. }
  2704. }
  2705. }
  2706. //if(audioSource.isPlaying == false)
  2707. //audioSource.Play();
  2708. }
  2709. }
  2710. }
  2711. }//while(fLastFrameTime < fCurrentSeekTime );
  2712. //Debug.Log(listAudio.Count);
  2713. }
  2714. }
  2715. private void Call_SetVolume(float fVolume)
  2716. {
  2717. if (audioSource != null)
  2718. audioSource.volume = fVolume;
  2719. }
  2720. bool bSeekTo = false;
  2721. private void Call_SetSeekPosition(int iSeek)
  2722. {
  2723. if( threadVideo != null)
  2724. {
  2725. while(threadVideo.IsAlive == true)
  2726. {
  2727. threadVideo.Abort();
  2728. }
  2729. threadVideo = null;
  2730. }
  2731. bSeekTo = true;
  2732. iInitCount = 0;
  2733. long seek_target = (long)iSeek * 1000;
  2734. Debug.Log (seek_target);
  2735. seek_target= ffmpeg.av_rescale_q(seek_target, ffmpeg.av_get_time_base_q() , pStream->time_base);
  2736. Debug.Log (seek_target);
  2737. //int seek_flags = iSeek - (int)(fLastFrameTime * 1000.0f) < 0 ? ffmpeg.AVSEEK_FLAG_BACKWARD : ffmpeg.AVSEEK_FLAG_BACKWARD;
  2738. if(ffmpeg.av_seek_frame(pFormatContext, iStreamIndex,
  2739. seek_target, ffmpeg.AVSEEK_FLAG_BACKWARD) < 0) {
  2740. //error
  2741. } else {
  2742. /* handle packet queues... more later... */
  2743. }
  2744. fCurrentSeekTime = (float)iSeek / 1000.0f;
  2745. //fLastFrameTime = (float)iSeek / 1000.0f;
  2746. listVideo.Clear();
  2747. listVideoPts.Clear();
  2748. listAudio.Clear();
  2749. listAudioPts.Clear();
  2750. listAudioPtsTime.Clear();
  2751. int iCount = m_queuePacketVideo.Count;
  2752. for (int i = 0; i < iCount; i++)
  2753. {
  2754. if (m_queuePacketVideo.Count > 0)
  2755. pPacket = (AVPacket*)m_queuePacketVideo.Dequeue();
  2756. if (pPacket != null)
  2757. {
  2758. ffmpeg.av_free_packet(pPacket);
  2759. Marshal.FreeCoTaskMem((IntPtr)pPacket);
  2760. pPacket = null;
  2761. }
  2762. }
  2763. iCount = m_queuePacketSound.Count;
  2764. for (int i = 0; i < iCount; i++)
  2765. {
  2766. if (m_queuePacketSound.Count > 0)
  2767. pPacket = (AVPacket*)m_queuePacketSound.Dequeue();
  2768. if (pPacket != null)
  2769. {
  2770. ffmpeg.av_free_packet(pPacket);
  2771. Marshal.FreeCoTaskMem((IntPtr)pPacket);
  2772. pPacket = null;
  2773. }
  2774. }
  2775. Destroy(audioClip);
  2776. audioClip = null;
  2777. ffmpeg.avcodec_flush_buffers (pCodecContext);
  2778. //Debug.Log (fLastFrameTime + " " + fCurrentSeekTime);
  2779. }
  2780. private int Call_GetSeekPosition()
  2781. {
  2782. return (int)(fCurrentSeekTime * 1000.0f);
  2783. }
  2784. private void Call_Play(int iSeek)
  2785. {
  2786. if (m_CurrentState == MEDIAPLAYER_STATE.READY || m_CurrentState == MEDIAPLAYER_STATE.STOPPED || m_CurrentState == MEDIAPLAYER_STATE.END || m_CurrentState == MEDIAPLAYER_STATE.PAUSED) {
  2787. SeekTo (iSeek);
  2788. if (audioSource != null) {
  2789. if( audioSource.isPlaying == false)
  2790. audioSource.Play();
  2791. audioSource.time = (float) iSeek / 1000.0f;
  2792. }
  2793. bEnd = false;
  2794. m_CurrentState = MEDIAPLAYER_STATE.PLAYING;
  2795. }
  2796. }
  2797. private void Call_Reset()
  2798. {
  2799. }
  2800. private void Call_Stop()
  2801. {
  2802. SeekTo (0);
  2803. if (audioSource != null) {
  2804. audioSource.Stop ();
  2805. audioSource.time = 0.0f;
  2806. }
  2807. m_CurrentState = MEDIAPLAYER_STATE.STOPPED;
  2808. }
  2809. private void Call_RePlay()
  2810. {
  2811. if (audioSource != null) {
  2812. if( audioSource.isPlaying == false)
  2813. audioSource.Play();
  2814. }
  2815. m_CurrentState = MEDIAPLAYER_STATE.PLAYING;
  2816. }
  2817. private void Call_Pause()
  2818. {
  2819. if (audioSource != null) {
  2820. audioSource.Pause();
  2821. }
  2822. m_CurrentState = MEDIAPLAYER_STATE.PAUSED;
  2823. }
  2824. private int Call_GetVideoWidth()
  2825. {
  2826. //Debug.Log (m_iWidth);
  2827. return m_iWidth;
  2828. }
  2829. private int Call_GetVideoHeight()
  2830. {
  2831. //Debug.Log (m_iHeight);
  2832. return m_iHeight;
  2833. }
  2834. private void Call_SetUnityTexture(int iTextureID)
  2835. {
  2836. }
  2837. private void Call_SetWindowSize()
  2838. {
  2839. }
  2840. private void Call_SetLooping(bool bLoop)
  2841. {
  2842. }
  2843. private void Call_SetRockchip(bool bValue)
  2844. {
  2845. }
  2846. public void Call_SetUnityActivity()
  2847. {
  2848. ffmpeg.av_register_all();
  2849. ffmpeg.avcodec_register_all();
  2850. ffmpeg.avformat_network_init();
  2851. m_iID = SetTexture ();
  2852. }
  2853. private int Call_GetError()
  2854. {
  2855. return 0;
  2856. }
  2857. private int Call_GetErrorExtra()
  2858. {
  2859. return 0;
  2860. }
  2861. private int Call_GetDuration()
  2862. {
  2863. //Debug.Log ((int)(pFormatContext->duration / 1000));
  2864. if (pFormatContext != null)
  2865. return (int)(pFormatContext->duration / 1000);
  2866. return 0;
  2867. }
  2868. private int Call_GetCurrentSeekPercent()
  2869. {
  2870. if (pStream != null)
  2871. return (int)(((double)fCurrentSeekTime + ((double)m_queuePacketVideo.Count / av_q2d(pStream->avg_frame_rate))) / (Call_GetDuration() / 1000.0) * 100);
  2872. return -1;
  2873. }
  2874. private void Call_SetSplitOBB(bool bValue, string strOBBName)
  2875. {
  2876. }
  2877. private void Call_SelectSoundTrack(int iIndex)
  2878. {
  2879. }
  2880. private int[] Call_GetSoundTrack()
  2881. {
  2882. return null;
  2883. }
  2884. private void Call_SetSpeed(float fSpeed)
  2885. {
  2886. if (audioSource != null) {
  2887. audioSource.pitch = fSpeed;
  2888. }
  2889. }
  2890. private MEDIAPLAYER_STATE Call_GetStatus()
  2891. {
  2892. return m_CurrentState;
  2893. }
  2894. #endif // !UNITY_EDITOR
  2895. public IEnumerator DownloadStreamingVideoAndLoad(string strURL)
  2896. {
  2897. strURL = strURL.Trim();
  2898. Debug.Log("DownloadStreamingVideo : " + strURL);
  2899. WWW www = new WWW(strURL);
  2900. yield return www;
  2901. if (string.IsNullOrEmpty(www.error))
  2902. {
  2903. if (System.IO.Directory.Exists(Application.persistentDataPath + "/Data") == false)
  2904. System.IO.Directory.CreateDirectory(Application.persistentDataPath + "/Data");
  2905. string write_path = Application.persistentDataPath + "/Data" + strURL.Substring(strURL.LastIndexOf("/"));
  2906. /* if(System.IO.File.Exists(write_path) == true)
  2907. {
  2908. Debug.Log("Delete : " + write_path);
  2909. System.IO.File.Delete(write_path);
  2910. }
  2911. */
  2912. System.IO.File.WriteAllBytes(write_path, www.bytes);
  2913. Load("file://" + write_path);
  2914. }
  2915. else
  2916. {
  2917. Debug.Log(www.error);
  2918. }
  2919. www.Dispose();
  2920. www = null;
  2921. Resources.UnloadUnusedAssets();
  2922. }
  2923. public IEnumerator DownloadStreamingVideoAndLoad2(string strURL)
  2924. {
  2925. strURL = strURL.Trim();
  2926. string write_path = Application.persistentDataPath + "/Data" + strURL.Substring(strURL.LastIndexOf("/"));
  2927. if (System.IO.File.Exists(write_path) == true)
  2928. {
  2929. Load("file://" + write_path);
  2930. }
  2931. else
  2932. {
  2933. WWW www = new WWW(strURL);
  2934. yield return www;
  2935. if (string.IsNullOrEmpty(www.error))
  2936. {
  2937. if (System.IO.Directory.Exists(Application.persistentDataPath + "/Data") == false)
  2938. System.IO.Directory.CreateDirectory(Application.persistentDataPath + "/Data");
  2939. System.IO.File.WriteAllBytes(write_path, www.bytes);
  2940. Load("file://" + write_path);
  2941. }
  2942. else
  2943. {
  2944. Debug.Log(www.error);
  2945. }
  2946. www.Dispose();
  2947. www = null;
  2948. Resources.UnloadUnusedAssets();
  2949. }
  2950. }
  2951. IEnumerator CopyStreamingAssetVideoAndLoad(string strURL)
  2952. {
  2953. strURL = strURL.Trim();
  2954. string write_path = Application.persistentDataPath + "/" + strURL;
  2955. if (System.IO.File.Exists(write_path) == false)
  2956. {
  2957. Debug.Log("CopyStreamingAssetVideoAndLoad : " + strURL);
  2958. WWW www = new WWW(Application.streamingAssetsPath + "/" + strURL);
  2959. yield return www;
  2960. if (string.IsNullOrEmpty(www.error))
  2961. {
  2962. Debug.Log(write_path);
  2963. System.IO.File.WriteAllBytes(write_path, www.bytes);
  2964. Load("file://" + write_path);
  2965. }
  2966. else
  2967. {
  2968. Debug.Log(www.error);
  2969. }
  2970. www.Dispose();
  2971. www = null;
  2972. }
  2973. else
  2974. {
  2975. Load("file://" + write_path);
  2976. }
  2977. }
  2978. #endif
  2979. #region UnityMainThread adapter
  2980. private List<Action> unityMainThreadActionList = new List<Action>();
  2981. private bool checkNewActions = false;
  2982. private object thisLock = new object();
  2983. /// <summary>
  2984. /// Execute UnityMainThread operations from unityMainThreadActionList List
  2985. /// </summary>
  2986. void CheckThreading()
  2987. {
  2988. lock (thisLock)
  2989. {
  2990. if (unityMainThreadActionList.Count > 0)
  2991. {
  2992. foreach(var a in unityMainThreadActionList)
  2993. {
  2994. a();
  2995. }
  2996. unityMainThreadActionList.Clear ();
  2997. }
  2998. }
  2999. }
  3000. /// <summary>
  3001. /// Add a sequence of Code enclosed into the Action (a). It triggers checkNewActions to execute code into the Unity Thread Update
  3002. /// </summary>
  3003. /// <param name="a">The alpha component.</param>
  3004. void AddActionForUnityMainThread(Action a)
  3005. {
  3006. lock (thisLock)
  3007. {
  3008. unityMainThreadActionList.Add(a);
  3009. }
  3010. checkNewActions = true;
  3011. }
  3012. #endregion
  3013. }