main.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. import os
  2. import os.path
  3. import sys
  4. import time
  5. import queue
  6. import argparse
  7. import tempfile
  8. import threading
  9. from itertools import groupby
  10. import cv2
  11. import requests
  12. import bitstring
  13. from loguru import logger
  14. from Crypto.Hash import BLAKE2b
  15. try:
  16. import rdrand
  17. except ImportError:
  18. logger.warning("RdRand is not available.")
  19. try:
  20. from linuxpy.video.device import Device, VideoCapture
  21. except ImportError:
  22. logger.warning("linuxpy is not available.")
  23. tmp_dir = None
  24. push_timeout = 10
  25. class TemporaryFile:
  26. def __init__(self, name, io, delete):
  27. self.name = name
  28. self.__io = io
  29. self.__delete = delete
  30. def __getattr__(self, k):
  31. return getattr(self.__io, k)
  32. def __del__(self):
  33. if self.__delete:
  34. try:
  35. os.unlink(self.name)
  36. except FileNotFoundError:
  37. pass
  38. def NamedTemporaryFile(
  39. mode="w+b", bufsize=-1, suffix="", prefix="tmp", dir=None, delete=True
  40. ):
  41. if not dir:
  42. dir = tempfile.gettempdir()
  43. name = os.path.join(dir, prefix + os.urandom(32).hex() + suffix)
  44. if mode is None:
  45. return TemporaryFile(name, None, delete)
  46. fh = open(name, "w+b", bufsize)
  47. if mode != "w+b":
  48. fh.close()
  49. fh = open(name, mode)
  50. return TemporaryFile(name, fh, delete)
  51. def chunks(lst, n):
  52. for i in range(0, len(lst), n):
  53. yield lst[i : i + n]
  54. def run_check(cmd):
  55. logger.info(f"Executing '{cmd}'.")
  56. if os.system(cmd) != 0:
  57. raise ValueError("Exit code != 0.")
  58. def extract_image(path):
  59. logger.info(f"Extract image '{path}'.")
  60. im = cv2.imread(path)
  61. data = []
  62. rows, cols, _ = im.shape
  63. for i in range(rows):
  64. for j in range(cols):
  65. r, g, b = im[i, j]
  66. data.extend((r, g, b))
  67. return bytes(data)
  68. def extract_wav(path):
  69. logger.info(f"Extract audio: '{path}'.")
  70. data = []
  71. with open(path, "rb") as f:
  72. for sample in chunks(f.read()[44:], 2):
  73. data.append(sample[0])
  74. return bytes(data)
  75. def extract_video(path):
  76. logger.info(f"Extract video: '{path}'.")
  77. with tempfile.TemporaryDirectory(dir=tmp_dir) as tmpd:
  78. run_check(
  79. f"ffmpeg -hide_banner -loglevel error -y -i {path} -vf mpdecimate -r 1/1 {tmpd}/%d.bmp"
  80. )
  81. data = b""
  82. for filename in sorted(
  83. os.listdir(tmpd), key=lambda filename: int(filename.split(".")[0])
  84. ):
  85. data += extract_image(os.path.join(tmpd, filename))
  86. return data
  87. def extract_lsbs(data):
  88. logger.info("Extract LSBs.")
  89. buffer = []
  90. data = [k for k, _ in groupby(data)]
  91. data = chunks(data, 8)
  92. for chunk in data:
  93. if len(chunk) != 8:
  94. break
  95. ba = bitstring.BitArray(8)
  96. for i, byte in zip(range(len(chunk)), chunk):
  97. ba[i] = byte & 1
  98. buffer.append(ba.u)
  99. return bytes(buffer)
  100. def whiten(data):
  101. logger.info("Whitening.")
  102. buffer = b""
  103. for chunk in chunks(data, 32):
  104. if len(chunk) < 32:
  105. break
  106. buffer += BLAKE2b.new(data=chunk, digest_bits=256).digest()
  107. return buffer
  108. def read_video(source, duration=60):
  109. tmpf = NamedTemporaryFile(suffix=".mkv", mode=None, dir=tmp_dir)
  110. run_check(
  111. f"ffmpeg -hide_banner -loglevel error -y -i {source} -t {duration} -acodec copy -vcodec copy {tmpf.name}"
  112. )
  113. return extract_video(tmpf.name)
  114. def read_audio(source, duration=60):
  115. tmpf = NamedTemporaryFile(suffix=".wav", mode=None, dir=tmp_dir)
  116. run_check(
  117. f"ffmpeg -hide_banner -loglevel error -y -f alsa -i {source} -t {duration} -ar 44100 -f s16le -acodec pcm_s16le {tmpf.name}"
  118. )
  119. return extract_wav(tmpf.name)
  120. def read_audio_video(source, duration=60):
  121. tmpf = NamedTemporaryFile(suffix=".mkv", mode=None, dir=tmp_dir)
  122. run_check(
  123. f"ffmpeg -hide_banner -loglevel error -y -i {source} -t {duration} -acodec copy -vcodec copy {tmpf.name}"
  124. )
  125. data_a = extract_video(tmpf.name)
  126. tmpf2 = NamedTemporaryFile(suffix=".wav", mode=None, dir=tmp_dir)
  127. run_check(
  128. f"ffmpeg -hide_banner -loglevel error -y -i {tmpf.name} -vn -ar 44100 -f s16le -acodec pcm_s16le {tmpf2.name}"
  129. )
  130. data_b = extract_wav(tmpf2.name)
  131. return bytes(a ^ b for a, b in zip(data_a, data_b))
  132. def read_rdseed(_, amount=16):
  133. data = rdrand.rdseed_get_bytes(amount)
  134. if len(data) != amount or data.count(0) == amount:
  135. raise ValueError("bad data")
  136. return data
  137. def sample(source, source_type, multiplier=1):
  138. match source_type:
  139. case "video":
  140. sampler = read_video
  141. multiplier *= 60
  142. case "audio":
  143. sampler = read_audio
  144. multiplier *= 60
  145. case "video+audio":
  146. sampler = read_audio_video
  147. multiplier *= 60
  148. case "rdseed":
  149. sampler = read_rdseed
  150. case _:
  151. raise ValueError(source_type)
  152. multiplier = int(multiplier)
  153. if multiplier < 1:
  154. raise ValueError(multiplier)
  155. logger.info("Sampling...")
  156. data = sampler(source, multiplier)
  157. logger.info(f"Sample ready: {len(data)}b.")
  158. if source_type != "rdseed":
  159. data = extract_lsbs(data)
  160. data = whiten(data)
  161. return data
  162. def video2_extractor(q, q2):
  163. while True:
  164. data = q2.get()
  165. data = chunks(data, 8)
  166. newdata = b""
  167. for chunk in data:
  168. newdata += chunk[:4]
  169. data = extract_lsbs(newdata)
  170. data = whiten(data)
  171. logger.info(f"Sample ready: {len(data)}b.")
  172. q.put(data)
  173. def video2_sampler(q, q2, source):
  174. with Device.from_id(abs(int(source))) as device:
  175. device.set_format(
  176. 1,
  177. device.info.frame_sizes[0].width,
  178. device.info.frame_sizes[0].height,
  179. pixel_format="YUYV",
  180. )
  181. last = 0
  182. for frame in device:
  183. new = time.monotonic()
  184. if new - last > 10:
  185. q2.put(bytes(frame))
  186. last = new
  187. def push(pool_url, data, secret):
  188. logger.info(f"Pushing {len(data)}b.")
  189. resp = requests.post(
  190. f"{pool_url}/api/pool",
  191. data=data,
  192. headers={"X-Secret": secret},
  193. timeout=(push_timeout, push_timeout),
  194. )
  195. (logger.success if resp.status_code == 200 else logger.error)(
  196. f"{resp.status_code}: {resp.text}"
  197. )
  198. def puller(queue, source, source_type, multiplier):
  199. while True:
  200. try:
  201. data = sample(source, source_type, multiplier)
  202. except KeyboardInterrupt:
  203. logger.info("Interrupted by user.")
  204. sys.exit(0)
  205. except Exception as e:
  206. logger.error(f"Pull exception: {e}")
  207. continue
  208. for piece in chunks(data, 1024 * 500):
  209. queue.put(piece)
  210. def pusher(queue, pool_url, secret, cooldown=0):
  211. while True:
  212. piece = queue.get()
  213. try:
  214. push(pool_url, piece, secret)
  215. except KeyboardInterrupt:
  216. logger.info("Interrupted by user.")
  217. sys.exit(0)
  218. except Exception as e:
  219. logger.error(f"Push exception: {e}")
  220. queue.put(piece)
  221. if cooldown:
  222. time.sleep(cooldown)
  223. if __name__ == "__main__":
  224. parser = argparse.ArgumentParser()
  225. parser.add_argument("--source", type=str, required=True)
  226. parser.add_argument("--source-type", type=str, default="video+audio")
  227. parser.add_argument("--multiplier", type=float, default=1)
  228. parser.add_argument("--secret-file", type=str, default="./.secret")
  229. parser.add_argument("--cooldown", type=int, default=0)
  230. parser.add_argument("--pool-url", type=str, default="https://yebi.su")
  231. parser.add_argument("--push-timeout", type=int, default=10)
  232. parser.add_argument("--tmp-dir", type=str)
  233. args = parser.parse_args()
  234. if args.tmp_dir and os.path.isdir(args.tmp_dir):
  235. tmp_dir = args.tmp_dir
  236. logger.info(f"Changed temp-dir: '{tmp_dir}'")
  237. push_timeout = max(args.push_timeout, 1)
  238. with open(args.secret_file, "r") as f:
  239. lines = f.read().strip().split("\n")
  240. ident = lines[0].strip()
  241. secret = lines[1].strip()
  242. secret = f"{ident} {secret}"
  243. q = queue.Queue()
  244. pusher_th = threading.Thread(
  245. target=pusher, args=(q, args.pool_url, secret, args.cooldown)
  246. )
  247. if args.source_type == "linuxvideo":
  248. q2 = queue.Queue()
  249. threading.Thread(target=video2_sampler, args=(q, q2, args.source)).start()
  250. threading.Thread(target=video2_extractor, args=(q, q2)).start()
  251. else:
  252. threading.Thread(
  253. target=puller, args=(q, args.source, args.source_type, args.multiplier)
  254. ).start()
  255. pusher_th = threading.Thread(
  256. target=pusher, args=(q, args.pool_url, secret, args.cooldown)
  257. )
  258. pusher_th.start()
  259. pusher_th.join()