/
avcOsxLinux.py
2400 lines (2223 loc) · 103 KB
/
avcOsxLinux.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#*****************************************************************************
#
# Linux and OSX version of Audiovideocours
# Using Python 2.7 coming with OS X Lion
#
# (c) Universite de Strasbourg 2006-2011
# Conception and development : francois.schnell [AT] unistra.fr
#---
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
#*******************************************************************************
__version__="1.22"
## Python import (base Python 2.4)
import sys,os,time,datetime,tarfile,ConfigParser,threading,shutil,gettext,zipfile
if sys.platform=="darwin":
# To enable AppleScript launch:
os.chdir(os.path.expanduser("~/Documents/workspace/audiovideocours/"))
import subprocess, socket, traceback, webbrowser
#import winsound # windows libs
from thread import start_new_thread, exit
from urllib2 import urlopen
from os import chdir
from ftplib import FTP
if False:
import wx
## External Python libs import
import wx, wx.lib.colourdb # GUI
import wx.lib.hyperlink as hl
#import msvcrt,pythoncom,pyHook,serial # access MS C/C++ Runtime lib, MS COM, hook, serial port
import cherrypy
if sys.platform =="darwin":
import PIL
from PIL import GifImagePlugin # Python Imaging Lib
from PIL import JpegImagePlugin # Static imports from PIL for py2exe
from PIL import Image
from AppKit import NSBeep,NSApp,NSApplication
#from PIL import ImageGrab #Used for taking screenshots but only works on Windows (will use built in screencapture in OS X)
#import pymedia.audio.sound as sound # for mp3 or ogg encoding
#import pymedia.audio.acodec as acodec
#import pymedia.muxer as muxer
#from pywinauto import * # used to put app. back on foreground
#from reportlab.platypus.doctemplate import FrameBreak # PDF lib.
## Local imports
from FMEcmd import * # Script to control Flash Media Encoder and genrate profile.xml file
import htmlBits # HTML chuncks for html format output
## Linux hook specific
if sys.platform=="linux2": from pyxhook import *
## OS X hook specific
if sys.platform=="darwin":
from Quartz import *
def MyFunction(p, t, e, c):
#print "*",e,dir(e)
#print "Event Tye", CGEventGetType(e)
if CGEventGetType(e)==10: # Event from the keyboard
#print CGEventGetFlags(e) # Indicates modifier key used (shift, fn, etc)
keyPressed=CGEventGetIntegerValueField(e,9)
print "Key pressed", keyPressed
if keyPressed ==100:
print "- F8 detected! -"
stopFromKBhook()
if keyPressed in [49,124,126,125,123]:
screenshot()
# see constants event fields in http://developer.apple.com/library/mac/#documentation/Carbon/Reference/QuartzEventServicesRef/Reference/reference.html
# Key pressed is number 100 for F8
if CGEventGetType(e)==1 and recording==True:
print "Mouse left click"
screenshot()
tap = CGEventTapCreate(kCGHIDEventTap, kCGHeadInsertEventTap,
kCGEventTapOptionListenOnly, CGEventMaskBit(kCGEventLeftMouseDown) | CGEventMaskBit(kCGEventKeyDown),
MyFunction, None)
runLoopSource = CFMachPortCreateRunLoopSource(None, tap, 0);
CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, kCFRunLoopDefaultMode);
CGEventTapEnable(tap, True);
#CGEventTapEnable(tap, False);
# CFRelease(tap); # something to do to manage memory ??
# CFRunLoopRun(); # No comprendo! I have the events if i comment this because i'm using the GUI loop?
#----------------------------------------------------------------------------------------
## Some default global variables in case no configuration file is found
remoteControl=False
"If True the client will also act as a mini server for maintenance purposes. Go to http://your-PC:port"
remotePort="8080"
"Remote access port"
standalone=True
"GUI design, False=amphi (always running in background, minimal choices), True= individual PC"
# Publishing form variables
publishingForm=False
"Indicates there's no publishing form on the client and everything is done on the website"
title=""
"Recording's title"
description=""
"Recording's description"
name=""
"Author's name"
firstname=""
"Author's firstname"
login=""
"Author's login"
genre=""
"Eventual access code"
ue=""
" To use the app without a webserver to publish to"
recording = False
" Recording Status : to know if we are recording now"
last_session_recording_start="None"
" Date/time of the last recording start since the app. is running"
last_session_recording_stop="None"
" Date/time of the last recording stop since the app. is running"
app_startup_date="None"
"Date/time when the app. has been launched"
last_session_publish_order="None"
"Date/time when the app. has been launched"
last_session_publish_problem="None"
"Date/time when the app. encountered an error while publishing "
workDirectory=""
"The working/current directory"
dirName=""
"The data directory"
pathData=None
"Path/name of the folder containing the recordings"
id= ""
"An id which can be received and send from the socket (for external control or monitoring)"
samplingFrequency= 48000
"Default sampling frequency for audio recording"
stopKey= "F8"
"Default key to start/stop recording if you don't have the serial Kb"
socketEnabled=False
"To listen to a socket for eventual orders from a server"
portNumber= 3737
"Socket port to listen to for server orders (sending an eventual ID also)"
READ_CHUNK= 512
"Chunck size for pymedia audio reading"
if sys.platform == 'win32':
cparams= { 'id': acodec.getCodecID( 'mp3' ),
'bitrate': 64000,
'sample_rate': 48000 ,
'channels': 1 }
"Set of parameters for the pymedia audio Encoder"
nameRecord="enregistrement-micro.mp3"
"Dafault name of the audio recording"
tryFocus=False
"A boolean variable to inform when the app is trying to get focus back on a frame"
serialKeyboard=False
"To indicate if the special keyboard must be used"
keyboardPort=0
"Serial port number to use for serial keyboard"
videoprojectorInstalled=False
"To indicate if a videoprojector bust be used on a serial plug"
videoprojectorPort=1
"Port number of the serial port for the videoprojector"
tempo = 0
"If tempp = 0 => no tempo (Nb of seconds to wait before each screenshot)"
lastEvent=time.time()
"Initialize last Event time as a global variable"
videoProjON='PWR ON\x0D'
"Video proj protocol : ON (EPSON here)"
videoProjOFF='PWR OFF\x0D'
"Video proj protocol : OFF (EPSON here)"
ftpUrl="audiovideocours.u-strasbg.fr"
"FTP URL server for online publication"
urlserver= "https://audiovideocours.u-strasbg.fr/avc/publication"
"Default URL of the audiovideocours server containing the submit form"
urlLiveState="http://audiovideocours.u-strasbg.fr/audiocours_v2/servlet/LiveState"
"URL of the live form status"
eventDelay=1.5
"Number of seconds before allowing a new screenshot"
recordingPlace= "not given"
"Optional location indication for the log file and the server"
maxRecordingLength=18000
"Maximum recording length in seconds(1h=3600s,5h=18000s)"
usage="audio"
"Usage ='audio' for audio and 'video' for video recording "
"A generic access code"
videoEncoder="wmv"
"""Choice of the videoencoder to use if usage=video
'wmv' = Windows Media Encoder ; 'real'= Real producer """
smilBegin=""" <?xml version="1.0"?>
<!DOCTYPE smil PUBLIC "-//W3C//DTD SMIL 2.0//EN" "http://www.w3.org/2001/SMIL20/SMIL20.dtd">
<smil xmlns="http://www.w3.org/2001/SMIL20/Language">
<head>
<meta name="title" content="MediaCours"/>
<meta name="author" content="ULP Multimedia"/>
<meta name="copyright" content="Copyright ULP Multimedia"/>
<layout>
<root-layout width="1024" height="768"/>
<region id="Images" width="1024" height="768" fit="meet" />
</layout>
</head>
<body>
<par>
"""
"Smil template"
loginENT="initial"
"Login"
emailENT="initial"
"Email"
live=False
"Live choice enable or not in GUI"
language="French"
"Current language in the GUI"
videoinput="0"
"Video input"
audioinput="0"
"Audio input"
flashServerIP="130.79.188.196"
"Flash Server IP for live sessions"
formFormation="" # a default entry for "formation" in the publishing form
"Automatically fills the formation field with this value"
lastGlobalEvent=time.time()
"Indicates last keyboard or mouse activity"
liveCheckBox=False
"Indicates if user wants(checked) a live session from the GUI"
audioVideoChoice=False # give the possibility to choose between an audio or video recording
"Show in the GUI the choice between a video or audio recording"
ftpHandleReady=False
"For live session: indicates if we have an open FTP connection to send live screenshots"
previewPlayer="realplayer"
"Standalone preview player ( realplayer or browser), used in standalone mode only"
if 1:# in case no server informations found in the configuration file
ftpLogin=""
"FTP login for publishing and live screenshots"
ftpPass=""
"FTP password for publishing and live screenshots"
#------- i18n settings ------------------------------------------------------------------
gettext.install("mediacours","locale")
#----------------------------------------------------------------------------------------
def readConfFile(confFile="mediacours.conf"):
"""
Read the configuration file and get those values as global vars
"""
print "Search and read configuration (if it exist):"
global confFileReport,id,urlserver,samplingFrequency,createMp3,stopKey,portNumber,pathData\
,serialKeyboard,startKey,videoprojectorInstalled,videoprojectorPort,keyboardPort\
,videoProjON,videoProjOFF,ftpUrl,eventDelay,maxRecordingLength,recordingPlace\
,usage,cparams,bitrate,socketEnabled,standalone,videoEncoder,amxKeyboard,liveCheckBox,\
language,ftpLogin,ftpPass,cparams, videoinput,audioinput,flashServerIP\
,formFormation, audioVideoChoice,urlLiveState,publishingForm, remoteControl, remotePort,previewPlayer
confFileReport=""
section="mediacours"
def readParam(param):
global confFileReport
param=str(param)
paramValue= config.get(section,param)
if paramValue=="True" or paramValue=="False":
paramValue=eval(paramValue)
if (param != "ftpPass") and (param != "ftpLogin"):
print "... "+param+" = ", paramValue
#writeInLogs("\n\t:"+param+"= "+paramValue)
confFileReport += "\n\t:"+str(param)+"= "+str(paramValue)
return paramValue
#try:
if 1:
fconf=open(confFile,"r")
config= ConfigParser.ConfigParser()
config.readfp(fconf)
if config.has_option(section,"language") == True: language=readParam("language")
if config.has_option(section,"usage") == True: usage=readParam("usage")
if config.has_option(section,"pathData") == True: pathData=readParam("pathData")
if config.has_option(section,"standalone") == True: standalone=readParam("standalone")
if config.has_option(section,"videoEncoder") == True: videoEncoder=readParam("videoEncoder")
if config.has_option(section,"urlserver") == True: urlserver=readParam("urlserver")
if sys.platform == 'win32':
if config.has_option(section,"samplingFrequency") == True: samplingFrequency=readParam("samplingFrequency")
if config.has_option(section,"bitrate") == True: cparams['bitrate']=eval(readParam("bitrate"))
if config.has_option(section,"stopKey") == True: stopKey=readParam("stopKey")
if config.has_option(section,"socketEnabled") == True: socketEnabled=readParam("socketEnabled")
if config.has_option(section,"portNumber") == True: portNumber=int(readParam("portNumber"))
if config.has_option(section,"serialKeyboard") == True: serialKeyboard=readParam("serialKeyboard")
if config.has_option(section,"amxKeyboard") == True: amxKeyboard=readParam("amxKeyboard")
if config.has_option(section,"keyboardPort") == True: keyboardPort=int(readParam("keyboardPort"))
if config.has_option(section,"videoprojectorInstalled") == True: videoprojectorInstalled=readParam("videoprojectorInstalled")
if config.has_option(section,"videoprojectorPort") == True: videoprojectorPort=int(readParam("videoprojectorPort"))
if config.has_option(section,"videoProjON") == True: videoProjON=readParam("videoProjON")
if config.has_option(section,"videoProjOFF") == True: videoProjOFF=readParam("videoProjOFF")
if config.has_option(section,"ftpUrl") == True: ftpUrl=readParam("ftpUrl")
if config.has_option(section,"eventDelay") == True: eventDelay=float(readParam("eventDelay"))
if config.has_option(section,"maxRecordingLength") == True: maxRecordingLength=float(readParam("maxRecordingLength"))
if config.has_option(section,"ftpLogin") == True: ftpLogin=readParam("ftpLogin")
if config.has_option(section,"ftpPass") == True: ftpPass=readParam("ftpPass")
if config.has_option(section,"live") == True: liveCheckBox=readParam("live")
if config.has_option(section,"videoinput") == True: videoinput=readParam("videoinput")
if config.has_option(section,"audioinput") == True: audioinput=readParam("audioinput")
if config.has_option(section,"flashServerIP") == True: flashServerIP=readParam("flashServerIP")
if config.has_option(section,"formFormation") == True: formFormation=readParam("formFormation")
if config.has_option(section,"audioVideoChoice") == True: audioVideoChoice=readParam("audioVideoChoice")
if config.has_option(section,"urlLiveState") == True: urlLiveState=readParam("urlLiveState")
if config.has_option(section,"publishingForm") == True: publishingForm=readParam("publishingForm")
if config.has_option(section,"remoteControl") == True: remoteControl=readParam("remoteControl")
if config.has_option(section,"remotePort") == True: remotePort=int(readParam("remotePort"))
if config.has_option(section,"previewPlayer") == True: previewPlayer=readParam("previewPlayer")
fconf.close()
#except:
if 0:
print "Something went wrong while reading the configuration file..."
def showVuMeter():
""" If available in installation folder show VUMeter.exe
http://www.vuplayer.com/files/vumeter.zip """
try:
subprocess.Popen(["VUMeter.exe"])
except:
print "Couldn't find VUMeter.exe"
def stopFromKBhook():
"""
Start/stop recording when asked from the PC keyboard 'stopKey'
"""
global frameEnd, frameBegin, tryFocus,id
#screenshot()#gives a delay too long in case of live recording here
print ">> In stopFromKBhook now..."
print ">> In stopFromKB hook order recordStop() now"
recordStop()
#sys.exit()
print ">> In stopFromKBhook order recordStop() passed"
print ">> Closing hook now..."
if sys.platform!="darwin":
hm.cancel()
print ">> hm.cancel() passed..."
print "In stopFromKBhook order frameEndShow() now"
wx.CallAfter(frameEndShow)
if sys.platform=="darwin":
#frameEndShow()
print "."
print ">> In stopFromKBhook order frameEndShow() passed"
if 0:
#if recording==False and tryFocus==False:
if recording==False: # no tryFocus for Linux version?
print "!!!!! Trying to put frameBegin back in stopFromHook"
if sys.platform=="win32": showVuMeter()
# try to show a vumeter here
#showVuMeter()
if recording==True and tryFocus==False:
print "id:",id
if id=="":
print "Trying to put Ending frame back foreground..."
if live==False:
if sys.platform!="darwin": screenshot()
print "stop recording now recordStop()"
if sys.platform=="win32": windowBack(frameEnd)
if sys.platform=="linux2":
print "<<<< trying frameEnd.Show() on Linux >>>>>"
wx.CallAfter(frameEndShow)
recordStop()
#frameEnd.Show()
else:
print "hello?"
recordStop()
print "Not showing usual publishing form"
start_new_thread(confirmPublish,())
frameUnivr.Show()
# make sure buttons "publish" and "cancel" are enabled for user input
if 0:
try:
if btnPublish.IsEnabled()==False:
btnPublish.Enable(True)
if btnCancel.IsEnabled()==False:
btnCancel.Enable(True)
except:
print "warning! tried to check if buttons 'publish' and 'cancel' were enabled but had problems"
def OnKeyboardEventAfter(event):
wx.CallAfter(OnKeyboardEvent(event))
def OnKeyboardEvent(event):
"""
Catching keyboard events from the hook and deciding what to do
"""
global stopKey,lastEvent,lastGlobalEvent,frameBegin,frameEnd
if 0: winsound.Beep(300,50) # For testing purposes
lastGlobalEvent=time.time()# For shutdownPC_if_noactivity
screenshotKeys=["Snapshot","Space","space","Return","Up","Down","Right",
"Left","Prior","Next"]
print "Key event seen : ", event.Key
if (stopKey!="") and (event.Key== stopKey)and (tryFocus==False):
print "Received order to stop recording ..."
print "from hook stopKey= :", stopKey
global recording, fen1
print "Escape Key pressed from the hook ..."
if sys.platform=="win32":
start_new_thread(stopFromKBhook,())
else:
print "launching CallAfter stopFromKBhook now"
stopFromKBhook()
print"after launch"
if 0:
if event.Key in screenshotKeys and( (time.time()-lastEvent)>eventDelay):
start_new_thread(screenshot,())
lastEvent=time.time()
# Show each key stroke (for debug only)
if 0:
print 'MessageName:',event.MessageName
print 'Message:',event.Message
print 'Time:',event.Time
print 'Window:',event.Window
print 'WindowName:',event.WindowName
print 'Ascii:', event.Ascii, chr(event.Ascii)
print 'Key:', event.Key
print 'KeyID:', event.KeyID
print 'ScanCode:', event.ScanCode
print 'Extended:', event.Extended
print 'Injected:', event.Injected
print 'Alt', event.Alt
print 'Transition', event.Transition
print '---'
return True # return True to pass the event to other handlers
def OnMouseEvent(event):
"""
Catching mouse events from the hook and deciding what to do
"""
global recording,lastEvent,lastGlobalEvent
lastGlobalEvent=time.time()# For shutdownPC_if_noactivity
if (recording == True) and (tryFocus == False)\
and( (time.time()-lastEvent)>eventDelay):
if (event.MessageName == "mouse left down") or (event.MessageName=="mouse wheel down")\
or (event.MessageName=="mouse wheel up"):
if 0: winsound.Beep(300,50) # For testing purposes
start_new_thread(screenshot,())
lastEvent=time.time()
if 0: # For debug purpose put 0 for example
print 'MessageName:',event.MessageName
print 'Message:',event.Message
print 'Time:',event.Time
print 'Window:',event.Window
print 'WindowName:',event.WindowName
print 'Position:',event.Position
print 'Wheel:',event.Wheel
print 'Injected:',event.Injected
print '---'
return True # return True to pass the event to other handlers
def recordNow():
"""
Record the audio input now with pymedia or video via an external encoder
"""
print "Entering recordNow() function"
global recording, diaId, timecodeFile, t0, dateTime0, dirName, workDirectory
global snd,ac,cparams, nameRecord,usage,smil,pathData, last_session_recording_start
usage=frameBegin.usage
recording= True
last_session_recording_start=getTime()
ftpHandleReady=False
if sys.platform in ("win32","darwin"):
# Visual cue to confirm recording state
tbicon.SetIcon(icon2, "Enregistrement en cours")
# Audio cue to confirm recording state
if sys.platform=="win32":
winsound.Beep(800,100)
diaId = 0 # initialize screenshot number and time
t0 = time.time()
dateTime0 = datetime.datetime.now()
dirName = str(dateTime0)
dirName = dirName[0:10]+'-'+ dirName[11:13] +"h-"+dirName[14:16] +"m-" +dirName[17:19]+"s"+"-"+recordingPlace#+ "-"+ dirName[20:22]
workDirectory=pathData+"/"+dirName
print "workDirectory= ",workDirectory
os.mkdir(workDirectory)
writeInLogs("- Begin recording at "+ str(datetime.datetime.now())+"\n")
os.mkdir(workDirectory + "/screenshots")
if sys.platform=="linux2":
print "launching screenshot() thread from recordNow()"
start_new_thread(screenshot,())
def record():
""" Record audio only - mp3 - with pymedia"""
global recording, cparams
f= open( workDirectory+'/'+nameRecord, 'wb' )
ac= acodec.Encoder( cparams )
snd= sound.Input(cparams["sample_rate"],cparams["channels"], sound.AFMT_S16_LE)
snd.start()
while recording==True:
time.sleep(0.1)
if (time.time()-t0 > maxRecordingLength):
writeInLogs("- Recording duration > maxRecordingLength => Stop recording "+\
str(datetime.datetime.now())+"\n")
recordStop()
s= snd.getData()
if s and len( s ):
for fr in ac.encode(s):
f.write( fr )
#print "*",
if recording == False:
snd.stop()
print "-- stopped recording now --"
def windowsMediaEncoderRecord():
"""
Record Video with Windows Media Encoder Series 9
"""
scriptPath=r' cscript.exe C:\"Program Files\Windows Media Components\Encoder\WMCmd.vbs"'
arguments=" -adevice 1 -vdevice 1 -output "+\
dirName+"\enregistrement-video.wmv -duration "+str(maxRecordingLength)
os.system(scriptPath+arguments)
def realProducerRecord():
"""
Record video with Real Producer basic
"""
MaximumRecordingLength=str(maxRecordingLength)
fileVideo=workDirectory+ '\\enregistrement-video.rm'
if live==False:
print "Videoinput and audio port = ",videoinput,audioinput
os.system(('producer.exe -vc %s -ac %s -pid pid.txt -o "%s" -d %s')%(videoinput,audioinput,fileVideo,MaximumRecordingLength))
elif live==True:
#todoLiveReal=r'producer.exe -vc '+videoinput+' -ac '+videoinput+' -pid pid.txt -o '+fileVideo+" -sp 130.79.188.5/"+recordingPlace+".rm"
page = urlopen(urlLiveState,\
"recordingPlace="+recordingPlace+"&status="+"begin")
print "------ Response from Audiocours : -----"
serverAnswer= page.read() # Read/Check the result
print serverAnswer
todoLiveReal=('producer.exe -vc %s -ac %s -pid pid.txt -o "%s" -sp 130.79.188.5/%s.rm')%(videoinput,audioinput,fileVideo,recordingPlace)
print todoLiveReal
os.system(todoLiveReal)
def ffmpegLinuxAudioRecord():
""" Record mp3 in Linux with FFMPEG and liblamemp3 """
print "In ffmpegLinuxAudioRecord"
cmd="ffmpeg -f alsa -ac 2 -i pulse -acodec libmp3lame -aq 0 -y -loglevel 0 "+workDirectory+"/"+nameRecord
os.system(cmd)
def flashMediaEncoderRecord():
"""
Record video with Flash Media Encoder
"""
print "In flashMediaEncoderRecord()"
global flv,flashServer,FMLEpid,urlLiveState
if live==True:
print "Going for live==True"
liveParams="""<rtmp>
<url>rtmp://"""+flashServerIP+"""/live</url>
<backup_url></backup_url>
<stream>"""+recordingPlace+"""</stream>
</rtmp>"""
#Send the information that live is ON
#urlLiveState="http://audiovideocours.u-strasbg.fr/audiocours_v2/servlet/LiveState"
page = urlopen(urlLiveState,\
"recordingPlace="+recordingPlace+"&status="+"begin")
if 0:
print "------ Response from Audiocours : -----"
serverAnswer= page.read() # Read/Check the result
print serverAnswer
else:
liveParams=""
#flvPath=r"C:\Documents and Settings\franz\Bureau\newsample.flv"
if usage=="video":
flvPath=pathData+'/'+ dirName+ '/enregistrement-video.flv'
elif usage=="audio":
flvPath=pathData+'/'+ dirName+ '/enregistrement-micro.flv'
print flvPath
print "In FlashMediaRecord() videoinput=",videoinput,"audioinput=",audioinput
print "Current directory is", os.getcwd()
if os.path.isfile("startup.xml")==True:
print ">>> Found startup.xml in AudioVideoCours folder. This profile will be used by Flash Media Encoder insted of the configuration file parameters."
#subprocess.Popen(["FMEcmd.exe", "/P","startup.xml"])
flv=FMEcmd(videoDeviceName=videoinput,audioDeviceName=audioinput,
flvPath=flvPath,liveParams=liveParams,externalProfile=True,usage=usage,live=live,pathData=pathData)
flv.record()
#FMEprocess=flv.record()
#FMLEpid=FMEprocess.pid
FMLEpid=flvPath # FME use the full path of the flv not the pid...
else:
print "FME: using configuration file parameters"
flv=FMEcmd(videoDeviceName=videoinput,audioDeviceName=audioinput,
flvPath=flvPath,liveParams=liveParams,externalProfile=False,usage=usage,live=live,pathData=pathData)
flv.record()
#FMEprocess=flv.record()
#FMLEpid=FMEprocess.pid
FMLEpid=flvPath # FME use the full path of the flv not the pid...
def liveStream():
""" Control VLC for *audio* live stream """
global vlcPid,dirName
time.sleep(2)
print "Going audio live with VLC ..."
vlcapp='C:\\Program'+' '+'Files\\VideoLAN\\VLC\\vlc.exe'
command=r'C:\"Program Files"\VideoLAN\VLC\vlc.exe -vvvv '
file=pathData+"/"+dirName+"/enregistrement-micro.mp3"
typeout="#standard{access=http,mux=raw}"
# try to launch a pre-configured trayit!.exe to hide VLC GUI
try:
subprocess.Popen(['trayit!'])
#time.sleep(0.5)
except:
pass
if 0: # Using os.system (meaning there will be a DOS window visible)
os.system('%s -vvvv "%s" --sout %s'%(command,file,typeout))
if 1: # Using subprocess (no DOS window visible)
arg1= '-vvvv '+file
arg2= '"#standard{access=http,mux=asf}"'
subprocess.Popen(['%s'%(vlcapp),"-vvvv",file,"--sout","%s"%typeout])
# Check for usage and engage recording
if usage=="audio":
if sys.platform=="win32":
start_new_thread(record,())
if sys.platform=="linux2":
start_new_thread(ffmpegLinuxAudioRecord,())
if live==True:
start_new_thread(liveScreenshotStart,())
if live==True and usage=="audio":
#start_new_thread(liveStream,())
start_new_thread(flashMediaEncoderRecord,())
#Send the information that live is ON
page = urlopen(urlLiveState,\
"recordingPlace="+recordingPlace+"&status="+"begin")
if 0:#For Degub
print "------ Response from Audiocours : -----"
serverAnswer= page.read() # Read/Check the result
print serverAnswer
print "Usage is > ", usage
if usage=="video" and videoEncoder=="flash":
print "searching Flash Media Encoder"
start_new_thread(flashMediaEncoderRecord,())
if usage=="audio" and videoEncoder=="flash" and sys.platform=="darwin":
start_new_thread(flashMediaEncoderRecord,())
if usage=="video" and videoEncoder=="wmv":
print "searching Windows Media Encoder ..."
start_new_thread(windowsMediaEncoderRecord,())
if usage=="video" and videoEncoder=="real":
print "searching Real media encoder"
start_new_thread(realProducerRecord,())
def screenshot():
"""
Take a screenshot and thumbnails of the screen
"""
global recording, diaId, t0, timecodeFile
time.sleep(tempo)
if recording == True:
if sys.platform=="win32":
myscreen= ImageGrab.grab() #print "screenshot from mouse"
t = time.time()
diaId += 1
myscreen.save(workDirectory+"/screenshots/" + 'D'+ str(diaId)+'.jpg')
timeStamp = str(round((t-t0),2))
print "Screenshot number ", diaId," taken at timeStamp = ", timeStamp
timecodeFile = open (workDirectory +'/timecode.csv','a')
timecodeFile.write(timeStamp+"\n")
timecodeFile.close()
"""smilFile.write('<a href="screenshots/D'+str(diaId)+'.jpg" external="true">\n'\
+ '<img begin="'+timeStamp+'" region="Images" src="screenshots/D'\
+ str(diaId)+'.jpg"/> </a>\n')"""
myscreen.thumbnail((256,192))
myscreen.save(workDirectory+"/screenshots/" + 'D'+ str(diaId)+'-thumb'+'.jpg')
if sys.platform=="darwin" or "linux2":
t = time.time()
diaId += 1
if sys.platform=="darwin":
os.system("screencapture -t jpg "+workDirectory+"/screenshots/" + 'D'+ str(diaId)+'.jpg')
#os.system("screencapture "+workDirectory+"/screenshots/" + 'D'+ str(diaId)+'.png')
if sys.platform=="linux2":
os.system("scrot "+workDirectory+"/screenshots/" + 'D'+ str(diaId)+'.jpg')
t = time.time()
timeStamp = str(round((t-t0),2))
print "Screenshot number ", diaId," taken at timeStamp = ", timeStamp
timecodeFile = open (workDirectory +'/timecode.csv','a')
timecodeFile.write(timeStamp+"\n")
timecodeFile.close()
if sys.platform=="linux2":
myscreen= Image.open(workDirectory+"/screenshots/" + 'D'+ str(diaId)+'.jpg')
#myscreen= Image.open(workDirectory+"/screenshots/" + 'D'+ str(diaId-1)+'.png')
myscreen.thumbnail((256,192))
#print "WARNING: must see how to avoid this error when creating jpg thumbs, png work fine for now"
myscreen.save(workDirectory+"/screenshots/" + 'D'+ str(diaId)+'-thumb'+'.jpg')
#myscreen.save(workDirectory+"/screenshots/" + 'D'+ str(diaId)+'-thumb'+'.png')
if sys.platform=="darwin":
print "Creating thumb with sips"
os.system("sips -z 192 256 "+workDirectory+"/screenshots/" + 'D'+ str(diaId)+'.jpg --out '+workDirectory+"/screenshots/" + 'D'+ str(diaId)+'-thumb.jpg')
if live==True and ftpHandleReady:
time.sleep(3) # in live mode add a tempo to have the current dia (after an eventual transition)
#if 1:
print "sending screenshot live, note to self: code MUST BE OSXified!"
try:
livescreen= ImageGrab.grab()
livescreen.save(workDirectory+"/screenshots/Dlive.jpg")
print "[FTP] sending live screenshot"
f = open(workDirectory+"/screenshots/Dlive.jpg",'rb')
ftpHandle.storbinary('STOR '+recordingPlace+'.jpg', f)
f.close()
#if 0:
except:
print "Couldn't send live screenshot to FTP port"
if recording==True:
try:
print "trying to open a new FTP handle..."
liveScreenshotStart()
except:
print "Couldn't retry FTP send"
def liveScreenshotStream():
""" send screenshot at regular interval in live mode"""
# Function not currently used
while live==True and recording==True:
time.sleep(5) # in live mode add a tempo to have the current dia (after an eventual transition)
f = open(workDirectory+"/screenshots/" + 'D'+ str(diaId)+'.jpg','rb')
ftp.storbinary('STOR '+recordingPlace+'.jpg', f)
f.close()
def liveScreenshotStart():
""" Open ftpLiveHandle for live screenshots capabilities """
global ftpHandle, ftpHandleReady
#ftpHandleReady=False
try:
ftpHandle = FTP(ftpUrl)
ftpHandle.login(ftpLogin, ftpPass)
ftpHandle.cwd("live")
print "[FTP] Opened ftpLiveHandle for live screenshots capabilities "
ftpHandleReady=True
except:
print "couldn't open ftpHandle"
def liveScreenshotStop():
""" Close ftpLiveHandle """
global ftpHandle
ftpHandle.quit()
ftpHandleReady=False
def recordStop():
"""
Stop recording the audio input now
"""
global recording,timecodeFile,FMLEpid, last_session_recording_stop
print "In recordStop() now..."
## Create smile file
print "trying to create smile file now..."
try:
smil=SmilGen(usage,workDirectory)
f=open(workDirectory+"/timecode.csv")
diaTime=f.read().split("\n")[:-2]
f.close()
diaId=1
for timeStamp in diaTime:
smil.smilEvent(timeStamp,diaId+1)
diaId+=1
smil.smilEnd(usage,videoEncoder)
except:
writeInLogs("- Problem while genration smil file... "+ str(datetime.datetime.now())+"\n")
## Create html file and thirdparty forlder
print "trying to create html file now..."
try:
htmlGen()
except:
writeInLogs("- Problem at generating html and thirdparty folder... "+ str(datetime.datetime.now())+"\n")
print "setting recording variable to False ..."
recording= False
last_session_recording_stop=getTime()
print "recording is now = ", recording
if sys.platform in ("win32","darwin"):
print "changing systray icon to non-recording"
# Visual cue to confirm recording state
tbicon.SetIcon(icon1, usage+"cours en attente")
# Audio cue to confirming recording state (2 bis when recording stopped)
if sys.platform=="win32":
winsound.Beep(800,100)
time.sleep(0.2)
winsound.Beep(800,100)
if live==True:
flv.stop(FMLEpid="rtmp://"+flashServerIP+"/live+"+recordingPlace)
#if 1:
try:
liveScreenshotStop()
#if 0:
except:
print "problem with FTP connection"
if live==True:
page = urlopen(urlLiveState,\
"recordingPlace="+recordingPlace+"&status="+"end")
if 0:#For debug
print "------ Response from Audiocours : -----"
serverAnswer= page.read() # Read/Check the result
print serverAnswer
lastEvent=time.time()
#timecodeFile.close()
if usage=="video" and videoEncoder=="wmv":
os.popen("taskkill /F /IM cscript.exe")#stop MWE !!!
if usage=="video" and videoEncoder=="real":
os.popen("signalproducer.exe -P pid.txt")#stop Real producer
if usage=="video" and videoEncoder=="flash":
flv.stop(FMLEpid)
if usage=="audio" and sys.platform=="linux2":
print "trying to stop ffmpeg now"
os.popen("killall ffmpeg")
if usage=="audio" and sys.platform=="darwin":
print "trying to stop FMLE"
flv.stop(FMLEpid)
if live==True:
liveFeed.SetValue(False) #uncheck live checkbox for next user in GUI
writeInLogs("- Stopped recording at "+ str(datetime.datetime.now())+"\n")
def playAudio():
"""
Play the sound file from the folder selected
"""
global workDirectory, fen1
print "... playSound"
mixer= sound.Mixer()
dm= muxer.Demuxer( 'mp3' )
dc= acodec.Decoder( cparams )
sndOut= sound.Output( cparams["sample_rate"],cparams["channels"], sound.AFMT_S16_LE )
bytesRead= 0
f= open( workDirectory+'/'+nameRecord, 'rb' )
s=' '
while len( s ):
s= f.read(READ_CHUNK)
frames= dm.parse( s )
if frames:
for fr in frames:
r= dc.decode( fr[ 1 ] )
if r and r.data:
sndOut.play( r.data )
else:
time.sleep( .01 )
while sndOut.isPlaying(): time.sleep( 0.05 )
sndOut.stop()
def createZip():
""" zip all recording data in a .zip folder """
frameEnd.statusBar.SetStatusText("Please wait ...(creating archive) ...")
#frameEnd.statusBar.w
zip = zipfile.ZipFile(pathData+"/"+dirName+".zip", 'w')
for fileName in os.listdir ( workDirectory ):
if os.path.isfile (workDirectory+"/"+fileName):
zip.write(workDirectory+"/"+fileName,
dirName+"/"+fileName,zipfile.ZIP_DEFLATED)
for fileName in os.listdir ( workDirectory+"/screenshots"):
zip.write(workDirectory+"/screenshots/"+fileName,
dirName+"/"+"screenshots/"+fileName,zipfile.ZIP_DEFLATED)
zip.close()
def confirmPublish(folder=''):
"""
Publish the recording when hitting the 'publish' button
"""
global id,entryTitle,entryDescription,entryTraining,workDirectoryToPublish, dirNameToPublish,loginENT
global emailENT,pathData, last_session_publish_order, last_session_publish_problem, standalone
idtosend=id
print "sockedEnabled: ", socketEnabled, "id: ",id
last_session_publish_order=getTime()
if socketEnabled==True and id != "": # useful for remote order only (doesn't go through publish())
print "=> Creating Zip file (no publishing form, distant order)"
workDirectoryToPublish=workDirectory # pathData + dirName
dirNameToPublish=dirName
#if 1:
try:
createZip()
#if 0:
except:
print "Warning! couldn't create zip file!"
id="" # if confirmPublsih fails id is back to ""
if sys.platform=='win32': # gives memory leak on OS X see what can be done ??
frameEnd.statusBar.SetStatusText(" Publication en cours, merci de patienter ...")
# !!!! Test: changing dirName and workDirectory to dirNameToPublish and workDirectoryToPublish
# to avoid conflicts when publishing and recording a new file straight away
if dirNameToPublish =="":
frameEnd.statusBar.SetStatusText("Rien a publier ...")
print ">>> before if dirNameToPublish != '' :"
if dirNameToPublish != "":
print ">>> after if dirNameToPublish != '' : and before writeInlogs"
writeInLogs("- Asked for publishing at "+ str(datetime.datetime.now())+\
" with id="+idtosend+" title="+title+" description="+description+" mediapath="+\
dirNameToPublish+".zip"+" prenom "+firstname+" name="+name+" genre="+genre+" ue="+ue+ " To server ="+urlserver+"\n")
print ">>> after writeInLogs and before if"
if 1:
#try:
# Send by ftp
print "Sending an FTP version..."
ftp = FTP(ftpUrl)
ftp.login(ftpLogin, ftpPass)
print "debut de ftp"
f = open(workDirectoryToPublish+".zip",'rb')# file to send
#f = open(pathData+"/"+dirName+".zip",'rb')# file to send
if folder=="canceled":
print "Trying to open cancel forlder"
ftp.cwd("canceled")
ftp.storbinary('STOR '+ dirNameToPublish+".zip", f) # Send the file
f.close() # Close file and FTP
ftp.quit()
print "fin de ftp"
if sys.platform=='win32':
if standalone == True:
frameEnd.Hide()
frameBegin.Show()
if 0:
#except:
print "!!! Something went wrong while sending the archive to the server !!!"
last_session_publish_problem=getTime()
if standalone == False:
start_new_thread(rss_warning_client_feed,())
writeInLogs("!!! Something went wrong while sending the Tar to the server at "\
+str(datetime.datetime.now())+" !!!\n")
frameEnd.statusBar.SetStatusText("Impossible d'ouvrir la connexion FTP")
# Information DialogBox
caption=_("!!! Publication ERROR !!!")
text=_("IMPOSSIBLE TO PUBLISH\
\nIs there an internet connection?\nIs the FTP port opened?")
dialog=wx.MessageDialog(None,message=text,caption=caption,
style=wx.OK|wx.ICON_INFORMATION)
dialog.ShowModal()
if folder=="":
#try:
if 1:
#Send data to the AudioCours server (submit form)
print "login ENT, emailENT >>>>>>>>> " ,loginENT, emailENT
if publishingForm==True:
urlParams="id="+idtosend+"&title="+title+"&description="+description+\
"&name="+name+"&firstname="+firstname+"&login="+loginENT+"&email="+emailENT+"&genre="+genre+"&ue="+ue+"&mediapath="+\
dirNameToPublish+".zip"
page = urlopen(urlserver,urlParams)
print "urlParams",urlParams
print "------ Response from Audiocours : -----"
serverAnswer= page.read() # Read/Check the result
print serverAnswer
if publishingForm==False:
if idtosend=="": idtosend="none"
#urlParams="mediapath="+dirNameToPublish+".zip"+"&id="+idtosend
urlParams="mediapath="+dirNameToPublish+".zip"
def launch():
print "params>>"+urlserver+"?"+urlParams
useBrowser(urlserver+"?"+urlParams)
#command='"c:\program files\internet explorer\iexplore" '+urlserver+'?'+urlParams
#print "commande URL= ", command
#os.system(command)
start_new_thread(launch,())
#except:
if 0:
print "Had problem while submitting the form"
# set the id variable to id="" again
idtosend= ""
print "setting entry fields back to empty"
entryTitle.SetValue("")
entryDescription.SetValue("")
entryLastname.SetValue("")
entryFirstname.SetValue("")
if formFormation=="": entryTraining.SetValue("")
frameEnd.statusBar.SetStatusText("---")
else:
print "Pas de publication: pas d'enregistrement effectue"