<commit_before>#!/usr/bin/env python

# Released under the GPL v2 (or later) by <NAME> (<EMAIL>)
#
# Sample application to connect to camera, and start a video recording
# with or without a GUI LiveView screen

import signal
import threading
import datetime
import time
import argparse
import Image
import io
from pysony import SonyAPI, payload_header

try:
   import pygtk
   import gtk
   from gtk import gdk
   import cairo
   gtk.gdk.threads_init()
   _hasPyGTK = True
except ImportError:
   _hasPyGTK = False
'''
_hasPyGTK = False
'''

# Global Variables
options  = None
image_copy = None
image_file = None

display = None
grabber = None

# =====================================================================
class liveview_grabber(threading.Thread):
   def run(self):
      global options, grabber, decoder, display, image_copy

      if options.debug:
         print "using LiveView grabber"
   
      self.active = False

      # grabber control signals
      self.event_start_stream = threading.Event()
      self.event_stop_stream = threading.Event()
      self.event_stopped_stream = threading.Event()
      self.event_terminate = threading.Event()
      self.event_terminated = threading.Event()

      # decoder control signals
      self.event_decoding = threading.Event()
      self.event_decoder_terminated = threading.Event()

      # display control signals
      self.lock_offscreen = threading.Semaphore()

      # export to other threads
      self.frame_count = 0
      grabber = self

      camera = SonyAPI()

      # Check if we need to do 'startRecMode'
      mode = camera.getAvailableApiList()

      # Need a better method to check for the presence of a camera
      if type(mode) != dict:
         print "No camera found, aborting"
         display.terminate_clicked()
         self.event_terminated.set()
         return

      if options.debug:
         print "Versions:", camera.getVersions()
         print "API List:", mode

      # For those cameras which need it
      if 'startRecMode' in (mode['result'])[0]:
         camera.startRecMode()

      # Ensure that we're in 'Movie' mode
      mode = camera.getAvailableShootMode()
      if (mode['result'])[0] != 'movie':
         if 'movie' in (mode['result'])[1]:
            camera.setShootMode(["movie"])

            # Force wait for camera to be ready
            camera.getEvent(["true"])
         else:
            print "'movie' mode not supported"

      incoming = camera.liveview()

      while not self.event_terminate.isSet():
         if options.gui == True :
            # read next image
            data = incoming.read(8)
            data = incoming.read(128)
            payload = payload_header(data)
            image_file = io.BytesIO(incoming.read(payload['jpeg_data_size']))
            incoming_image = Image.open(image_file)
            incoming.read(payload['padding_size'])

            # set initial width/height
            if display.offscreen == None:
               display.width = (incoming_image.size)[0]
               display.height = (incoming_image.size)[1]
               if options.debug:
                  print "Display set to",(incoming_image.size)[0],"x", (incoming_image.size)[1]

               display.offscreen = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8,
                  display.width, display.height)

            # Correct display size if changed
            if ((incoming_image.size)[0] != display.width):
               if options.debug:
                  print "adjusted width from", display.width, "to", (incoming_image.size)[0]
               display.width = (incoming_image.size)[0]
               display.offscreen = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8,
                  display.width, display.height)

            if ((incoming_image.size)[1] != display.height):
               if options.debug:
                  print "adjusted height from", display.height, "to", (incoming_image.size)[1]
               display.height = (incoming_image.size)[1]
               display.offscreen = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8,
                  display.width, display.height)

            # copy image to the display
            image_copy = incoming_image.convert("RGB")
            display.copy_to_offscreen(image_copy)

         if self.event_start_stream.isSet():
            camera.startMovieRec()
            self.frame_count = 0

            # and we're ready to go..
            self.start_time = datetime.datetime.now()
            self.event_start_stream.clear()

            # loop until request to stop
            while not self.event_stop_stream.isSet():
               if options.gui == True :
                  # read next image
                  data = incoming.read(8)
                  data = incoming.read(128)
                  payload = payload_header(data)
                  image_file = io.BytesIO(incoming.read(payload['jpeg_data_size']))
                  incoming_image = Image.open(image_file)
                  incoming.read(payload['padding_size'])

                  image_copy = incoming_image.convert("RGB")
                  display.copy_to_offscreen(image_copy)

                  # copy image to the display
                  display.offscreen = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8, 
                     display.width, display.height * 2)
                  display.copy_to_offscreen(image_copy)
  
               self.frame_count = self.frame_count + 1

               if self.event_terminate.isSet():
                  break

         if self.event_stop_stream.isSet():
            # clean up
            camera.stopMovieRec()
            self.end_time = datetime.datetime.now()
            self.event_stop_stream.clear()
            self.active = False

         time.sleep(0.1)

      # declare that we're done...
      self.event_terminated.set()
      self.event_terminate.clear()
            

   def start_stream(self):
      if self.active == False:
         self.active = True 
         self.event_start_stream.set()
         while self.event_start_stream.isSet():
            time.sleep(0.1)

         if options.debug:
            print "started capture"

         self.event_stopped_stream.clear()

   def stop_stream(self):
      if self.active == True:
         self.event_stop_stream.set()
         self.active = False

         while self.event_stop_stream.isSet():
            time.sleep(0.1)

         if options.debug:
            elapsed = self.end_time - self.start_time
            print "Stopped capture: frames = ", self.frame_count,
            print ", delta = ", elapsed.seconds + (float(elapsed.microseconds) / 1000000),
            print ", fps = ", self.frame_count / (elapsed.seconds + (float(elapsed.microseconds) / 1000000))


   def terminate(self):
      if options.debug:
         print "terminating..."

      self.stop_stream()
      self.event_terminate.set()

      while self.event_terminate.isSet():
         time.sleep(0.1)
 
      if options.debug:
         print "terminated"

# =====================================================================
class liveview_display:
   def copy_to_offscreen(self, image):
      global options, grabber, display

      # Convert a PIL Image to a gtk.gdk.Pixbuf  
      file1 = io.BytesIO()  
      if (file1 != False):
         image.save(file1, "ppm")  
         contents = file1.getvalue()  

         loader = gtk.gdk.PixbufLoader("pnm")  
         loader.write(contents, len(contents))  
         pixbuf = loader.get_pixbuf()  
         loader.close() 

      file1.close()
<commit_msg>Check whether we're already recording when we connect<commit_after>#!/usr/bin/env python

# Released under the GPL v2 (or later) by <NAME> (<EMAIL>)
#
# Sample application to connect to camera, and start a video recording
# with or without a GUI LiveView screen

import signal
import threading
import datetime
import time
import argparse
import Image
import io
from pysony import SonyAPI, payload_header

try:
   import pygtk
   import gtk
   from gtk import gdk
   import cairo
   gtk.gdk.threads_init()
   _hasPyGTK = True
except ImportError:
   _hasPyGTK = False
'''
_hasPyGTK = False
'''

# Global Variables
options  = None
image_copy = None
image_file = None

display = None
grabber = None

# =====================================================================
class liveview_grabber(threading.Thread):
   def run(self):
      global options, grabber, decoder, display, image_copy

      if options.debug:
         print "using LiveView grabber"
   
      self.active = False

      # grabber control signals
      self.event_start_stream = threading.Event()
      self.event_stop_stream = threading.Event()
      self.event_stopped_stream = threading.Event()
      self.event_terminate = threading.Event()
      self.event_terminated = threading.Event()

      # decoder control signals
      self.event_decoding = threading.Event()
      self.event_decoder_terminated = threading.Event()

      # display control signals
      self.lock_offscreen = threading.Semaphore()

      # export to other threads
      self.frame_count = 0
      grabber = self

      camera = SonyAPI()

      # Check if we need to do 'startRecMode'
      mode = camera.getAvailableApiList()

      # Need a better method to check for the presence of a camera
      if type(mode) != dict:
         print "No camera found, aborting"
         display.terminate_clicked()
         self.event_terminated.set()
         return

      if options.debug:
         print "Versions:", camera.getVersions()
         print "API List:", mode

      # For those cameras which need it
      if 'startRecMode' in (mode['result'])[0]:
         camera.startRecMode()

      # Ensure that we're in 'Movie' mode
      mode = camera.getAvailableShootMode()
      if type(mode) == dict:
         if (mode['result'])[0] != 'movie':
            if 'movie' in (mode['result'])[1]:
               camera.setShootMode(["movie"])
            else:
               print "'movie' mode not supported"

      # Wait for camera to be ready and check whether we're recoding
      mode = camera.getEvent(["true"])
      if options.debug:
         print "Event:", mode
      if type(mode) == dict:
         status = mode['result'][1]
         if status['cameraStatus'] == 'MovieRecording':
            self.active = True
            self.start_time = datetime.datetime.now()

      incoming = camera.liveview()

      while not self.event_terminate.isSet():
         if options.gui == True :
            # read next image
            data = incoming.read(8)
            data = incoming.read(128)
            payload = payload_header(data)
            image_file = io.BytesIO(incoming.read(payload['jpeg_data_size']))
            incoming_image = Image.open(image_file)
            incoming.read(payload['padding_size'])

            # set initial width/height
            if display.offscreen == None:
               display.width = (incoming_image.size)[0]
               display.height = (incoming_image.size)[1]
               if options.debug:
                  print "Display set to",(incoming_image.size)[0],"x", (incoming_image.size)[1]

               display.offscreen = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8,
                  display.width, display.height)

            # Correct display size if changed
            if ((incoming_image.size)[0] != display.width):
               if options.debug:
                  print "adjusted width from", display.width, "to", (incoming_image.size)[0]
               display.width = (incoming_image.size)[0]
               display.offscreen = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8,
                  display.width, display.height)

            if ((incoming_image.size)[1] != display.height):
               if options.debug:
                  print "adjusted height from", display.height, "to", (incoming_image.size)[1]
               display.height = (incoming_image.size)[1]
               display.offscreen = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8,
                  display.width, display.height)

            # copy image to the display
            image_copy = incoming_image.convert("RGB")
            display.copy_to_offscreen(image_copy)

         if self.event_start_stream.isSet():
            camera.startMovieRec()
            self.frame_count = 0

            # and we're ready to go..
            self.start_time = datetime.datetime.now()
            self.event_start_stream.clear()

         # loop until request to stop
         if self.active == True:
            while not self.event_stop_stream.isSet():
               if options.gui == True :
                  # read next image
                  data = incoming.read(8)
                  data = incoming.read(128)
                  payload = payload_header(data)
                  image_file = io.BytesIO(incoming.read(payload['jpeg_data_size']))
                  incoming_image = Image.open(image_file)
                  incoming.read(payload['padding_size'])

                  image_copy = incoming_image.convert("RGB")
                  display.copy_to_offscreen(image_copy)

                  # copy image to the display
                  display.offscreen = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8, 
                     display.width, display.height * 2)
                  display.copy_to_offscreen(image_copy)
  
               self.frame_count = self.frame_count + 1

               if self.event_terminate.isSet():
                  break

         if self.event_stop_stream.isSet():
            # clean up
            camera.stopMovieRec()
            self.end_time = datetime.datetime.now()
            self.event_stop_stream.clear()
            self.active = False

         time.sleep(0.1)

      # declare that we're done...
      self.event_terminated.set()
      self.event_terminate.clear()
            

   def start_stream(self):
      if self.active == False:
         self.active = True 
         self.event_start_stream.set()
         while self.event_start_stream.isSet():
            time.sleep(0.1)

         if options.debug:
            print "started capture"

         self.event_stopped_stream.clear()

   def stop_stream(self):
      if self.active == True:
         self.event_stop_stream.set()
         self.active = False

         while self.event_stop_stream.isSet():
            time.sleep(0.1)

         if options.debug:
            elapsed = self.end_time - self.start_time
            print "Stopped capture: frames = ", self.frame_count,
            print ", delta = ", elapsed.seconds + (float(elapsed.microseconds) / 1000000),
            print ", fps = ", self.frame_count / (elapsed.seconds + (float(elapsed.microseconds) / 1000000))


   def terminate(self):
      if options.debug:
         print "terminating..."

      if options.gui != True:
         self.stop_stream()
      self.event_terminate.set()

      while self.event_terminate.isSet():
         time.sleep(0.1)
 
      if options.debug:
         print "terminated"

# =====================================================================
class liveview_display:
   def copy_to_offscreen(self, image):
      global options, grabber, display

      # Convert a PIL Image to a gtk.gdk.Pixbuf  
      file1 = io.BytesIO()  
      if (file1 != False):
         image.save(file1, "ppm")  
         contents = file1.getvalue()  

         loader = gtk.gdk.PixbufLoader("pnm")  
         loader.write(contents, len(contents))  
         pixbuf = loader.get_pixbuf()  
         loader.close() 

      file1.close()

{'fraction_non_alphanumeric': 0.11579082122511682, 'fraction_numerical': 0.007360942200601677, 'mean_word_length': 2.0432411375146087, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7557077', 'n_tokens_mistral': 4567, 'n_tokens_neox': 4302, 'n_words': 1014}