You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

video_looper.py 9.5 KiB

9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. # Copyright 2015 Adafruit Industries.
  2. # Author: Tony DiCola
  3. # License: GNU GPLv2, see LICENSE.txt
  4. import atexit
  5. import ConfigParser
  6. import importlib
  7. import os
  8. import re
  9. import sys
  10. import time
  11. import pygame
  12. from model import Playlist
  13. # Basic video looper architecure:
  14. #
  15. # - VideoLooper class contains all the main logic for running the looper program.
  16. #
  17. # - Almost all state is configured in a .ini config file which is required for
  18. # loading and using the VideoLooper class.
  19. #
  20. # - VideoLooper has loose coupling with file reader and video player classes that
  21. # are used to find movie files and play videos respectively. The configuration
  22. # defines which file reader and video player module will be loaded.
  23. #
  24. # - A file reader module needs to define at top level create_file_reader function
  25. # that takes as a parameter a ConfigParser config object. The function should
  26. # return an instance of a file reader class. See usb_drive.py and directory.py
  27. # for the two provided file readers and their public interface.
  28. #
  29. # - Similarly a video player modules needs to define a top level create_player
  30. # function that takes in configuration. See omxplayer.py and hello_video.py
  31. # for the two provided video players and their public interface.
  32. #
  33. # - Future file readers and video players can be provided and referenced in the
  34. # config to extend the video player use to read from different file sources
  35. # or use different video players.
  36. class VideoLooper(object):
  37. def __init__(self, config_path):
  38. """Create an instance of the main video looper application class. Must
  39. pass path to a valid video looper ini configuration file.
  40. """
  41. # Load the configuration.
  42. self._config = ConfigParser.SafeConfigParser()
  43. if len(self._config.read(config_path)) == 0:
  44. raise RuntimeError('Failed to find configuration file at {0}, is the application properly installed?'.format(config_path))
  45. self._console_output = self._config.getboolean('video_looper', 'console_output')
  46. # Load configured video player and file reader modules.
  47. self._player = self._load_player()
  48. atexit.register(self._player.stop) # Make sure to stop player on exit.
  49. self._reader = self._load_file_reader()
  50. # Load other configuration values.
  51. self._osd = self._config.getboolean('video_looper', 'osd')
  52. # Parse string of 3 comma separated values like "255, 255, 255" into
  53. # list of ints for colors.
  54. self._bgcolor = map(int, self._config.get('video_looper', 'bgcolor') \
  55. .translate(None, ',') \
  56. .split())
  57. self._fgcolor = map(int, self._config.get('video_looper', 'fgcolor') \
  58. .translate(None, ',') \
  59. .split())
  60. # Initialize pygame and display a blank screen.
  61. pygame.display.init()
  62. pygame.font.init()
  63. pygame.mouse.set_visible(False)
  64. size = (pygame.display.Info().current_w, pygame.display.Info().current_h)
  65. self._screen = pygame.display.set_mode(size, pygame.FULLSCREEN)
  66. self._blank_screen()
  67. # Set other static internal state.
  68. self._extensions = self._player.supported_extensions()
  69. self._small_font = pygame.font.Font(None, 50)
  70. self._big_font = pygame.font.Font(None, 250)
  71. def _print(self, message):
  72. """Print message to standard output if console output is enabled."""
  73. if self._console_output:
  74. print(message)
  75. def _load_player(self):
  76. """Load the configured video player and return an instance of it."""
  77. module = self._config.get('video_looper', 'video_player')
  78. return importlib.import_module('.' + module, 'Adafruit_Video_Looper') \
  79. .create_player(self._config)
  80. def _load_file_reader(self):
  81. """Load the configured file reader and return an instance of it."""
  82. module = self._config.get('video_looper', 'file_reader')
  83. return importlib.import_module('.' + module, 'Adafruit_Video_Looper') \
  84. .create_file_reader(self._config)
  85. def _build_playlist(self):
  86. """Search all the file reader paths for movie files with the provided
  87. extensions.
  88. """
  89. # Get list of paths to search from the file reader.
  90. paths = self._reader.search_paths()
  91. # Enumerate all movie files inside those paths.
  92. movies = []
  93. for ex in self._extensions:
  94. for path in paths:
  95. # Skip paths that don't exist or are files.
  96. if not os.path.exists(path) or not os.path.isdir(path):
  97. continue
  98. movies.extend(['{0}/{1}'.format(path.rstrip('/'), x) \
  99. for x in os.listdir(path) \
  100. if re.search('\.{0}$'.format(ex), x,
  101. flags=re.IGNORECASE)])
  102. # Create a playlist with the sorted list of movies.
  103. return Playlist(sorted(movies))
  104. def _blank_screen(self):
  105. """Render a blank screen filled with the background color."""
  106. self._screen.fill(self._bgcolor)
  107. pygame.display.update()
  108. def _render_text(self, message, font=None):
  109. """Draw the provided message and return as pygame surface of it rendered
  110. with the configured foreground and background color.
  111. """
  112. # Default to small font if not provided.
  113. if font is None:
  114. font = self._small_font
  115. return font.render(message, True, self._fgcolor, self._bgcolor)
  116. def _animate_countdown(self, playlist, seconds=10):
  117. """Print text with the number of loaded movies and a quick countdown
  118. message if the on screen display is enabled.
  119. """
  120. # Print message to console with number of movies in playlist.
  121. message = 'Found {0} movie{1}.'.format(playlist.length(),
  122. 's' if playlist.length() >= 2 else '')
  123. self._print(message)
  124. # Do nothing else if the OSD is turned off.
  125. if not self._osd:
  126. return
  127. # Draw message with number of movies loaded and animate countdown.
  128. # First render text that doesn't change and get static dimensions.
  129. label1 = self._render_text(message + ' Starting playback in:')
  130. l1w, l1h = label1.get_size()
  131. sw, sh = self._screen.get_size()
  132. for i in range(seconds, 0, -1):
  133. # Each iteration of the countdown rendering changing text.
  134. label2 = self._render_text(str(i), self._big_font)
  135. l2w, l2h = label2.get_size()
  136. # Clear screen and draw text with line1 above line2 and all
  137. # centered horizontally and vertically.
  138. self._screen.fill(self._bgcolor)
  139. self._screen.blit(label1, (sw/2-l1w/2, sh/2-l2h/2-l1h))
  140. self._screen.blit(label2, (sw/2-l2w/2, sh/2-l2h/2))
  141. pygame.display.update()
  142. # Pause for a second between each frame.
  143. time.sleep(1)
  144. def _idle_message(self):
  145. """Print idle message from file reader."""
  146. # Print message to console.
  147. message = self._reader.idle_message()
  148. self._print(message)
  149. # Do nothing else if the OSD is turned off.
  150. if not self._osd:
  151. return
  152. # Display idle message in center of screen.
  153. label = self._render_text(message)
  154. lw, lh = label.get_size()
  155. sw, sh = self._screen.get_size()
  156. self._screen.fill(self._bgcolor)
  157. self._screen.blit(label, (sw/2-lw/2, sh/2-lh/2))
  158. pygame.display.update()
  159. def _prepare_to_run_playlist(self, playlist):
  160. """Display messages when a new playlist is loaded."""
  161. # If there are movies to play show a countdown first (if OSD enabled),
  162. # or if no movies are available show the idle message.
  163. if playlist.length() > 0:
  164. self._animate_countdown(playlist)
  165. self._blank_screen()
  166. else:
  167. self._idle_message()
  168. def run(self):
  169. """Main program loop. Will never return!"""
  170. # Get playlist of movies to play from file reader.
  171. playlist = self._build_playlist()
  172. self._prepare_to_run_playlist(playlist)
  173. # Main loop to play videos in the playlist and listen for file changes.
  174. while True:
  175. # Load and play a new movie if nothing is playing.
  176. if not self._player.is_playing():
  177. movie = playlist.get_next()
  178. if movie is not None:
  179. # Start playing the first available movie.
  180. self._print('Playing movie: {0}'.format(movie))
  181. self._player.play(movie, loop=playlist.length() == 1)
  182. # Check for changes in the file search path (like USB drives added)
  183. # and rebuild the playlist.
  184. if self._reader.is_changed():
  185. self._player.stop(3) # Up to 3 second delay waiting for old
  186. # player to stop.
  187. # Rebuild playlist and show countdown again (if OSD enabled).
  188. playlist = self._build_playlist()
  189. self._prepare_to_run_playlist(playlist)
  190. # Give the CPU some time to do other tasks.
  191. time.sleep(0)
  192. # Main entry point.
  193. def main():
  194. # Default config path to /boot.
  195. config_path = '/boot/video_looper.ini'
  196. # Override config path if provided as parameter.
  197. if len(sys.argv) == 2:
  198. config_path = sys.argv[1]
  199. # Create video looper and run it.
  200. videolooper = VideoLooper(config_path)
  201. videolooper.run()