@Override
    protected Product doInBackground(com.bc.ceres.core.ProgressMonitor pm) throws Exception {
      final TargetProductSelectorModel model = getTargetProductSelector().getModel();
      pm.beginTask("Writing...", model.isOpenInAppSelected() ? 100 : 95);
      ProgressMonitorList.instance().add(pm); // NESTMOD
      saveTime = 0L;
      Product product = null;
      try {
        // free cache	// NESTMOD
        JAI.getDefaultInstance().getTileCache().flush();
        System.gc();

        executeStartTime = Calendar.getInstance().getTime();
        long t0 = System.currentTimeMillis();
        Operator operator = null;
        if (targetProduct.getProductReader() instanceof OperatorProductReader) {
          final OperatorProductReader opReader =
              (OperatorProductReader) targetProduct.getProductReader();
          if (opReader.getOperatorContext().getOperator() instanceof Output) {
            operator = opReader.getOperatorContext().getOperator();
          }
        }
        if (operator == null) {
          WriteOp writeOp =
              new WriteOp(targetProduct, model.getProductFile(), model.getFormatName());
          writeOp.setDeleteOutputOnFailure(true);
          writeOp.setWriteEntireTileRows(true);
          writeOp.setClearCacheAfterRowWrite(false);
          operator = writeOp;
        }
        final OperatorExecutor executor = OperatorExecutor.create(operator);
        executor.execute(SubProgressMonitor.create(pm, 95));

        saveTime = System.currentTimeMillis() - t0;
        File targetFile = model.getProductFile();
        if (model.isOpenInAppSelected() && targetFile.exists()) {
          product = ProductIO.readProduct(targetFile);
          if (product == null) {
            product = targetProduct; // todo - check - this cannot be ok!!! (nf)
          }
          pm.worked(5);
        }
      } finally {
        // free cache
        JAI.getDefaultInstance().getTileCache().flush();
        System.gc();

        pm.done();
        ProgressMonitorList.instance().remove(pm); // NESTMOD
        if (product != targetProduct) {
          targetProduct.dispose();
        }
      }
      return product;
    }
 public static void main(String[] args) {
   System.gc();
   // Schedule a job for the event-dispatching thread:
   // creating and showing this application's GUI.
   javax.swing.SwingUtilities.invokeLater(
       new Runnable() {
         public void run() {
           createAndShowGUI();
         }
       });
 } // end of main
 /** Frees memory by deleting a few slices from the end of the stack. */
 public void trim() {
   int n = (int) Math.round(Math.log(nSlices) + 1.0);
   for (int i = 0; i < n; i++) {
     deleteLastSlice();
     System.gc();
   }
 }
示例#4
0
 public void shutdownMinecraftApplet() {
   try {
     statFileWriter.func_27175_b();
     statFileWriter.syncStats();
     if (mcApplet != null) {
       mcApplet.clearApplet();
     }
     try {
       if (downloadResourcesThread != null) {
         downloadResourcesThread.closeMinecraft();
       }
     } catch (Exception exception) {
     }
     System.out.println("Stopping!");
     try {
       changeWorld1(null);
     } catch (Throwable throwable) {
     }
     try {
       GLAllocation.deleteTexturesAndDisplayLists();
     } catch (Throwable throwable1) {
     }
     sndManager.closeMinecraft();
     Mouse.destroy();
     Keyboard.destroy();
   } finally {
     Display.destroy();
     if (!hasCrashed) {
       System.exit(0);
     }
   }
   System.gc();
 }
 public void mouseClicked(MouseEvent e) {
   int x = e.getX();
   int y = e.getY();
   int currentTabIndex = -1;
   int tabCount = tabPane.getTabCount();
   for (int i = 0; i < tabCount; i++) {
     if (rects[i].contains(x, y)) {
       currentTabIndex = i;
       break;
     } // if contains
   } // for i
   if (currentTabIndex >= 0) {
     Rectangle tabRect = rects[currentTabIndex];
     x = x - tabRect.x;
     y = y - tabRect.y;
     if ((x >= 5) && (x <= 15) && (y >= 5) && (y <= 15)) {
       try {
         tabbedPane.remove(currentTabIndex);
       } catch (Exception ex) {
         ex.printStackTrace();
       }
     } // if
   } // if currentTabIndex >= 0
   System.gc();
 } // mouseClicked
示例#6
0
  /**
   * Called to process events. Mouse events will be rewritten to indicate the position in the
   * document clicked, instead of the position of the panel.
   *
   * @param event to process.
   */
  protected void processEvent(AWTEvent event) {
    try {
      if (event instanceof MouseEvent) {
        final Point scrollPosition = getScrollPosition();

        if (scrollPosition != null) {
          final MouseEvent mouseEvent = (MouseEvent) event;
          event =
              new MouseEvent(
                  (Component) mouseEvent.getSource(),
                  mouseEvent.getID(),
                  mouseEvent.getWhen(),
                  mouseEvent.getModifiers(),
                  mouseEvent.getX() + scrollPosition.x,
                  mouseEvent.getY() + scrollPosition.y,
                  mouseEvent.getClickCount(),
                  mouseEvent.isPopupTrigger());
        }
      }
    } catch (final Throwable exp) {
      exp.printStackTrace(DjVuOptions.err);
      System.gc();
    }

    super.processEvent(event);
  }
示例#7
0
文件: Life.java 项目: dragon66/icafe
  public void init() {

    // get initial cell parameters from HTML file
    try {
      cellSize = Integer.parseInt(getParameter("cellSize"));
      cellCount = Integer.parseInt(getParameter("cellCount"));
      speed = Integer.parseInt(getParameter("speed"));
    } catch (NumberFormatException e) {
      cellSize = 20;
      cellCount = 30;
      speed = 50;
    }
    if (cellCount == 0) cellCount = 30;
    if (cellSize == 0) cellSize = 20;
    if (speed == 0) speed = 50;
    // construct a square cell grid
    cell = new int[cellCount][cellCount];
    // record the neighbors of a certain cell
    cellNeighbours = new int[cellCount][cellCount];

    live = new DoublyLinkedList<CellCoordinate>();
    die = new DoublyLinkedList<CellCoordinate>();
    nextLive = new DoublyLinkedList<CellCoordinate>();
    nextDie = new DoublyLinkedList<CellCoordinate>();
    initCells();
    setComponents();
    firstTime = true;
    System.gc();
  }
  /** Method declaration Adjust this method for large strings...ie multi megabtypes. */
  void execute() {

    String sCmd = null;

    if (4096 <= ifHuge.length()) {
      sCmd = ifHuge;
    } else {
      sCmd = txtCommand.getText();
    }

    if (sCmd.startsWith("-->>>TEST<<<--")) {
      testPerformance();

      return;
    }

    String g[] = new String[1];

    lTime = System.currentTimeMillis();

    try {
      sStatement.execute(sCmd);

      lTime = System.currentTimeMillis() - lTime;

      int r = sStatement.getUpdateCount();

      if (r == -1) {
        formatResultSet(sStatement.getResultSet());
      } else {
        g[0] = "update count";

        gResult.setHead(g);

        g[0] = String.valueOf(r);

        gResult.addRow(g);
      }

      addToRecent(txtCommand.getText());
    } catch (SQLException e) {
      lTime = System.currentTimeMillis() - lTime;
      g[0] = "SQL Error";

      gResult.setHead(g);

      String s = e.getMessage();

      s += " / Error Code: " + e.getErrorCode();
      s += " / State: " + e.getSQLState();
      g[0] = s;

      gResult.addRow(g);
    }

    updateResult();
    System.gc();
  }
示例#9
0
 public void func_28002_e() {
   try {
     field_28006_b = new byte[0];
     renderGlobal.func_28137_f();
   } catch (Throwable throwable) {
   }
   try {
     System.gc();
     AxisAlignedBB.func_28196_a();
     Vec3D.func_28215_a();
   } catch (Throwable throwable1) {
   }
   try {
     System.gc();
     changeWorld1(null);
   } catch (Throwable throwable2) {
   }
   System.gc();
 }
 public static void assertTiming(
     String message, long expected, int attempts, @NotNull Runnable actionToMeasure) {
   while (true) {
     attempts--;
     long duration = measure(actionToMeasure);
     try {
       assertTiming(message, expected, duration);
       break;
     } catch (AssertionFailedError e) {
       if (attempts == 0) throw e;
       System.gc();
       System.gc();
       System.gc();
       String s = "Another epic fail (remaining attempts: " + attempts + "): " + e.getMessage();
       TeamCityLogger.warning(s, null);
       System.err.println(s);
     }
   }
 }
示例#11
0
 /**
  * Called to process scrollbar events.
  *
  * @param event to process.
  */
 public void adjustmentValueChanged(AdjustmentEvent event) {
   try {
     final Scrollbar hScroll = getScrollbar(Scrollbar.HORIZONTAL);
     final Scrollbar vScroll = getScrollbar(Scrollbar.VERTICAL);
     final Point scrollPosition = getScrollPosition();
     setScrollPosition(
         (hScroll != null) ? hScroll.getValue() : scrollPosition.x,
         (vScroll != null) ? vScroll.getValue() : scrollPosition.y);
   } catch (final Throwable exp) {
     exp.printStackTrace(DjVuOptions.err);
     System.gc();
   }
 }
示例#12
0
 public void update(GameEvent e) {
   this.m_map = e.getMap();
   if (e.getState() == Snake.DEAD) {
     int respond = JOptionPane.showConfirmDialog(this, "Snake is DEAD!!\nPlay again?");
     if (respond == JOptionPane.OK_OPTION) {
       this.m_isBegin = true;
       this.m_body = new GameBody(this, this.m_map, 125);
       System.gc();
     } else if (respond == JOptionPane.CANCEL_OPTION || respond == JOptionPane.NO_OPTION) {
       System.exit(0);
     }
   }
   this.repaint();
 }
示例#13
0
 private BufferedImage allocateNewBufferedImage(Dimension dimension, int attemtps) {
   try {
     BufferedImage image =
         new BufferedImage(dimension.width, dimension.height, BufferedImage.TYPE_INT_ARGB);
     return image;
   } catch (OutOfMemoryError e) {
     if (attemtps > 1) {
       entries.clear();
       System.gc();
       return allocateNewBufferedImage(dimension, attemtps - 1);
     }
     throw e;
   }
 }
示例#14
0
  // Static main program for executing a test of the class.
  public static void main(String args[]) {
    // Define int variables.
    int width = 0;
    int height = 0;

    // If arguments are greater than zero.
    if (args.length > 0) {

      // If arguments are two.
      if (args.length >= 2) {
        // Use try block to parse for an integer.
        try {
          // Verify first argument is an integer.
          width = Integer.parseInt(args[0]);
          height = Integer.parseInt(args[1]);

          // Define a default instance of JMessagingFrame.
          JMessagingFrame f = new JMessagingFrame(width, height);

        } // Catch parsing failure exception.
        catch (NumberFormatException e) {
          // Print default runtime message.
          System.out.println("If you are testing the override constructor,");
          System.out.println("then you need to provide two integer values.");
        } // End try-catch block on integer parse.

      } // End of if two arguments provided.
      else // When there are less than or more than two arguments.
      {
        // Print default runtime message.
        System.out.println("If you are testing the override constructor,");
        System.out.println("then you need to provide two integer values.");
      } // End of else when there are less than or more than two arguments.

    } // End of else when there are two arguments.
    else // No arguments provided.
    {
      // Define a default instance of JMessagingFrame.
      JMessagingFrame f = new JMessagingFrame();

      // Clean-up by signaling the garbage collector.
      System.gc();
    } // End of else when no arguments are provided.
  } // End of static main.
示例#15
0
 /**
  * This method represents the application code that we'd like to run on a separate thread. It
  * simulates slowly computing a value, in this case just a string 'All Done'. It updates the
  * progress bar every half second to remind the user that we're still busy.
  */
 Object doWork() {
   try {
     if (Thread.interrupted()) {
       throw new InterruptedException();
     }
     while (!this.state.terminator.isTerminated(this.state.optimizer.getPopulation())) {
       if (Thread.interrupted()) {
         throw new InterruptedException();
       }
       this.state.optimizer.optimize();
     }
     System.gc();
   } catch (InterruptedException e) {
     updateStatus("Interrupted", 0);
     return "Interrupted";
   }
   updateStatus("All Done", 0);
   return "All Done";
 }
示例#16
0
 public void startWorld(String s, String s1, long l) {
   changeWorld1(null);
   System.gc();
   if (saveLoader.isOldMapFormat(s)) {
     convertMapFormat(s, s1);
   } else {
     net.minecraft.src.ISaveHandler isavehandler = saveLoader.getSaveLoader(s, false);
     World world = null;
     world = new World(isavehandler, s1, l);
     if (world.isNewWorld) {
       statFileWriter.readStat(StatList.createWorldStat, 1);
       statFileWriter.readStat(StatList.startGameStat, 1);
       changeWorld2(world, "Generating level");
     } else {
       statFileWriter.readStat(StatList.loadWorldStat, 1);
       statFileWriter.readStat(StatList.startGameStat, 1);
       changeWorld2(world, "Loading level");
     }
   }
 }
示例#17
0
  public void setup() {
    Random.createUniform();
    if (surface != null) surface.dispose();
    if (degreeDist != null) degreeDist.dispose();
    if (graph != null) graph.dispose();

    surface = null;
    schedule = null;
    degreeDist = null;
    graph = null;

    System.gc();

    surface = new DisplaySurface(this, "JinGirModelII Display");
    registerDisplaySurface("Main Display", surface);
    schedule = new Schedule();
    agentList = new ArrayList();
    worldXSize = 500;
    worldYSize = 500;
  }
示例#18
0
  /**
   * Called with a DjVuBean property has changed.
   *
   * @param e the PropertyChangeEvent.
   */
  public void propertyChange(final PropertyChangeEvent e) {
    try {
      final String name = e.getPropertyName();

      if ("page".equalsIgnoreCase(name)) {
        final Object object = e.getNewValue();

        if (object instanceof Number) {
          setCheckedPage(((Number) object).intValue() - 1);
        }
      } else if ("propertyName".equalsIgnoreCase(name)) {
        final String propertyName = (String) e.getNewValue();

        if ("navpane".equalsIgnoreCase(propertyName)) {
          setVisible("Outline".equalsIgnoreCase(djvuBean.properties.getProperty(propertyName)));
        }
      }
    } catch (final Throwable exp) {
      exp.printStackTrace(DjVuOptions.err);
      System.gc();
    }
  }
示例#19
0
  /** Calls the algorithm. */
  protected void callAlgorithm() {

    try {
      resultImage =
          new ModelImage(imageA.getType(), imageA.getExtents(), (imageA.getImageName() + "_isn"));
      resultImage.copyFileTypeInfo(imageA);

      // Make algorithm
      isnAlgo = new PlugInAlgorithmISN(resultImage, imageA);

      // This is very important. Adding this object as a listener allows the algorithm to
      // notify this object when it has completed of failed. See algorithm performed event.
      // This is made possible by implementing AlgorithmedPerformed interface
      isnAlgo.addListener(this);

      createProgressBar(imageA.getImageName(), " ...", isnAlgo);

      // Hide dialog
      setVisible(false);

      if (isRunInSeparateThread()) {

        // Start the thread as a low priority because we wish to still have user interface work
        // fast.
        if (isnAlgo.startMethod(Thread.MIN_PRIORITY) == false) {
          MipavUtil.displayError("A thread is already running on this object");
        }
      } else {
        isnAlgo.run();
      }
    } catch (OutOfMemoryError x) {
      System.gc();
      MipavUtil.displayError("AlgorithmAbsoluteValue: unable to allocate enough memory");

      return;
    }
  }
  /**
   * Use the GUI results to set up the variables needed to run the algorithm.
   *
   * @return <code>true</code> if parameters set successfully, <code>false</code> otherwise.
   */
  private boolean setVariables() {
    String tmpStr;

    System.gc();

    if (replaceImage.isSelected()) {
      displayLoc = REPLACE;
    } else if (newImage.isSelected()) {
      displayLoc = NEW;
    }

    tmpStr = textSearchWindowSide.getText();

    if (testParameter(tmpStr, 5, 101)) {
      searchWindowSide = Integer.valueOf(tmpStr).intValue();
    } else {
      MipavUtil.displayError("Search window side must be between 5 and 101");
      textSearchWindowSide.requestFocus();
      textSearchWindowSide.selectAll();

      return false;
    }

    if ((searchWindowSide % 2) == 0) {
      MipavUtil.displayError("Search window side must be an odd number");
      textSearchWindowSide.requestFocus();
      textSearchWindowSide.selectAll();
      return false;
    }

    tmpStr = textSimilarityWindowSide.getText();

    if (testParameter(tmpStr, 3, 99)) {
      similarityWindowSide = Integer.valueOf(tmpStr).intValue();
    } else {
      MipavUtil.displayError("Similarity window side must be between 3 and 99");
      textSimilarityWindowSide.requestFocus();
      textSimilarityWindowSide.selectAll();

      return false;
    }

    if ((similarityWindowSide % 2) == 0) {
      MipavUtil.displayError("Similarity window side must be an odd number");
      textSimilarityWindowSide.requestFocus();
      textSimilarityWindowSide.selectAll();
      return false;
    }

    if (similarityWindowSide >= searchWindowSide) {
      MipavUtil.displayError("Similarity window side must be less than search window side");
      textSimilarityWindowSide.requestFocus();
      textSimilarityWindowSide.selectAll();
      return false;
    }

    tmpStr = textNoiseStandardDeviation.getText();

    if (testParameter(tmpStr, 0.001, 1000.0)) {
      noiseStandardDeviation = Float.valueOf(tmpStr).floatValue();
    } else {
      MipavUtil.displayError("Radius must be between 0.001 and 1000.0");
      textNoiseStandardDeviation.requestFocus();
      textNoiseStandardDeviation.selectAll();

      return false;
    }

    doRician = doRicianCheckBox.isSelected();

    if (doRician) {
      tmpStr = textDegree.getText();
      if (testParameter(tmpStr, 1.0, 10.0)) {
        degreeOfFiltering = Float.valueOf(tmpStr).floatValue();
      } else {
        MipavUtil.displayError("Degree of filtering must be between 1.0 and 10.0");
        textDegree.requestFocus();
        textDegree.selectAll();
      }
    }

    if (image.getNDims() > 2) {
      image25D = image25DCheckBox.isSelected();
    }

    return true;
  }
  /**
   * Initializes the GUI by creating the components, placing them in the dialog, and displaying
   * them.
   */
  private void init() {
    setForeground(Color.black);

    setTitle("Nonlocal Means Filter");

    JPanel mainPanel;
    mainPanel = new JPanel();
    mainPanel.setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3));
    mainPanel.setLayout(new GridBagLayout());

    GridBagConstraints gbc = new GridBagConstraints();
    gbc.gridwidth = 1;
    gbc.gridheight = 1;
    gbc.anchor = GridBagConstraints.WEST;
    gbc.weightx = 1;
    gbc.insets = new Insets(3, 3, 3, 3);
    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.fill = GridBagConstraints.HORIZONTAL;

    paramPanel = new JPanel(new GridBagLayout());
    paramPanel.setForeground(Color.black);
    paramPanel.setBorder(buildTitledBorder("Parameters"));
    mainPanel.add(paramPanel, gbc);

    GridBagConstraints gbc2 = new GridBagConstraints();
    gbc2.gridwidth = 1;
    gbc2.gridheight = 1;
    gbc2.anchor = GridBagConstraints.WEST;
    gbc2.weightx = 1;
    gbc2.insets = new Insets(3, 3, 3, 3);
    gbc2.gridx = 0;
    gbc2.gridy = 0;
    gbc2.fill = GridBagConstraints.HORIZONTAL;

    labelSearchWindowSide = createLabel("Search window side (odd)");

    paramPanel.add(labelSearchWindowSide, gbc2);

    gbc2.gridx = 1;
    textSearchWindowSide = createTextField("15");
    paramPanel.add(textSearchWindowSide, gbc2);

    gbc2.gridx = 0;
    gbc2.gridy = 1;
    labelSimilarityWindowSide = createLabel("Similarity window side (odd) ");
    paramPanel.add(labelSimilarityWindowSide, gbc2);

    gbc2.gridx = 1;
    textSimilarityWindowSide = createTextField("7");
    paramPanel.add(textSimilarityWindowSide, gbc2);

    gbc2.gridx = 0;
    gbc2.gridy = 2;
    labelNoiseStandardDeviation = createLabel("Noise standard deviation ");
    paramPanel.add(labelNoiseStandardDeviation, gbc2);

    gbc2.gridx = 1;
    textNoiseStandardDeviation = createTextField("10.0");
    paramPanel.add(textNoiseStandardDeviation, gbc2);

    gbc2.gridx = 0;
    gbc2.gridy = 3;
    labelDegree = createLabel("Degree of filtering ");
    labelDegree.setEnabled(doRician);
    paramPanel.add(labelDegree, gbc2);

    gbc2.gridx = 1;
    textDegree = createTextField("1.414");
    textDegree.setEnabled(doRician);
    paramPanel.add(textDegree, gbc2);

    gbc2.gridx = 0;
    gbc2.gridy = 4;
    doRicianCheckBox = new JCheckBox("Deal with Rician noise in MRI");
    doRicianCheckBox.setFont(serif12);
    doRicianCheckBox.setSelected(false);
    doRicianCheckBox.addActionListener(this);
    paramPanel.add(doRicianCheckBox, gbc2);

    if (image.getNDims() > 2) {
      gbc2.gridx = 0;
      gbc2.gridy = 5;
      gbc2.gridwidth = 2;

      image25DCheckBox = new JCheckBox("Process each slice independently (2.5D)");
      image25DCheckBox.setFont(serif12);
      paramPanel.add(image25DCheckBox, gbc2);
      image25DCheckBox.setSelected(false);
    } // if (image.getNDims > 2)

    JPanel outputOptPanel = new JPanel(new GridLayout(1, 2));
    destinationPanel = new JPanel(new BorderLayout());
    destinationPanel.setForeground(Color.black);
    destinationPanel.setBorder(buildTitledBorder("Destination"));
    outputOptPanel.add(destinationPanel);

    destinationGroup = new ButtonGroup();
    newImage = new JRadioButton("New image", true);
    newImage.setBounds(10, 16, 120, 25);
    newImage.setFont(serif12);
    destinationGroup.add(newImage);
    destinationPanel.add(newImage, BorderLayout.NORTH);

    replaceImage = new JRadioButton("Replace image", false);
    replaceImage.setFont(serif12);
    destinationGroup.add(replaceImage);
    destinationPanel.add(replaceImage, BorderLayout.CENTER);

    // Only if the image is unlocked can it be replaced.
    if (image.getLockStatus() == ModelStorageBase.UNLOCKED) {
      replaceImage.setEnabled(true);
    } else {
      replaceImage.setEnabled(false);
    }

    gbc.gridx = 0;
    gbc.gridy = 1;
    mainPanel.add(outputOptPanel, gbc);

    mainDialogPanel.add(mainPanel, BorderLayout.CENTER);
    mainDialogPanel.add(buildButtons(), BorderLayout.SOUTH);

    getContentPane().add(mainDialogPanel);

    pack();
    setResizable(true);
    // setVisible(true);

    System.gc();
  }
  public MarioInput actionSelectionAI() {

    Vector<HashMap<Pair, Node>> solutionStates = new Vector<HashMap<Pair, Node>>();
    LinkedList<HashMap<Pair, Node>> frontierStates = new LinkedList<HashMap<Pair, Node>>();
    Vector<HashMap<Pair, Node>> seenStates = new Vector<HashMap<Pair, Node>>();
    if (!graph) { // If the graph hasn't been generated yet, generate it.
      Graph = new GraphGenerator(9, 9, mario);
      Graph.generateGraph(e, t);
      Graph.isGraphGenerated = true;
      graph = true;
    } else {
      Graph.resetNodes(e, t, mario);
    }
    MyMario simM = Graph.State.get(new Pair(0, 0)).alterMario;
    Action[] modPosAction;
    if (simM.onGround) {
      modPosAction = groundPossibleActions;
    } else {
      if (!simM.onGround) modPosAction = airPossibleActions;
      else modPosAction = airHangPossibleActions;
    }
    int runs = 0;
    boolean firstStateSeenCurrent = false;
    frontierStates.push(mapCopy(Graph.State));
    solutionStates.add(mapCopy(Graph.State));
    Vector<Action> actionsDo = new Vector<>();

    HashMap<Pair, Node> currentState = frontierStates.removeFirst();
    for (Map.Entry<Pair, Node> x : currentState.entrySet()) {
      if (x.getValue().mario) simM = x.getValue().alterMario;
    }
    solutionStates.add(currentState);
    seenStates.add(currentState);
    Vector<genPair<Pair, genPair<Action, HashMap<Pair, Node>>>> childStates = null;
    System.out.println("HERE Tick");
    childStates = Graph.tick(currentState, modPosAction);
    firstStateSeenCurrent = true;

    if (mario.onGround && !g1) g1 = true;
    if (!g1) return action;
    for (genPair<Pair, genPair<Action, HashMap<Pair, Node>>> x : childStates) {
      Pair marioPosChild = x.x;
      HashMap<Pair, Node> child = x.y.y;
      Node Center = child.get(new Pair(0, 0));
      Node CenterRight = child.get(new Pair(1, 0));
      Id3Node Root = null;
      Action thisOne = null;
      for (Id3Node r : ThisTree) {
        if (r.root) Root = r;
      }
      Id3Node curr = Root;

      int count = 0;
      while (actionsDo.isEmpty()) {
        switch (curr.atrib) {
          case Enemy:
            if (CenterRight.enemyHere || Center.enemyHere) {
              actionsDo.add(Action.Jump);
            } else {
              curr = curr.no;
            }
            break;
          case Block:
            if (CenterRight.blockHere && !CenterRight.doubleBlock) {
              if (mario.onGround) {
                actionsDo.add(Action.Jump);
              } else {
                actionsDo.add(Action.RightLongJump);
              }
              break;
            } else {
              curr = curr.no;
            }
            break;
          case DoubleBlock:
            if (CenterRight.doubleBlock || Center.doubleBlock) {

              // actionsDo.add(Action.Jump);
              actionsDo.add(Action.RightLongJump);
            } else {
              curr = curr.no;
            }
            break;

          case None:
            actionsDo.add(Action.RightSpeed);
            break;
          default:
            actionsDo.add(Action.Right);
        }
      }

      // actionsDo.add(Action.RightSpeed);

      if (thisOne != null) actionsDo.add(thisOne);
      break;
    }
    ++runs;

    System.out.println("REturning");
    System.gc();
    return doActions(actionsDo);
  }
示例#23
0
  protected void process() {
    int i, j, len, ch, chunkLength;
    long progOff, progLen;
    float f1;

    // io
    AudioFile inF = null;
    AudioFile outF = null;
    AudioFileDescr inStream;
    AudioFileDescr outStream;
    FloatFile[] floatF = null;
    File tempFile[] = null;

    // buffers
    float[][] inBuf, outBuf;
    float[] win;
    float[] convBuf1, convBuf2;
    float[] tempFlt;

    int inChanNum, inLength, inputStep, outputStep, winSize;
    int transLen, skip, inputLen, outputLen, fltLen;
    int framesRead, framesWritten;
    float warp, a1, b0, b1, x0, x1, y0, y1, b0init;

    Param ampRef = new Param(1.0, Param.ABS_AMP); // transform-Referenz
    Param peakGain;
    float gain = 1.0f; // gain abs amp
    float maxAmp = 0.0f;

    PathField ggOutput;

    topLevel:
    try {

      // ---- open input, output ----

      // input
      inF = AudioFile.openAsRead(new File(pr.text[PR_INPUTFILE]));
      inStream = inF.getDescr();
      inChanNum = inStream.channels;
      inLength = (int) inStream.length;
      // this helps to prevent errors from empty files!
      if ((inLength * inChanNum) < 1) throw new EOFException(ERR_EMPTY);
      // .... check running ....
      if (!threadRunning) break topLevel;

      // output
      ggOutput = (PathField) gui.getItemObj(GG_OUTPUTFILE);
      if (ggOutput == null) throw new IOException(ERR_MISSINGPROP);
      outStream = new AudioFileDescr(inStream);
      ggOutput.fillStream(outStream);
      outF = AudioFile.openAsWrite(outStream);
      // .... check running ....
      if (!threadRunning) break topLevel;

      // ---- parameter inits ----

      warp =
          Math.max(-0.98f, Math.min(0.98f, (float) (pr.para[PR_WARP].val / 100))); // DAFx2000 'b'
      f1 = (1.0f - warp) / (1.0f + warp); // DAFx2000 (25)
      winSize = 32 << pr.intg[PR_FRAMESIZE]; // DAFx2000 'N'
      j = winSize >> 1;
      transLen = (int) (f1 * winSize + 0.5f); // DAFx2000 'P' (26)
      i = pr.intg[PR_OVERLAP] + 1;
      while (((float) transLen / (float) i) > j) i++;
      inputStep = (int) (((float) transLen / (float) i) + 0.5f); // DAFx2000 'L'
      fltLen = Math.max(winSize, transLen);
      // System.out.println( "inputStep "+inputStep+"; winSize "+winSize+"; transLen "+transLen+";
      // fltLen "+fltLen+"; warp "+warp+"; � "+f1 );
      win = Filter.createFullWindow(winSize, Filter.WIN_HANNING); // DAFx2000 (27)
      outputStep = inputStep;

      b0init = (float) Math.sqrt(1.0f - warp * warp);

      progOff = 0;
      progLen = (long) inLength * (2 + inChanNum); // + winSize;

      tempFlt = new float[fltLen];
      inputLen = winSize + inputStep;
      inBuf = new float[inChanNum][inputLen];
      outputLen = transLen + outputStep;
      outBuf = new float[inChanNum][outputLen];

      // normalization requires temp files
      if (pr.intg[PR_GAINTYPE] == GAIN_UNITY) {
        tempFile = new File[inChanNum];
        floatF = new FloatFile[inChanNum];
        for (ch = 0; ch < inChanNum; ch++) { // first zero them because an exception might be thrown
          tempFile[ch] = null;
          floatF[ch] = null;
        }
        for (ch = 0; ch < inChanNum; ch++) {
          tempFile[ch] = IOUtil.createTempFile();
          floatF[ch] = new FloatFile(tempFile[ch], GenericFile.MODE_OUTPUT);
        }
        progLen += (long) inLength;
      } else {
        gain = (float) ((Param.transform(pr.para[PR_GAIN], Param.ABS_AMP, ampRef, null)).val);
      }
      // .... check running ....
      if (!threadRunning) break topLevel;

      // ----==================== the real stuff ====================----

      framesRead = 0;
      framesWritten = 0;
      skip = 0;

      while (threadRunning && (framesWritten < inLength)) {

        chunkLength = Math.min(inputLen, inLength - framesRead + skip);
        // ---- read input chunk ----
        len = Math.max(0, chunkLength - skip);
        inF.readFrames(inBuf, skip, len);
        framesRead += len;
        progOff += len;
        //				off			+= len;
        // .... progress ....
        setProgression((float) progOff / (float) progLen);
        // .... check running ....
        if (!threadRunning) break topLevel;

        // zero padding
        if (chunkLength < inputLen) {
          for (ch = 0; ch < inChanNum; ch++) {
            convBuf1 = inBuf[ch];
            for (i = chunkLength; i < convBuf1.length; i++) {
              convBuf1[i] = 0.0f;
            }
          }
        }

        for (ch = 0; threadRunning && (ch < inChanNum); ch++) {
          convBuf1 = inBuf[ch];
          convBuf2 = outBuf[ch];

          for (i = 0, j = fltLen; i < winSize; i++) {
            tempFlt[--j] = convBuf1[i] * win[i];
          }
          while (j > 0) {
            tempFlt[--j] = 0.0f;
          }

          a1 = -warp; // inital allpass
          b0 = b0init;
          b1 = 0.0f;
          for (j = 0; j < transLen; j++) {
            x1 = 0.0f;
            y1 = 0.0f;

            //						for( i = 0; i < transLen; i++ ) {		// DAFx2000 (2 resp. 3)
            for (i = 0; i < fltLen; i++) { // DAFx2000 (2 resp. 3)
              x0 = tempFlt[i];
              y0 = b0 * x0 + b1 * x1 - a1 * y1;
              tempFlt[i] = y0; // (work with double precision while computing cascades)
              y1 = y0;
              x1 = x0;
            }

            a1 = -warp; // cascaded allpasses
            b0 = -warp;
            b1 = 1.0f;

            convBuf2[j] += (float) y1;
          }
          // .... progress ....
          progOff += chunkLength - skip;
          setProgression((float) progOff / (float) progLen);
        } // for channels
        // .... check running ....
        if (!threadRunning) break topLevel;

        chunkLength = Math.min(outputStep, inLength - framesWritten);
        // ---- write output chunk ----
        if (floatF != null) {
          for (ch = 0; ch < inChanNum; ch++) {
            floatF[ch].writeFloats(outBuf[ch], 0, chunkLength);
          }
          progOff += chunkLength;
          //					off			  += len;
          framesWritten += chunkLength;
          // .... progress ....
          setProgression((float) progOff / (float) progLen);

        } else {
          for (ch = 0; ch < inChanNum; ch++) {
            Util.mult(outBuf[ch], 0, chunkLength, gain);
          }
          outF.writeFrames(outBuf, 0, chunkLength);
          progOff += chunkLength;
          //					off			  += len;
          framesWritten += chunkLength;
          // .... progress ....
          setProgression((float) progOff / (float) progLen);
        }
        // .... check running ....
        if (!threadRunning) break topLevel;

        // check max amp
        for (ch = 0; ch < inChanNum; ch++) {
          convBuf1 = outBuf[ch];
          for (i = 0; i < chunkLength; i++) {
            f1 = Math.abs(convBuf1[i]);
            if (f1 > maxAmp) {
              maxAmp = f1;
            }
          }
        }

        // overlaps
        skip = winSize;
        for (ch = 0; ch < inChanNum; ch++) {
          System.arraycopy(inBuf[ch], inputStep, inBuf[ch], 0, winSize);
          convBuf1 = outBuf[ch];
          System.arraycopy(convBuf1, outputStep, convBuf1, 0, transLen);
          for (i = transLen; i < outputLen; ) {
            convBuf1[i++] = 0.0f;
          }
        }
      } // until framesWritten == outLength
      // .... check running ....
      if (!threadRunning) break topLevel;

      // ----==================== normalize output ====================----

      if (pr.intg[PR_GAINTYPE] == GAIN_UNITY) {
        peakGain = new Param((double) maxAmp, Param.ABS_AMP);
        gain =
            (float)
                (Param.transform(
                        pr.para[PR_GAIN],
                        Param.ABS_AMP,
                        new Param(1.0 / peakGain.val, peakGain.unit),
                        null))
                    .val;
        normalizeAudioFile(floatF, outF, inBuf, gain, 1.0f);
        maxAmp *= gain;

        for (ch = 0; ch < inChanNum; ch++) {
          floatF[ch].cleanUp();
          floatF[ch] = null;
          tempFile[ch].delete();
          tempFile[ch] = null;
        }
      }
      // .... check running ....
      if (!threadRunning) break topLevel;

      // ---- Finish ----

      outF.close();
      outF = null;
      outStream = null;
      inF.close();
      inF = null;
      inStream = null;
      inBuf = null;

      // inform about clipping/ low level
      handleClipping(maxAmp);
    } catch (IOException e1) {
      setError(e1);
    } catch (OutOfMemoryError e2) {
      inStream = null;
      outStream = null;
      inBuf = null;
      convBuf1 = null;
      convBuf2 = null;
      System.gc();

      setError(new Exception(ERR_MEMORY));
      ;
    }

    // ---- cleanup (topLevel) ----
    if (inF != null) {
      inF.cleanUp();
      inF = null;
    }
    if (outF != null) {
      outF.cleanUp();
      outF = null;
    }
    if (floatF != null) {
      for (ch = 0; ch < floatF.length; ch++) {
        if (floatF[ch] != null) {
          floatF[ch].cleanUp();
          floatF[ch] = null;
        }
        if (tempFile[ch] != null) {
          tempFile[ch].delete();
          tempFile[ch] = null;
        }
      }
    }
  } // process()
示例#24
0
 public void mousePressed(MouseEvent e) {
   Undo.reset();
   if (!Prefs.noClickToGC) System.gc();
   IJ.showStatus(version() + IJ.freeMemory());
   if (IJ.debugMode) IJ.log("Windows: " + WindowManager.getWindowCount());
 }
  /** Sets up the GUI (panels, buttons, etc) and displays it on the screen. */
  private void init() {
    DecimalFormat df;
    int xUnits;
    String unitStr;
    String distStr;
    setForeground(Color.black);
    setTitle("Center Distances version 2  07/14/08");

    df = new DecimalFormat("0.000E0");

    GridBagConstraints gbc = new GridBagConstraints();
    int yPos = 0;
    gbc.gridwidth = 1;
    gbc.gridheight = 1;
    gbc.anchor = GridBagConstraints.WEST;
    gbc.weightx = 1;
    gbc.insets = new Insets(3, 3, 3, 3);
    gbc.fill = GridBagConstraints.HORIZONTAL;
    gbc.gridx = 0;
    gbc.gridy = yPos++;

    JPanel mainPanel = new JPanel(new GridBagLayout());
    mainPanel.setForeground(Color.black);
    mainPanel.setBorder(buildTitledBorder("Input parameters"));

    blueMinLabel = new JLabel("Minimum number of blue pixels per nucleus");
    blueMinLabel.setForeground(Color.black);
    blueMinLabel.setFont(serif12);
    gbc.gridx = 0;
    gbc.gridy = yPos;
    mainPanel.add(blueMinLabel, gbc);

    blueMinText = new JTextField(5);
    if (image.getNDims() == 2) {
      blueMinText.setText("1000");
    } else {
      blueMinText.setText("20000");
    }
    blueMinText.setFont(serif12);
    gbc.gridx = 1;
    gbc.gridy = yPos++;
    mainPanel.add(blueMinText, gbc);

    redMinLabel = new JLabel("Minimum red pixel count");
    redMinLabel.setForeground(Color.black);
    redMinLabel.setFont(serif12);
    gbc.gridx = 0;
    gbc.gridy = yPos;
    mainPanel.add(redMinLabel, gbc);

    redMinText = new JTextField(5);
    redMinText.setText("50");
    redMinText.setFont(serif12);
    gbc.gridx = 1;
    gbc.gridy = yPos++;
    mainPanel.add(redMinText, gbc);

    redFractionLabel = new JLabel("Fraction of red pixels to consider");
    redFractionLabel.setForeground(Color.black);
    redFractionLabel.setFont(serif12);
    gbc.gridx = 0;
    gbc.gridy = yPos;
    mainPanel.add(redFractionLabel, gbc);

    redFractionText = new JTextField(5);
    redFractionText.setText("0.15");
    redFractionText.setFont(serif12);
    gbc.gridx = 1;
    gbc.gridy = yPos++;
    mainPanel.add(redFractionText, gbc);

    xUnits = image.getFileInfo(0).getUnitsOfMeasure()[0];
    if (xUnits != Unit.UNKNOWN_MEASURE.getLegacyNum()) {
      unitStr = (Unit.getUnitFromLegacyNum(xUnits)).toString();
      greenMergingLabel = new JLabel("Green merging radius around peak (" + unitStr + ")");
    } else {
      greenMergingLabel = new JLabel("Green merging radius around peak");
    }
    greenMergingLabel.setForeground(Color.black);
    greenMergingLabel.setFont(serif12);
    gbc.gridx = 0;
    gbc.gridy = yPos;
    mainPanel.add(greenMergingLabel, gbc);

    if (image.getNDims() == 2) {
      // mergingDistance = 8.0f * image.getFileInfo(0).getResolutions()[0];
      mergingDistance = 0.0f;
    } else {
      // mergingDistance = 4.0f * image.getFileInfo(0).getResolutions()[0];
      mergingDistance = 0.0f;
    }
    distStr = df.format(mergingDistance);
    greenMergingText = new JTextField(10);
    greenMergingText.setText(distStr);
    greenMergingText.setFont(serif12);
    gbc.gridx = 1;
    gbc.gridy = yPos++;
    mainPanel.add(greenMergingText, gbc);

    greenMinLabel = new JLabel("Minimum green pixel count");
    greenMinLabel.setForeground(Color.black);
    greenMinLabel.setFont(serif12);
    gbc.gridx = 0;
    gbc.gridy = yPos;
    mainPanel.add(greenMinLabel, gbc);

    greenMinText = new JTextField(5);
    greenMinText.setText("10");
    greenMinText.setFont(serif12);
    gbc.gridx = 1;
    gbc.gridy = yPos++;
    mainPanel.add(greenMinText, gbc);

    greenFractionLabel = new JLabel("Fraction of green pixels to consider");
    greenFractionLabel.setForeground(Color.black);
    greenFractionLabel.setFont(serif12);
    gbc.gridx = 0;
    gbc.gridy = yPos;
    mainPanel.add(greenFractionLabel, gbc);

    greenFractionText = new JTextField(5);
    greenFractionText.setText("0.01");
    greenFractionText.setFont(serif12);
    gbc.gridx = 1;
    gbc.gridy = yPos++;
    mainPanel.add(greenFractionText, gbc);

    greenRegionsLabel = new JLabel("Green regions per cell");
    greenRegionsLabel.setForeground(Color.black);
    greenRegionsLabel.setFont(serif12);
    gbc.gridx = 0;
    gbc.gridy = yPos;
    mainPanel.add(greenRegionsLabel, gbc);

    JPanel buttonPanel = new JPanel(new GridBagLayout());

    greenGroup = new ButtonGroup();

    oneButton = new JRadioButton("1", false);
    oneButton.setForeground(Color.black);
    oneButton.setFont(serif12);
    greenGroup.add(oneButton);
    gbc.gridx = 0;
    gbc.gridy = 0;
    buttonPanel.add(oneButton, gbc);

    twoButton = new JRadioButton("2", true);
    twoButton.setForeground(Color.black);
    twoButton.setFont(serif12);
    greenGroup.add(twoButton);
    gbc.gridx = 1;
    gbc.gridy = 0;
    buttonPanel.add(twoButton, gbc);

    threeButton = new JRadioButton("3", false);
    threeButton.setForeground(Color.black);
    threeButton.setFont(serif12);
    greenGroup.add(threeButton);
    gbc.gridx = 2;
    gbc.gridy = 0;
    buttonPanel.add(threeButton, gbc);

    fourButton = new JRadioButton("4", false);
    fourButton.setForeground(Color.black);
    fourButton.setFont(serif12);
    greenGroup.add(fourButton);
    gbc.gridx = 3;
    gbc.gridy = 0;
    buttonPanel.add(fourButton, gbc);

    gbc.gridx = 1;
    gbc.gridy = yPos++;
    mainPanel.add(buttonPanel, gbc);

    twoBox = new JCheckBox("Use 2 top gray levels in green segmentation", true);
    twoBox.setForeground(Color.black);
    twoBox.setFont(serif12);
    gbc.gridx = 0;
    gbc.gridy = yPos++;
    mainPanel.add(twoBox, gbc);

    blueValueLabel =
        new JLabel("Fraction of blue transition from image min to max at nucleus boundary");
    blueValueLabel.setForeground(Color.black);
    blueValueLabel.setFont(serif12);
    gbc.gridx = 0;
    gbc.gridy = yPos;
    mainPanel.add(blueValueLabel, gbc);

    blueValueText = new JTextField(5);
    blueValueText.setText("0.15");
    blueValueText.setFont(serif12);
    gbc.gridx = 1;
    gbc.gridy = yPos++;
    mainPanel.add(blueValueText, gbc);

    blueSmoothBox = new JCheckBox("Smooth blue VOI contours with AlgorithmBSmooth", true);
    blueSmoothBox.setForeground(Color.black);
    blueSmoothBox.setFont(serif12);
    blueSmoothBox.addActionListener(this);
    gbc.gridx = 0;
    gbc.gridy = yPos++;
    mainPanel.add(blueSmoothBox, gbc);

    interpolationLabel = new JLabel("Number of interpolation points determined by divisor (> 1.0)");
    interpolationLabel.setForeground(Color.black);
    interpolationLabel.setFont(serif12);
    gbc.gridx = 0;
    gbc.gridy = yPos;
    mainPanel.add(interpolationLabel, gbc);

    interpolationText = new JTextField(5);
    interpolationText.setText("24.0");
    interpolationText.setFont(serif12);
    gbc.gridx = 1;
    gbc.gridy = yPos++;
    mainPanel.add(interpolationText, gbc);

    getContentPane().add(mainPanel, BorderLayout.CENTER);
    getContentPane().add(buildButtons(), BorderLayout.SOUTH);

    pack();
    setVisible(true);
    setResizable(false);
    System.gc();
  } // end init()
示例#26
0
  // create a new profile: read the script and possibly execute the queries,
  // save the stats (if 'import' == true, we assume the profile already exists
  // and don't run the queries)
  public void createWkld(String name, String scriptFile, boolean runQueries) {
    System.gc();
    Workload wkld = new Workload(name);

    if (showCmdsItem.getState()) {
      consoleFrame.echoCmd((!runQueries ? "importprof " : "newwkld ") + name + " " + scriptFile);
    }

    // construct the Workload object from the script;
    // first, check if the file exists
    try {
      FileReader reader = new FileReader(scriptFile);
      reader.close();
    } catch (FileNotFoundException e) {
      System.out.println("couldn't open " + scriptFile);
      return;
    } catch (IOException e) {
      System.out.println("couldn't close " + scriptFile);
    }

    // now, check if it contains only queries
    int scriptId = 0;
    try {
      scriptId = Libgist.openScript(scriptFile);
    } catch (LibgistException e) {
      System.out.println("couldn't open (C) " + scriptFile);
      return;
    }
    char[] arg1 = new char[64 * 1024];
    StringBuffer arg1Buf = new StringBuffer();
    char[] arg2 = new char[64 * 1024];
    StringBuffer arg2Buf = new StringBuffer();
    // for (;;) {
    // int cmd = Libgist.getCommand(scriptId, arg1, arg2);
    // if (cmd == Libgist.EOF) break;
    // if (cmd != Libgist.FETCH) {
    // there should only be queries
    // System.out.println("Script file contains non-SELECT command");
    // return;
    // }
    // }

    if (runQueries) {
      // turn profiling on and execute queries
      // Libgist.setProfilingEnabled(true);
      Libgist.disableBps(true); // we don't want to stop at breakpoints

      // rescan queries
      try {
        scriptId = Libgist.openScript(scriptFile);
      } catch (LibgistException e) {
        System.out.println("couldn't open (C) " + scriptFile);
        return;
      }
      int cnt = 1;
      // for (;;) {
      // int cmd = Libgist.getCommand(scriptId, arg1, arg2);
      // if (cmd == Libgist.EOF) break;
      // arg1Buf.setLength(0);
      // arg1Buf.append(arg1, 0, strlen(arg1));
      // arg2Buf.setLength(0);
      // arg2Buf.append(arg2, 0, strlen(arg2));
      // OpThread.execCmd(LibgistCommand.FETCH, arg1Buf.toString(),
      // arg2Buf.toString(), false);
      // System.out.print(cnt + " ");
      // System.out.println(cnt + ": execute " + arg2Buf.toString() + " "
      // + arg1Buf.toString());
      // cnt++;
      // }
      System.out.println();

      Libgist.disableBps(false);
      // compute optimal clustering and some more statistics
      // Libgist.computeMetrics(wkld.filename);
    }

    // save profile
    try {
      // we're saving Java and C++ data in separate files (filename and filename.prof)
      // the profile object only contains the filename, the queries will be
      // read in from the file when the profile is opened (faster that way)
      ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(wkld.filename));
      out.writeObject(wkld);
      out.close();
      System.out.println("copy query file");
      Runtime.getRuntime().exec("cp " + scriptFile + " " + wkld.filename + ".queries");
      System.out.println("saving tree and profile");
      Libgist.saveToFile(wkld.filename + ".idx");
      if (runQueries) {
        // Libgist.saveProfile(wkld.filename + ".prof");
      }
    } catch (Exception e) {
      System.out.println("Error saving profile: " + e);
      return;
    }

    if (runQueries) {
      // turn profiling off (after the metrics were computed and
      // the profile saved)
      // Libgist.setProfilingEnabled(false);
    }
  }
示例#27
0
  /**
   * This method represents the application code that we'd like to run on a separate thread. It
   * simulates slowly computing a value, in this case just a string 'All Done'. It updates the
   * progress bar every half second to remind the user that we're still busy.
   */
  public Object doWork() {
    try {
      this.optimizationParameters.saveInstance();
      if (this.show) {
        this.statusField.setText("Optimizing...");
      }

      RNG.setRandomSeed(optimizationParameters.getRandomSeed());
      // opening output file...
      if (!this.outputFileName.equalsIgnoreCase("none")) {
        String name = "";
        SimpleDateFormat formatter = new SimpleDateFormat("E'_'yyyy.MM.dd'_'HH.mm.ss");
        String startDate = formatter.format(new Date());
        name =
            this.outputPath
                + this.outputFileName
                + "_"
                + this.experimentName
                + "_"
                + startDate
                + ".dat";
        try {
          this.outputFile = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(name)));
        } catch (FileNotFoundException e) {
          System.out.println("Could not open output file! Filename: " + name);
        }
      } else {
        this.outputFile = null;
      }

      // initialize problem
      this.optimizationParameters.getProblem().initializeProblem();
      this.optimizationParameters
          .getOptimizer()
          .setProblem(this.optimizationParameters.getProblem());
      // int optimizer and population
      // this.optimizationParameters.getOptimizer().initialize();

      // initialize the log data
      ArrayList tmpMultiRun = new ArrayList();
      this.performedRuns.add(tmpMultiRun);

      // something to log file
      // if (outputFile != null)
      // this.writeToFile(this.optimizationParameters.getOptimizer().getStringRepresentation());
      // this.writeToFile("Here i'll write something characterizing the algorithm.");

      for (int j = 0; j < this.multiRuns; j++) {
        this.optimizationParameters
            .getProblem()
            .initializeProblem(); // in the loop as well, dynamic probs may need that (MK)
        this.tmpData = new ArrayList<>();
        this.currentRun = j;
        if (this.show) {
          this.statusField.setText(
              "Optimizing Run " + (j + 1) + " of " + this.multiRuns + " Multi Runs...");
        }
        if (Thread.interrupted()) {
          throw new InterruptedException();
        }
        // write header to file
        this.writeToFile(
            " FitnessCalls\t Best\t Mean\t Worst \t"
                + BeanInspector.toString(
                    this.optimizationParameters.getProblem().getAdditionalDataHeader(),
                    '\t',
                    false,
                    ""));
        if ((this.continueFlag) && (this.backupPopulation != null)) {
          this.recentFunctionCalls += this.backupPopulation.getFunctionCalls();
          this.optimizationParameters.getOptimizer().getProblem().initializeProblem();
          this.optimizationParameters.getOptimizer().addPopulationChangedEventListener(null);
          this.optimizationParameters.getOptimizer().setPopulation(this.backupPopulation);
          this.optimizationParameters
              .getOptimizer()
              .getProblem()
              .evaluate(this.optimizationParameters.getOptimizer().getPopulation());
          this.optimizationParameters
              .getOptimizer()
              .getProblem()
              .evaluate(this.optimizationParameters.getOptimizer().getPopulation().getArchive());
          this.optimizationParameters
              .getOptimizer()
              .initializeByPopulation(this.backupPopulation, false);
          this.optimizationParameters.getOptimizer().getPopulation().setFunctionCalls(0);
          this.optimizationParameters.addPopulationChangedEventListener(this);
        } else {
          this.recentFunctionCalls = 0;
          this.optimizationParameters.getOptimizer().initialize();
        }
        // while (this.optimizationParameters.getOptimizer().getPopulation().getFunctionCalls() <
        // this.functionCalls) {
        while (!this.optimizationParameters
            .getTerminator()
            .isTerminated(this.optimizationParameters.getOptimizer().getPopulation())) {
          // System.out.println("Simulated Function calls "+
          // this.optimizer.getPopulation().getFunctionCalls());
          if (Thread.interrupted()) {
            throw new InterruptedException();
          }
          optimizationParameters.getOptimizer().optimize();
        }
        System.gc();
        // @TODO if you want the final report include this
        // this.writeToFile(this.optimizationParameters.getProblem().getStringRepresentationForProblem(this.optimizationParameters.getOptimizer()));
        tmpMultiRun.add(this.tmpData);
      }
      if (this.show) {
        this.plot.setInfoString(this.currentExperiment, this.experimentName, 0.5f);
      }
      if (this.show) {
        this.draw();
      }
      this.experimentName =
          this.optimizationParameters.getOptimizer().getName() + "-" + this.performedRuns.size();
    } catch (InterruptedException e) {
      updateStatus(0);
      if (this.show) {
        this.statusField.setText("Interrupted...");
      }
      return "Interrupted";
    }
    if (this.outputFile != null) {
      try {
        this.outputFile.close();
      } catch (IOException e) {
        System.out.println("Failed to close output file!");
      }
    }
    if (this.show) {
      for (int i = 0; i < this.multiRuns; i++) {
        this.plot.clearGraph(1000 + i);
      }
    }
    updateStatus(0);
    if (this.show) {
      this.statusField.setText("Finished...");
    }
    return "All Done";
  }
示例#28
0
  /** Translation durchfuehren */
  public void process() {
    int i, j, k;
    int ch, len;
    float f1;
    double d1, d2, d3, d4, d5;
    long progOff, progLen, lo;

    // io
    AudioFile reInF = null;
    AudioFile imInF = null;
    AudioFile reOutF = null;
    AudioFile imOutF = null;
    AudioFileDescr reInStream = null;
    AudioFileDescr imInStream = null;
    AudioFileDescr reOutStream = null;
    AudioFileDescr imOutStream = null;
    FloatFile reFloatF[] = null;
    FloatFile imFloatF[] = null;
    File reTempFile[] = null;
    File imTempFile[] = null;
    int outChanNum;

    float[][] reInBuf; // [ch][i]
    float[][] imInBuf; // [ch][i]
    float[][] reOutBuf = null; // [ch][i]
    float[][] imOutBuf = null; // [ch][i]
    float[] convBuf1, convBuf2;
    boolean complex;

    PathField ggOutput;

    // Synthesize
    Param ampRef = new Param(1.0, Param.ABS_AMP); // transform-Referenz
    float gain; // gain abs amp
    float dryGain, wetGain;
    float inGain;
    float maxAmp = 0.0f;
    Param peakGain;

    int inLength, inOff;
    int pre;
    int post;
    int length;
    int framesRead, framesWritten, outLength;
    boolean polarIn, polarOut;

    // phase unwrapping
    double[] phi;
    int[] wrap;
    double[] carry;

    Param lenRef;

    topLevel:
    try {

      complex = pr.bool[PR_HASIMINPUT] || pr.bool[PR_HASIMOUTPUT];
      polarIn = pr.intg[PR_OPERATOR] == OP_POLAR2RECT;
      polarOut = pr.intg[PR_OPERATOR] == OP_RECT2POLAR;
      if ((polarIn || polarOut) && !complex) throw new IOException(ERR_NOTCOMPLEX);

      // ---- open input ----

      reInF = AudioFile.openAsRead(new File(pr.text[PR_REINPUTFILE]));
      reInStream = reInF.getDescr();
      inLength = (int) reInStream.length;
      reInBuf = new float[reInStream.channels][8192];
      imInBuf = new float[reInStream.channels][8192];

      if (pr.bool[PR_HASIMINPUT]) {
        imInF = AudioFile.openAsRead(new File(pr.text[PR_IMINPUTFILE]));
        imInStream = imInF.getDescr();
        if (imInStream.channels != reInStream.channels) throw new IOException(ERR_COMPLEX);
        inLength = (int) Math.min(inLength, imInStream.length);
      }

      lenRef = new Param(AudioFileDescr.samplesToMillis(reInStream, inLength), Param.ABS_MS);
      d1 =
          AudioFileDescr.millisToSamples(
              reInStream, (Param.transform(pr.para[PR_OFFSET], Param.ABS_MS, lenRef, null).value));
      j = (int) (d1 >= 0.0 ? (d1 + 0.5) : (d1 - 0.5)); // correct rounding for negative values!
      length =
          (int)
              (AudioFileDescr.millisToSamples(
                      reInStream,
                      (Param.transform(pr.para[PR_LENGTH], Param.ABS_MS, lenRef, null)).value)
                  + 0.5);

      // System.err.println( "offset = "+j );

      if (j >= 0) {
        inOff = Math.min(j, inLength);
        if (!pr.bool[PR_REVERSE]) {
          reInF.seekFrame(inOff);
          if (pr.bool[PR_HASIMINPUT]) {
            imInF.seekFrame(inOff);
          }
        }
        inLength -= inOff;
        pre = 0;
      } else {
        inOff = 0;
        pre = Math.min(-j, length);
      }
      inLength = Math.min(inLength, length - pre);
      post = length - pre - inLength;

      if (pr.bool[PR_REVERSE]) {
        i = pre;
        pre = post;
        post = i;
        inOff += inLength;
      }

      // .... check running ....
      if (!threadRunning) break topLevel;

      // for( op = 0; op < 2; op++ ) {
      // 	System.out.println( op +": pre "+pre[op]+" / len "+inLength[op]+" / post "+post[op] );
      // }
      // System.out.println( "tot "+length[0]);

      outLength = length;
      outChanNum = reInStream.channels;

      // ---- open output ----

      ggOutput = (PathField) gui.getItemObj(GG_REOUTPUTFILE);
      if (ggOutput == null) throw new IOException(ERR_MISSINGPROP);
      reOutStream = new AudioFileDescr(reInStream);
      ggOutput.fillStream(reOutStream);
      reOutStream.channels = outChanNum;
      // well, more sophisticated code would
      // move and truncate the markers...
      if ((pre == 0) /* && (post == 0) */) {
        reInF.readMarkers();
        reOutStream.setProperty(
            AudioFileDescr.KEY_MARKERS, reInStream.getProperty(AudioFileDescr.KEY_MARKERS));
      }
      reOutF = AudioFile.openAsWrite(reOutStream);
      reOutBuf = new float[outChanNum][8192];
      imOutBuf = new float[outChanNum][8192];

      if (pr.bool[PR_HASIMOUTPUT]) {
        imOutStream = new AudioFileDescr(reInStream);
        ggOutput.fillStream(imOutStream);
        imOutStream.channels = outChanNum;
        imOutStream.file = new File(pr.text[PR_IMOUTPUTFILE]);
        imOutF = AudioFile.openAsWrite(imOutStream);
      }
      // .... check running ....
      if (!threadRunning) break topLevel;

      // ---- Further inits ----

      phi = new double[outChanNum];
      wrap = new int[outChanNum];
      carry = new double[outChanNum];
      for (ch = 0; ch < outChanNum; ch++) {
        phi[ch] = 0.0;
        wrap[ch] = 0;
        carry[ch] = Double.NEGATIVE_INFINITY;
      }

      progOff = 0; // read, transform, write
      progLen = (long) outLength * 3;

      wetGain = (float) (Param.transform(pr.para[PR_WETMIX], Param.ABS_AMP, ampRef, null)).value;
      dryGain = (float) (Param.transform(pr.para[PR_DRYMIX], Param.ABS_AMP, ampRef, null)).value;
      if (pr.bool[PR_DRYINVERT]) {
        dryGain = -dryGain;
      }
      inGain = (float) (Param.transform(pr.para[PR_INPUTGAIN], Param.ABS_AMP, ampRef, null)).value;
      if (pr.bool[PR_INVERT]) {
        inGain = -inGain;
      }

      // normalization requires temp files
      if (pr.intg[PR_GAINTYPE] == GAIN_UNITY) {
        reTempFile = new File[outChanNum];
        reFloatF = new FloatFile[outChanNum];
        for (ch = 0;
            ch < outChanNum;
            ch++) { // first zero them because an exception might be thrown
          reTempFile[ch] = null;
          reFloatF[ch] = null;
        }
        for (ch = 0; ch < outChanNum; ch++) {
          reTempFile[ch] = IOUtil.createTempFile();
          reFloatF[ch] = new FloatFile(reTempFile[ch], GenericFile.MODE_OUTPUT);
        }
        if (pr.bool[PR_HASIMOUTPUT]) {
          imTempFile = new File[outChanNum];
          imFloatF = new FloatFile[outChanNum];
          for (ch = 0;
              ch < outChanNum;
              ch++) { // first zero them because an exception might be thrown
            imTempFile[ch] = null;
            imFloatF[ch] = null;
          }
          for (ch = 0; ch < outChanNum; ch++) {
            imTempFile[ch] = IOUtil.createTempFile();
            imFloatF[ch] = new FloatFile(imTempFile[ch], GenericFile.MODE_OUTPUT);
          }
        }
        progLen += outLength;
      } else {
        gain = (float) (Param.transform(pr.para[PR_GAIN], Param.ABS_AMP, ampRef, null)).value;
        wetGain *= gain;
        dryGain *= gain;
      }
      // .... check running ....
      if (!threadRunning) break topLevel;

      // ----==================== the real stuff ====================----

      framesRead = 0;
      framesWritten = 0;

      while (threadRunning && (framesWritten < outLength)) {
        // ---- choose chunk len ----
        len = Math.min(8192, outLength - framesWritten);
        if (pre > 0) {
          len = Math.min(len, pre);
        } else if (inLength > 0) {
          len = Math.min(len, inLength);
        } else {
          len = Math.min(len, post);
        }

        // ---- read input chunks ----
        if (pre > 0) {
          Util.clear(reInBuf);
          if (complex) {
            Util.clear(imInBuf);
          }
          pre -= len;
        } else if (inLength > 0) {
          if (pr.bool[PR_REVERSE]) { // ---- read reversed ----
            reInF.seekFrame(inOff - framesRead - len);
            reInF.readFrames(reInBuf, 0, len);
            for (ch = 0; ch < reInStream.channels; ch++) {
              convBuf1 = reInBuf[ch];
              for (i = 0, j = len - 1; i < j; i++, j--) {
                f1 = convBuf1[j];
                convBuf1[j] = convBuf1[i];
                convBuf1[i] = f1;
              }
            }
            if (pr.bool[PR_HASIMINPUT]) {
              imInF.seekFrame(inOff - framesRead - len);
              imInF.readFrames(imInBuf, 0, len);
              for (ch = 0; ch < imInStream.channels; ch++) {
                convBuf1 = imInBuf[ch];
                for (i = 0, j = len - 1; i < j; i++, j--) {
                  f1 = convBuf1[j];
                  convBuf1[j] = convBuf1[i];
                  convBuf1[i] = f1;
                }
              }
            } else if (complex) {
              Util.clear(imInBuf);
            }
          } else { // ---- read normal ----
            reInF.readFrames(reInBuf, 0, len);
            if (pr.bool[PR_HASIMINPUT]) {
              imInF.readFrames(imInBuf, 0, len);
            } else if (complex) {
              Util.clear(imInBuf);
            }
          }
          inLength -= len;
          framesRead += len;
        } else {
          Util.clear(reInBuf);
          if (complex) {
            Util.clear(imInBuf);
          }
          post -= len;
        }
        progOff += len;
        // .... progress ....
        setProgression((float) progOff / (float) progLen);
        // .... check running ....
        if (!threadRunning) break topLevel;

        // ---- save dry signal ----
        for (ch = 0; ch < outChanNum; ch++) {
          convBuf1 = reInBuf[ch];
          convBuf2 = reOutBuf[ch];
          for (i = 0; i < len; i++) {
            convBuf2[i] = convBuf1[i] * dryGain;
          }
          if (complex) {
            convBuf1 = imInBuf[ch];
            convBuf2 = imOutBuf[ch];
            for (i = 0; i < len; i++) {
              convBuf2[i] = convBuf1[i] * dryGain;
            }
          }
        }

        // ---- rectify + apply input gain ----
        for (ch = 0; ch < reInStream.channels; ch++) {
          convBuf1 = reInBuf[ch];
          convBuf2 = imInBuf[ch];
          // ---- rectify ----
          if (pr.bool[PR_RECTIFY]) {
            if (complex) {
              if (polarIn) {
                for (i = 0; i < len; i++) {
                  convBuf2[i] = 0.0f;
                }
              } else {
                for (i = 0; i < len; i++) {
                  d1 = convBuf1[i];
                  d2 = convBuf2[i];
                  convBuf1[i] = (float) Math.sqrt(d1 * d1 + d2 * d2);
                  convBuf2[i] = 0.0f;
                }
              }
            } else {
              for (i = 0; i < len; i++) {
                convBuf1[i] = Math.abs(convBuf1[i]);
              }
            }
          }
          // ---- apply input gain ----
          Util.mult(convBuf1, 0, len, inGain);
          if (complex & !polarIn) {
            Util.mult(convBuf2, 0, len, inGain);
          }
        }

        // ---- heart of the dragon ----
        for (ch = 0; ch < outChanNum; ch++) {
          convBuf1 = reInBuf[ch];
          convBuf2 = imInBuf[ch];

          switch (pr.intg[PR_OPERATOR]) {
            case OP_NONE: // ================ None ================
              for (i = 0; i < len; i++) {
                reOutBuf[ch][i] += wetGain * convBuf1[i];
              }
              if (complex) {
                for (i = 0; i < len; i++) {
                  imOutBuf[ch][i] += wetGain * convBuf2[i];
                }
              }
              break;

            case OP_SIN: // ================ Cosinus ================
              if (complex) {
                for (i = 0; i < len; i++) {
                  reOutBuf[ch][i] += wetGain * (float) Math.sin(convBuf1[i] * Math.PI);
                  imOutBuf[ch][i] += wetGain * (float) Math.sin(convBuf2[i] * Math.PI);
                }
              } else {
                for (i = 0; i < len; i++) {
                  reOutBuf[ch][i] += wetGain * (float) Math.sin(convBuf1[i] * Math.PI);
                }
              }
              break;

            case OP_SQR: // ================ Square ================
              if (complex) {
                for (i = 0; i < len; i++) {
                  reOutBuf[ch][i] +=
                      wetGain * (convBuf1[i] * convBuf1[i] - convBuf2[i] * convBuf2[i]);
                  imOutBuf[ch][i] -= wetGain * (convBuf1[i] * convBuf2[i] * 2);
                }
              } else {
                for (i = 0; i < len; i++) {
                  reOutBuf[ch][i] += wetGain * (convBuf1[i] * convBuf1[i]);
                }
              }
              break;

            case OP_SQRT: // ================ Square root ================
              if (complex) {
                d3 = phi[ch];
                k = wrap[ch];
                d4 = k * Constants.PI2;
                for (i = 0; i < len; i++) {
                  d1 =
                      wetGain
                          * Math.pow(convBuf1[i] * convBuf1[i] + convBuf2[i] * convBuf2[i], 0.25);
                  d2 = Math.atan2(convBuf2[i], convBuf1[i]);
                  if (d2 - d3 > Math.PI) {
                    k--;
                    d4 = k * Constants.PI2;
                  } else if (d3 - d2 > Math.PI) {
                    k++;
                    d4 = k * Constants.PI2;
                  }
                  d2 += d4;
                  d3 = d2;
                  d2 /= 2;
                  reOutBuf[ch][i] += (float) (d1 * Math.cos(d2));
                  imOutBuf[ch][i] += (float) (d1 * Math.sin(d2));
                }
                phi[ch] = d3;
                wrap[ch] = k;

              } else {
                for (i = 0; i < len; i++) {
                  f1 = convBuf1[i];
                  if (f1 > 0) {
                    reOutBuf[ch][i] += wetGain * (float) Math.sqrt(f1);
                  } // else undefiniert
                }
              }
              break;

            case OP_RECT2POLARW: // ================ Rect->Polar (wrapped) ================
              for (i = 0; i < len; i++) {
                d1 = wetGain * Math.sqrt(convBuf1[i] * convBuf1[i] + convBuf2[i] * convBuf2[i]);
                d2 = Math.atan2(convBuf2[i], convBuf1[i]);
                reOutBuf[ch][i] += (float) d1;
                imOutBuf[ch][i] += (float) d2;
              }
              break;

            case OP_RECT2POLAR: // ================ Rect->Polar ================
              d3 = phi[ch];
              k = wrap[ch];
              d4 = k * Constants.PI2;
              for (i = 0; i < len; i++) {
                d1 = wetGain * Math.sqrt(convBuf1[i] * convBuf1[i] + convBuf2[i] * convBuf2[i]);
                d2 = Math.atan2(convBuf2[i], convBuf1[i]);
                if (d2 - d3 > Math.PI) {
                  k--;
                  d4 = k * Constants.PI2;
                } else if (d3 - d2 > Math.PI) {
                  k++;
                  d4 = k * Constants.PI2;
                }
                d2 += d4;
                reOutBuf[ch][i] += (float) d1;
                imOutBuf[ch][i] += (float) d2;
                d3 = d2;
              }
              phi[ch] = d3;
              wrap[ch] = k;
              break;

            case OP_POLAR2RECT: // ================ Polar->Rect ================
              for (i = 0; i < len; i++) {
                f1 = wetGain * convBuf1[i];
                reOutBuf[ch][i] += f1 * (float) Math.cos(convBuf2[i]);
                imOutBuf[ch][i] += f1 * (float) Math.sin(convBuf2[i]);
              }
              break;

            case OP_LOG: // ================ Log ================
              if (complex) {
                d3 = phi[ch];
                k = wrap[ch];
                d4 = k * Constants.PI2;
                d5 = carry[ch];
                for (i = 0; i < len; i++) {
                  d1 = Math.sqrt(convBuf1[i] * convBuf1[i] + convBuf2[i] * convBuf2[i]);
                  d2 = Math.atan2(convBuf2[i], convBuf1[i]);
                  if (d2 - d3 > Math.PI) {
                    k--;
                    d4 = k * Constants.PI2;
                  } else if (d3 - d2 > Math.PI) {
                    k++;
                    d4 = k * Constants.PI2;
                  }
                  if (d1 > 0.0) {
                    d5 = Math.log(d1);
                  }
                  d2 += d4;
                  reOutBuf[ch][i] += (float) d5;
                  imOutBuf[ch][i] += (float) d2;
                  d3 = d2;
                }
                phi[ch] = d3;
                wrap[ch] = k;
                carry[ch] = d5;

              } else {
                for (i = 0; i < len; i++) {
                  f1 = convBuf1[i];
                  if (f1 > 0) {
                    reOutBuf[ch][i] += wetGain * (float) Math.log(f1);
                  } // else undefiniert
                }
              }
              break;

            case OP_EXP: // ================ Exp ================
              if (complex) {
                for (i = 0; i < len; i++) {
                  d1 = wetGain * Math.exp(convBuf1[i]);
                  reOutBuf[ch][i] += (float) (d1 * Math.cos(convBuf2[i]));
                  imOutBuf[ch][i] += (float) (d1 * Math.sin(convBuf2[i]));
                }
              } else {
                for (i = 0; i < len; i++) {
                  reOutBuf[ch][i] += wetGain * (float) Math.exp(convBuf1[i]);
                }
              }
              break;

            case OP_NOT: // ================ NOT ================
              for (i = 0; i < len; i++) {
                lo = ~((long) (convBuf1[i] * 2147483647.0));
                reOutBuf[ch][i] += wetGain * (float) ((lo & 0xFFFFFFFFL) / 2147483647.0);
              }
              if (complex) {
                for (i = 0; i < len; i++) {
                  lo = ~((long) (convBuf2[i] * 2147483647.0));
                  imOutBuf[ch][i] += wetGain * (float) ((lo & 0xFFFFFFFFL) / 2147483647.0);
                }
              }
              break;
          }
        } // for outChan
        progOff += len;
        // .... progress ....
        setProgression((float) progOff / (float) progLen);
        // .... check running ....
        if (!threadRunning) break topLevel;

        // ---- write output chunk ----
        if (reFloatF != null) {
          for (ch = 0; ch < outChanNum; ch++) {
            reFloatF[ch].writeFloats(reOutBuf[ch], 0, len);
            if (pr.bool[PR_HASIMOUTPUT]) {
              imFloatF[ch].writeFloats(imOutBuf[ch], 0, len);
            }
          }
        } else {
          reOutF.writeFrames(reOutBuf, 0, len);
          if (pr.bool[PR_HASIMOUTPUT]) {
            imOutF.writeFrames(imOutBuf, 0, len);
          }
        }
        // check max amp
        for (ch = 0; ch < outChanNum; ch++) {
          convBuf1 = reOutBuf[ch];
          for (i = 0; i < len; i++) {
            f1 = Math.abs(convBuf1[i]);
            if (f1 > maxAmp) {
              maxAmp = f1;
            }
          }
          if (pr.bool[PR_HASIMOUTPUT]) {
            convBuf1 = imOutBuf[ch];
            for (i = 0; i < len; i++) {
              f1 = Math.abs(convBuf1[i]);
              if (f1 > maxAmp) {
                maxAmp = f1;
              }
            }
          }
        }

        progOff += len;
        framesWritten += len;
        // .... progress ....
        setProgression((float) progOff / (float) progLen);
      } // while not framesWritten

      // ----==================== normalize output ====================----

      if (pr.intg[PR_GAINTYPE] == GAIN_UNITY) {
        peakGain = new Param(maxAmp, Param.ABS_AMP);
        gain =
            (float)
                (Param.transform(
                        pr.para[PR_GAIN],
                        Param.ABS_AMP,
                        new Param(1.0 / peakGain.value, peakGain.unit),
                        null))
                    .value;
        f1 = pr.bool[PR_HASIMOUTPUT] ? ((1.0f + getProgression()) / 2) : 1.0f;
        normalizeAudioFile(reFloatF, reOutF, reOutBuf, gain, f1);
        if (pr.bool[PR_HASIMOUTPUT]) {
          normalizeAudioFile(imFloatF, imOutF, imOutBuf, gain, 1.0f);
        }
        maxAmp *= gain;

        for (ch = 0; ch < outChanNum; ch++) {
          reFloatF[ch].cleanUp();
          reFloatF[ch] = null;
          reTempFile[ch].delete();
          reTempFile[ch] = null;
          if (pr.bool[PR_HASIMOUTPUT]) {
            imFloatF[ch].cleanUp();
            imFloatF[ch] = null;
            imTempFile[ch].delete();
            imTempFile[ch] = null;
          }
        }
      }
      // .... check running ....
      if (!threadRunning) break topLevel;

      // ---- Finish ----

      reOutF.close();
      reOutF = null;
      reOutStream = null;
      if (imOutF != null) {
        imOutF.close();
        imOutF = null;
        imOutStream = null;
      }
      reInF.close();
      reInF = null;
      reInStream = null;
      if (pr.bool[PR_HASIMINPUT]) {
        imInF.close();
        imInF = null;
        imInStream = null;
      }
      reOutBuf = null;
      imOutBuf = null;
      reInBuf = null;
      imInBuf = null;

      // inform about clipping/ low level
      handleClipping(maxAmp);
    } catch (IOException e1) {
      setError(e1);
    } catch (OutOfMemoryError e2) {
      reOutBuf = null;
      imOutBuf = null;
      reInBuf = null;
      imInBuf = null;
      convBuf1 = null;
      convBuf2 = null;
      System.gc();

      setError(new Exception(ERR_MEMORY));
    }

    // ---- cleanup (topLevel) ----
    convBuf1 = null;
    convBuf2 = null;

    if (reInF != null) {
      reInF.cleanUp();
      reInF = null;
    }
    if (imInF != null) {
      imInF.cleanUp();
      imInF = null;
    }
    if (reOutF != null) {
      reOutF.cleanUp();
      reOutF = null;
    }
    if (imOutF != null) {
      imOutF.cleanUp();
      imOutF = null;
    }
    if (reFloatF != null) {
      for (ch = 0; ch < reFloatF.length; ch++) {
        if (reFloatF[ch] != null) {
          reFloatF[ch].cleanUp();
          reFloatF[ch] = null;
        }
        if (reTempFile[ch] != null) {
          reTempFile[ch].delete();
          reTempFile[ch] = null;
        }
      }
    }
    if (imFloatF != null) {
      for (ch = 0; ch < imFloatF.length; ch++) {
        if (imFloatF[ch] != null) {
          imFloatF[ch].cleanUp();
          imFloatF[ch] = null;
        }
        if (imTempFile[ch] != null) {
          imTempFile[ch].delete();
          imTempFile[ch] = null;
        }
      }
    }
  } // process()
示例#29
0
  public GameServerStartup() throws Exception {
    long serverLoadStart = System.currentTimeMillis();

    gameServer = this;

    printSection("Database Engine");
    L2DatabaseFactory.getInstance();

    printSection("IDFactory Engine");
    IdFactory.getInstance();
    _log.log(Level.INFO, "IdFactory: Free ObjectID's remaining: " + IdFactory.getInstance().size());

    ThreadPoolManager.getInstance();

    printSection("Engines");
    ScriptsManager.getInstance();
    ServerPacketOpCodeManager.getInstance();

    printSection("World Engine");
    Colors.loadColors();
    GameTimeController.init();
    InstanceManager.getInstance();
    WorldManager.getInstance();
    MapRegionManager.getInstance();
    Announcements.getInstance();
    GlobalVariablesManager.getInstance();
    AccountShareDataTable.getInstance();
    DynamicSpawnData.getInstance();
    ResidenceFunctionData.getInstance();

    printSection("Skills Engine");
    BuffStackGroupData.getInstance();
    EnchantSkillGroupsTable.getInstance();
    SkillTable.getInstance().load(false);
    SkillTreesData.getInstance();

    printSection("Items Engine");
    ItemTable.getInstance().loadClient();
    ItemTable.getInstance().load(false);
    SummonItemsData.getInstance();
    EnchantBonusData.getInstance();
    BuyListData.getInstance();
    MultiSellData.getInstance();
    RecipeData.getInstance();
    // PrimeShopTable.getInstance(); TODO
    ArmorSetsTable.getInstance();
    FishData.getInstance();
    FishingRodsData.getInstance();
    EnchantItemData.getInstance();
    EnchantEffectTable.getInstance();
    CrystallizationData.getInstance();
    SoulCrystalData.getInstance();
    ShapeShiftingItemsData.getInstance();
    HennaTable.getInstance();
    HennaTreeTable.getInstance();
    AugmentationData.getInstance();
    ItemPriceData.getInstance();
    AbilityPointsData.getInstance();
    AlchemyDataTable.getInstance();

    printSection("Characters Engine");
    CharTemplateTable.getInstance();
    ClassTemplateTable.getInstance();
    CharNameTable.getInstance();
    ExperienceTable.getInstance();
    AdminTable.getInstance();
    RaidBossPointsManager.getInstance();
    RelationListManager.getInstance();
    PetDataTable.getInstance();
    CharSummonTable.getInstance();
    SummonPointsTable.getInstance();
    HitConditionBonus.getInstance();
    ObsceneFilterTable.getInstance();

    printSection("Clans Engine");
    ClanTable.getInstance();
    ClanTable.getInstance().restoreWars();
    ClanHallSiegeManager.getInstance();
    ClanHallManager.getInstance();
    AuctionManager.getInstance();

    printSection("Geodata Engine");
    GeoEngine.init();
    PathFinding.init();
    DoorGeoEngine.init();

    printSection("NPCs Engine");
    HerbDropTable.getInstance();
    NpcTable.getInstance();
    AutoChatDataTable.getInstance();
    NpcWalkerRoutesData.getInstance();
    WalkingManager.getInstance();
    ZoneManager.getInstance();
    StaticObjectsData.getInstance();
    ItemAuctionManager.getInstance();
    CastleManager.getInstance();
    FortManager.getInstance().init();
    SpawnTable.getInstance();
    AutoSpawnHandler.getInstance();
    HellboundManager.getInstance();
    RaidBossSpawnManager.getInstance();
    DayNightSpawnManager.getInstance().trim().notifyChangeMode();
    GrandBossManager.getInstance().initZones();
    FourSepulchersManager.getInstance().init();
    TeleportListTable.getInstance();
    BeautyShopData.getInstance();
    CustomDropListDataXml.getInstance();

    printSection("Residence Siege Engine");
    CastleSiegeManager.getInstance().getSieges();
    FortSpawnList.getInstance();
    FortSiegeManager.getInstance();
    CastleManorManager.getInstance();
    CastleMercTicketManager.getInstance();
    ManorData.getInstance();
    ResidenceSiegeMusicList.getInstance();

    printSection("Olympiad Engine");
    Olympiad.getInstance();
    HeroManager.getInstance();

    printSection("Cache Engine");
    CrestCache.getInstance();
    HtmCache.getInstance();

    PartyMatchWaitingList.getInstance();
    PartyMatchRoomList.getInstance();
    PetitionManager.getInstance();
    CursedWeaponsManager.getInstance();
    CommunityBuffTable.getInstance();
    CommunityTeleportData.getInstance();

    printSection("Mods Engine");
    PcCafePointsManager.getInstance();

    if (Config.MMO_TOP_MANAGER_ENABLED) {
      MMOTopManager.getInstance();
    }
    if (Config.L2_TOP_MANAGER_ENABLED) {
      L2TopManager.getInstance();
    }

    printSection("Handlers Engine");
    ActionHandler.getInstance();
    ActionShiftHandler.getInstance();
    AdminCommandHandler.getInstance();
    BypassCommandManager.getInstance();
    ChatCommandManager.getInstance();
    EffectHandler.getInstance();
    ItemHandler.getInstance();
    SkillHandler.getInstance();
    TargetHandler.getInstance();
    TransformHandler.getInstance();
    UserCommandManager.getInstance();
    VoicedHandlerManager.getInstance();

    printSection("Transformations Engine");
    TransformationManager.getInstance();
    TransformationManager.getInstance().report();

    printSection("Jump Engine");
    CharJumpRoutesTable.getInstance();

    printSection("Commission Engine");
    CommissionManager.getInstance();

    printSection("ClanSearch Engine");
    ClanSearchManager.getInstance();

    printSection("Awakening Engine");
    AwakeningManager.getInstance();

    printSection("World Statistics Engine");
    if (ConfigWorldStatistic.WORLD_STATISTIC_ENABLED) {
      WorldStatisticsManager.getInstance();
    } else {
      _log.log(Level.INFO, "World Statistic Engine Disabled");
    }

    printSection("Quests Engine");
    QuestManager.getInstance();
    DynamicQuestManager.getInstance();
    BoatManager.getInstance();
    AirShipManager.getInstance();
    ShuttleManager.getInstance();
    GraciaSeedsManager.getInstance();
    if (Config.ALLOW_WEDDING) {
      WeddingManager.getInstance();
    }
    AutoChatDataTable.getInstance().setAutoChatActive(true);

    printSection("Scripts Engine");
    ScriptsManager.getInstance().executeCoreScripts();

    TaskManager.getInstance();

    QuestManager.getInstance().report();

    if (Config.SAVE_DROPPED_ITEM) {
      ItemsOnGroundManager.getInstance();
    }

    if (Config.AUTODESTROY_ITEM_AFTER > 0 || Config.HERB_AUTO_DESTROY_TIME > 0) {
      ItemsOnGroundAutoDestroyManager.getInstance();
    }

    CastleManager.getInstance().spawnDoors();
    FortManager.getInstance().spawnDoors();

    if (Config.ALLOW_MAIL) {
      MailManager.getInstance();
    }

    MentorManager.getInstance();
    DuelManager.getInstance();

    Runtime.getRuntime().addShutdownHook(GameServerShutdown.getInstance());

    _log.log(Level.INFO, "IdFactory: Free ObjectID's remaining: " + IdFactory.getInstance().size());

    EventManager.getEventsInstances();

    KnownListUpdateTaskManager.getInstance();

    if ((Config.OFFLINE_TRADE_ENABLE || Config.OFFLINE_CRAFT_ENABLE) && Config.RESTORE_OFFLINERS) {
      OfflineTradersTable.restoreOfflineTraders();
    }

    if (Config.DEADLOCK_DETECTOR) {
      _deadDetectThread = new DeadLockDetector();
      _deadDetectThread.setDaemon(true);
      _deadDetectThread.start();
    } else {
      _deadDetectThread = null;
    }

    printSection("Finalization");
    System.runFinalization();
    System.gc();
    Util.printMemoryInfo();
    Util.printCpuInfo();
    Util.printOSInfo();
    Toolkit.getDefaultToolkit().beep();

    printSection("Server Thread");
    LoginServerThread.getInstance().start();

    SelectorConfig sc = new SelectorConfig();
    sc.MAX_READ_PER_PASS = Config.MMO_MAX_READ_PER_PASS;
    sc.MAX_SEND_PER_PASS = Config.MMO_MAX_SEND_PER_PASS;
    sc.SLEEP_TIME = Config.MMO_SELECTOR_SLEEP_TIME;
    sc.HELPER_BUFFER_COUNT = Config.MMO_HELPER_BUFFER_COUNT;
    sc.TCP_NODELAY = Config.MMO_TCP_NODELAY;

    _gamePacketHandler = new L2GamePacketHandler();
    _selectorThread =
        new SelectorThread<>(
            sc, _gamePacketHandler, _gamePacketHandler, _gamePacketHandler, new IPv4Filter());

    InetAddress bindAddress = null;
    if (!Config.GAMESERVER_HOSTNAME.equals("*")) {
      try {
        bindAddress = InetAddress.getByName(Config.GAMESERVER_HOSTNAME);
      } catch (UnknownHostException e1) {
        _log.log(
            Level.ERROR,
            "GameServerStartup: The GameServer bind address is invalid, using all avaliable IPs. Reason: "
                + e1.getMessage(),
            e1);
      }
    }

    try {
      _selectorThread.openServerSocket(bindAddress, Config.PORT_GAME);
    } catch (IOException e) {
      _log.log(
          Level.FATAL,
          "GameServerStartup:: Failed to open server socket. Reason: " + e.getMessage(),
          e);
      System.exit(1);
    }
    _selectorThread.start();
    _log.log(Level.INFO, "Maximum Numbers of Connected Players: " + Config.MAXIMUM_ONLINE_USERS);
    long serverLoadEnd = System.currentTimeMillis();
    _log.log(
        Level.INFO, "Server Loaded in " + (serverLoadEnd - serverLoadStart) / 1000L + " seconds");

    AutoAnnounceTaskManager.getInstance();

    XMLRPCServer.getInstance();
  }
示例#30
0
  protected void process() {
    int i, j, ch, len, off, chunkLength;
    long progOff, progLen;
    float f1, f2;
    double d1;
    boolean extraAudioFile;

    // io
    AudioFile inF = null;
    AudioFile outF = null;
    AudioFile envInF = null;
    AudioFile envOutF = null;
    AudioFileDescr inStream = null;
    AudioFileDescr outStream = null;
    AudioFileDescr envInStream = null;
    AudioFileDescr envOutStream = null;
    FloatFile[] outFloatF = null;
    FloatFile[] envFloatF = null;
    File outTempFile[] = null;
    File envTempFile[] = null;
    int inChanNum, outChanNum, envInChanNum, envOutChanNum, shapeChanNum;

    int[][] shapeChan = null;
    int[][] inChan = null;
    float[][] shapeChanWeight = null;
    float[][] inChanWeight = null;

    // buffers
    float[][] inBuf = null; // Sound-In
    float[][] outBuf = null; // Sound-Out
    float[][] inEnvBuf = null; // Envelope of Input
    float[][] shapeEnvBuf = null; // Envelope of Shaper
    float[][] envInBuf = null; // Direct-In of Shaper-File
    float[] convBuf1, convBuf2;

    int inLength, outLength, envInLength, envOutLength;
    int framesRead, framesWritten; // re sound-files
    int framesRead2, framesWritten2; // re env-files

    Param ampRef = new Param(1.0, Param.ABS_AMP); // transform-Referenz
    Param peakGain;
    float gain = 1.0f; // gain abs amp
    float envGain = 1.0f; // gain abs amp
    float maxAmp = 0.0f;
    float envMaxAmp = 0.0f;

    float maxChange;
    int average, avrOff;

    double[] inEnergy, envInEnergy;

    PathField ggOutput;

    topLevel:
    try {

      // ---- open input, output; init ----

      // input
      inF = AudioFile.openAsRead(new File(pr.text[PR_INPUTFILE]));
      inStream = inF.getDescr();
      inChanNum = inStream.channels;
      inLength = (int) inStream.length;
      // this helps to prevent errors from empty files!
      if ((inLength < 1) || (inChanNum < 1)) throw new EOFException(ERR_EMPTY);
      // .... check running ....
      if (!threadRunning) break topLevel;

      envInLength = 0;
      envInChanNum = inChanNum;
      shapeChanNum = 0;

      // shape input
      switch (pr.intg[PR_ENVSOURCE]) {
        case SRC_SOUNDFILE:
        case SRC_ENVFILE:
          envInF = AudioFile.openAsRead(new File(pr.text[PR_ENVINFILE]));
          envInStream = envInF.getDescr();
          envInChanNum = envInStream.channels;
          shapeChanNum = envInChanNum;
          envInLength = (int) envInStream.length;
          // this helps to prevent errors from empty files!
          if ((envInLength < 1) || (envInChanNum < 1)) throw new EOFException(ERR_EMPTY);

          i = Math.min(inLength, envInLength);
          inLength = i;
          envInLength = i;
          break;

        case SRC_ENV:
          if (pr.bool[PR_RIGHTCHAN]) {
            shapeChanNum = 2;
            envInChanNum = Math.max(envInChanNum, shapeChanNum); // ggf. mono => stereo
          } else {
            shapeChanNum = 1;
          }
          break;

        case SRC_INPUT:
          shapeChanNum = inChanNum;
          break;
      }
      // .... check running ....
      if (!threadRunning) break topLevel;

      outChanNum = Math.max(inChanNum, envInChanNum);
      outLength = inLength;

      shapeChan = new int[outChanNum][2];
      shapeChanWeight = new float[outChanNum][2];
      inChan = new int[outChanNum][2];
      inChanWeight = new float[outChanNum][2];
      extraAudioFile =
          (envInF != null) && (pr.intg[PR_ENVSOURCE] == SRC_SOUNDFILE); // not if SRC_ENVFILE!!!

      // calc weights
      for (ch = 0; ch < outChanNum; ch++) {
        if (shapeChanNum == 1) {
          shapeChan[ch][0] = 0;
          shapeChan[ch][1] = 0;
          shapeChanWeight[ch][0] = 1.0f;
          shapeChanWeight[ch][1] = 0.0f;
        } else {
          f1 = ((float) ch / (float) (outChanNum - 1)) * (float) (shapeChanNum - 1);
          shapeChan[ch][0] = (int) f1; // Math.max verhindert ArrayIndex-Fehler
          shapeChan[ch][1] = Math.min((int) f1 + 1, shapeChanNum - 1); // (Weight ist dabei eh Null)
          f1 %= 1.0f;
          shapeChanWeight[ch][0] = 1.0f - f1;
          shapeChanWeight[ch][1] = f1;
        }
        if (inChanNum == 1) {
          inChan[ch][0] = 0;
          inChan[ch][1] = 0;
          inChanWeight[ch][0] = 1.0f;
          inChanWeight[ch][1] = 0.0f;
        } else {
          f1 = ((float) ch / (float) (outChanNum - 1)) * (float) (inChanNum - 1);
          inChan[ch][0] = (int) f1;
          inChan[ch][1] = Math.min((int) f1 + 1, inChanNum - 1);
          f1 %= 1.0f;
          inChanWeight[ch][0] = 1.0f - f1;
          inChanWeight[ch][1] = f1;
        }
        /*
        for( i = 0; i < 2; i++ ) {
        	System.out.println( "shapeChan["+ch+"]["+i+"] = "+shapeChan[ch][i] );
        	System.out.println( "shapeWeig["+ch+"]["+i+"] = "+shapeChanWeight[ch][i] );
        	System.out.println( "inputChan["+ch+"]["+i+"] = "+inChan[ch][i] );
        	System.out.println( "inputWeig["+ch+"]["+i+"] = "+inChanWeight[ch][i] );
        }
        */
      }

      // output
      ggOutput = (PathField) gui.getItemObj(GG_OUTPUTFILE);
      if (ggOutput == null) throw new IOException(ERR_MISSINGPROP);
      outStream = new AudioFileDescr(inStream);
      ggOutput.fillStream(outStream);
      outStream.channels = outChanNum;
      outF = AudioFile.openAsWrite(outStream);
      // .... check running ....
      if (!threadRunning) break topLevel;

      envOutLength = 0;
      envOutChanNum = 0;

      // envelope output
      if (pr.bool[PR_ENVOUTPUT]) {
        ggOutput = (PathField) gui.getItemObj(GG_ENVOUTFILE);
        if (ggOutput == null) throw new IOException(ERR_MISSINGPROP);
        envOutStream = new AudioFileDescr(inStream);
        ggOutput.fillStream(envOutStream);
        envOutStream.file = new File(pr.text[PR_ENVOUTFILE]);
        envOutF = AudioFile.openAsWrite(envOutStream);
        envOutLength = inLength;
        envOutChanNum = inChanNum;
      }
      // .... check running ....
      if (!threadRunning) break topLevel;

      // average buffer size
      d1 =
          Param.transform(
                  pr.para[PR_AVERAGE],
                  Param.ABS_MS,
                  new Param(AudioFileDescr.samplesToMillis(inStream, inLength), Param.ABS_MS),
                  null)
              .val; // average in millis
      average = ((int) (AudioFileDescr.millisToSamples(inStream, d1) + 0.5) & ~1) + 1; // always odd
      avrOff = (average >> 1) + 1; // first element needed for subtraction (see calcEnv())

      progOff = 0;
      progLen =
          (long) Math.max(average - avrOff, inLength)
              + (long) (extraAudioFile ? Math.max(average - avrOff, envInLength) : envInLength)
              + (long) outLength
              + (long) envOutLength;

      // normalization requires temp files
      if (pr.intg[PR_GAINTYPE] == GAIN_UNITY) {
        outTempFile = new File[outChanNum];
        outFloatF = new FloatFile[outChanNum];
        for (ch = 0;
            ch < outChanNum;
            ch++) { // first zero them because an exception might be thrown
          outTempFile[ch] = null;
          outFloatF[ch] = null;
        }
        for (ch = 0; ch < outChanNum; ch++) {
          outTempFile[ch] = IOUtil.createTempFile();
          outFloatF[ch] = new FloatFile(outTempFile[ch], GenericFile.MODE_OUTPUT);
        }
        progLen += (long) outLength;
      } else {
        gain = (float) (Param.transform(pr.para[PR_GAIN], Param.ABS_AMP, ampRef, null)).val;
      }
      // .... check running ....
      if (!threadRunning) break topLevel;

      // normalization requires temp files
      if (pr.intg[PR_ENVGAINTYPE] == GAIN_UNITY) {
        envTempFile = new File[envOutChanNum];
        envFloatF = new FloatFile[envOutChanNum];
        for (ch = 0;
            ch < envOutChanNum;
            ch++) { // first zero them because an exception might be thrown
          envTempFile[ch] = null;
          envFloatF[ch] = null;
        }
        for (ch = 0; ch < envOutChanNum; ch++) {
          envTempFile[ch] = IOUtil.createTempFile();
          envFloatF[ch] = new FloatFile(envTempFile[ch], GenericFile.MODE_OUTPUT);
        }
        progLen += (long) envOutLength;
      } else {
        envGain = (float) (Param.transform(pr.para[PR_ENVGAIN], Param.ABS_AMP, ampRef, null)).val;
      }
      // .... check running ....
      if (!threadRunning) break topLevel;

      // ---- further inits ----
      maxChange = (float) (Param.transform(pr.para[PR_MAXCHANGE], Param.ABS_AMP, ampRef, null)).val;

      inBuf = new float[inChanNum][8192 + average];
      Util.clear(inBuf);
      outBuf = new float[outChanNum][8192];
      Util.clear(outBuf);
      if (extraAudioFile) {
        envInBuf = new float[envInChanNum][8192 + average];
        Util.clear(envInBuf);
      }
      inEnvBuf = new float[inChanNum][8192]; // = envOutBuf
      Util.clear(inEnvBuf);
      shapeEnvBuf = new float[envInChanNum][8192];
      Util.clear(shapeEnvBuf);

      inEnergy = new double[inChanNum];
      for (ch = 0; ch < inChanNum; ch++) {
        inEnergy[ch] = 0.0;
      }
      envInEnergy = new double[envInChanNum];
      for (ch = 0; ch < envInChanNum; ch++) {
        envInEnergy[ch] = 0.0;
      }

      // System.out.println( "inLength "+inLength+"; envInLength "+envInLength+"; envOutLength
      // "+envOutLength+"; outLength "+outLength );
      // System.out.println( "average "+average+"; avrOff "+avrOff );

      // ----==================== buffer init ====================----

      framesRead = 0; // re inF
      framesRead2 = 0; // re envInF

      // ---- init buffers ----
      for (off = avrOff; threadRunning && (off < average); ) {
        len = Math.min(inLength - framesRead, Math.min(8192, average - off));
        if (len == 0) break;

        inF.readFrames(inBuf, off, len);
        // calc initial energy per channel (see calcEnv())
        for (ch = 0; ch < inChanNum; ch++) {
          convBuf1 = inBuf[ch];
          d1 = 0.0;
          for (i = 0, j = off; i < len; i++) {
            f1 = convBuf1[j++];
            d1 += f1 * f1;
          }
          inEnergy[ch] += d1;
        }
        framesRead += len;
        off += len;
        progOff += len;
        // .... progress ....
        setProgression((float) progOff / (float) progLen);
      }
      // zero padding bereits durch initialisierung mit Util.clear() passiert!

      if (extraAudioFile) {
        for (off = avrOff; threadRunning && (off < average); ) {
          len = Math.min(envInLength - framesRead2, Math.min(8192, average - off));
          if (len == 0) break;

          envInF.readFrames(envInBuf, off, len);
          // calc initial energy per channel (see calcEnv())
          for (ch = 0; ch < envInChanNum; ch++) {
            convBuf1 = envInBuf[ch];
            d1 = 0.0;
            for (i = 0, j = off; i < len; i++) {
              f1 = convBuf1[j++];
              d1 += f1 * f1;
            }
            envInEnergy[ch] += d1;
          }
          framesRead2 += len;
          off += len;
          progOff += len;
          // .... progress ....
          setProgression((float) progOff / (float) progLen);
        }
        // zero padding bereits durch initialisierung mit Util.clear() passiert!
      }
      // .... check running ....
      if (!threadRunning) break topLevel;

      // ----==================== the real stuff ====================----

      framesWritten = 0; // re OutF
      framesWritten2 = 0; // re envOutF

      while (threadRunning && (framesWritten < outLength)) {

        chunkLength = Math.min(8192, outLength - framesWritten);
        // ---- read input chunk ----
        len = Math.min(inLength - framesRead, chunkLength);
        inF.readFrames(inBuf, average, len);
        // zero padding
        for (ch = 0; ch < inChanNum; ch++) {
          convBuf1 = inBuf[ch];
          for (i = len, j = len + average; i < chunkLength; i++) {
            convBuf1[j++] = 0.0f;
          }
        }
        framesRead += len;
        progOff += len;
        // .... progress ....
        setProgression((float) progOff / (float) progLen);
        // .... check running ....
        if (!threadRunning) break topLevel;

        // ---- read input env chunk ----
        if (envInF != null) {
          len = Math.min(envInLength - framesRead2, chunkLength);
          if (extraAudioFile) { // ........ needs averaging ........
            envInF.readFrames(envInBuf, average, len);
            // zero padding
            for (ch = 0; ch < envInChanNum; ch++) {
              convBuf1 = envInBuf[ch];
              for (i = len, j = len + average; i < chunkLength; i++) {
                convBuf1[j++] = 0.0f;
              }
            }
          } else { // ........ is already env ........
            envInF.readFrames(shapeEnvBuf, 0, len);
            // zero padding
            for (ch = 0; ch < envInChanNum; ch++) {
              convBuf1 = shapeEnvBuf[ch];
              for (i = len; i < chunkLength; i++) {
                convBuf1[i] = 0.0f;
              }
            }
          }
          framesRead2 += len;
          progOff += len;
          // .... progress ....
          setProgression((float) progOff / (float) progLen);
        }
        // .... check running ....
        if (!threadRunning) break topLevel;

        // ---- calc input envelope ----
        for (ch = 0; ch < inChanNum; ch++) {
          inEnergy[ch] = calcEnv(inBuf[ch], inEnvBuf[ch], average, chunkLength, inEnergy[ch]);
        }

        // ---- write output env file ----
        if (pr.bool[PR_ENVOUTPUT]) {
          if (envFloatF != null) { // i.e. unity gain
            for (ch = 0; ch < envOutChanNum; ch++) {
              convBuf1 = inEnvBuf[ch];
              for (i = 0; i < chunkLength; i++) { // measure max amp
                f1 = Math.abs(convBuf1[i]);
                if (f1 > envMaxAmp) {
                  envMaxAmp = f1;
                }
              }
              envFloatF[ch].writeFloats(convBuf1, 0, chunkLength);
            }
          } else { // i.e. abs gain
            for (ch = 0; ch < envOutChanNum; ch++) {
              convBuf1 = inEnvBuf[ch];
              for (i = 0; i < chunkLength; i++) { // measure max amp + adjust gain
                f1 = Math.abs(convBuf1[i]);
                convBuf1[i] *= envGain;
                if (f1 > envMaxAmp) {
                  envMaxAmp = f1;
                }
              }
            }
            envOutF.writeFrames(inEnvBuf, 0, chunkLength);
          }
          framesWritten2 += chunkLength;
          progOff += chunkLength;
          // .... progress ....
          setProgression((float) progOff / (float) progLen);
        }
        // .... check running ....
        if (!threadRunning) break topLevel;

        // ---- calc shape envelope ----
        switch (pr.intg[PR_ENVSOURCE]) {
          case SRC_INPUT: // shape env = input env
            for (ch = 0; ch < inChanNum; ch++) {
              System.arraycopy(inEnvBuf[ch], 0, shapeEnvBuf[ch], 0, chunkLength);
            }
            break;
          case SRC_SOUNDFILE: // calc shape env from envInBuf
            for (ch = 0; ch < envInChanNum; ch++) {
              envInEnergy[ch] =
                  calcEnv(envInBuf[ch], shapeEnvBuf[ch], average, chunkLength, envInEnergy[ch]);
            }
            break;
          case SRC_ENVFILE: // nothing to do, we have already loaded the env
            break; //    in the correct buffer
          case SRC_ENV:
            throw new IOException("Graphic env not yet supported");
        }

        // ---- calc output ----
        // first generate output envelope
        switch (pr.intg[PR_MODE]) {
          case MODE_SUPERPOSE:
            if (!pr.bool[PR_INVERT]) { // multiply by shape
              for (ch = 0; ch < outChanNum; ch++) {
                convBuf1 = outBuf[ch];
                for (i = 0; i < chunkLength; i++) {
                  f1 =
                      shapeEnvBuf[shapeChan[ch][0]][i] * shapeChanWeight[ch][0]
                          + shapeEnvBuf[shapeChan[ch][1]][i] * shapeChanWeight[ch][1];
                  convBuf1[i] = Math.min(maxChange, f1);
                }
              }

            } else { // divide by shape
              for (ch = 0; ch < outChanNum; ch++) {
                convBuf1 = outBuf[ch];
                for (i = 0; i < chunkLength; i++) {
                  f1 =
                      shapeEnvBuf[shapeChan[ch][0]][i] * shapeChanWeight[ch][0]
                          + shapeEnvBuf[shapeChan[ch][1]][i] * shapeChanWeight[ch][1];
                  if (f1 > 0.0f) {
                    convBuf1[i] = Math.min(maxChange, 1.0f / f1);
                  } else {
                    convBuf1[i] = maxChange;
                  }
                }
              }
            }
            break;

          case MODE_REPLACE:
            if (!pr.bool[PR_INVERT]) { // shape / input
              for (ch = 0; ch < outChanNum; ch++) {
                convBuf1 = outBuf[ch];
                for (i = 0; i < chunkLength; i++) {
                  f1 =
                      shapeEnvBuf[shapeChan[ch][0]][i] * shapeChanWeight[ch][0]
                          + shapeEnvBuf[shapeChan[ch][1]][i] * shapeChanWeight[ch][1];
                  f2 =
                      inEnvBuf[inChan[ch][0]][i] * inChanWeight[ch][0]
                          + inEnvBuf[inChan[ch][1]][i] * inChanWeight[ch][1];
                  if (f2 > 0.0f) {
                    convBuf1[i] = Math.min(maxChange, f1 / f2);
                  } else {
                    convBuf1[i] = 0.0f; // input ist eh ueberall null, somit unveraenderlich
                  }
                }
              }

            } else { // 1 / (shape * input)
              for (ch = 0; ch < outChanNum; ch++) {
                convBuf1 = outBuf[ch];
                for (i = 0; i < chunkLength; i++) {
                  f1 =
                      shapeEnvBuf[shapeChan[ch][0]][i] * shapeChanWeight[ch][0]
                          + shapeEnvBuf[shapeChan[ch][1]][i] * shapeChanWeight[ch][1];
                  f1 *=
                      inEnvBuf[inChan[ch][0]][i] * inChanWeight[ch][0]
                          + inEnvBuf[inChan[ch][1]][i] * inChanWeight[ch][1];
                  if (f1 > 0.0f) {
                    convBuf1[i] = Math.min(maxChange, 1.0f / f1);
                  } else {
                    convBuf1[i] = maxChange;
                  }
                }
              }
            }
            break;
        }
        // then multiply input bites
        if (inChanNum == outChanNum) { // no weighting - use faster routine
          for (ch = 0; ch < outChanNum; ch++) {
            convBuf1 = outBuf[ch];
            convBuf2 = inBuf[ch];
            for (i = 0, j = avrOff; i < chunkLength; i++, j++) {
              convBuf1[i] *= convBuf2[j];
            }
          }
        } else {
          for (ch = 0; ch < outChanNum; ch++) {
            convBuf1 = outBuf[ch];
            for (i = 0, j = avrOff; i < chunkLength; i++, j++) {
              f1 =
                  inBuf[inChan[ch][0]][j] * inChanWeight[ch][0]
                      + inBuf[inChan[ch][1]][j] * inChanWeight[ch][1];
              convBuf1[i] *= f1;
            }
          }
        }

        // ---- write output sound file ----
        if (outFloatF != null) { // i.e. unity gain
          for (ch = 0; ch < outChanNum; ch++) {
            convBuf1 = outBuf[ch];
            for (i = 0; i < chunkLength; i++) { // measure max amp
              f1 = Math.abs(convBuf1[i]);
              if (f1 > maxAmp) {
                maxAmp = f1;
              }
            }
            outFloatF[ch].writeFloats(convBuf1, 0, chunkLength);
          }
        } else { // i.e. abs gain
          for (ch = 0; ch < outChanNum; ch++) {
            convBuf1 = outBuf[ch];
            for (i = 0; i < chunkLength; i++) { // measure max amp + adjust gain
              f1 = Math.abs(convBuf1[i]);
              convBuf1[i] *= gain;
              if (f1 > maxAmp) {
                maxAmp = f1;
              }
            }
          }
          outF.writeFrames(outBuf, 0, chunkLength);
        }
        framesWritten += chunkLength;
        progOff += chunkLength;
        // .... progress ....
        setProgression((float) progOff / (float) progLen);

        // ---- shift buffers ----
        for (ch = 0;
            ch < inChanNum;
            ch++) { // zero padding is performed after AudioFile.readFrames()!
          System.arraycopy(inBuf[ch], chunkLength, inBuf[ch], 0, average);
        }
        if (extraAudioFile) {
          for (ch = 0;
              ch < envInChanNum;
              ch++) { // zero padding is performed after AudioFile.readFrames()!
            System.arraycopy(envInBuf[ch], chunkLength, envInBuf[ch], 0, average);
          }
        }
      } // until framesWritten == outLength
      // .... check running ....
      if (!threadRunning) break topLevel;

      // ---- normalize output ----

      // sound file
      if (pr.intg[PR_GAINTYPE] == GAIN_UNITY) {
        peakGain = new Param((double) maxAmp, Param.ABS_AMP);
        gain =
            (float)
                (Param.transform(
                        pr.para[PR_GAIN],
                        Param.ABS_AMP,
                        new Param(1.0 / peakGain.val, peakGain.unit),
                        null))
                    .val;
        f1 = 1.0f;
        if ((envOutF != null) && (pr.intg[PR_ENVGAINTYPE] == GAIN_UNITY)) { // leave prog space
          f1 = (1.0f + getProgression()) / 2;
        }
        normalizeAudioFile(outFloatF, outF, outBuf, gain, f1);
        for (ch = 0; ch < outChanNum; ch++) {
          outFloatF[ch].cleanUp();
          outFloatF[ch] = null;
          outTempFile[ch].delete();
          outTempFile[ch] = null;
        }
      }
      // .... check running ....
      if (!threadRunning) break topLevel;

      // envelope file
      if ((envOutF != null) && (pr.intg[PR_ENVGAINTYPE] == GAIN_UNITY)) {
        peakGain = new Param((double) envMaxAmp, Param.ABS_AMP);
        envGain =
            (float)
                (Param.transform(
                        pr.para[PR_ENVGAIN],
                        Param.ABS_AMP,
                        new Param(1.0 / peakGain.val, peakGain.unit),
                        null))
                    .val;

        normalizeAudioFile(envFloatF, envOutF, inEnvBuf, envGain, 1.0f);
        for (ch = 0; ch < envOutChanNum; ch++) {
          envFloatF[ch].cleanUp();
          envFloatF[ch] = null;
          envTempFile[ch].delete();
          envTempFile[ch] = null;
        }
      }
      // .... check running ....
      if (!threadRunning) break topLevel;

      // ---- Finish ----

      outF.close();
      outF = null;
      outStream = null;
      if (envOutF != null) {
        envOutF.close();
        envOutF = null;
        envOutStream = null;
      }
      if (envInF != null) {
        envInF.close();
        envInF = null;
        envInStream = null;
      }
      inF.close();
      inF = null;
      inStream = null;
      outBuf = null;
      inBuf = null;
      inEnvBuf = null;
      envInBuf = null;
      shapeEnvBuf = null;

      // inform about clipping/ low level
      maxAmp *= gain;
      handleClipping(maxAmp);
      envMaxAmp *= envGain;
      //			handleClipping( envMaxAmp );	// ;( routine nicht flexibel genug!

    } catch (IOException e1) {
      setError(e1);
    } catch (OutOfMemoryError e2) {
      inStream = null;
      outStream = null;
      envInStream = null;
      envOutStream = null;
      inBuf = null;
      outBuf = null;
      inEnvBuf = null;
      envInBuf = null;
      shapeEnvBuf = null;
      convBuf1 = null;
      convBuf2 = null;
      System.gc();

      setError(new Exception(ERR_MEMORY));
      ;
    }

    // ---- cleanup (topLevel) ----
    if (inF != null) {
      inF.cleanUp();
      inF = null;
    }
    if (outF != null) {
      outF.cleanUp();
      outF = null;
    }
    if (envInF != null) {
      envInF.cleanUp();
      envInF = null;
    }
    if (envOutF != null) {
      envOutF.cleanUp();
      envOutF = null;
    }
    if (outFloatF != null) {
      for (ch = 0; ch < outFloatF.length; ch++) {
        if (outFloatF[ch] != null) outFloatF[ch].cleanUp();
        if (outTempFile[ch] != null) outTempFile[ch].delete();
      }
    }
    if (envFloatF != null) {
      for (ch = 0; ch < envFloatF.length; ch++) {
        if (envFloatF[ch] != null) envFloatF[ch].cleanUp();
        if (envTempFile[ch] != null) envTempFile[ch].delete();
      }
    }
  } // process()