Open FFmpeg process as capture 1 frame.
551200
async def get_image(
        self,
        input_source: str,
        output_format: str = IMAGE_JPEG,
        extra_cmd: Optional[str] = None,
        timeout: int = 15,
    ) -> Optional[bytes]:
        """"""
        command = ["-an", "-frames:v", "1", "-c:v", output_format]

        # open input for capture 1 frame
        is_open = await self.open(
            cmd=command,
            input_source=input_source,
            output="-f image2pipe -",
            extra_cmd=extra_cmd,
        )

        # error after open?
        if not is_open:
            _LOGGER.warning("Error starting FFmpeg.")
            return None

        # read image
        try:
            proc_func = functools.partial(self._proc.communicate, timeout=timeout)
            image, _ = await self._loop.run_in_executor(None, proc_func)
            return image

        except (subprocess.TimeoutExpired, ValueError):
            _LOGGER.warning("Timeout reading image.")
            self.kill()
            return None
620579
protected void openVideo(boolean reopen , String ...filePaths) {
		synchronized (lockStartingProcess) {
			if( startingProcess ) {
				System.out.println("Ignoring video request.  Detected spamming");
				return;
			}
			startingProcess = true;
		}

		synchronized (inputStreams) {
			if (inputStreams.size() != filePaths.length)
				throw new IllegalArgumentException("Input streams not equal to "+filePaths.length+".  Override openVideo()");
		}

		stopAllInputProcessing();

		streamPaused = false;

		boolean failed = false;
		for( int which = 0; which < filePaths.length; which++ ) {
			CacheSequenceStream cache = inputStreams.get(which);

			SimpleImageSequence sequence = media.openVideo(filePaths[which], cache.getImageType());
			if( sequence == null ) {
				failed = true;
				System.out.println("Can't find file. "+filePaths[which]);
				break;
			}
			configureVideo(which,sequence);

			synchronized (inputStreams) {
				cache.reset();
				cache.setSequence(sequence);
			}
		}

		if (!failed) {
			setInputName(new File(filePaths[0]).getName());
			synchronized (inputStreams) {
				inputMethod = InputMethod.VIDEO;
				streamPeriod = 33; // default to 33 FPS for a video
				if( threadProcess != null )
					throw new RuntimeException("There was still an active stream thread!");
				threadProcess = new SynchronizedStreamsThread();
			}
			if( !reopen ) {
				for (int i = 0; i < inputStreams.size(); i++) {
					CacheSequenceStream stream = inputStreams.get(i);
					handleInputChange(i, inputMethod, stream.getWidth(), stream.getHeight());
				}
			}
			threadPool.execute(threadProcess);
		} else {
			synchronized (inputStreams) {
				inputMethod = InputMethod.NONE;
				inputFilePath = null;
			}
			synchronized (lockStartingProcess) {
				startingProcess = false;
			}
			showRejectDiaglog("Can't open file");
		}
	}
229723
def _frame_generator(self, frame_duration_ms, audio, sample_rate):
        
        n = int(sample_rate * (frame_duration_ms / 1000.0) * 2)
        offset = 0
        timestamp = 0.0
        duration = (float(n) / sample_rate) / 2.0
        while offset + n < len(audio):
            yield self.Frame(audio[offset:offset + n], timestamp, duration)
            timestamp += duration
            offset += n
454691
def skip(self, video_name, out, start, duration):
        
        cfilter = (r"[0:v]trim=duration={start}[av];"
                   r"[0:a]atrim=duration={start}[aa];"
                   r"[0:v]trim=start={offset},setpts=PTS-STARTPTS[bv];"
                   r"[0:a]atrim=start={offset},asetpts=PTS-STARTPTS[ba];"
                   r"[av][bv]concat[outv];[aa][ba]concat=v=0:a=1[outa]")\
            .format(start=start, offset=start + duration)\
            .replace(' ', '')

        command = ['ffmpeg', '-i', video_name,
            '-filter_complex', cfilter, '-y',
            '-map', '[outv]',
            '-map', '[outa]', '-c:v', 'huffyuv', '-preset', 'veryslow',
            out]

        if self.verbose:
            print 'Skipping {0} into {1}'.format(video_name, out)
            print ' '.join(command)

        call(command)
419982
def OnLinkVLCVideo(self, event):
        """"""

        key = self.grid.actions.cursor

        if event.videofile:
            try:
                video_volume = \
                    self.grid.code_array.cell_attributes[key]["video_volume"]
            except KeyError:
                video_volume = None

            self.grid.actions.set_attr("panel_cell", True)

            if video_volume is not None:
                code = 'vlcpanel_factory("{}", {})'.format(
                    event.videofile, video_volume)
            else:
                code = 'vlcpanel_factory("{}")'.format(event.videofile)

            self.grid.actions.set_code(key, code)

        else:
            try:
                video_panel = self.grid.grid_renderer.video_cells.pop(key)
                video_panel.player.stop()
                video_panel.player.release()
                video_panel.Destroy()
            except KeyError:
                pass

            self.grid.actions.set_code(key, u"")
867512
def pause(self, pause=0):
        """"""
        fr = self.frames[-1]
        n = int(self.fps * pause)
        for i in range(n):
            fr2 = "/tmp/vpvid/" + str(len(self.frames)) + ".png"
            self.frames.append(fr2)
            os.system("cp -f %s %s" % (fr, fr2))
1032366
def close(self):
        """"""
        if self.duration:
            _fps = len(self.frames) / float(self.duration)
            colors.printc("Recalculated video FPS to", round(_fps, 3), c="yellow")
        else:
            _fps = int(_fps)
        self.name = self.name.split('.')[0]+'.mp4'
        out = os.system("ffmpeg -loglevel panic -y -r " + str(_fps)
                        + " -i /tmp/vpvid/%01d.png "+self.name)
        if out:
            colors.printc("ffmpeg returning error", c=1)
        colors.printc("~save Video saved as", self.name, c="green")
        return
872834
def _open(self, mode=None):
        
        if mode is None:
            mode = self.mode
        if self.encoding is None:
            stream = open(self.baseFilename, mode)
        else:
            stream = codecs.open(self.baseFilename, mode, self.encoding)
        return stream
137176
def transcode_movie
      FFMPEG.logger.info("Running transcoding...\n#{command}\n")
      @output = ""

      Open3.popen3(*command) do |_stdin, _stdout, stderr, wait_thr|
        begin
          yield(0.0) if block_given?
          next_line = Proc.new do |line|
            fix_encoding(line)
            @output << line
            if line.include?("time=")
              if line =~ /time=(\d+):(\d+):(\d+.\d+)/ # ffmpeg 0.8 and above style
                time = ($1.to_i * 3600) + ($2.to_i * 60) + $3.to_f
              else # better make sure it wont blow up in case of unexpected output
                time = 0.0
              end

              if @movie
                progress = time / @movie.duration
                yield(progress) if block_given?
              end
            end
          end

          if timeout
            stderr.each_with_timeout(wait_thr.pid, timeout, 'size=', &next_line)
          else
            stderr.each('size=', &next_line)
          end

        @errors << "ffmpeg returned non-zero exit code" unless wait_thr.value.success?

        rescue Timeout::Error => e
          FFMPEG.logger.error "Process hung...\n@command\n#{command}\nOutput\n#{@output}\n"
          raise Error, "Process hung. Full output: #{@output}"
        end
      end
    end
409542
def get_frame(self, index):
        ''' 
        '''

        frame_num = self.frame_index[index]
        onset = float(frame_num) / self.fps

        if index < self.n_frames - 1:
            next_frame_num = self.frame_index[index + 1]
            end = float(next_frame_num) / self.fps
        else:
            end = float(self.duration)

        duration = end - onset if end > onset else 0.0

        return VideoFrameStim(self, frame_num,
                              data=self.clip.get_frame(onset),
                              duration=duration)
14396
def read_data(self, timeout=10.0):
        """"""
        # Read from stdout in a separate thread and consume data from
        # the queue.
        start_time = time.time()
        while True:
            # Wait for data to be available or a timeout.
            data = None
            try:
                data = self.stdout_reader.queue.get(timeout=timeout)
                if data:
                    yield data
                else:
                    # End of file.
                    break
            except queue.Empty:
                # Queue read timed out.
                end_time = time.time()
                if not data:
                    if end_time - start_time >= timeout:
                        # Nothing interesting has happened for a while --
                        # FFmpeg is probably hanging.
                        raise ReadTimeoutError('ffmpeg output: {}'.format(
                            ''.join(self.stderr_reader.queue.queue)
                        ))
                    else:
                        start_time = end_time
                        # Keep waiting.
                        continue
557434
public void reprocessInput() {
		if ( inputMethod == InputMethod.VIDEO ) {
			openVideo(true,inputFilePath);
		} else if( inputMethod == InputMethod.IMAGE ) {
			BufferedImage buff = inputStreams.get(0).getBufferedImage();
			openImage(true,new File(inputFilePath).getName(),buff);// TODO still does a pointless image conversion
		} else if( inputMethod == InputMethod.IMAGE_SET ) {
			openImageSet(inputFileSet);
		}
	}
549362
def start_capture(self, data_link_type="DLT_EN10MB", capture_file_name=None):
        

        self._capturing = True
        self._capture_file_name = capture_file_name
        self._streaming_pcap = asyncio.async(self._start_streaming_pcap())
        self._project.controller.notification.emit("link.updated", self.__json__())
887916
def main(source_samplerate, target_samplerate, params, converter_type):
    """"""
    from time import sleep

    ratio = target_samplerate / source_samplerate

    with sr.CallbackResampler(get_input_callback(source_samplerate, params),
                              ratio, converter_type) as resampler, \
            sd.OutputStream(channels=1, samplerate=target_samplerate,
                            callback=get_playback_callback(
                                resampler, target_samplerate, params)):
        print("Playing back...  Ctrl+C to stop.")
        try:
            while True:
                sleep(1)
        except KeyboardInterrupt:
            print("Aborting.")
1295555
def start_capture(self, override_configs=None,
                      additional_args=None, duration=None,
                      packet_count=None):
        
        if self._process is not None:
            raise sniffer.InvalidOperationError(
                    "Trying to start a sniff while another is still running!")
        capture_dir = os.path.join(self._logger.log_path,
                                   "Sniffer-{}".format(self._interface))
        os.makedirs(capture_dir, exist_ok=True)
        self._capture_file_path = os.path.join(capture_dir,
                      "capture_{}.pcap".format(logger.get_log_file_timestamp()))

        self._pre_capture_config(override_configs)
        _, self._temp_capture_file_path = tempfile.mkstemp(suffix=".pcap")

        cmd = self._get_command_line(additional_args=additional_args,
                                duration=duration, packet_count=packet_count)

        self._process = utils.start_standing_subprocess(cmd)
        return sniffer.ActiveCaptureContext(self, duration)
239886
def open_for_group_write(fp, mode, encoding='utf-8'):
    
    d = os.path.split(fp)[0]
    if not os.path.exists(d):
        os.makedirs(d)
    o = codecs.open(fp, mode, encoding=encoding)
    o.flush()
    os.chmod(fp, stat.S_IRGRP | stat.S_IROTH | stat.S_IRUSR | stat.S_IWGRP | stat.S_IWUSR)
    return o
1044181
def get_playback_callback(resampler, samplerate, params):
    

    def callback(outdata, frames, time, _):
        """Playback callback.

        Read samples from the resampler and modulate them onto a carrier
        frequency.
        """
        last_fmphase = getattr(callback, 'last_fmphase', 0)
        df = params['fm_gain'] * resampler.read(frames)
        df = np.pad(df, (0, frames - len(df)), mode='constant')
        t = time.outputBufferDacTime + np.arange(frames) / samplerate
        phase = 2 * np.pi * params['carrier_frequency'] * t
        fmphase = last_fmphase + 2 * np.pi * np.cumsum(df) / samplerate
        outdata[:, 0] = params['output_volume'] * np.cos(phase + fmphase)
        callback.last_fmphase = fmphase[-1]

    return callback