2 Copyright 2004-2005 Chris Tallon
4 This file is part of VOMP.
6 VOMP is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
11 VOMP is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with VOMP; if not, write to the Free Software
18 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 #define USER_RESPONSE_TIME 500 // Milliseconds
25 // ----------------------------------- Called from outside, one offs or info funcs
27 Player::Player(MessageQueue* tmessageQueue, void* tmessageReceiver, bool tIsRecording)
28 : vfeed(this), afeed(this)
30 messageQueue = tmessageQueue;
31 messageReceiver = tmessageReceiver;
32 audio = Audio::getInstance();
33 video = Video::getInstance();
34 logger = Log::getInstance();
35 vdr = VDR::getInstance();
39 currentFrameNumber = 0;
45 isRecording = tIsRecording;
50 startupBlockSize = 250000;
51 preBufferSize = 500000;
57 if (initted) shutdown();
62 if (initted) return 0;
64 pthread_mutex_init(&mutex, NULL);
66 mutex=CreateMutex(NULL,FALSE,NULL);
70 demuxer = new DemuxerVDR();
72 demuxer = new DemuxerTS();
73 if (!demuxer) return 0;
75 if (!demuxer->init(this, audio, video, 2097152, 524288))
77 logger->log("Player", Log::ERR, "Demuxer failed to init");
93 int Player::shutdown()
95 if (!initted) return 0;
109 void Player::setStartFrame(ULONG startFrame)
111 currentFrameNumber = startFrame;
114 void Player::setLengthBytes(ULLONG length)
116 lengthBytes = length;
117 logger->log("Player", Log::DEBUG, "Player has received length bytes of %llu", lengthBytes);
120 void Player::setLengthFrames(ULONG length)
122 lengthFrames = length;
123 logger->log("Player", Log::DEBUG, "Player has received length frames of %lu", lengthFrames);
126 ULONG Player::getLengthFrames()
131 ULONG Player::getCurrentFrameNum()
133 if (startup) return 0;
138 return demuxer->getFrameNumFromPTS(video->getCurrentTimestamp());
142 return currentFrameNumber;
144 return 0; // shouldn't happen
148 bool* Player::getDemuxerMpegAudioChannels()
150 return demuxer->getmpAudioChannels();
153 bool* Player::getDemuxerAc3AudioChannels()
155 return demuxer->getac3AudioChannels();
158 int Player::getCurrentAudioChannel()
160 return demuxer->getselAudioChannel();
163 void Player::setAudioChannel(int newChannel)
165 demuxer->setAudioChannel(newChannel);
168 // ----------------------------------- Externally called events
170 void Player::play(ULONG Vpid, ULONG Apid)
173 DemuxerTS* dts = (DemuxerTS*)demuxer;
181 if (!initted) return;
182 if (state == S_PLAY) return;
185 bool doUnlock = false;
186 if (state == S_PAUSE_P) doUnlock = true;
188 if (doUnlock) unLock();
193 if (!initted) return;
194 if (state == S_STOP) return;
196 logger->log("Player", Log::DEBUG, "Stop called lock");
203 if (!initted) return;
206 if ((state == S_FFWD) || (state == S_FBWD))
208 switchState(S_PAUSE_I);
210 else if ((state == S_PAUSE_I) || (state == S_PAUSE_P))
216 switchState(S_PAUSE_P);
222 void Player::fastForward()
224 if (!initted) return;
232 case 4: ifactor = 8; break;
233 case 8: ifactor = 16; break;
234 case 16: ifactor = 32; break;
235 case 32: ifactor = 4; break;
246 void Player::fastBackward()
248 if (!initted) return;
256 case 4: ifactor = 8; break;
257 case 8: ifactor = 16; break;
258 case 16: ifactor = 32; break;
259 case 32: ifactor = 4; break;
270 void Player::jumpToPercent(double percent)
273 logger->log("Player", Log::DEBUG, "JUMP TO %i%%", percent);
274 ULONG newFrame = (ULONG)(percent * lengthFrames / 100);
275 switchState(S_JUMP, newFrame);
276 // unLock(); - let thread unlock this
279 void Player::jumpToMark(int mark)
282 logger->log("Player", Log::DEBUG, "JUMP TO MARK %i%%", mark);
283 switchState(S_JUMP, mark);
284 // unLock(); - let thread unlock this
287 void Player::jumpToFrameP(int newFrame)
290 logger->log("Player", Log::DEBUG, "JUMP TO FRAME AND PAUSE %i", newFrame);
291 switchState(S_JUMP_PI, newFrame);
295 void Player::skipForward(int seconds)
298 logger->log("Player", Log::DEBUG, "SKIP FORWARD %i SECONDS", seconds);
299 ULONG newFrame = getCurrentFrameNum();
300 if (newFrame == 0) { unLock(); return; } // Current pos from demuxer is not valid
301 newFrame += seconds * video->getFPS();
302 if (newFrame > lengthFrames) { switchState(S_PLAY); unLock(); }
303 else switchState(S_JUMP, newFrame);
304 // unLock(); - let thread unlock this
307 void Player::skipBackward(int seconds)
310 logger->log("Player", Log::DEBUG, "SKIP BACKWARD %i SECONDS", seconds);
311 long newFrame = getCurrentFrameNum();
312 if (newFrame == 0) { unLock(); return; } // Current pos from demuxer is not valid
313 newFrame -= seconds * video->getFPS();
314 if (newFrame < 0) newFrame = 0;
315 switchState(S_JUMP, newFrame);
316 // unLock(); - let thread unlock this
319 // ----------------------------------- Implementations called events
321 void Player::switchState(UCHAR toState, ULONG jumpFrame)
323 if (!initted) return;
325 logger->log("Player", Log::DEBUG, "Switch state from %u to %u", state, toState);
327 switch(state) // current state selector
329 case S_PLAY: // from S_PLAY -----------------------------------
333 case S_PLAY: // to S_PLAY
337 case S_PAUSE_P: // to S_PAUSE_P
344 case S_PAUSE_I: // to S_PAUSE_I
349 case S_FFWD: // to S_FFWD
351 currentFrameNumber = getCurrentFrameNum();
352 audio->systemMuteOn();
361 case S_FBWD: // to S_FBWD
363 currentFrameNumber = getCurrentFrameNum();
364 audio->systemMuteOn();
373 case S_STOP: // to S_STOP
387 case S_JUMP: // to S_JUMP
389 restartAtFrame(jumpFrame);
392 case S_JUMP_PI: // to S_JUMP_PI
394 audio->systemMuteOn();
402 restartAtFramePI(jumpFrame);
407 case S_PAUSE_P: // from S_PAUSE_P -----------------------------------
411 case S_PLAY: // to S_PLAY
418 case S_PAUSE_P: // to S_PAUSE_P
422 case S_PAUSE_I: // to S_PAUSE_I
426 case S_FFWD: // to S_FFWD
428 currentFrameNumber = getCurrentFrameNum();
429 audio->systemMuteOn();
439 case S_FBWD: // to S_FBWD
441 currentFrameNumber = getCurrentFrameNum();
442 audio->systemMuteOn();
452 case S_STOP: // to S_STOP
463 audio->systemMuteOff();
467 case S_JUMP: // to S_JUMP
471 restartAtFrame(jumpFrame);
474 case S_JUMP_PI: // to S_JUMP_PI
476 audio->systemMuteOn();
485 restartAtFramePI(jumpFrame);
490 case S_PAUSE_I: // from S_PAUSE_I -----------------------------------
494 case S_PLAY: // to S_PLAY
497 restartAtFrame(currentFrameNumber);
500 case S_PAUSE_P: // to S_PAUSE_P
504 case S_PAUSE_I: // to S_PAUSE_I
508 case S_FFWD: // to S_FFWD
514 case S_FBWD: // to S_FBWD
520 case S_STOP: // to S_STOP
527 audio->systemMuteOff();
531 case S_JUMP: // to S_JUMP
534 restartAtFrame(jumpFrame);
537 case S_JUMP_PI: // to S_JUMP_PI
539 restartAtFramePI(jumpFrame);
544 case S_FFWD: // from S_FFWD -----------------------------------
548 case S_PLAY: // to S_PLAY
551 ULONG stepback = USER_RESPONSE_TIME * video->getFPS() * ifactor / 1000;
552 if (stepback < currentFrameNumber)
553 currentFrameNumber -= stepback;
555 currentFrameNumber = 0;
556 restartAtFrame(currentFrameNumber);
559 case S_PAUSE_P: // to S_PAUSE_P
564 case S_PAUSE_I: // to S_PAUSE_I
570 case S_FFWD: // to S_FFWD
574 case S_FBWD: // to S_FBWD
581 case S_STOP: // to S_STOP
592 case S_JUMP: // to S_JUMP
595 restartAtFrame(jumpFrame);
598 case S_JUMP_PI: // to S_JUMP_PI
602 restartAtFramePI(jumpFrame);
607 case S_FBWD: // from S_FBWD -----------------------------------
611 case S_PLAY: // to S_PLAY
614 restartAtFrame(currentFrameNumber);
617 case S_PAUSE_P: // to S_PAUSE_P
622 case S_PAUSE_I: // to S_PAUSE_I
628 case S_FFWD: // to S_FFWD
635 case S_FBWD: // to S_FBWD
639 case S_STOP: // to S_STOP
650 case S_JUMP: // to S_JUMP
653 restartAtFrame(jumpFrame);
656 case S_JUMP_PI: // to S_JUMP_PI
660 restartAtFramePI(jumpFrame);
665 case S_STOP: // from S_STOP -----------------------------------
669 case S_PLAY: // to S_PLAY
674 audio->systemMuteOff();
679 // FIXME use restartAtFrame here?
680 if (currentFrameNumber > lengthFrames) currentFrameNumber = 0;
681 demuxer->setFrameNum(currentFrameNumber);
691 logger->log("Player", Log::DEBUG, "Immediate play");
699 else // do prebuffering
701 logger->log("Player", Log::DEBUG, "Prebuffering...");
706 case S_PAUSE_P: // to S_PAUSE_P
710 case S_PAUSE_I: // to S_PAUSE_I
714 case S_FFWD: // to S_FFWD
718 case S_FBWD: // to S_FBWD
722 case S_STOP: // to S_STOP
726 case S_JUMP: // to S_JUMP
730 case S_JUMP_PI: // to S_JUMP_PI
736 // case S_JUMP cannot be a start state because it auto flips to play
737 // case S_JUMP_PI cannot be a start state because it auto flips to S_PAUSE_I
741 // ----------------------------------- Internal functions
746 pthread_mutex_lock(&mutex);
747 logger->log("Player", Log::DEBUG, "LOCKED");
750 WaitForSingleObject(mutex, INFINITE);
754 void Player::unLock()
757 logger->log("Player", Log::DEBUG, "UNLOCKING");
758 pthread_mutex_unlock(&mutex);
764 void Player::restartAtFrame(ULONG newFrame)
774 currentFrameNumber = newFrame;
775 demuxer->setFrameNum(newFrame);
783 audio->systemMuteOff();
788 void Player::restartAtFramePI(ULONG newFrame)
791 ULONG nextiframeNumber;
799 // newFrame could be anywhere, go forwards to next I-Frame
800 if (!vdr->getNextIFrame(newFrame, 1, &filePos, &nextiframeNumber, &iframeLength)) return;
802 // Now step back a GOP. This ensures we go to the greatest I-Frame equal to or less than the requested frame
803 vdr->getNextIFrame(nextiframeNumber, 0, &filePos, &iframeNumber, &iframeLength);
805 buffer = vdr->getBlock(filePos, iframeLength, &amountReceived);
806 videoLength = demuxer->stripAudio(buffer, amountReceived);
807 video->displayIFrame(buffer, videoLength);
808 video->displayIFrame(buffer, videoLength); // If you do it twice, it works :)
811 currentFrameNumber = iframeNumber;
814 void Player::doConnectionLost()
816 logger->log("Player", Log::DEBUG, "Connection lost, sending message");
817 Message* m = new Message();
818 m->to = messageReceiver;
820 m->message = Message::PLAYER_EVENT;
821 m->parameter = Player::CONNECTION_LOST;
822 messageQueue->postMessage(m);
825 // ----------------------------------- Callback
827 void Player::call(void* caller)
829 if (caller == demuxer)
831 logger->log("Player", Log::DEBUG, "Callback from demuxer");
833 if (video->getTVsize() == Video::ASPECT4X3)
835 logger->log("Player", Log::DEBUG, "TV is 4:3, ignoring aspect switching");
839 int dxCurrentAspect = demuxer->getAspectRatio();
840 if (dxCurrentAspect == Demuxer::ASPECT_4_3)
842 logger->log("Player", Log::DEBUG, "Demuxer said video is 4:3 aspect, switching TV");
843 video->setAspectRatio(Video::ASPECT4X3);
845 Message* m = new Message();
847 m->to = messageReceiver;
848 m->message = Message::PLAYER_EVENT;
849 m->parameter = Player::ASPECT43;
850 messageQueue->postMessageFromOuterSpace(m);
852 else if (dxCurrentAspect == Demuxer::ASPECT_16_9)
854 logger->log("Player", Log::DEBUG, "Demuxer said video is 16:9 aspect, switching TV");
855 video->setAspectRatio(Video::ASPECT16X9);
857 Message* m = new Message();
859 m->to = messageReceiver;
860 m->message = Message::PLAYER_EVENT;
861 m->parameter = Player::ASPECT169;
862 messageQueue->postMessageFromOuterSpace(m);
866 logger->log("Player", Log::DEBUG, "Demuxer said video is something else... ignoring");
874 videoStartup = false;
882 threadSignalNoLock();
886 // ----------------------------------- Feed thread
888 void Player::threadMethod()
890 // this method used to be simple, the only thing it does
891 // is farm out to threadFeed Live/Play/Scan
892 // All the guff is to support scan hitting one end
896 if ((state == S_FFWD) || (state == S_FBWD))
899 // if this returns then scan hit one end
900 if (state == S_FFWD) // scan hit the end. stop
903 Message* m = new Message(); // Must be done after this thread finishes, and must break into master mutex
904 m->to = messageReceiver;
906 m->message = Message::PLAYER_EVENT;
907 m->parameter = STOP_PLAYBACK;
908 logger->log("Player", Log::DEBUG, "Posting message to %p...", messageQueue);
909 messageQueue->postMessage(m);
910 logger->log("Player", Log::DEBUG, "Message posted...");
913 // if execution gets to here, threadFeedScan hit the start, go to play mode
918 demuxer->setFrameNum(currentFrameNumber);
924 audio->systemMuteOff();
928 if (state == S_PLAY) threadFeedPlay();
936 void Player::threadFeedLive()
941 UINT preBufferTotal = 0;
953 askFor = startupBlockSize; // find audio streams sized block
955 askFor = blockSize; // normal
957 threadBuffer = vdr->getBlock(0, askFor, &thisRead);
959 if (!vdr->isConnected())
965 if (!threadBuffer) break;
969 int a_stream = demuxer->scan(threadBuffer, thisRead);
970 demuxer->setAudioStream(a_stream);
971 logger->log("Player", Log::DEBUG, "Startup Audio stream chosen %x", a_stream);
977 preBufferTotal += thisRead;
978 if (preBufferTotal >= preBufferSize)
980 logger->log("Player", Log::DEBUG, "Got >500K, prebuffering complete");
982 preBuffering = false;
986 // FIXME check the win32 code on the mvp
1003 // unLock(); // thread will be locked by play until here
1004 // FIXME - see if this can segfault because it is starting threads out of the master mutex
1010 while(writeLength < thisRead)
1012 thisWrite = demuxer->put(threadBuffer + writeLength, thisRead - writeLength);
1013 writeLength += thisWrite;
1015 // logger->log("Player", Log::DEBUG, "Player put %u to demuxer", thisWrite);
1019 // logger->log("Player", Log::DEBUG, "Demuxer full");
1020 // demuxer is full and can't take anymore
1022 threadWaitForSignal();
1030 threadBuffer = NULL;
1034 logger->log("Player", Log::DEBUG, "Live play failed to start or interrupted");
1036 if (videoStartup) // oh woe. there never was a stream, I was conned!
1038 videoStartup = false;
1040 MILLISLEEP(500); // I think this will solve a race
1045 Message* m = new Message(); // Must be done after this thread finishes, and must break into master mutex
1046 m->to = messageReceiver;
1048 m->message = Message::PLAYER_EVENT;
1049 m->parameter = Player::STREAM_END;
1050 logger->log("Player", Log::DEBUG, "Posting message to %p...", messageQueue);
1051 messageQueue->postMessage(m);
1052 logger->log("Player", Log::DEBUG, "Message posted...");
1055 void Player::threadFeedPlay()
1057 ULLONG feedPosition;
1058 UINT thisRead, writeLength, thisWrite, askFor;
1059 time_t lastRescan = time(NULL);
1061 feedPosition = vdr->positionFromFrameNumber(currentFrameNumber);
1062 if (!vdr->isConnected()) { doConnectionLost(); return; }
1063 logger->log("Player", Log::DEBUG, "startFeedPlay: wantedframe %i goto %llu", currentFrameNumber, feedPosition);
1074 // If we havn't rescanned for a while..
1075 if ((lastRescan + 60) < time(NULL))
1077 lengthBytes = vdr->rescanRecording(&lengthFrames);
1078 if (!vdr->isConnected()) { doConnectionLost(); return; }
1079 logger->log("Player", Log::DEBUG, "Rescanned and reset length: %llu", lengthBytes);
1080 lastRescan = time(NULL);
1083 if (feedPosition >= lengthBytes) break; // finished playback
1087 if (startupBlockSize > lengthBytes)
1088 askFor = lengthBytes; // is a very small recording!
1090 askFor = startupBlockSize; // normal, but a startup sized block to detect all the audio streams
1094 if ((feedPosition + blockSize) > lengthBytes) // last block of recording
1095 askFor = lengthBytes - feedPosition;
1100 threadBuffer = vdr->getBlock(feedPosition, askFor, &thisRead);
1101 feedPosition += thisRead;
1103 if (!vdr->isConnected())
1109 if (!threadBuffer) break;
1113 int a_stream = demuxer->scan(threadBuffer, thisRead);
1114 demuxer->setAudioStream(a_stream);
1115 logger->log("Player", Log::DEBUG, "Startup Audio stream chosen %x", a_stream);
1121 while(writeLength < thisRead)
1123 thisWrite = demuxer->put(threadBuffer + writeLength, thisRead - writeLength);
1124 writeLength += thisWrite;
1128 // demuxer is full and can't take anymore
1130 threadWaitForSignal();
1138 threadBuffer = NULL;
1143 logger->log("Player", Log::DEBUG, "Recording playback ends");
1145 if (videoStartup) // oh woe. there never was a stream, I was conned!
1147 videoStartup = false;
1149 MILLISLEEP(500); // I think this will solve a race
1155 Message* m = new Message(); // Must be done after this thread finishes, and must break into master mutex
1156 m->to = messageReceiver;
1158 m->message = Message::PLAYER_EVENT;
1159 m->parameter = Player::STOP_PLAYBACK;
1160 logger->log("Player", Log::DEBUG, "Posting message to %p...", messageQueue);
1161 messageQueue->postMessage(m);
1164 void Player::threadFeedScan()
1166 // This method is actually really simple - get frame from vdr,
1167 // spit it at the video chip, wait for a time. Most of the code here
1168 // is to get the wait right so that the scan occurs at the correct rate.
1170 ULONG direction = 0;
1171 ULONG baseFrameNumber = 0;
1172 ULONG iframeNumber = 0;
1173 ULONG iframeLength = 0;
1175 UINT amountReceived;
1179 struct timeval clock0 = {0,0}; // Time stamp after fetching I-frame info
1180 struct timeval clock1 = {0,0}; // Time stamp after fetching I-frame data
1181 struct timeval clock2 = {0,0} ; // Time stamp after displaying I-frame
1183 DWORD clock0 = 0, clock1 = 0, clock2 = 0;
1186 int frameTimeOffset = 0; // Time in msec between frames
1187 int disp_msec = 0; // Time taken to display data
1188 int total_msec = 0; // Time taken to fetch data and display it
1191 if (state == S_FFWD) direction = 1; // and 0 for backward
1195 // Fetch I-frames until we get one that can be displayed in good time
1196 // Repeat while clock0 + total_msec > clock2 + frameTimeOffset
1197 baseFrameNumber = currentFrameNumber;
1201 if (!vdr->getNextIFrame(baseFrameNumber, direction, &filePos, &iframeNumber, &iframeLength))
1204 if (iframeNumber >= lengthFrames) return;
1205 // scan has got to the end of what we knew to be there before we started scanning
1207 baseFrameNumber = iframeNumber;
1208 frameTimeOffset = abs((int)iframeNumber - (int)currentFrameNumber) * 1000 / (video->getFPS() * ifactor);
1210 gettimeofday(&clock0, NULL);
1212 clock0 = timeGetTime();
1216 while (clock2.tv_sec != 0 &&
1217 (clock0.tv_sec - clock2.tv_sec) * 1000 +
1218 (clock0.tv_usec - clock2.tv_usec) / 1000 > frameTimeOffset - total_msec);
1220 while (clock2 != 0 && clock0 + total_msec > clock2 + frameTimeOffset);
1222 // logger->log("Player", Log::DEBUG, "XXX Got frame");
1224 threadBuffer = vdr->getBlock(filePos, iframeLength, &amountReceived);
1226 gettimeofday(&clock1, NULL);
1227 if (clock2.tv_sec != 0)
1228 sleepTime = (clock2.tv_sec - clock1.tv_sec) * 1000
1229 + (clock2.tv_usec - clock1.tv_usec) / 1000
1230 + frameTimeOffset - disp_msec;
1232 clock1 = timeGetTime();
1234 sleepTime = clock2 + frameTimeOffset - disp_msec - clock1;
1236 if (sleepTime < 0) sleepTime = 0;
1238 MILLISLEEP(sleepTime);
1239 // logger->log("Player", Log::DEBUG, "XXX Slept for %d", sleepTime);
1241 videoLength = demuxer->stripAudio(threadBuffer, amountReceived);
1242 video->displayIFrame(threadBuffer, videoLength);
1243 currentFrameNumber = iframeNumber;
1245 threadBuffer = NULL;
1248 gettimeofday(&clock2, NULL);
1249 total_msec = (clock2.tv_sec - clock0.tv_sec) * 1000
1250 + (clock2.tv_usec - clock0.tv_usec) / 1000
1252 disp_msec = (clock2.tv_sec - clock1.tv_sec) * 1000
1253 + (clock2.tv_usec - clock1.tv_usec) / 1000
1256 clock2 = timeGetTime();
1257 total_msec = clock2 - clock0 - sleepTime;
1258 disp_msec = clock2 - clock1 - sleepTime;
1260 // logger->log("Player", Log::DEBUG, "XXX disp_msec = %4d total_msec = %4d", disp_msec, total_msec);
1264 void Player::threadPostStopCleanup()
1269 threadBuffer = NULL;
1273 // ----------------------------------- Dev
1276 void Player::test1()
1278 logger->log("Player", Log::DEBUG, "PLAYER TEST 1");
1280 // video->setAspectRatio(Video::ASPECT4X3);
1281 jumpToFrameP(37507);
1284 void Player::test2()
1286 logger->log("Player", Log::DEBUG, "PLAYER TEST 2");
1287 video->setAspectRatio(Video::ASPECT16X9);