forked from fzellini/camfetcher
/
Cam.py
278 lines (250 loc) · 11 KB
/
Cam.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
import os
import logging
import time
import subprocess
import threading
import re
import datetime
import pytz
import shutil
from m3u8 import m3u8
class Cam:
@staticmethod
def mkdir(d):
if os.path.exists(d):
if not os.path.isdir(d):
raise NameError("%s must be a directory" % d)
else:
os.makedirs(d)
@staticmethod
def simplelog(*args):
print args[0]
def log(self):
if self.log:
return self.log
else:
return logging.getLogger(self.name)
def __init__(self, name, url, source_type, raw, chunks_path, fps=5, chunk_size=10, chunks=3, hours=24, logger=None,
tempdir=None, m3u8_path=None, webpath_chunks_prefix="", font=None, curl_options="",
ffmpeg_options=None, ffmpeg_prefilter=None):
if ffmpeg_prefilter is None:
ffmpeg_prefilter = ""
else:
ffmpeg_prefilter += ","
self.ffmpeg_prefilter = ffmpeg_prefilter
if ffmpeg_options is None:
ffmpeg_options = "-c:v libx264 -crf 18 -profile:v baseline -maxrate 128k -bufsize 256k -pix_fmt yuv420p"
self.ffmpeg_options = ffmpeg_options
self.name = name
self.url = url
self.source_type = source_type
self.raw = os.path.abspath(raw)
self.chunks_path = os.path.abspath(chunks_path)
self.chunk_size = chunk_size
self.hours = hours
self.fps = fps
self.font = font
self.curl_options = curl_options
if tempdir is None:
tempdir = raw+"/tmp"
self.tempdir = os.path.abspath(tempdir)
if m3u8_path is None:
m3u8_path = name
self.m3u8_path = m3u8_path
self.webpath_chunks_prefix = webpath_chunks_prefix
self.m3u8 = m3u8(targetduration=chunk_size, nseq=chunks, fname=self.m3u8_path)
# create paths if not exists
Cam.mkdir(self.raw)
Cam.mkdir(self.tempdir)
Cam.mkdir(self.chunks_path)
self.log = logger
self.pid = None
def do_chunks(self):
# wait for chunk_size
while True:
t = int(time.time())
if t % self.chunk_size:
time.sleep(.1)
continue
self.log.debug("chunk [%d] fetcher pid [%s]" % (t, self.pid))
ti = t - self.chunk_size
period = 1 / float(self.fps)
# make IMage Array index -> (imagetime, imagename)
# save directories for removal
imad = []
ima = []
while ti < t:
# convert ti in gmtime and directory
gmt = time.gmtime(ti)
ddir = "%s/%04d/%02d/%02d/%02d/%02d/%02d" % (self.raw, gmt.tm_year, gmt.tm_mon, gmt.tm_mday, gmt.tm_hour, gmt.tm_min, gmt.tm_sec)
imad.append(ddir)
# self.log.debug("[%s]: directory for sec %d: [%s]" % (self.name, ti, ddir))
for root, dirs, files in os.walk(ddir):
for name in files:
if name.endswith(".jpg"):
usec = int(name[:-4])
# self.log.debug("[%s]: found FILE [%s], usec [%d]" % (self.name, name, usec))
f = "%s/%s" % (root, name)
ima.append((f, float(ti+float(usec)/1000000)))
ti += 1
# self.log.debug("[%s]: images for chunk [%s]" % (self.name, ima))
# links to images to make chunks
if not len(ima):
if self.pid:
self.log.warning("killing pid [%d]" % self.pid)
try:
os.system("pkill -P %d" % self.pid)
os.system("pkill %d" % self.pid)
# os.kill(self.pid, signal.SIGTERM) # SIGKILL ?
except:
self.log.exception("while killing pid [%d]" % self.pid)
self.pid = None
time.sleep(1)
continue
t = float(t)
ti = float(t - self.chunk_size)
outim = []
while ti < t:
# search image nearest to "ti"
td = 999.0
imname = None
for name, tim in ima:
# self.log.debug("[%s]: searching for image nearesto to [%f]" % (self.name, ti))
dt = abs(tim-ti)
if dt < td:
td = dt
imname = name
if imname:
# self.log.debug("[%s]: found [%s]" % (self.name, imname))
outim.append(imname)
ti += period
# self.log.debug("[%s]: ordered images for chunk [%s]" % (self.name, outim))
# now gen symlink in tmp dir
i = 0
for imax in outim:
tmpfname = "%s/%d.jpg" % (self.tempdir, i)
if os.path.lexists(tmpfname):
os.remove(tmpfname)
os.symlink(imax, tmpfname)
i += 1
# generate chunk with ffmpeg
gmt = time.gmtime(t)
chunkdir = "%04d-%02d-%02d_%02d" % (gmt.tm_year, gmt.tm_mon, gmt.tm_mday, gmt.tm_hour)
chunkname = "%04d-%02d-%02d_%02d-%02d-%02d.ts" % (gmt.tm_year, gmt.tm_mon, gmt.tm_mday, gmt.tm_hour, gmt.tm_min, gmt.tm_sec)
chunkdirpath = "%s/%s" % (self.chunks_path, chunkdir)
chunkfullpath = "%s/%s" % (chunkdirpath, chunkname)
chunkwebpath = "%s/%s/%s" % (self.webpath_chunks_prefix, chunkdir, chunkname)
# make chunk dir if not exists
Cam.mkdir(chunkdirpath)
frames = len(outim)
wtime = time.localtime(t)
ptso = wtime.tm_hour*3600 + wtime.tm_min*60 + wtime.tm_sec
cmd = "ffmpeg -loglevel panic -y -framerate %d -start_number 0 -i \"%s/%%d.jpg\" -frames %d " \
"-vf %ssetpts=PTS+%d/TB,drawbox=t=20:x=0:y=0:width=120:height=30:color=black@0.5," \
"drawtext=\"fontfile=%s:text=%02d\\\\\\:%02d\\\\\\:%d%%{expr_int_format\\\\\\:n/5\\\\\\:u\\\\\\:1}.%%{expr_int_format\\\\\\:mod(n\,5)*2\\\\\\:u\\\\\\:1}00:y=10:x=10:fontcolor=yellow\" " \
"%s " \
"%s" % (self.fps, self.tempdir, frames, self.ffmpeg_prefilter, ptso, self.font, wtime.tm_hour, wtime.tm_min, int(wtime.tm_sec/10), self.ffmpeg_options, chunkfullpath)
self.log.debug("ffmpeg cmd: [%s]" % cmd)
os.system(cmd)
# update m3u8
self.m3u8.addstream(chunkwebpath)
self.m3u8.write()
# remove work images
for imax, imt in ima:
if os.path.exists(imax):
# self.log.debug("[%s]: removing : [%s]" % (self.name, imax))
os.remove(imax)
# remove dirs
for dirname in imad:
if os.path.exists(dirname):
# self.log.debug("[%s]: removing dir: [%s]" % (self.name, dirname))
os.rmdir(dirname)
while True:
t = int(time.time())
if t % self.chunk_size:
break
time.sleep(.1)
def mjpeg_fetcher(self):
cmd = "curl %s -s \"%s\" | ./mjpeg2jpg/mjpeg2jpg - %s" % (self.curl_options, self.url, self.raw)
self.log.debug("mjpeg_fetcher [%s] started" % cmd)
while True:
proc = subprocess.Popen(cmd, shell=True)
self.log.info("spawned pid [%d]" % proc.pid)
self.pid = proc.pid
proc.wait()
# os.system(cmd)
time.sleep(2)
def do_mjpeg(self):
self.log.debug("do_mjpeg start")
# run background mjpeg2 executable
# p = Process(target=self.mjpeg_fetcher)
# p.start()
threading.Thread(target=self.mjpeg_fetcher, name=self.name+".mjpeg_fetcher").start()
# run garbage collector
threading.Thread(target=self.garbage_collector, name=self.name+".garbage_collector").start()
# chunks
try:
self.do_chunks()
except:
self.log.exception("doing chunks")
def ffmpeg_fetcher(self):
cmd = "ffmpeg -loglevel panic -i \"%s\" -qscale 4 -f mpjpeg - | ./mjpeg2jpg/mjpeg2jpg - %s" % (self.url, self.raw)
self.log.debug("ffmpeg_fetcher [%s] started" % cmd)
while True:
proc = subprocess.Popen(cmd, shell=True)
self.log.info("spawned pid [%d]" % proc.pid)
self.pid = proc.pid
proc.wait()
# os.system(cmd)
time.sleep(2)
def do_ffmpeg(self):
self.log.debug("do_ffmpeg start")
# run background mjpeg2 executable
# p = Process(target=self.mjpeg_fetcher)
# p.start()
threading.Thread(target=self.ffmpeg_fetcher, name=self.name+".ffmpeg_fetcher").start()
# run garbage collector
threading.Thread(target=self.garbage_collector, name=self.name+".garbage_collector").start()
# chunks
try:
self.do_chunks()
except:
self.log.exception("doing chunks")
# remove chunks
def garbage_collector(self):
dir_re = re.compile("([\d]{4})-([\d]{2})-([\d]{2})_([\d]{2})")
while True:
utcnow = datetime.datetime.now(tz=pytz.timezone("GMT"))
tdref = datetime.timedelta(hours=self.hours)
self.log.debug("os.walk dir utcnow [%s], tdref [%s]" % (utcnow, tdref))
# scan chunk dir
for dirpath, dirnames, files in os.walk(self.chunks_path):
# self.log.debug("[%s]: os.walk [%s] [%s] [%s]" % (self.name, dirpath, dirnames, files))
for dirname in dirnames:
# dirname format is: AAAA-MM-DD_HH e.g. 2015-03-11_14
match = dir_re.match(dirname)
if match:
fullpath = os.path.join(dirpath, dirname)
self.log.debug("os.walk match dir [%s] [%s]" % (dirname, fullpath))
yyyy = int(match.group(1))
mm = int(match.group(2))
dd = int(match.group(3))
hh = int(match.group(4))
ddt = datetime.datetime(yyyy, mm, dd, hh, tzinfo=pytz.timezone("GMT"))
td = utcnow - ddt
self.log.debug("os.walk dir datetime [%s] delta [%s]" % (ddt, td))
if td > tdref:
self.log.debug("os.walk dir to delete [%s]" % fullpath)
try:
shutil.rmtree(fullpath)
except:
self.log.exception("exception removing tree")
time.sleep(self.hours*360)
def start(self):
self.log.debug("started")
# type check
fname = "do_"+self.source_type
if hasattr(self, fname):
getattr(self, fname)()
else:
self.log.error("type [%s] not managed" % self.source_type)