The final stage of the transmuxer that emits the flv tags
for audio, video, and metadata. Also tranlates in time and
outputs caption data and id3 cues.
769891
function(options) {
  // Number of Tracks per output segment
  // If greater than 1, we combine multiple
  // tracks into a single segment
  this.numberOfTracks = 0;
  this.metadataStream = options.metadataStream;

  this.videoTags = [];
  this.audioTags = [];
  this.videoTrack = null;
  this.audioTrack = null;
  this.pendingCaptions = [];
  this.pendingMetadata = [];
  this.pendingTracks = 0;
  this.processedTracks = 0;

  CoalesceStream.prototype.init.call(this);

  // Take output from multiple
  this.push = function(output) {
    // buffer incoming captions until the associated video segment
    // finishes
    if (output.text) {
      return this.pendingCaptions.push(output);
    }
    // buffer incoming id3 tags until the final flush
    if (output.frames) {
      return this.pendingMetadata.push(output);
    }

    if (output.track.type === 'video') {
      this.videoTrack = output.track;
      this.videoTags = output.tags;
      this.pendingTracks++;
    }
    if (output.track.type === 'audio') {
      this.audioTrack = output.track;
      this.audioTags = output.tags;
      this.pendingTracks++;
    }
  };
}
593992
def to_array(self):
        
        array = super(InputMediaAnimation, self).to_array()
        array['type'] = u(self.type)  # py2: type unicode, py3: type str

        array['media'] = u(self.media)  # py2: type unicode, py3: type str

        if self.thumb is not None:
            if isinstance(self.thumb, InputFile):
                array['thumb'] = self.thumb.to_array()  # type InputFile
            elif isinstance(self.thumb, str):
                array['thumb'] = u(self.thumb)  # py2: type unicode, py3: type str
            else:
                raise TypeError('Unknown type, must be one of InputFile, str.')
            # end if

        if self.caption is not None:
            array['caption'] = u(self.caption)  # py2: type unicode, py3: type str

        if self.parse_mode is not None:
            array['parse_mode'] = u(self.parse_mode)  # py2: type unicode, py3: type str

        if self.width is not None:
            array['width'] = int(self.width)  # type int
        if self.height is not None:
            array['height'] = int(self.height)  # type int
        if self.duration is not None:
            array['duration'] = int(self.duration)  # type int
        return array
894497
def finalizenames(self, client, finalimage):
        
        client.api.tag(finalimage, *self.targetname.split(':'))
        cprint('Tagged final image as "%s"' % self.targetname,
               'green')
        if not self.keepbuildtags:
            print('Untagging intermediate containers:', end='')
            for step in self.steps:
                client.api.remove_image(step.buildname, force=True)
                print(step.buildname, end=',')
            print()
814060
def get_audio_metadata_old(fname):
    
    audio_dict = {}
    print("IDv2 tag info for %s:" % fname)
    try:
        audio = mutagenx.id3.ID3(fname, translate=False)
    except StandardError as err:
        print("ERROR = " + str(err))
    #else:
        #print(audio.pprint().encode("utf-8", "replace"))
        #for frame in audio.values():
        #    print(repr(frame))
    
    try:
        audio_dict["title"] = audio["title"]
    except KeyError:
        print("No title")
        
    try:
        audio_dict["artist"] = audio["artist"] # tags['TPE1'] 
    except KeyError:
        print("No artist")
        
    try:
        audio_dict["album"] = audio["album"]
    except KeyError:
        print("No album")
        
    try:
        audio_dict["length"] = audio["length"]
    except KeyError:
        print("No length")
        
    #pprint.pprint(audio.tags)
        
    return audio_dict
395066
private RTPFormat createVideoFormat(int payload, Text description) {
        Iterator<Text> it = description.split('/').iterator();

        //encoding name
        Text token = it.next();
        token.trim();
        EncodingName name = new EncodingName(token);

        //clock rate
        //TODO : convert to frame rate
        token = it.next();
        token.trim();
        int clockRate = token.toInteger();

        RTPFormat rtpFormat = getFormat(payload);
        if (rtpFormat == null) {
            formats.add(new RTPFormat(payload, FormatFactory.createVideoFormat(name, clockRate)));
        } else {
            //TODO: recreate format anyway. it is illegal to use clock rate as frame rate
            ((VideoFormat)rtpFormat.getFormat()).setName(name);
            ((VideoFormat)rtpFormat.getFormat()).setFrameRate(clockRate);
        }

        return rtpFormat;
    }
1276388
def finalize(self):
        
        self._check_finalized()
        self._final = True

        for dest_w, values in self.dest_instrs_info.items():
            mux_vals = dict(zip(self.instructions, values))
            dest_w <<= sparse_mux(self.signal_wire, mux_vals)
345939
public void finishDefinition(){
		sequencer = null;
		states = ImmutableBiMap.copyOf(states);
		Map<S, Set<T>> validTransitionsCopied = new HashMap<S, Set<T>>();
		for (Map.Entry<S, Set<T>> entry: validTransitions.entrySet()){
			validTransitionsCopied.put(entry.getKey(), ImmutableSet.copyOf(entry.getValue()));
		}
		validTransitions = ImmutableMap.copyOf(validTransitions);
	}
76225
def finalize(self):
        

        method = "finalize"

        A = None
        metadata = {method: -1}

        send_array(self.socket, A, metadata)
        A, metadata = recv_array(
            self.socket, poll=self.poll, poll_timeout=self.poll_timeout,
            flags=self.zmq_flags)
1342037
def to_array(self):
        
        array = super(InputMediaAudio, self).to_array()
        # 'type' given by superclass
        # 'media' given by superclass
        if self.thumb is not None:
            if isinstance(self.thumb, InputFile):
                array['thumb'] = None  # type InputFile
            elif isinstance(self.thumb, str):
                array['thumb'] = u(self.thumb)  # py2: type unicode, py3: type str
            else:
                raise TypeError('Unknown type, must be one of InputFile, str.')
            # end if
        # 'caption' given by superclass
        # 'parse_mode' given by superclass
        if self.duration is not None:
            array['duration'] = int(self.duration)  # type int
        if self.performer is not None:
            array['performer'] = u(self.performer)  # py2: type unicode, py3: type str
        if self.title is not None:
            array['title'] = u(self.title)  # py2: type unicode, py3: type str
        return array
525225
def complete(self, stream):
            
            assert not self.is_complete()
            self._marker.addInputPort(outputPort=stream.oport)
            self.stream.oport.schema = stream.oport.schema
            # Update the pending schema to the actual schema
            # Any downstream filters that took the reference
            # will be automatically updated to the correct schema
            self._pending_schema._set(self.stream.oport.schema)

            # Mark the operator with the pending stream
            # a start point for graph travesal
            stream.oport.operator._start_op = True
776293
public void finishTransitionImmediately() {
    mTransitionState = TRANSITION_NONE;
    for (int i = 0; i < mLayers.length; i++) {
      mAlphas[i] = mIsLayerOn[i] ? 255 : 0;
    }
    invalidateSelf();
  }
141158
def ParseMetadataFile(
      self, parser_mediator, file_entry, data_stream_name):
    
    parent_path_spec = getattr(file_entry.path_spec, 'parent', None)
    filename_upper = file_entry.name.upper()
    if (self._mft_parser and parent_path_spec and
        filename_upper in ('$MFT', '$MFTMIRR') and not data_stream_name):
      self._ParseDataStreamWithParser(
          parser_mediator, self._mft_parser, file_entry, '')

    elif (self._usnjrnl_parser and parent_path_spec and
          filename_upper == '$USNJRNL' and data_stream_name == '$J'):
      # To be able to ignore the sparse data ranges the UsnJrnl parser
      # needs to read directly from the volume.
      volume_file_object = path_spec_resolver.Resolver.OpenFileObject(
          parent_path_spec, resolver_context=parser_mediator.resolver_context)

      try:
        self._ParseFileEntryWithParser(
            parser_mediator, self._usnjrnl_parser, file_entry,
            file_object=volume_file_object)
      finally:
        volume_file_object.close()
435339
def segment(self, webvtt, output='', seconds=SECONDS, mpegts=MPEGTS):
        """"""
        if isinstance(webvtt, str):
            # if a string is supplied we parse the file
            captions = WebVTT().read(webvtt).captions
        elif not self._validate_webvtt(webvtt):
            raise InvalidCaptionsError('The captions provided are invalid')
        else:
            # we expect to have a webvtt object
            captions = webvtt.captions

        self._total_segments = 0 if not captions else int(ceil(captions[-1].end_in_seconds / seconds))
        self._output_folder = output
        self._seconds = seconds
        self._mpegts = mpegts

        output_folder = os.path.join(os.getcwd(), output)
        if not os.path.exists(output_folder):
            os.makedirs(output_folder)

        self._slice_segments(captions)
        self._write_segments()
        self._write_manifest()
1040159
def complete(self):
        
        # Boolean to store the completeness of the analyses
        allcomplete = True
        # Clear the list of samples that still require more sequence data
        self.incomplete = list()
        for sample in self.runmetadata.samples:
            if sample.general.bestassemblyfile != 'NA':
                try:
                    # If the sample has been tagged as incomplete, only add it to the complete metadata list if the
                    # pipeline is on its final iteration
                    if sample.general.incomplete:
                        if self.final:
                            self.completemetadata.append(sample)
                        else:
                            sample.general.complete = False
                            allcomplete = False
                            self.incomplete.append(sample.name)
                except AttributeError:
                    sample.general.complete = True
                    self.completemetadata.append(sample)
            else:
                if self.final:
                    self.completemetadata.append(sample)
                else:
                    sample.general.complete = False
                    allcomplete = False
                    self.incomplete.append(sample.name)
        # If all the samples are complete, set the global variable for run completeness to True
        if allcomplete:
            self.analysescomplete = True
577631
@Override
    public ITag readTag() {
        ITag tag = null;
        if (log.isTraceEnabled()) {
            log.trace("Read tag - prevFrameSize {} audio: {} video: {}", new Object[] { prevFrameSize, audioCount, videoCount });
        }
        // ensure there are frames before proceeding
        if (!frames.isEmpty()) {
            try {
                lock.acquire();
                //log.debug("Read tag");
                //empty-out the pre-streaming tags first
                if (!firstTags.isEmpty()) {
                    //log.debug("Returning pre-tag");
                    // Return first tags before media data
                    return firstTags.removeFirst();
                }
                //get the current frame
                MP4Frame frame = frames.get(currentFrame);
                if (frame != null) {
                    log.debug("Playback #{} {}", currentFrame, frame);
                    int sampleSize = frame.getSize();
                    int time = (int) Math.round(frame.getTime() * 1000.0);
                    //log.debug("Read tag - dst: {} base: {} time: {}", new Object[]{frameTs, baseTs, time});
                    long samplePos = frame.getOffset();
                    //log.debug("Read tag - samplePos {}", samplePos);
                    //determine frame type and packet body padding
                    byte type = frame.getType();
                    //assume video type
                    int pad = 5;
                    if (type == TYPE_AUDIO) {
                        pad = 2;
                    }
                    //create a byte buffer of the size of the sample
                    ByteBuffer data = ByteBuffer.allocate(sampleSize + pad);
                    try {
                        //prefix is different for keyframes
                        if (type == TYPE_VIDEO) {
                            if (frame.isKeyFrame()) {
                                //log.debug("Writing keyframe prefix");
                                data.put(PREFIX_VIDEO_KEYFRAME);
                            } else {
                                //log.debug("Writing interframe prefix");
                                data.put(PREFIX_VIDEO_FRAME);
                            }
                            // match the sample with its ctts / mdhd adjustment time
                            int timeOffset = prevVideoTS != -1 ? time - prevVideoTS : 0;
                            data.put((byte) ((timeOffset >>> 16) & 0xff));
                            data.put((byte) ((timeOffset >>> 8) & 0xff));
                            data.put((byte) (timeOffset & 0xff));
                            if (log.isTraceEnabled()) {
                                byte[] prefix = new byte[5];
                                int p = data.position();
                                data.position(0);
                                data.get(prefix);
                                data.position(p);
                                log.trace("{}", prefix);
                            }
                            // track video frame count
                            videoCount++;
                            prevVideoTS = time;
                        } else {
                            //log.debug("Writing audio prefix");
                            data.put(PREFIX_AUDIO_FRAME);
                            // track audio frame count
                            audioCount++;
                        }
                        // do we need to add the mdat offset to the sample position?
                        dataSource.position(samplePos);
                        // read from the channel
                        dataSource.read(data);
                    } catch (IOException e) {
                        log.error("Error on channel position / read", e);
                    }
                    // chunk the data
                    IoBuffer payload = IoBuffer.wrap(data.array());
                    // create the tag
                    tag = new Tag(type, time, payload.limit(), payload, prevFrameSize);
                    //log.debug("Read tag - type: {} body size: {}", (type == TYPE_AUDIO ? "Audio" : "Video"), tag.getBodySize());
                    // increment the frame number
                    currentFrame++;
                    // set the frame / tag size
                    prevFrameSize = tag.getBodySize();
                }
            } catch (InterruptedException e) {
                log.warn("Exception acquiring lock", e);
            } finally {
                lock.release();
            }
        } else {
            log.warn("No frames are available for the requested item");
        }
        //log.debug("Tag: {}", tag);
        return tag;
    }
142129
def _read_metadata(self):
        
        if self._is_metadata_init():
            return
        try:
            log.debug('Reading metadata of "{path}" ...'.format(path=self._filepath))
            data = metadata.parse(self._filepath)
            videotracks = data.get_videotracks()
            if len(videotracks) > 0:
                self._fps = videotracks[0].get_framerate()
                self._time_ms = videotracks[0].get_duration_ms()
                self._framecount = videotracks[0].get_framecount()
        except:
            # FIXME: find out what type the metadata parser can throw
            log.debug('... FAIL')
            log.exception('Exception was thrown.')
1055436
function writeMediaSection(transceiver, caps, type, stream, dtlsRole) {
  var sdp = SDPUtils.writeRtpDescription(transceiver.kind, caps);

  // Map ICE parameters (ufrag, pwd) to SDP.
  sdp += SDPUtils.writeIceParameters(
    transceiver.iceGatherer.getLocalParameters());

  // Map DTLS parameters to SDP.
  sdp += SDPUtils.writeDtlsParameters(
    transceiver.dtlsTransport.getLocalParameters(),
    type === 'offer' ? 'actpass' : dtlsRole);

  sdp += 'a=mid:' + transceiver.mid + '\r\n';

  if (transceiver.rtpSender && transceiver.rtpReceiver) {
    sdp += 'a=sendrecv\r\n';
  } else if (transceiver.rtpSender) {
    sdp += 'a=sendonly\r\n';
  } else if (transceiver.rtpReceiver) {
    sdp += 'a=recvonly\r\n';
  } else {
    sdp += 'a=inactive\r\n';
  }

  if (transceiver.rtpSender) {
    var trackId = transceiver.rtpSender._initialTrackId ||
        transceiver.rtpSender.track.id;
    transceiver.rtpSender._initialTrackId = trackId;
    // spec.
    var msid = 'msid:' + (stream ? stream.id : '-') + ' ' +
        trackId + '\r\n';
    sdp += 'a=' + msid;
    // for Chrome. Legacy should no longer be required.
    sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].ssrc +
        ' ' + msid;

    // RTX
    if (transceiver.sendEncodingParameters[0].rtx) {
      sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].rtx.ssrc +
          ' ' + msid;
      sdp += 'a=ssrc-group:FID ' +
          transceiver.sendEncodingParameters[0].ssrc + ' ' +
          transceiver.sendEncodingParameters[0].rtx.ssrc +
          '\r\n';
    }
  }
  // FIXME: this should be written by writeRtpDescription.
  sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].ssrc +
      ' cname:' + SDPUtils.localCName + '\r\n';
  if (transceiver.rtpSender && transceiver.sendEncodingParameters[0].rtx) {
    sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].rtx.ssrc +
        ' cname:' + SDPUtils.localCName + '\r\n';
  }
  return sdp;
}