Files
@ 3f1b9b9b0505
Branch filter:
Location: light9/light9/vidref/replay.py
3f1b9b9b0505
8.0 KiB
text/x-python
add yapf tool
Ignore-this: 28fe07e21ca358a97282f5316c8820e0
Ignore-this: 28fe07e21ca358a97282f5316c8820e0
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 | from __future__ import division
import os, gtk, shutil, logging, time
from bisect import bisect_left
from decimal import Decimal
log = logging.getLogger()
framerate = 15
def songDir(song):
safeUri = song.split('://')[-1].replace('/','_')
return os.path.expanduser("~/light9-vidref/play-%s" % safeUri)
def takeDir(songDir, startTime):
"""
startTime: unix seconds (str ok)
"""
return os.path.join(songDir, str(int(startTime)))
def snapshotDir():
return os.path.expanduser("~/light9-vidref/snapshot")
class ReplayViews(object):
"""
the whole list of replay windows. parent is the scrolling area for
these windows to be added
"""
def __init__(self, parent):
# today, parent is the vbox the replay windows should appear in
self.parent = parent
self.lastStart = None
self.views = []
def update(self, position):
"""
freshen all replay windows. We get called this about every
time there's a new live video frame.
Calls loadViewsForSong if we change songs, or even if we just
restart the playback of the current song (since there could be
a new replay view)
"""
t1 = time.time()
if position.get('started') != self.lastStart and position['song']:
self.loadViewsForSong(position['song'])
self.lastStart = position['started']
for v in self.views:
v.updatePic(position)
log.debug("update %s views in %.2fms",
len(self.views), (time.time() - t1) * 1000)
def loadViewsForSong(self, song):
"""
replace previous views, and cleanup short ones
"""
for v in self.views:
v.destroy()
self.views[:] = []
d = songDir(song)
try:
takes = sorted(t for t in os.listdir(d) if t.isdigit())
except OSError:
return
for take in takes:
td = takeDir(songDir(song), take)
r = Replay(td)
if r.tooShort():
# this is happening even on full-song recordings, even
# after the Replay.__init__ attempt to catch it
log.warn("prob too short, but that's currently broken")
#log.warn("cleaning up %s; too short" % r.takeDir)
#r.deleteDir()
continue
rv = ReplayView(self.parent, r)
self.views.append(rv)
class ReplayView(object):
"""
one of the replay widgets
"""
def __init__(self, parent, replay):
self.replay = replay
self.enabled = True
self.showingPic = None
# this *should* be a composite widget from glade
delImage = gtk.Image()
delImage.set_visible(True)
delImage.set_from_stock("gtk-delete", gtk.ICON_SIZE_BUTTON)
def withLabel(cls, label):
x = cls()
x.set_visible(True)
x.set_label(label)
return x
def labeledProperty(key, value, width=12):
lab = withLabel(gtk.Label, key)
ent = gtk.Entry()
ent.set_visible(True)
ent.props.editable = False
ent.props.width_chars = width
ent.props.text = value
cols = gtk.HBox()
cols.set_visible(True)
cols.add(lab)
cols.add(ent)
return cols
replayPanel = gtk.HBox()
replayPanel.set_visible(True)
if True:
af = gtk.AspectFrame()
af.set_visible(True)
af.set_shadow_type(gtk.SHADOW_OUT)
af.props.obey_child = True
img = gtk.Image()
img.set_visible(True)
self.picWidget = img
af.add(img)
replayPanel.pack_start(af, False, False, 0)
if True:
rows = []
rows.append(labeledProperty("Started:", self.replay.getTitle()))
rows.append(labeledProperty("Seconds:", self.replay.getDuration()))
if True:
en = withLabel(gtk.ToggleButton, "Enabled")
en.set_active(True)
def tog(w):
self.enabled = w.get_active()
en.connect("toggled", tog)
rows.append(en)
if True:
d = withLabel(gtk.Button, "Delete")
d.props.image = delImage
def onClicked(w):
self.replay.deleteDir()
self.destroy()
d.connect("clicked", onClicked)
rows.append(d)
if True:
pin = withLabel(gtk.CheckButton, "Pin to top")
pin.props.draw_indicator = True
rows.append(pin)
stack = gtk.VBox()
stack.set_visible(True)
for r in rows:
stack.add(r)
stack.set_child_packing(r, False, False, 0, gtk.PACK_START)
replayPanel.pack_start(stack, False, False, 0)
parent.pack_start(replayPanel, False, False)
log.debug("packed ReplayView %s" % replayPanel)
self.replayPanel = replayPanel
def destroy(self):
self.replayPanel.destroy()
self.enabled = False
def updatePic(self, position, lag=.2):
# this should skip updating off-screen widgets! maybe that is
# done by declaring the widget dirty and then reacting to a
# paint message if one comes
if not self.enabled:
return
t = position.get('hoverTime', position['t'])
inPic = self.replay.findClosestFrame(t + lag)
if inPic == self.showingPic:
return
with gtk.gdk.lock:
self.picWidget.set_from_file(inPic)
if 0:
# force redraw of that widget
self.picWidget.queue_draw_area(0,0,320,240)
self.picWidget.get_window().process_updates(True)
self.showingPic = inPic
_existingFrames = {} # takeDir : frames
class Replay(object):
"""
model for one of the replay widgets
"""
def __init__(self, takeDir):
self.takeDir = takeDir
try:
self.existingFrames = _existingFrames[self.takeDir]
except KeyError:
log.info("scanning %s", self.takeDir)
self.existingFrames = sorted([Decimal(f.split('.jpg')[0])
for f in os.listdir(self.takeDir)])
if not self.existingFrames:
raise NotImplementedError("suspiciously found no frames in dir %s" % self.takeDir)
_existingFrames[self.takeDir] = self.existingFrames
def tooShort(self, minSeconds=5):
return len(self.existingFrames) < (minSeconds * framerate)
def deleteDir(self):
try:
shutil.rmtree(self.takeDir)
except OSError:
# probably was writing frames into this dir at the same time!
log.warn("partial delete- frames were probably still writing "
"into that dir")
def getTitle(self):
tm = time.localtime(int(os.path.basename(self.takeDir)))
return time.strftime("%a %H:%M:%S", tm)
def getDuration(self):
"""total number of seconds represented, which is most probably
a continuous section, but we aren't saying where in the song
that is"""
return "%.1f" % (len(self.existingFrames) / framerate)
def findClosestFrame(self, t):
# this is weird to be snapping our playback time to the frames
# on disk. More efficient and accurate would be to schedule
# the disk frames to playback exactly as fast as they want
# to. This might spread cpu load since the recorded streams
# might be a little more out of phase. It would also
# accomodate changes in framerate between playback streams.
i = bisect_left(self.existingFrames, Decimal(str(t)))
if i >= len(self.existingFrames):
i = len(self.existingFrames) - 1
return os.path.join(self.takeDir, "%08.03f.jpg" %
self.existingFrames[i])
|