@POST
  @Consumes(MediaType.MULTIPART_FORM_DATA)
  @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
  @ApiOperation(
      value = "Returns a GEO label LML representation",
      notes = "Requires metadata/feedback documents as data stream")
  @ApiResponses({@ApiResponse(code = 400, message = "Error in feedback/metadata document")})
  public Label getLabelByStream(
      /* @ApiParam("Metadata document") */ @FormDataParam(Constants.PARAM_METADATA)
          InputStream metadataInputStream,
      /* @ApiParam("Feedback document") */ @FormDataParam(Constants.PARAM_FEEDBACK)
          InputStream feedbackInputStream)
      throws IOException {
    MetadataTransformer metadataTransformer = this.transformer.get();

    Label label = new Label();
    label.setMetadataUrl(new URL("http://not.available.for.direct.upload"));
    label.setFeedbackUrl(new URL("http://not.available.for.direct.upload"));

    PushbackInputStream tempStream;
    boolean hasData = false;
    if (metadataInputStream != null) {
      tempStream = new PushbackInputStream(metadataInputStream);
      int t = tempStream.read();
      if (t != -1) {
        tempStream.unread(t);
        log.debug("Reading from metadata stream...");
        metadataTransformer.updateGeoLabel(tempStream, label);
        hasData = true;
      } else tempStream.close();
    }
    if (feedbackInputStream != null) {
      tempStream = new PushbackInputStream(feedbackInputStream);
      int t = tempStream.read();
      if (t != -1) {
        tempStream.unread(t);
        log.debug("Reading from feedback stream...");
        metadataTransformer.updateGeoLabel(tempStream, label);
        hasData = true;
      } else tempStream.close();
    }

    if (!hasData)
      throw new WebApplicationException(
          Response.status(Response.Status.BAD_REQUEST)
              .type(MediaType.TEXT_PLAIN)
              .entity("No metadata or feedback file specified")
              .build());

    return label;
  }
 /**
  * Close the Bitstream.
  *
  * @throws BitstreamException
  */
 public void close() throws BitstreamException {
   try {
     source.close();
   } catch (IOException ex) {
     throw newBitstreamException(STREAM_ERROR, ex);
   }
 }
示例#3
0
 /** Closes any files opened by this tokenizer. */
 public void close() {
   if (wantClose) {
     try {
       is.close();
     } catch (IOException e) {
     }
   }
 }
示例#4
0
 /**
  * @param args
  * @throws Exception
  */
 public static void main(String[] args) throws Exception {
   // TODO Auto-generated method stub
   String str = "123456.654321";
   ByteArrayInputStream b = new ByteArrayInputStream(str.getBytes());
   PushbackInputStream p = null;
   p = new PushbackInputStream(b);
   int temp = 0;
   while ((temp = p.read()) != -1) {
     if (temp != '.') {
       System.out.print((char) temp);
     } else {
       p.unread(temp);
       temp = p.read();
       System.out.println("");
       System.out.println((char) temp);
       // break;
     }
   }
   p.close();
 }
 public void close() throws Exception {
   in.close();
 }
    public Boolean call() throws AndroidEmulatorException {
      if (logger == null) {
        logger = listener.getLogger();
      }

      final File homeDir = Utils.getHomeDirectory(androidSdk.getSdkHome());
      final File avdDirectory = getAvdDirectory(homeDir);
      final boolean emulatorExists = getAvdConfigFile(homeDir).exists();

      // Can't do anything if a named emulator doesn't exist
      if (isNamedEmulator() && !emulatorExists) {
        throw new EmulatorDiscoveryException(Messages.AVD_DOES_NOT_EXIST(avdName, avdDirectory));
      }

      // Check whether AVD needs to be created
      boolean createSdCard = false;
      boolean createSnapshot = false;
      File snapshotsFile = new File(getAvdDirectory(homeDir), "snapshots.img");
      if (emulatorExists) {
        // AVD exists: check whether there's anything still to be set up
        File sdCardFile = new File(getAvdDirectory(homeDir), "sdcard.img");
        boolean sdCardRequired = getSdCardSize() != null;

        // Check if anything needs to be done for snapshot-enabled builds
        if (shouldUseSnapshots() && androidSdk.supportsSnapshots()) {
          if (!snapshotsFile.exists()) {
            createSnapshot = true;
          }

          // We should ensure that we start out with a clean SD card for the build
          if (sdCardRequired && sdCardFile.exists()) {
            sdCardFile.delete();
          }
        }

        // Flag that we need to generate an SD card, if there isn't one existing
        if (sdCardRequired && !sdCardFile.exists()) {
          createSdCard = true;
        }

        // If everything is ready, then return
        if (!createSdCard && !createSnapshot) {
          return true;
        }
      } else {
        AndroidEmulator.log(logger, Messages.CREATING_AVD(avdDirectory));
      }

      // We can't continue if we don't know where to find emulator images or tools
      if (!androidSdk.hasKnownRoot()) {
        throw new EmulatorCreationException(Messages.SDK_NOT_SPECIFIED());
      }
      final File sdkRoot = new File(androidSdk.getSdkRoot());
      if (!sdkRoot.exists()) {
        throw new EmulatorCreationException(Messages.SDK_NOT_FOUND(androidSdk.getSdkRoot()));
      }

      // If we need to initialise snapshot support for an existing emulator, do so
      if (createSnapshot) {
        // Copy the snapshots file into place
        File snapshotDir = new File(sdkRoot, "tools/lib/emulator");
        Util.copyFile(new File(snapshotDir, "snapshots.img"), snapshotsFile);

        // Update the AVD config file mark snapshots as enabled
        Map<String, String> configValues;
        try {
          configValues = parseAvdConfigFile(homeDir);
          configValues.put("snapshot.present", "true");
          writeAvdConfigFile(homeDir, configValues);
        } catch (IOException e) {
          throw new EmulatorCreationException(Messages.AVD_CONFIG_NOT_READABLE(), e);
        }
      }

      // If we need create an SD card for an existing emulator, do so
      if (createSdCard) {
        AndroidEmulator.log(logger, Messages.ADDING_SD_CARD(sdCardSize, getAvdName()));
        if (!createSdCard(homeDir)) {
          throw new EmulatorCreationException(Messages.SD_CARD_CREATION_FAILED());
        }

        // Update the AVD config file
        Map<String, String> configValues;
        try {
          configValues = parseAvdConfigFile(homeDir);
          configValues.put("sdcard.size", sdCardSize);
          writeAvdConfigFile(homeDir, configValues);
        } catch (IOException e) {
          throw new EmulatorCreationException(Messages.AVD_CONFIG_NOT_READABLE(), e);
        }
      }

      // Return if everything is now ready for use
      if (emulatorExists) {
        return true;
      }

      // Build up basic arguments to `android` command
      final StringBuilder args = new StringBuilder(100);
      args.append("create avd ");

      // Overwrite any existing files
      args.append("-f ");

      // Initialise snapshot support, regardless of whether we will actually use it
      if (androidSdk.supportsSnapshots()) {
        args.append("-a ");
      }

      if (sdCardSize != null) {
        args.append("-c ");
        args.append(sdCardSize);
        args.append(" ");
      }
      args.append("-s ");
      args.append(screenResolution.getSkinName());
      args.append(" -n ");
      args.append(getAvdName());
      boolean isUnix = !Functions.isWindows();
      ArgumentListBuilder builder =
          Utils.getToolCommand(androidSdk, isUnix, Tool.ANDROID, args.toString());

      // Tack on quoted platform name at the end, since it can be anything
      builder.add("-t");
      builder.add(osVersion.getTargetName());

      if (targetAbi != null) {
        builder.add("--abi");
        builder.add(targetAbi);
      }

      // Log command line used, for info
      AndroidEmulator.log(logger, builder.toStringWithQuote());

      // Run!
      boolean avdCreated = false;
      final Process process;
      try {
        ProcessBuilder procBuilder = new ProcessBuilder(builder.toList());
        if (androidSdk.hasKnownHome()) {
          procBuilder.environment().put("ANDROID_SDK_HOME", androidSdk.getSdkHome());
        }
        process = procBuilder.start();
      } catch (IOException ex) {
        throw new EmulatorCreationException(Messages.AVD_CREATION_FAILED());
      }

      // Redirect process's stderr to a stream, for logging purposes
      ByteArrayOutputStream stderr = new ByteArrayOutputStream();
      ByteArrayOutputStream stdout = new ByteArrayOutputStream();
      new StreamCopyThread("", process.getErrorStream(), stderr).start();

      // Command may prompt us whether we want to further customise the AVD.
      // Just "press" Enter to continue with the selected target's defaults.
      try {
        boolean processAlive = true;

        // Block until the command outputs something (or process ends)
        final PushbackInputStream in = new PushbackInputStream(process.getInputStream(), 10);
        int len = in.read();
        if (len == -1) {
          // Check whether the process has exited badly, as sometimes no output is valid.
          // e.g. When creating an AVD with Google APIs, no user input is requested.
          if (process.waitFor() != 0) {
            AndroidEmulator.log(logger, Messages.AVD_CREATION_FAILED());
            AndroidEmulator.log(logger, stderr.toString(), true);
            throw new EmulatorCreationException(Messages.AVD_CREATION_FAILED());
          }
          processAlive = false;
        }
        in.unread(len);

        // Write CRLF, if required
        if (processAlive) {
          final OutputStream stream = process.getOutputStream();
          stream.write('\r');
          stream.write('\n');
          stream.flush();
          stream.close();
        }

        // read the rest of stdout (for debugging purposes)
        Util.copyStream(in, stdout);
        in.close();

        // Wait for happy ending
        if (process.waitFor() == 0) {
          // Do a sanity check to ensure the AVD was really created
          avdCreated = getAvdConfigFile(homeDir).exists();
        }

      } catch (IOException e) {
        throw new EmulatorCreationException(Messages.AVD_CREATION_ABORTED(), e);
      } catch (InterruptedException e) {
        throw new EmulatorCreationException(Messages.AVD_CREATION_INTERRUPTED(), e);
      } finally {
        process.destroy();
      }

      // For reasons unknown, the return code may not be correctly reported on Windows.
      // So check whether stderr contains failure info (useful for other platforms too).
      String errOutput = stderr.toString();
      String output = stdout.toString();
      if (errOutput.contains("list targets")) {
        AndroidEmulator.log(logger, Messages.INVALID_AVD_TARGET(osVersion.getTargetName()));
        avdCreated = false;
        errOutput = null;
      } else if (errOutput.contains("more than one ABI")) {
        AndroidEmulator.log(
            logger, Messages.MORE_THAN_ONE_ABI(osVersion.getTargetName(), output), true);
        avdCreated = false;
        errOutput = null;
      }

      // Check everything went ok
      if (!avdCreated) {
        if (errOutput != null && errOutput.length() != 0) {
          AndroidEmulator.log(logger, stderr.toString(), true);
        }
        throw new EmulatorCreationException(Messages.AVD_CREATION_FAILED());
      }

      // Done!
      return false;
    }
  /** secondary PES Parser */
  public String parseStream(
      JobCollection collection,
      XInputFile aXInputFile,
      int _pes_streamtype,
      int action,
      String vptslog) {
    String fchild = collection.getOutputName(aXInputFile.getName());
    String fparent = collection.getOutputNameParent(fchild);

    if (collection.getSettings().getBooleanProperty(Keys.KEY_ExternPanel_appendExtension))
      fparent = collection.getOutputDirectory() + collection.getFileSeparator() + fchild;

    JobProcessing job_processing = collection.getJobProcessing();

    job_processing.clearStatusVariables();
    int[] clv = job_processing.getStatusVariables();

    /** split part */
    fparent += job_processing.getSplitSize() > 0 ? "(" + job_processing.getSplitPart() + ")" : "";

    String paname = fparent + ".ma1";

    String file_id = aXInputFile.getFileID();

    List tempfiles = job_processing.getTemporaryFileList();

    if (!tempfiles.isEmpty()) {
      for (int i = 0; i < tempfiles.size(); i += 4) {
        if (tempfiles.get(i + 1).toString().equals(aXInputFile.toString())) {
          Common.renameTo(tempfiles.get(i).toString(), paname);

          tempfiles.set(i, paname);

          Common.setMessage(Resource.getString("parseSecondaryPES.continue") + " " + aXInputFile);

          String str = tempfiles.get(i + 3).toString();

          if (str.equals("tt")) // vtx
          new StreamProcess(
                CommonParsing.TELETEXT,
                collection,
                tempfiles.get(i).toString(),
                tempfiles.get(i + 2).toString(),
                tempfiles.get(i + 3).toString(),
                vptslog);
          else if (str.equals("sp")) // subpics
          new StreamProcess(
                CommonParsing.SUBPICTURE,
                collection,
                tempfiles.get(i).toString(),
                tempfiles.get(i + 2).toString(),
                tempfiles.get(i + 3).toString(),
                vptslog);
          else if (str.equals("pc")) // lpcm
          new StreamProcess(
                CommonParsing.LPCM_AUDIO,
                collection,
                tempfiles.get(i).toString(),
                tempfiles.get(i + 2).toString(),
                tempfiles.get(i + 3).toString(),
                vptslog);
          else // other audio
          new StreamProcess(
                CommonParsing.MPEG_AUDIO,
                collection,
                tempfiles.get(i).toString(),
                tempfiles.get(i + 2).toString(),
                tempfiles.get(i + 3).toString(),
                vptslog);

          return vptslog;
        }
      }
    }

    boolean Message_2 = collection.getSettings().getBooleanProperty(Keys.KEY_MessagePanel_Msg2);
    boolean Debug = collection.getSettings().getBooleanProperty(Keys.KEY_DebugLog);
    boolean SimpleMPG = collection.getSettings().getBooleanProperty(Keys.KEY_simpleMPG);
    boolean GetEnclosedPackets =
        collection.getSettings().getBooleanProperty(Keys.KEY_Input_getEnclosedPackets);
    boolean IgnoreScrambledPackets =
        collection.getSettings().getBooleanProperty(Keys.KEY_TS_ignoreScrambled);

    boolean isTeletext = false;
    boolean missing_startcode = false;
    boolean scrambling_messaged = false;
    boolean pes_isMpeg2;
    boolean pes_alignment;
    boolean pes_scrambled;
    boolean containsPts = false;
    boolean foundObject;

    int pes_streamtype;
    int pes_payloadlength;
    int pes_packetlength;
    int pes_extensionlength;
    int pes_headerlength = 9;
    int pes_packetoffset = 6;
    int pes_extension2_id;
    int pesID;
    int subID;
    int offset;
    int returncode = 0;

    int tmp_value1 = 0;

    byte[] pes_packet = new byte[0x10006];
    byte[] buffered_data;

    long count = 0;
    long size;
    long qexit;

    job_processing.setMinBitrate(CommonParsing.MAX_BITRATE_VALUE);
    job_processing.setMaxBitrate(0);
    job_processing.setExportedVideoFrameNumber(0);
    job_processing.setEndPtsOfGop(-10000);
    job_processing.setSequenceHeader(true);
    job_processing.setAllMediaFilesExportLength(0);
    job_processing.setProjectFileExportLength(0);

    Hashtable substreams = new Hashtable();
    StandardBuffer sb;

    demuxList = job_processing.getSecondaryPESDemuxList();
    demuxList.clear();

    try {

      PushbackInputStream in =
          new PushbackInputStream(aXInputFile.getInputStream(), pes_packet.length);

      size = aXInputFile.length();

      Common.updateProgressBar(
          Resource.getString("parseSecondaryPES.demux.pes") + " " + aXInputFile.getName(), 0, 0);

      qexit =
          count
              + (0x100000L
                  * Integer.parseInt(
                      collection.getSettings().getProperty(Keys.KEY_ExportPanel_Infoscan_Value)));

      bigloop:
      while (true) {
        loop:
        while (count < size) {
          pes_streamtype = _pes_streamtype; // reset to original type

          Common.updateProgressBar(count, size);

          // yield();

          while (pause()) {}

          if (CommonParsing.isProcessCancelled() || (CommonParsing.isInfoScan() && count > qexit)) {
            CommonParsing.setProcessCancelled(false);
            job_processing.setSplitSize(0);

            break bigloop;
          }

          in.read(pes_packet, 0, pes_packetoffset);

          pesID = CommonParsing.getPES_IdField(pes_packet, 0);

          if ((returncode = CommonParsing.validateStartcode(pes_packet, 0)) < 0
              || pesID < CommonParsing.SYSTEM_END_CODE) {
            returncode = returncode < 0 ? -returncode : 4;

            if (Message_2 && !missing_startcode)
              Common.setMessage(
                  Resource.getString("parseSecondaryPES.missing.startcode") + " " + count);

            in.read(pes_packet, pes_packetoffset, pes_packet.length - pes_packetoffset);

            int i = returncode;

            for (; i < pes_packet.length - 3; ) {
              returncode = CommonParsing.validateStartcode(pes_packet, i);

              if (returncode < 0) {
                i += -returncode;
                continue;
              } else {
                in.unread(pes_packet, i, pes_packet.length - i);

                count += i;
                missing_startcode = true;

                continue loop;
              }
            }

            in.unread(pes_packet, i, pes_packet.length - i);

            count += i;
            missing_startcode = true;

            continue loop;
          }

          if (Message_2 && missing_startcode)
            Common.setMessage(
                Resource.getString("parseSecondaryPES.found.startcode") + " " + count);

          missing_startcode = false;

          if (pes_streamtype == CommonParsing.MPEG1PS_TYPE
              || pes_streamtype == CommonParsing.MPEG2PS_TYPE
              || SimpleMPG) {
            switch (pesID) {
              case CommonParsing.SYSTEM_END_CODE:
                in.unread(pes_packet, 4, 2);
                Common.setMessage("-> skip system_end_code @ " + count);
                count += 4;
                continue loop;

              case CommonParsing.PACK_START_CODE:
                if ((0xC0 & pes_packet[4]) == 0) // mpg1
                {
                  in.skip(6);
                  count += 12;
                  continue loop;
                } else if ((0xC0 & pes_packet[4]) == 0x40) // mpg2
                {
                  in.read(pes_packet, 6, 8);

                  offset = 7 & pes_packet[13];

                  count += 14;

                  in.read(pes_packet, 14, offset);

                  if (offset > 0) {
                    for (int i = 0; i < offset; i++)
                      if (pes_packet[14 + i] != -1) {
                        in.unread(pes_packet, 14, offset);

                        Common.setMessage("!> wrong pack header stuffing @ " + count);
                        missing_startcode = true;
                        continue loop;
                      }
                  }

                  count += offset;

                  continue loop;
                } else {
                  in.unread(pes_packet, 4, 2);
                  count += 4;
                  continue loop;
                }

              case CommonParsing.SYSTEM_START_CODE:
              case CommonParsing.PROGRAM_STREAM_MAP_CODE:
              case CommonParsing.PADDING_STREAM_CODE:
              case CommonParsing.PRIVATE_STREAM_2_CODE:
              case CommonParsing.ECM_STREAM_CODE:
              case CommonParsing.EMM_STREAM_CODE:
              case CommonParsing.DSM_CC_STREAM_CODE:
              case 0xF3:
              case 0xF4:
              case 0xF5:
              case 0xF6:
              case 0xF7:
              case 0xF8:
              case 0xF9:
              case 0xFA:
              case 0xFB:
              case 0xFC:
              case 0xFD:
              case 0xFE:
              case 0xFF:
                pes_payloadlength = CommonParsing.getPES_LengthField(pes_packet, 0);

                in.skip(pes_payloadlength);

                count += (pes_packetoffset + pes_payloadlength);
                continue loop;
            }
          }

          if ((0xF0 & pesID) != 0xE0
              && (0xE0 & pesID) != 0xC0
              && pesID != CommonParsing.PRIVATE_STREAM_1_CODE) {
            in.unread(pes_packet, 3, pes_packetoffset - 3);
            count += 3;
            continue loop;
          }

          pes_payloadlength = CommonParsing.getPES_LengthField(pes_packet, 0);

          if (pes_payloadlength == 0) {
            Common.setMessage(Resource.getString("parseSecondaryPES.packet.length") + " " + count);

            count += pes_packetoffset;
            continue loop;
          }

          in.read(pes_packet, pes_packetoffset, pes_payloadlength + 4);

          pes_packetlength = pes_packetoffset + pes_payloadlength;

          if (GetEnclosedPackets
              && CommonParsing.validateStartcode(pes_packet, pes_packetlength) < 0) {
            if (count + pes_packetlength < size) {
              if (Message_2 && !missing_startcode)
                Common.setMessage(
                    Resource.getString(
                        "parseSecondaryPES.miss.next.startcode",
                        String.valueOf(count + pes_packetlength),
                        String.valueOf(count),
                        Integer.toHexString(pesID).toUpperCase()));

              missing_startcode = true;

              in.unread(pes_packet, pes_packetoffset, pes_payloadlength + 4);
              count += pes_packetoffset;

              continue loop;
            }
          } else in.unread(pes_packet, pes_packetlength, 4);

          clv[5]++;

          if (Debug)
            System.out.print(
                "\r"
                    + Resource.getString(
                        "parseSecondaryPES.packs",
                        String.valueOf(clv[5]),
                        String.valueOf((count * 100 / size)),
                        String.valueOf(count)));

          pes_extensionlength = CommonParsing.getPES_ExtensionLengthField(pes_packet, 0);

          pes_isMpeg2 = (0xC0 & pes_packet[6]) == 0x80;
          pes_alignment = pes_isMpeg2 && (4 & pes_packet[6]) != 0;
          pes_scrambled = pes_isMpeg2 && (0x30 & pes_packet[6]) != 0;

          count += pes_packetlength;

          /** check scrambling */
          if (IgnoreScrambledPackets) {
            // cannot work with scrambled data
            if (pes_scrambled) {
              if (!scrambling_messaged) {
                scrambling_messaged = true;

                Common.setMessage(
                    Resource.getString(
                        "parseTS.scrambled",
                        Integer.toHexString(pesID).toUpperCase(),
                        String.valueOf(clv[5]),
                        String.valueOf(count - pes_packetlength)));
              }

              continue loop;
            } else if (scrambling_messaged) {
              Common.setMessage(
                  Resource.getString(
                      "parseTS.clear",
                      Integer.toHexString(pesID).toUpperCase(),
                      String.valueOf(clv[5]),
                      String.valueOf(count - pes_packetlength)));
              scrambling_messaged = false;
            }
          }

          /** vdr_dvbsub determination */
          pes_extension2_id =
              CommonParsing.getExtension2_Id(
                  pes_packet,
                  pes_headerlength,
                  pes_payloadlength,
                  pesID,
                  pes_isMpeg2,
                  count - pes_packetlength);

          isTeletext = false;
          subID = 0;

          if (pesID == CommonParsing.PRIVATE_STREAM_1_CODE && pes_payloadlength > 2) {
            offset = pes_headerlength + pes_extensionlength;

            if (offset < pes_packetlength) {
              subID = 0xFF & pes_packet[offset];
              isTeletext = pes_extensionlength == 0x24 && subID >>> 4 == 1;

              // vdr 1.5.x dvb-subs container
              if (pes_payloadlength >= 4 && subID >>> 4 == 2) {
                tmp_value1 =
                    CommonParsing.getIntValue(pes_packet, offset, 4, !CommonParsing.BYTEREORDERING);

                // vdr 1.5.x start packet of dvb-sub || subsequent packet
                // if ((pes_alignment && tmp_value1 == 0x20010000) || (!pes_alignment && tmp_value1
                // == 0x20010001))
                if ((pes_alignment && (0xF0FFFFFF & tmp_value1) == 0x20010000)
                    || (!pes_alignment && (0xF0FFFFFF & tmp_value1) == 0x20010001)) {
                  for (int i = offset, j = offset + 4; i < j; i++) pes_packet[i] = (byte) 0xFF;

                  pes_extensionlength += 4;
                  pes_packet[8] = (byte) (pes_extensionlength);
                  pes_payloadlength -= 4;

                  // pes_extension2_id = 1;
                  pes_extension2_id = subID = tmp_value1 >>> 24;
                  pes_streamtype =
                      CommonParsing.MPEG2PS_TYPE; // will be resetted before next packet

                  if (pes_alignment) pes_packet[offset + 4] = (byte) (subID);
                }
              }

              // subpic in vdr_pes before 1.5.x
              if (pes_alignment && !isTeletext && (subID >>> 4 == 2 || subID >>> 4 == 3))
                pes_streamtype = CommonParsing.MPEG2PS_TYPE; // will be resetted before next packet

              if (pes_streamtype != CommonParsing.MPEG1PS_TYPE
                  && pes_streamtype != CommonParsing.MPEG2PS_TYPE
                  && !isTeletext) subID = 0; // disables LPCM too
            } else if (pes_streamtype != CommonParsing.MPEG1PS_TYPE) // ?
            {
              pes_extensionlength = pes_payloadlength - 3;
              pes_packet[8] = (byte) (pes_extensionlength);
            }

            /** packet buffering esp. of subpics from vdr or other pes */
            if (pes_extension2_id != -1) {
              String str = String.valueOf(pes_extension2_id);
              offset = pes_headerlength + pes_extensionlength;

              if (!substreams.containsKey(str)) substreams.put(str, new StandardBuffer());

              sb = (StandardBuffer) substreams.get(str);

              // buffer raw packet data
              if (!pes_alignment) {
                sb.write(pes_packet, offset, pes_packetlength - offset);
                continue loop;
              }

              // start packet, buffer this and get last completed packet
              else {
                buffered_data = sb.getData();

                sb.reset();
                sb.write(pes_packet, 0, pes_packetlength);

                if (buffered_data == null || buffered_data.length < 10) continue loop;

                pes_packetlength = buffered_data.length;

                if (pes_packetlength > 0x10005) {
                  Common.setMessage(
                      "!> sub packet too long: 0x"
                          + Integer.toHexString(pesID).toUpperCase()
                          + " /ext2_id "
                          + pes_extension2_id);
                  pes_packetlength = 0x10005;
                }

                pes_payloadlength = pes_packetlength - pes_packetoffset;

                System.arraycopy(buffered_data, 0, pes_packet, 0, pes_packetlength);

                CommonParsing.setPES_LengthField(pes_packet, 0, pes_payloadlength);

                buffered_data = null;
              }
            }
          }

          foundObject = false;

          /** find ID object */
          for (int i = 0; i < demuxList.size(); i++) {
            streamdemultiplexer = (StreamDemultiplexer) demuxList.get(i);

            foundObject =
                pesID == streamdemultiplexer.getID()
                    && subID == streamdemultiplexer.subID()
                    && isTeletext == streamdemultiplexer.isTTX();

            if (foundObject) break;
          }

          /** create new ID object */
          if (!foundObject) {
            String IDtype = "";

            switch (0xF0 & pesID) {
              case 0xE0:
                IDtype = Resource.getString("idtype.mpeg.video.ignored");

                streamdemultiplexer = new StreamDemultiplexer(collection);
                streamdemultiplexer.setID(pesID);
                streamdemultiplexer.setsubID(0);
                streamdemultiplexer.setType(CommonParsing.MPEG_VIDEO);
                streamdemultiplexer.setStreamType(pes_streamtype);

                demuxList.add(streamdemultiplexer);
                break;

              case 0xC0:
              case 0xD0:
                IDtype = Resource.getString("idtype.mpeg.audio");

                streamdemultiplexer = new StreamDemultiplexer(collection);
                streamdemultiplexer.setID(pesID);
                streamdemultiplexer.setsubID(0);
                streamdemultiplexer.setType(CommonParsing.MPEG_AUDIO);
                streamdemultiplexer.setStreamType(pes_streamtype);

                demuxList.add(streamdemultiplexer);
                streamdemultiplexer.init(
                    collection,
                    fparent,
                    MainBufferSize / demuxList.size(),
                    demuxList.size(),
                    CommonParsing.SECONDARY_PES_PARSER);

                break;
            }

            switch (pesID) {
              case CommonParsing.PRIVATE_STREAM_1_CODE:
                IDtype = Resource.getString("idtype.private.stream");
                IDtype +=
                    (isTeletext ? " TTX " : "")
                        + (subID != 0
                            ? " (SubID 0x" + Integer.toHexString(subID).toUpperCase() + ")"
                            : "");

                streamdemultiplexer = new StreamDemultiplexer(collection);
                streamdemultiplexer.setID(pesID);
                streamdemultiplexer.setsubID(subID);

                switch (subID >>> 4) {
                  case 1:
                    streamdemultiplexer.setType(CommonParsing.TELETEXT);
                    break;

                  case 2:
                  case 3:
                    streamdemultiplexer.setType(CommonParsing.SUBPICTURE);
                    break;

                  case 8:
                    streamdemultiplexer.setType(CommonParsing.AC3_AUDIO);
                    break;

                  case 0xA:
                    streamdemultiplexer.setType(CommonParsing.LPCM_AUDIO);
                }

                streamdemultiplexer.setTTX(isTeletext);
                streamdemultiplexer.setStreamType(pes_streamtype);

                demuxList.add(streamdemultiplexer);
                streamdemultiplexer.init(
                    collection,
                    fparent,
                    MainBufferSize / demuxList.size(),
                    demuxList.size(),
                    CommonParsing.SECONDARY_PES_PARSER);

                break;
            }

            Common.setMessage(
                Resource.getString(
                    "parseSecondaryPES.found.pesid",
                    Integer.toHexString(pesID).toUpperCase(),
                    IDtype,
                    "" + (count - 6 - pes_payloadlength)));
          }

          if (!streamdemultiplexer.StreamEnabled()) continue loop;

          if (streamdemultiplexer.getType() == CommonParsing.MPEG_VIDEO) continue loop;
          else streamdemultiplexer.write(job_processing, pes_packet, 0, pes_packetlength, true);
        }

        /** loop not yet used */
        break bigloop;
      }

      Common.setMessage(
          Resource.getString(
              "parseSecondaryPES.packs",
              String.valueOf(clv[5]),
              String.valueOf(count * 100 / size),
              String.valueOf(count)));

      in.close();

      processNonVideoElementaryStreams(
          vptslog, action, clv, collection, job_processing, tempfiles, aXInputFile);

    } catch (IOException e2) {

      Common.setExceptionMessage(e2);
    }

    return vptslog;
  }
示例#8
0
    public void run() {
      try {
        System.out.println(
            "accepted connection " + socket.getInetAddress() + ":" + socket.getPort());
        PushbackInputStream inStream = new PushbackInputStream(socket.getInputStream());
        // 得到客户端发来的第一行协议数据:Content-Length=143253434;filename=xxx.3gp;sourceid=
        // 如果用户初次上传文件,sourceid的值为空。
        String head = StreamTool.readLine(inStream);
        System.out.println(head);
        if (head != null) {
          // 下面从协议数据中提取各项参数值
          String[] items = head.split(";");
          String filelength = items[0].substring(items[0].indexOf("=") + 1);
          String filename = items[1].substring(items[1].indexOf("=") + 1);
          String sourceid = items[2].substring(items[2].indexOf("=") + 1);
          long id = System.currentTimeMillis(); // 生产资源id,如果需要唯一性,可以采用UUID
          FileLog log = null;
          if (sourceid != null && !"".equals(sourceid)) {
            id = Long.valueOf(sourceid);
            log = find(id); // 查找上传的文件是否存在上传记录
          }
          File file = null;
          int position = 0;
          if (log == null) { // 如果不存在上传记录,为文件添加跟踪记录
            String path = new SimpleDateFormat("yyyy/MM/dd/HH/mm").format(new Date());
            File dir = new File("file/" + path);
            if (!dir.exists()) dir.mkdirs();
            file = new File(dir, filename);
            if (file.exists()) { // 如果上传的文件发生重名,然后进行改名
              filename =
                  filename.substring(0, filename.indexOf(".") - 1)
                      + dir.listFiles().length
                      + filename.substring(filename.indexOf("."));
              file = new File(dir, filename);
            }
            save(id, file);
          } else { // 如果存在上传记录,读取已经上传的数据长度
            file = new File(log.getPath()); // 从上传记录中得到文件的路径
            if (file.exists()) {
              File logFile = new File(file.getParentFile(), file.getName() + ".log");
              if (logFile.exists()) {
                Properties properties = new Properties();
                properties.load(new FileInputStream(logFile));
                // 读取已经上传的数据长度
                position = Integer.valueOf(properties.getProperty("length"));
              }
            }
          }

          OutputStream outStream = socket.getOutputStream();
          String response = "sourceid=" + id + ";position=" + position + "\r\n";
          // 服务器收到客户端的请求信息后,给客户端返回响应信息:sourceid=1274773833264;position=0
          // sourceid由服务器端生成,唯一标识上传的文件,position指示客户端从文件的什么位置开始上传
          outStream.write(response.getBytes());
          RandomAccessFile fileOutStream = new RandomAccessFile(file, "rwd");
          // 设置文件长度
          if (position == 0) fileOutStream.setLength(Integer.valueOf(filelength));
          fileOutStream.seek(position); // 指定从文件的特定位置开始写入数据
          byte[] buffer = new byte[1024];
          int len = -1;
          int length = position;
          while ((len = inStream.read(buffer)) != -1) { // 从输入流中读取数据写入到文件中
            fileOutStream.write(buffer, 0, len);
            length += len;
            Properties properties = new Properties();
            properties.put("length", String.valueOf(length));
            FileOutputStream logFile =
                new FileOutputStream(new File(file.getParentFile(), file.getName() + ".log"));
            properties.store(logFile, null); // 实时记录已经接收的文件长度
            logFile.close();
          }
          if (length == fileOutStream.length()) delete(id);
          fileOutStream.close();
          inStream.close();
          outStream.close();
          file = null;
        }
      } catch (Exception e) {
        e.printStackTrace();
      } finally {
        try {
          if (socket != null && !socket.isClosed()) socket.close();
        } catch (IOException e) {
        }
      }
    }