forked from albertz/music-player
-
Notifications
You must be signed in to change notification settings - Fork 0
/
debug.py
238 lines (195 loc) · 6.75 KB
/
debug.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
# -*- coding: utf-8 -*-
# MusicPlayer, https://github.com/albertz/music-player
# Copyright (c) 2013, Albert Zeyer, www.az2000.de
# All rights reserved.
# This code is under the 2-clause BSD license, see License.txt in the root directory of this project.
# This is the debug module: tools to debug MusicPlayer.
# This is mostly for debugging at runtime.
# - memory profiling. searching for mem-leaks
# - runtime profiling. searching slow code paths
# - other bugs
# Use socketcontrol-interactiveclient.py for interactively control.
# After being connected, just run `import debug` and use the functions from here.
import sys, os
import utils
def getDevelPath():
def check(path):
path = os.path.expanduser(path)
if not os.path.isdir(path): return None
if not os.path.isdir(path + "/.git"): return None
return path
for path in [
# send me a request to include your custom dir.
# if it isn't too unusual, i might add it here.
"~/Programmierung/music-player",
"~/Projects/music-player",
"~/Coding/music-player",
]:
path = check(path)
if path: return path
return None
def addDevelSysPath():
"adds your MusicPlayer development directory to sys.path"
path = getDevelPath()
assert path, "devel path not found"
sys.path = [path] + sys.path
def addSysPythonPath():
import appinfo
import os
def addpath(p):
try:
p = os.path.normpath(p)
p = os.path.abspath(p)
except OSError: return
if not os.path.exists(p): return
if p not in sys.path: sys.path += [p]
paths = os.environ.get("PYTHONPATH", "").split(":")
for p in paths:
addpath(p.strip())
versionStr = ".".join(map(str, sys.version_info[0:2]))
if sys.platform == "darwin":
addpath("/usr/local/Frameworks/Python.framework/Versions/%s/lib/python%s/lib-dynload/" % (versionStr, versionStr))
addpath("/System/Frameworks/Python.framework/Versions/%s/lib/python%s/lib-dynload/" % (versionStr, versionStr))
# This will add other custom paths, e.g. for eggs.
import site
site.main()
def addsitedir(d):
try:
d = os.path.normpath(d)
d = os.path.abspath(d)
except OSError: return
if os.path.exists(d):
site.addsitedir(d)
# We still might miss some site-dirs.
addsitedir("/usr/local/lib/python%s/site-packages" % versionStr)
addsitedir("/usr/lib/python%s/site-packages" % versionStr)
if sys.platform == "darwin":
addsitedir("/Library/Python/%s/site-packages" % versionStr)
if not appinfo.args.forkExecProc:
print("Python paths after: %r" % sys.path)
def reloadMe():
"Because this is so common, handy shortcut."
addDevelSysPath()
import debug
return reload(debug)
def iterEggPaths():
from glob import glob
versionStr = ".".join(map(str, sys.version_info[0:2]))
for path in [
sys.prefix, # = /System/Library/Frameworks/Python.framework/Versions/..
# mac specific. you might want to make that more generic.
"/Library/Python/%s/site-packages" % versionStr,
]:
for egg in glob(path + "/*.egg"):
yield egg
def addEggPaths():
"Deprecated. You might just want to use addSysPythonPath(). should do the same but better"
for egg in iterEggPaths():
if egg not in sys.path:
sys.path += [egg]
# Profiling run traces.
# sys.{setprofile/settrace} is not really a good fit in multi-threading envs.
# There is [yappi](https://code.google.com/p/yappi/).
class ProfileCtx:
def __enter__(self,*args):
import yappi
yappi.start()
def __exit__(self,*args):
import yappi
yappi.stop()
yappi.print_stats()
yappi.clear_stats()
def profile(func):
with ProfileCtx():
func()
def createCocoaKeyEvent(keyCode, down=True):
from AppKit import NSEvent, NSApplication, NSKeyDown, NSKeyUp, NSDate
modifierFlags = 0
return NSEvent.keyEventWithType_location_modifierFlags_timestamp_windowNumber_context_characters_charactersIgnoringModifiers_isARepeat_keyCode_(
NSKeyDown if down else NSKeyUp, (0, 0), modifierFlags,
NSDate.timeIntervalSinceReferenceDate(), #theEvent.timestamp(),
0, #theEvent.windowNumber(),
None, # context
None, # characters
None, # charactersIgnoringModifiers
False, # isARepeat
keyCode # keyCode
)
def testCocoaPlaylistUpDown():
# keyCode: 125 - down / 126 - up
obj = cocoaGetPlaylistObj()
utils.do_in_mainthread(lambda: obj.keyDown_(createCocoaKeyEvent(125,True)), wait=True)
utils.do_in_mainthread(lambda: obj.keyDown_(createCocoaKeyEvent(126,True)), wait=True)
def cocoaGetPlaylistObj():
import guiCocoa
w = guiCocoa.windows["mainWindow"]
q = w.childs["queue"]
ql = q.childs["queue"]
return ql.nativeGuiObject
def dump10Secs():
from State import state
player = state.player
fmtTagStr,bitsPerSample = player.outSampleFormat
bytesPerSample = bitsPerSample / 8
def write_wavheader(stream, datalen):
# http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/WAVE.html
from struct import pack
numSamples = datalen / bytesPerSample
assert bitsPerSample in [8,16,24,32]
if fmtTagStr == "int":
fmttag = 1 # PCM format. integers
fmtchunksize = 16 # for PCM
needExtendedSection = False
needFactChunk = False
elif fmtTagStr == "float":
# IEEE format has always extended section (which is empty), thus 18 bytes long
fmttag = 3 # IEEE float
fmtchunksize = 18
needExtendedSection = True
needFactChunk = True
factchunksize = 4
#wavechunksize = 36 + datalen # PCM
wavechunksize = 20 + fmtchunksize + datalen
if needFactChunk:
wavechunksize += factchunksize + 8
stream.write(pack("<4sI4s", "RIFF", wavechunksize, "WAVE"))
stream.write("fmt ")
stream.write(pack("<L", fmtchunksize))
stream.write(pack("<H", fmttag))
numChannels = player.outNumChannels
samplerate = player.outSamplerate
byteRate = samplerate * numChannels * bytesPerSample
blockAlign = numChannels * bytesPerSample
stream.write(pack("<H", numChannels))
stream.write(pack("<L", samplerate))
stream.write(pack("<L", byteRate))
stream.write(pack("<H", blockAlign))
stream.write(pack("<H", bitsPerSample))
if needExtendedSection:
stream.write(pack("<H", 0)) # size of extended section
if needFactChunk:
stream.write("fact")
stream.write(pack("<L", factchunksize))
stream.write(pack("<L", numChannels * numSamples))
stream.write("data")
stream.write(pack("<L", datalen))
player.playing = False
player.soundcardOutputEnabled = False
player.playing = True
wholebuf = ""
# read up to 10 secs
while len(wholebuf) < player.outNumChannels * player.outSamplerate * bytesPerSample * 10:
wholebuf += player.readOutStream(player.outNumChannels * player.outSamplerate)
player.playing = False
player.soundcardOutputEnabled = True
player.seekRel(-10) # seek back 10 secs
import appinfo
wavfn = appinfo.userdir + "/debugdump.wav"
f = open(wavfn, "w")
write_wavheader(f, len(wholebuf))
f.write(wholebuf)
f.close()
return wavfn
def hangMainThread(secs):
import utils, time
utils.do_in_mainthread(lambda: time.sleep(secs), True)