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