PageRenderTime 59ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/actionscript/happyworm/jPlayer/JplayerMp4.as

http://github.com/happyworm/jPlayer
ActionScript | 413 lines | 364 code | 25 blank | 24 comment | 100 complexity | f09825ba9d2d2211edfab4744a59f876 MD5 | raw file
  1. /*
  2. * jPlayer Plugin for jQuery JavaScript Library
  3. * http://www.happyworm.com/jquery/jplayer
  4. *
  5. * Copyright (c) 2009 - 2011 Happyworm Ltd
  6. * Dual licensed under the MIT and GPL licenses.
  7. * - http://www.opensource.org/licenses/mit-license.php
  8. * - http://www.gnu.org/copyleft/gpl.html
  9. *
  10. * Author: Mark J Panaghiston
  11. * Date: 7th August 2011
  12. */
  13. package happyworm.jPlayer {
  14. import flash.display.Sprite;
  15. import flash.media.Video;
  16. import flash.media.SoundTransform;
  17. import flash.net.NetConnection;
  18. import flash.net.NetStream;
  19. import flash.utils.Timer;
  20. import flash.events.NetStatusEvent;
  21. import flash.events.SecurityErrorEvent;
  22. import flash.events.TimerEvent;
  23. public class JplayerMp4 extends Sprite {
  24. public var myVideo:Video = new Video();
  25. private var myConnection:NetConnection;
  26. private var myStream:NetStream;
  27. private var myTransform:SoundTransform = new SoundTransform();
  28. public var myStatus:JplayerStatus = new JplayerStatus();
  29. private var timeUpdateTimer:Timer = new Timer(250, 0); // Matched to HTML event freq
  30. private var progressTimer:Timer = new Timer(250, 0); // Matched to HTML event freq
  31. private var seekingTimer:Timer = new Timer(100, 0); // Internal: How often seeking is checked to see if it is over.
  32. public function JplayerMp4(volume:Number) {
  33. myConnection = new NetConnection();
  34. myConnection.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
  35. myConnection.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
  36. myVideo.smoothing = true;
  37. this.addChild(myVideo);
  38. timeUpdateTimer.addEventListener(TimerEvent.TIMER, timeUpdateHandler);
  39. progressTimer.addEventListener(TimerEvent.TIMER, progressHandler);
  40. seekingTimer.addEventListener(TimerEvent.TIMER, seekingHandler);
  41. myStatus.volume = volume;
  42. }
  43. private function progressUpdates(active:Boolean):void {
  44. if(active) {
  45. progressTimer.start();
  46. } else {
  47. progressTimer.stop();
  48. }
  49. }
  50. private function progressHandler(e:TimerEvent):void {
  51. if(myStatus.isLoading) {
  52. if(getLoadRatio() == 1) { // Close as can get to a loadComplete event since client.onPlayStatus only works with FMS
  53. this.dispatchEvent(new JplayerEvent(JplayerEvent.DEBUG_MSG, myStatus, "progressHandler: loadComplete"));
  54. myStatus.loaded();
  55. progressUpdates(false);
  56. }
  57. }
  58. progressEvent();
  59. }
  60. private function progressEvent():void {
  61. this.dispatchEvent(new JplayerEvent(JplayerEvent.DEBUG_MSG, myStatus, "progressEvent:"));
  62. updateStatusValues();
  63. this.dispatchEvent(new JplayerEvent(JplayerEvent.JPLAYER_PROGRESS, myStatus));
  64. }
  65. private function timeUpdates(active:Boolean):void {
  66. if(active) {
  67. timeUpdateTimer.start();
  68. } else {
  69. timeUpdateTimer.stop();
  70. }
  71. }
  72. private function timeUpdateHandler(e:TimerEvent):void {
  73. timeUpdateEvent();
  74. }
  75. private function timeUpdateEvent():void {
  76. updateStatusValues();
  77. this.dispatchEvent(new JplayerEvent(JplayerEvent.JPLAYER_TIMEUPDATE, myStatus));
  78. }
  79. private function seeking(active:Boolean):void {
  80. if(active) {
  81. if(!myStatus.isSeeking) {
  82. seekingEvent();
  83. }
  84. seekingTimer.start();
  85. } else {
  86. if(myStatus.isSeeking) {
  87. seekedEvent();
  88. }
  89. seekingTimer.stop();
  90. }
  91. }
  92. private function seekingHandler(e:TimerEvent):void {
  93. if(getSeekTimeRatio() <= getLoadRatio()) {
  94. seeking(false);
  95. if(myStatus.playOnSeek) {
  96. myStatus.playOnSeek = false; // Capture the flag.
  97. play(myStatus.pausePosition); // Must pass time or the seek time is never set.
  98. } else {
  99. pause(myStatus.pausePosition); // Must pass time or the stream.time is read.
  100. }
  101. } else if(myStatus.metaDataReady && myStatus.pausePosition > myStatus.duration) {
  102. // Illegal seek time
  103. seeking(false);
  104. pause(0);
  105. }
  106. }
  107. private function seekingEvent():void {
  108. myStatus.isSeeking = true;
  109. updateStatusValues();
  110. this.dispatchEvent(new JplayerEvent(JplayerEvent.JPLAYER_SEEKING, myStatus));
  111. }
  112. private function seekedEvent():void {
  113. myStatus.isSeeking = false;
  114. updateStatusValues();
  115. this.dispatchEvent(new JplayerEvent(JplayerEvent.JPLAYER_SEEKED, myStatus));
  116. }
  117. private function netStatusHandler(e:NetStatusEvent):void {
  118. this.dispatchEvent(new JplayerEvent(JplayerEvent.DEBUG_MSG, myStatus, "netStatusHandler: '" + e.info.code + "'"));
  119. switch(e.info.code) {
  120. case "NetConnection.Connect.Success":
  121. connectStream();
  122. break;
  123. case "NetStream.Play.Start":
  124. // This event code occurs once, when the media is opened. Equiv to loadOpen() in mp3 player.
  125. myStatus.loading();
  126. this.dispatchEvent(new JplayerEvent(JplayerEvent.JPLAYER_LOADSTART, myStatus));
  127. progressUpdates(true);
  128. // See onMetaDataHandler() for other condition, since duration is vital.
  129. break;
  130. case "NetStream.Play.Stop":
  131. this.dispatchEvent(new JplayerEvent(JplayerEvent.DEBUG_MSG, myStatus, "NetStream.Play.Stop: getDuration() - getCurrentTime() = " + (getDuration() - getCurrentTime())));
  132. // Check if media is at the end (or close) otherwise this was due to download bandwidth stopping playback. ie., Download is not fast enough.
  133. if(Math.abs(getDuration() - getCurrentTime()) < 150) { // Testing found 150ms worked best for M4A files, where playHead(99.9) caused a stuck state due to firing with ~116ms left to play.
  134. endedEvent();
  135. }
  136. break;
  137. case "NetStream.Seek.InvalidTime":
  138. // Used for capturing invalid set times and clicks on the end of the progress bar.
  139. endedEvent();
  140. break;
  141. case "NetStream.Play.StreamNotFound":
  142. myStatus.error(); // Resets status except the src, and it sets srcError property.
  143. this.dispatchEvent(new JplayerEvent(JplayerEvent.JPLAYER_ERROR, myStatus));
  144. break;
  145. }
  146. // "NetStream.Seek.Notify" event code is not very useful. It occurs after every seek(t) command issued and does not appear to wait for the media to be ready.
  147. }
  148. private function endedEvent():void {
  149. var wasPlaying:Boolean = myStatus.isPlaying;
  150. pause(0);
  151. timeUpdates(false);
  152. timeUpdateEvent();
  153. if(wasPlaying) {
  154. this.dispatchEvent(new JplayerEvent(JplayerEvent.JPLAYER_ENDED, myStatus));
  155. }
  156. }
  157. private function securityErrorHandler(event:SecurityErrorEvent):void {
  158. this.dispatchEvent(new JplayerEvent(JplayerEvent.DEBUG_MSG, myStatus, "securityErrorHandler."));
  159. }
  160. private function connectStream():void {
  161. this.dispatchEvent(new JplayerEvent(JplayerEvent.DEBUG_MSG, myStatus, "connectStream."));
  162. var customClient:Object = new Object();
  163. customClient.onMetaData = onMetaDataHandler;
  164. // customClient.onPlayStatus = onPlayStatusHandler; // According to the forums and my tests, onPlayStatus only works with FMS (Flash Media Server).
  165. myStream = null;
  166. myStream = new NetStream(myConnection);
  167. myStream.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
  168. myStream.client = customClient;
  169. myVideo.attachNetStream(myStream);
  170. setVolume(myStatus.volume);
  171. myStream.play(myStatus.src);
  172. }
  173. public function setFile(src:String):void {
  174. if(myStream != null) {
  175. myStream.close();
  176. }
  177. myVideo.clear();
  178. progressUpdates(false);
  179. timeUpdates(false);
  180. myStatus.reset();
  181. myStatus.src = src;
  182. myStatus.srcSet = true;
  183. timeUpdateEvent();
  184. }
  185. public function clearFile():void {
  186. setFile("");
  187. myStatus.srcSet = false;
  188. }
  189. public function load():Boolean {
  190. if(myStatus.loadRequired()) {
  191. myStatus.startingDownload();
  192. myConnection.connect(null);
  193. return true;
  194. } else {
  195. return false;
  196. }
  197. }
  198. public function play(time:Number = NaN):Boolean {
  199. var wasPlaying:Boolean = myStatus.isPlaying;
  200. if(!isNaN(time) && myStatus.srcSet) {
  201. if(myStatus.isPlaying) {
  202. myStream.pause();
  203. myStatus.isPlaying = false;
  204. }
  205. myStatus.pausePosition = time;
  206. }
  207. if(myStatus.isStartingDownload) {
  208. myStatus.playOnLoad = true; // Raise flag, captured in onMetaDataHandler()
  209. return true;
  210. } else if(myStatus.loadRequired()) {
  211. myStatus.playOnLoad = true; // Raise flag, captured in onMetaDataHandler()
  212. return load();
  213. } else if((myStatus.isLoading || myStatus.isLoaded) && !myStatus.isPlaying) {
  214. if(myStatus.metaDataReady && myStatus.pausePosition > myStatus.duration) { // The time is invalid, ie., past the end.
  215. myStream.pause(); // Since it is playing by default at this point.
  216. myStatus.pausePosition = 0;
  217. myStream.seek(0);
  218. timeUpdates(false);
  219. timeUpdateEvent();
  220. if(wasPlaying) { // For when playing and then get a play(huge)
  221. this.dispatchEvent(new JplayerEvent(JplayerEvent.JPLAYER_PAUSE, myStatus));
  222. }
  223. } else if(getSeekTimeRatio() > getLoadRatio()) { // Use an estimate based on the downloaded amount
  224. myStatus.playOnSeek = true;
  225. seeking(true);
  226. myStream.pause(); // Since it is playing by default at this point.
  227. } else {
  228. if(!isNaN(time)) { // Avoid using seek() when it is already correct.
  229. myStream.seek(myStatus.pausePosition/1000); // Since time is in ms and seek() takes seconds
  230. }
  231. myStatus.isPlaying = true; // Set immediately before playing. Could affects events.
  232. myStream.resume();
  233. timeUpdates(true);
  234. if(!wasPlaying) {
  235. this.dispatchEvent(new JplayerEvent(JplayerEvent.JPLAYER_PLAY, myStatus));
  236. }
  237. }
  238. return true;
  239. } else {
  240. return false;
  241. }
  242. }
  243. public function pause(time:Number = NaN):Boolean {
  244. myStatus.playOnLoad = false; // Reset flag in case load/play issued immediately before this command, ie., before onMetadata() event.
  245. myStatus.playOnSeek = false; // Reset flag in case play(time) issued before the command and is still seeking to time set.
  246. var wasPlaying:Boolean = myStatus.isPlaying;
  247. // To avoid possible loops with timeupdate and pause(time). A pause() does not have the problem.
  248. var alreadyPausedAtTime:Boolean = false;
  249. if(!isNaN(time) && myStatus.pausePosition == time) {
  250. alreadyPausedAtTime = true;
  251. }
  252. // Need to wait for metadata to load before ever issuing a pause. The metadata handler will call this function if needed, when ready.
  253. if(myStream != null && myStatus.metaDataReady) { // myStream is a null until the 1st media is loaded. ie., The 1st ever setMedia being followed by a pause() or pause(t).
  254. myStream.pause();
  255. }
  256. if(myStatus.isPlaying) {
  257. myStatus.isPlaying = false;
  258. myStatus.pausePosition = myStream.time * 1000;
  259. }
  260. if(!isNaN(time) && myStatus.srcSet) {
  261. myStatus.pausePosition = time;
  262. }
  263. if(wasPlaying) {
  264. this.dispatchEvent(new JplayerEvent(JplayerEvent.JPLAYER_PAUSE, myStatus));
  265. }
  266. if(myStatus.isStartingDownload) {
  267. return true;
  268. } else if(myStatus.loadRequired()) {
  269. if(time > 0) { // We do not want the stop() command, which does pause(0), causing a load operation.
  270. return load();
  271. } else {
  272. return true; // Technically the pause(0) succeeded. ie., It did nothing, since nothing was required.
  273. }
  274. } else if(myStatus.isLoading || myStatus.isLoaded) {
  275. if(myStatus.metaDataReady && myStatus.pausePosition > myStatus.duration) { // The time is invalid, ie., past the end.
  276. myStatus.pausePosition = 0;
  277. myStream.seek(0);
  278. seekedEvent(); // Deals with seeking effect when using setMedia() then pause(huge). NB: There is no preceeding seeking event.
  279. } else if(!isNaN(time)) {
  280. if(getSeekTimeRatio() > getLoadRatio()) { // Use an estimate based on the downloaded amount
  281. seeking(true);
  282. } else {
  283. if(myStatus.metaDataReady) { // Otherwise seek(0) will stop the metadata loading.
  284. myStream.seek(myStatus.pausePosition/1000);
  285. }
  286. }
  287. }
  288. timeUpdates(false);
  289. // Need to be careful with timeupdate event, otherwise a pause in a timeupdate event can cause a loop.
  290. // Neither pause() nor pause(time) will cause a timeupdate loop.
  291. if(wasPlaying || !isNaN(time) && !alreadyPausedAtTime) {
  292. timeUpdateEvent();
  293. }
  294. return true;
  295. } else {
  296. return false;
  297. }
  298. }
  299. public function playHead(percent:Number):Boolean {
  300. var time:Number = percent * getDuration() * getLoadRatio() / 100;
  301. if(myStatus.isPlaying || myStatus.playOnLoad || myStatus.playOnSeek) {
  302. return play(time);
  303. } else {
  304. return pause(time);
  305. }
  306. }
  307. public function setVolume(v:Number):void {
  308. myStatus.volume = v;
  309. myTransform.volume = v;
  310. if(myStream != null) {
  311. myStream.soundTransform = myTransform;
  312. }
  313. }
  314. private function updateStatusValues():void {
  315. myStatus.seekPercent = 100 * getLoadRatio();
  316. myStatus.currentTime = getCurrentTime();
  317. myStatus.currentPercentRelative = 100 * getCurrentRatioRel();
  318. myStatus.currentPercentAbsolute = 100 * getCurrentRatioAbs();
  319. myStatus.duration = getDuration();
  320. }
  321. public function getLoadRatio():Number {
  322. if((myStatus.isLoading || myStatus.isLoaded) && myStream.bytesTotal > 0) {
  323. return myStream.bytesLoaded / myStream.bytesTotal;
  324. } else {
  325. return 0;
  326. }
  327. }
  328. public function getDuration():Number {
  329. return myStatus.duration; // Set from meta data.
  330. }
  331. public function getCurrentTime():Number {
  332. if(myStatus.isPlaying) {
  333. return myStream.time * 1000;
  334. } else {
  335. return myStatus.pausePosition;
  336. }
  337. }
  338. public function getCurrentRatioRel():Number {
  339. if((getLoadRatio() > 0) && (getCurrentRatioAbs() <= getLoadRatio())) {
  340. return getCurrentRatioAbs() / getLoadRatio();
  341. } else {
  342. return 0;
  343. }
  344. }
  345. public function getCurrentRatioAbs():Number {
  346. if(getDuration() > 0) {
  347. return getCurrentTime() / getDuration();
  348. } else {
  349. return 0;
  350. }
  351. }
  352. public function getSeekTimeRatio():Number {
  353. if(getDuration() > 0) {
  354. return myStatus.pausePosition / getDuration();
  355. } else {
  356. return 1;
  357. }
  358. }
  359. public function onMetaDataHandler(info:Object):void { // Used in connectStream() in myStream.client object.
  360. // This event occurs when jumping to the start of static files! ie., seek(0) will cause this event to occur.
  361. if(!myStatus.metaDataReady) {
  362. this.dispatchEvent(new JplayerEvent(JplayerEvent.DEBUG_MSG, myStatus, "onMetaDataHandler: " + info.duration + " | " + info.width + "x" + info.height));
  363. myStatus.metaDataReady = true; // Set flag so that this event only effects jPlayer the 1st time.
  364. myStatus.metaData = info;
  365. myStatus.duration = info.duration * 1000; // Only available via Meta Data.
  366. if(info.width != undefined) {
  367. myVideo.width = info.width;
  368. }
  369. if(info.height != undefined) {
  370. myVideo.height = info.height;
  371. }
  372. if(myStatus.playOnLoad) {
  373. myStatus.playOnLoad = false; // Capture the flag
  374. if(myStatus.pausePosition > 0 ) { // Important for setMedia followed by play(time).
  375. play(myStatus.pausePosition);
  376. } else {
  377. play(); // Not always sending pausePosition avoids the extra seek(0) for a normal play() command.
  378. }
  379. } else {
  380. pause(myStatus.pausePosition); // Always send the pausePosition. Important for setMedia() followed by pause(time). Deals with not reading stream.time with setMedia() and play() immediately followed by stop() or pause(0)
  381. }
  382. this.dispatchEvent(new JplayerEvent(JplayerEvent.JPLAYER_LOADEDMETADATA, myStatus));
  383. } else {
  384. this.dispatchEvent(new JplayerEvent(JplayerEvent.DEBUG_MSG, myStatus, "onMetaDataHandler: Already read (NO EFFECT)"));
  385. }
  386. }
  387. }
  388. }