summaryrefslogtreecommitdiff
path: root/voctocore/lib/pipeline.py
blob: b89d2aff132014e16bdae16993cf706f99242ea2 (plain)
  1. #!/usr/bin/python3
  2. import os, errno, time, logging
  3. from gi.repository import GLib, Gst
  4. # import controlserver annotation
  5. from lib.controlserver import controlServerEntrypoint
  6. # import library components
  7. from lib.config import Config
  8. from lib.quadmix import QuadMix
  9. from lib.videomix import VideoMix
  10. # from lib.audiomix import AudioMix
  11. from lib.distributor import TimesTwoDistributor
  12. from lib.shmsrc import FailsafeShmSrc
  13. class Pipeline(Gst.Pipeline):
  14. """mixing, streaming and encoding pipeline constuction and control"""
  15. log = logging.getLogger('Pipeline')
  16. videonames = []
  17. audionames = []
  18. def __init__(self):
  19. super().__init__()
  20. self.log.debug('Creating Video-Mixer')
  21. # create audio and video mixer
  22. self.quadmixer = QuadMix()
  23. self.add(self.quadmixer)
  24. self.videomixer = VideoMix()
  25. self.add(self.videomixer)
  26. # self.audiomixer = AudioMix()
  27. # self.add(self.audiomixer)
  28. # read the path where the shm-control-sockets are located and ensure it exists
  29. socketpath = Config.get('sources', 'socketpath')
  30. self.log.info('Ensuring the configured socketpath exists: %s', socketpath)
  31. try:
  32. os.makedirs(socketpath)
  33. except OSError as exception:
  34. if exception.errno != errno.EEXIST:
  35. raise
  36. self.videonames = Config.getlist('sources', 'video')
  37. self.audionames = Config.getlist('sources', 'video')
  38. for name in self.videonames:
  39. socket = os.path.join(socketpath, 'v-'+name)
  40. self.log.info('Creating video-source %s at socket-path %s', name, socket)
  41. sourcebin = FailsafeShmSrc(socket)
  42. self.add(sourcebin)
  43. distributor = TimesTwoDistributor()
  44. self.add(distributor)
  45. sourcebin.link(distributor)
  46. self.quadmixer.add_source(distributor)
  47. self.videomixer.add_source(distributor)
  48. # distributor.link(self.quadmixer)
  49. # distributor.link(self.videomixer)
  50. # for audiosource in Config.getlist('sources', 'audio'):
  51. # sourcebin = FailsafeShmSrc(os.path.join(socketpath, audiosource))
  52. # self.add(sourcebin)
  53. # sourcebin.link(self.audiomixer)
  54. # tell the quadmix that this were all sources and no more sources will come after this
  55. self.quadmixer.finalize()
  56. self.quadmixer.set_active(0)
  57. self.videomixer.set_active(0)
  58. self.quadmixsink = Gst.ElementFactory.make('autovideosink', 'quadmixsink')
  59. self.quadmixsink.set_property('sync', False)
  60. self.add(self.quadmixsink)
  61. self.quadmixer.link(self.quadmixsink)
  62. self.videosink = Gst.ElementFactory.make('autovideosink', 'videosink')
  63. self.videosink.set_property('sync', False)
  64. self.add(self.videosink)
  65. self.videomixer.link(self.videosink)
  66. # self.audiosink = Gst.ElementFactory.make('autoaudiosink', 'audiosink')
  67. # self.add(self.audiosink)
  68. # self.audiomixer.link(self.audiosink)
  69. def run(self):
  70. self.set_state(Gst.State.PAUSED)
  71. time.sleep(0.5)
  72. self.set_state(Gst.State.PLAYING)
  73. def quit(self):
  74. self.set_state(Gst.State.NULL)
  75. # # collection of video-sources to connect to the quadmix
  76. # quadmixSources = []
  77. # # create camera sources
  78. # for camberabin in self.createDummyCamSources():
  79. # # link camerasource to audiomixer
  80. # camberabin.get_by_name('audio_src').link(self.pipeline.get_by_name('liveaudio'))
  81. # # inject a ×2 distributor and link one end to the live-mixer
  82. # distributor = self.createDistributor(camberabin.get_by_name('video_src'), camberabin.get_name())
  83. # distributor.get_by_name('a').link(self.pipeline.get_by_name('livevideo'))
  84. # # collect the other end to add it later to the quadmix
  85. # quadmixSources.append(distributor.get_by_name('b'))
  86. # # TODO: generate pause & slides with another generator here which only
  87. # # yields if the respective files are present and which only have a video-pad
  88. # # add all video-sources to the quadmix-monitor-screen
  89. # self.addVideosToQuadmix(quadmixSources, self.pipeline.get_by_name('quadmix'))
  90. # # initialize to known defaults
  91. # # TODO: make configurable
  92. # self.switchVideo(0)
  93. # self.switchAudio(0)
  94. # Gst.debug_bin_to_dot_file(self.pipeline, Gst.DebugGraphDetails.ALL, 'test')
  95. # self.pipeline.set_state(Gst.State.PLAYING)
  96. # def createMixer(self):
  97. # """create audio and video mixer"""
  98. # # create mixer-pipeline from string
  99. # mixerbin = Gst.parse_bin_from_description("""
  100. # videomixer name=livevideo ! autovideosink
  101. # input-selector name=liveaudio ! autoaudiosink
  102. # videotestsrc pattern="solid-color" foreground-color=0x808080 ! capsfilter name=filter ! videomixer name=quadmix ! autovideosink
  103. # """, False)
  104. # # define caps for the videotestsrc which generates the background-color for the quadmix
  105. # bgcaps = Gst.Caps.new_empty_simple('video/x-raw')
  106. # bgcaps.set_value('width', round(self.monitorSize[0]))
  107. # bgcaps.set_value('height', round(self.monitorSize[1]))
  108. # mixerbin.get_by_name('filter').set_property('caps', bgcaps)
  109. # # name the bin, add and return it
  110. # mixerbin.set_name('mixerbin')
  111. # self.pipeline.add(mixerbin)
  112. # return mixerbin
  113. # def addVideosToQuadmix(self, videosources, quadmix):
  114. # """add all avaiable videosources to the quadmix"""
  115. # count = len(videosources)
  116. # # coordinate of the cell where we place the next video
  117. # place = [0, 0]
  118. # # number of cells in the quadmix-monitor
  119. # grid = [0, 0]
  120. # grid[0] = math.ceil(math.sqrt(count))
  121. # grid[1] = math.ceil(count / grid[0])
  122. # # size of each cell in the quadmix-monitor
  123. # cellSize = (
  124. # self.monitorSize[0] / grid[0],
  125. # self.monitorSize[1] / grid[1]
  126. # )
  127. # print("showing {} videosources in a {}×{} grid in a {}×{} px window, which gives cells of {}×{} px per videosource".format(
  128. # count, grid[0], grid[1], self.monitorSize[0], self.monitorSize[1], cellSize[0], cellSize[1]))
  129. # # iterate over all video-sources
  130. # for idx, videosource in enumerate(videosources):
  131. # # generate a pipeline for this videosource which
  132. # # - scales the video to the request
  133. # # - remove n px of the video (n = 5 if the video is highlighted else 0)
  134. # # - add a colored border of n px of the video (n = 5 if the video is highlighted else 0)
  135. # # - overlay the index of the video as text in the top left corner
  136. # # - known & named output
  137. # previewbin = Gst.parse_bin_from_description("""
  138. # videoscale name=in !
  139. # capsfilter name=caps !
  140. # videobox name=crop top=0 left=0 bottom=0 right=0 !
  141. # videobox fill=red top=-0 left=-0 bottom=-0 right=-0 name=add !
  142. # textoverlay color=0xFFFFFFFF halignment=left valignment=top xpad=10 ypad=5 font-desc="sans 35" name=text !
  143. # identity name=out
  144. # """, False)
  145. # # name the bin and add it
  146. # previewbin.set_name('previewbin-{}'.format(idx))
  147. # self.pipeline.add(previewbin)
  148. # self.previewbins.append(previewbin)
  149. # # set the overlay-text
  150. # previewbin.get_by_name('text').set_property('text', str(idx))
  151. # # query the video-source caps and extract its size
  152. # caps = videosource.get_static_pad('src').query_caps(None)
  153. # capsstruct = caps.get_structure(0)
  154. # srcSize = (
  155. # capsstruct.get_int('width')[1],
  156. # capsstruct.get_int('height')[1],
  157. # )
  158. # # calculate the ideal scale factor and scale the sizes
  159. # f = max(srcSize[0] / cellSize[0], srcSize[1] / cellSize[1])
  160. # scaleSize = (
  161. # srcSize[0] / f,
  162. # srcSize[1] / f,
  163. # )
  164. # # calculate the top/left coordinate
  165. # coord = (
  166. # place[0] * cellSize[0] + (cellSize[0] - scaleSize[0]) / 2,
  167. # place[1] * cellSize[1] + (cellSize[1] - scaleSize[1]) / 2,
  168. # )
  169. # print("placing videosource {} of size {}×{} scaled by {} to {}×{} in a cell {}×{} px cell ({}/{}) at position ({}/{})".format(
  170. # idx, srcSize[0], srcSize[1], f, scaleSize[0], scaleSize[1], cellSize[0], cellSize[1], place[0], place[1], coord[0], coord[1]))
  171. # # link the videosource to the input of the preview-bin
  172. # videosource.link(previewbin.get_by_name('in'))
  173. # # create and set the caps for the preview-scaler
  174. # scalecaps = Gst.Caps.new_empty_simple('video/x-raw')
  175. # scalecaps.set_value('width', round(scaleSize[0]))
  176. # scalecaps.set_value('height', round(scaleSize[1]))
  177. # previewbin.get_by_name('caps').set_property('caps', scalecaps)
  178. # # request a pad from the quadmixer and configure x/y position
  179. # sinkpad = quadmix.get_request_pad('sink_%u')
  180. # sinkpad.set_property('xpos', round(coord[0]))
  181. # sinkpad.set_property('ypos', round(coord[1]))
  182. # # link the output of the preview-bin to the mixer
  183. # previewbin.get_by_name('out').link(quadmix)
  184. # # increment grid position
  185. # place[0] += 1
  186. # if place[0] >= grid[0]:
  187. # place[1] += 1
  188. # place[0] = 0
  189. # def createDistributor(self, videosource, name):
  190. # """create a simple ×2 distributor"""
  191. # distributor = Gst.parse_bin_from_description("""
  192. # tee name=t
  193. # t. ! queue name=a
  194. # t. ! queue name=b
  195. # """, False)
  196. # # set a name and add to pipeline
  197. # distributor.set_name('distributor({0})'.format(name))
  198. # self.pipeline.add(distributor)
  199. # # link input to the tee
  200. # videosource.link(distributor.get_by_name('t'))
  201. # return distributor
  202. # def createDummyCamSources(self):
  203. # """create test-video-sources from files or urls"""
  204. # # TODO make configurable
  205. # uris = ('file:///home/peter/122.mp4', 'file:///home/peter/10025.mp4',)
  206. # for idx, uri in enumerate(uris):
  207. # # create a bin for a simulated camera input
  208. # # force the input resolution to 1024x576 because that way the following elements
  209. # # in the pipeline cam know the size even if the file is not yet loaded. the quadmixer
  210. # # is not resize-capable
  211. # camberabin = Gst.parse_bin_from_description("""
  212. # uridecodebin name=input
  213. # input. ! videoconvert ! videoscale ! videorate ! video/x-raw,width=1024,height=576,framerate=25/1 ! identity name=video_src
  214. # input. ! audioconvert name=audio_src
  215. # """, False)
  216. # # set name and uri
  217. # camberabin.set_name('dummy-camberabin({0})'.format(uri))
  218. # camberabin.get_by_name('input').set_property('uri', uri)
  219. # # add to pipeline and pass the bin upstream
  220. # self.pipeline.add(camberabin)
  221. # yield camberabin
  222. # def createCamSources(self):
  223. # """create real-video-sources from the bmd-drivers"""
  224. # # TODO make number of installed cams configurable
  225. # for cam in range(2):
  226. # # create a bin for camera input
  227. # camberabin = Gst.parse_bin_from_description("""
  228. # decklinksrc name=input input=sdi input-mode=1080p25
  229. # input. ! videoconvert ! videoscale ! videorate ! video/x-raw,width=1920,height=1080,framerate=25/1 ! identity name=video_src
  230. # input. ! audioconvert name=audio_src
  231. # """, False)
  232. # # set name and subdevice
  233. # camberabin.set_name('camberabin({0})'.format(cam))
  234. # camberabin.get_by_name('input').set_property('subdevice', cam)
  235. # # add to pipeline and pass the bin upstream
  236. # self.pipeline.add(camberabin)
  237. # yield camberabin
  238. ### below are access-methods for the ControlServer
  239. @controlServerEntrypoint
  240. def status(self):
  241. """System Status Query"""
  242. raise NotImplementedError("status command is not implemented yet")
  243. @controlServerEntrypoint
  244. def numAudioSources(self):
  245. """return number of available audio sources"""
  246. raise NotImplementedError("audio is not implemented yet")
  247. @controlServerEntrypoint
  248. def switchAudio(self, audiosource):
  249. """switch audio to the selected audio"""
  250. raise NotImplementedError("audio is not implemented yet")
  251. @controlServerEntrypoint
  252. def numVideoSources(self):
  253. """return number of available video sources"""
  254. livevideo = self.pipeline.get_by_name('livevideo')
  255. return str(len(self.videonames))
  256. @controlServerEntrypoint
  257. def switchVideo(self, videosource):
  258. """switch audio to the selected video"""
  259. if videosource.isnumeric():
  260. idx = int(videosource)
  261. self.log.info("interpreted input as videosource-index %u", idx)
  262. if idx >= len(self.videonames):
  263. idx = None
  264. else:
  265. try:
  266. idx = self.videonames.index(videosource)
  267. self.log.info("interpreted input as videosource-name, lookup to %u", idx)
  268. except IndexError:
  269. idx = None
  270. if idx == None:
  271. return 'unknown video-source: %s' % (videosource)
  272. self.log.info("switching quadmix to video-source %u", idx)
  273. self.quadmixer.set_active(idx)
  274. self.videomixer.set_active(idx)
  275. @controlServerEntrypoint
  276. def fadeVideo(self, videosource):
  277. """fade video to the selected video"""
  278. raise NotImplementedError("fade command is not implemented yet")
  279. @controlServerEntrypoint
  280. def setPipVideo(self, videosource):
  281. """switch video-source in the PIP to the selected video"""
  282. raise NotImplementedError("pip commands are not implemented yet")
  283. @controlServerEntrypoint
  284. def fadePipVideo(self, videosource):
  285. """fade video-source in the PIP to the selected video"""
  286. raise NotImplementedError("pip commands are not implemented yet")
  287. class PipPlacements:
  288. """enumeration of possible PIP-Placements"""
  289. TopLeft, TopRight, BottomLeft, BottomRight = range(4)
  290. @controlServerEntrypoint
  291. def setPipPlacement(self, placement):
  292. """place PIP in the selected position"""
  293. assert(isinstance(placement, PipPlacements))
  294. raise NotImplementedError("pip commands are not implemented yet")
  295. @controlServerEntrypoint
  296. def setPipStatus(self, enabled):
  297. """show or hide PIP"""
  298. raise NotImplementedError("pip commands are not implemented yet")
  299. @controlServerEntrypoint
  300. def fadePipStatus(self, enabled):
  301. """fade PIP in our out"""
  302. raise NotImplementedError("pip commands are not implemented yet")
  303. class StreamContents:
  304. """enumeration of possible PIP-Placements"""
  305. Live, Pause, NoStream = range(3)
  306. @controlServerEntrypoint
  307. def selectStreamContent(self, content):
  308. """switch the livestream-content between selected mixer output, pause-image or nostream-imag"""
  309. assert(isinstance(content, StreamContents))
  310. raise NotImplementedError("pause/nostream switching is not implemented yet")