Esempio n. 1
0
 public void disconnect(String name, I_InfoPlayer player) {
   InfoGame tmpGame = game;
   I_InfoPlayer tmpPlayer = player;
   try {
     Naming.unbind("rmi://" + serverInfo.getIpAddr() + ":1099/I_InfoGame");
     Naming.unbind("rmi://" + serverInfo.getIpAddr() + ":1099/" + name);
   } catch (Exception e) {
     System.out.println("Failed unbind");
     System.exit(128);
   }
   game = null;
   player = null;
   System.gc();
   System.out.println("Disconnected");
   ServerTimer timer = new ServerTimer(5);
   Thread thread = new Thread(timer);
   thread.start();
   while (!timer.finished()) ;
   timer.shutDown();
   timer = null;
   System.gc();
   game = tmpGame;
   player = tmpPlayer;
   try {
     Naming.rebind("rmi://" + serverAddress + ":1099/I_InfoGame", game);
     Naming.rebind("rmi://" + serverAddress + ":1099/" + name, player);
   } catch (Exception e) {
     System.out.println("Failed rebind");
     System.exit(128);
   }
   System.out.println("Reconnected");
 }
Esempio n. 2
0
 private static void unloadPlugin(String name) {
   loadedPlugins.get(name).unload();
   loadedPlugins.remove(name);
   System.gc();
   System.gc();
   System.gc();
 }
Esempio n. 3
0
  /**
   * This method is the main function of the thread of the collective. It does housekeeping and
   * regularly talks to peers to exchange information. It can be stopped by calling <code>close()
   * </code>.
   *
   * @see #close()
   */
  public final void run() {

    while (shouldLive) {
      // try{
      System.gc();
      removeOldStuff();
      if (!refresh()) {
        Address[] a = observer.getPeerAddresses();
        if (a != null)
          synchronized (cache) {
            for (int i = 0; i < a.length; ++i)
              cache.put(a[i].name, new ContributionBox(a[i], null));
          }
      }
      for (int i = 0; i < REFRESHRATE; i += 1000) {
        try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          shouldLive = false;
        }
        if (shouldLive == false) break;
        Thread.yield();
      }
      /*}
      catch( RuntimeException e )
      {
      	Logger.error( "Collective#run()",
      	"Runtime exception caught, something is going wrong",e);

      }*/
    }

    cache = null;
    observer = null;
  }
  private void resolveClasspath() throws MojoExecutionException {
    parsePatchArtifacts();

    getLog()
        .info(
            "Resolving dependencies"
                + (useTransitives
                    ? ""
                    : " - warning! we are not using transitive dependencies, only those directly in the pom.xml"));

    resolvedArtifacts = collectAllProjectArtifacts();

    /*
     * Remove any Grails plugins that may be in the resolved artifact set.  This is because we
     * do not need them on the classpath, as they will be handled later on by a separate call to
     * "install" them.
     */
    pluginArtifacts = removePluginArtifacts(resolvedArtifacts);

    pluginDirectories = new ArrayList<File>();

    for (Artifact artifact : pluginArtifacts)
      pluginDirectories.add(getPluginDirAndInstallIfNecessary(artifact));

    if (getLog().isInfoEnabled()) {
      for (File f : pluginDirectories) {
        getLog().info("plugin: " + f.getAbsolutePath());
      }
    }

    classpath = generateGrailsExecutionClasspath(resolvedArtifacts);

    System.gc();
  }
Esempio n. 5
0
 public static void recycleBitmap(Bitmap bitmap) {
   if (bitmap != null && !bitmap.isRecycled()) {
     bitmap.recycle();
     bitmap = null;
     System.gc();
   }
 }
Esempio n. 6
0
    private Bitmap scaleBitmap(Bitmap bitmap) {
      // resize to desired dimensions
      int width = bitmap.getWidth();
      int height = bitmap.getHeight();
      int[] newSize = getScaleSize(width, height);
      Bitmap workBitmap = Bitmap.createScaledBitmap(bitmap, newSize[0], newSize[1], true);
      if (workBitmap != bitmap) {
        bitmap.recycle();
        bitmap = workBitmap;
        System.gc();
      }

      if (mScaleType == ScaleType.CENTER_CROP) {
        // Crop it
        int diffWidth = newSize[0] - mOutputWidth;
        int diffHeight = newSize[1] - mOutputHeight;
        workBitmap =
            Bitmap.createBitmap(
                bitmap,
                diffWidth / 2,
                diffHeight / 2,
                newSize[0] - diffWidth,
                newSize[1] - diffHeight);
        if (workBitmap != bitmap) {
          bitmap.recycle();
          bitmap = workBitmap;
        }
      }

      return bitmap;
    }
Esempio n. 7
0
  /**
   * Run the main GP run loop until the generation limit it met, or until the provided number of
   * generations has elapsed.
   *
   * @param inGenerations The maximum number of generations to run during this call. This is
   *     distinct from the hard generation limit which determines when the GA is actually complete.
   * @return true if the the execution of the GA is complete.
   */
  public boolean Run(int inGenerations) throws Exception {
    // inGenerations below must have !=, not >, since often inGenerations
    // is called at -1
    while (!Terminate() && inGenerations != 0) {
      BeginGeneration();

      Evaluate();
      Reproduce();

      EndGeneration();

      Print(Report());

      Checkpoint();

      System.gc();

      _currentPopulation = (_currentPopulation == 0 ? 1 : 0);
      _generationCount++;
      inGenerations--;
    }

    if (Terminate()) {
      // Since this value was changed after termination conditions were
      // set, revert back to previous state.
      _currentPopulation = (_currentPopulation == 0 ? 1 : 0);

      Print(FinalReport());
    }

    return (_generationCount < _maxGenerations);
  }
Esempio n. 8
0
 /** @brief Check if it's time to save the auctions out yet. */
 private void checkSnapshot() {
   if ((mLastCheckpointed + mCheckpointFrequency) < System.currentTimeMillis()) {
     mLastCheckpointed = System.currentTimeMillis();
     saveAuctions();
     System.gc();
   }
 }
  /** Reload this texture's bitmap data from the given input stream. */
  public void refreshData(InputStream in) throws IOException {
    // throw away old data
    this.data = null;
    System.gc();

    // get new data
    this.loadTextureData(in);
  }
Esempio n. 10
0
  public int clearDeleted() {
    int rval = DeletedEntry.clear();

    saveAuctions();
    System.gc();

    return rval;
  }
  public void test() throws Exception {
    int i = 0;
    int sum = 0;

    ByteArrayOutputStream result = new ByteArrayOutputStream();

    final MediaItem item = buildItem();
    final ObjectWriter writer = itemWriter;
    final GenericRecord itemRecord = itemToRecord(item);
    final ObjectWriter jsonWriter = new ObjectMapper().writerFor(MediaItem.class);

    while (true) {
      //            Thread.sleep(150L);
      ++i;
      int round = (i % 3);

      // override?
      round = 0;

      long curr = System.currentTimeMillis();
      int len;
      String msg;

      switch (round) {
        case 0:
          msg = "Serialize, Avro/Jackson";
          len = testObjectSer(writer, item, REPS + REPS, result);
          sum += len;
          break;
        case 1:
          msg = "Serialize, Avro/STD";
          len = testAvroSer(itemRecord, REPS + REPS, result);
          sum += len;
          break;
        case 2:
          msg = "Serialize, JSON";
          len = testObjectSer(jsonWriter, item, REPS + REPS, result);
          sum += len;
          break;
        default:
          throw new Error("Internal error");
      }

      curr = System.currentTimeMillis() - curr;
      if (round == 0) {
        System.out.println();
      }
      System.out.println(
          "Test '" + msg + "' -> " + curr + " msecs (" + len + " / " + (sum & 0xFF) + ").");
      if ((i & 0x1F) == 0) { // GC every 64 rounds
        System.out.println("[GC]");
        Thread.sleep(20L);
        System.gc();
        Thread.sleep(20L);
      }
    }
  }
Esempio n. 12
0
 static void main1() throws Exception {
   writeFile("tmpCompileClose.java", "public class tmpCompileClose {}");
   // Any old jar file will do
   SameJVM.jar("cf", "tmpCompileClose.jar", "tmpCompileClose.java");
   System.gc(); // Inhibit gc during next compile
   SameJVM.javac("-cp", "tmpCompileClose.jar", "tmpCompileClose.java");
   // The following rm is the actual test!
   rm("tmpCompileClose.jar");
 }
Esempio n. 13
0
 // To be called exactly twice by the child process
 public static void rendezvousChild() {
   try {
     for (int i = 0; i < 100; i++) {
       System.gc();
       System.runFinalization();
       Thread.sleep(50);
     }
     System.out.write((byte) '\n');
     System.out.flush();
     System.in.read();
   } catch (Throwable t) {
     throw new Error(t);
   }
 }
  public String doTask() throws IOException, TemplateException {
    Task task = tasks.get(itask++);
    String path = task.getFile().getAbsolutePath();
    path = path.replace(fsrc, ftarget);
    path = path.replace("${packageName}", packagepath);
    File outfile = new File(path);

    StringBuilder log = new StringBuilder(path + "\r\n");
    if (task.getFile().getName().endsWith(".ftl")) {
      Template template = getTemplate(task.getFile());
      for (Table table : tables) {
        String outpath =
            outfile
                .getAbsolutePath()
                .replace(".ftl", "")
                .replace("${className}", table.getClassName());
        log.append("  =>>");
        log.append(outpath);
        log.append("\r\n");
        Writer out = getFileWriter(new File(outpath));
        model.bindTable(table);
        template.process(model, out);
        out.close();
      }
    } else if (FileUtil.isTextFile(task.getFile())) {
      log.append("  =>>");
      log.append(outfile.getAbsolutePath());
      log.append("\r\n");
      Template template = getTemplate(task.getFile());
      Writer out = getFileWriter(outfile);
      template.process(model, out);
      out.close();
    } else {
      log.append("  =>>");
      log.append(outfile.getAbsolutePath());
      log.append("\r\n");
      FileInputStream inputStream = new FileInputStream(task.getFile());
      FileOutputStream outputStream = new FileOutputStream(outfile);
      byte[] bytes = new byte[inputStream.available()];
      inputStream.read(bytes);
      outputStream.write(bytes);
      outputStream.close();
      inputStream.close();
      System.gc();
    }
    return log.toString();
  }
 /** method to disconnect from the server */
 public void disconnect() throws IOException {
   // if stream connection is present then
   if (streamConnection != null) {
     // close all streams
     dataOutputStream.close();
     dataInputStream.close();
     streamConnection.close();
   }
   // nullify all stream objects
   dataOutputStream = null;
   dataInputStream = null;
   streamConnection = null;
   // initiate garbage collector
   System.gc();
   // set the connected flag to false indicating no connection
   connected = false;
 }
Esempio n. 16
0
  @Override
  public void readData(DataInputStream in) throws IOException {
    x = in.readInt();
    z = in.readInt();
    biomes = in.readBoolean();
    bitmask = in.readShort();
    additionalBitmask = in.readShort();
    int tempLength = in.readInt();

    byte[] compressedChunkData = new byte[tempLength];
    in.readFully(compressedChunkData, 0, tempLength);
    int i = 0;

    for (int j = 0; j < 16; j++) i += bitmask >> j & 1;

    int k = 12288 * i;

    if (biomes) k += 256;

    chunkData = new byte[k];
    Inflater inflater = new Inflater();
    inflater.setInput(compressedChunkData, 0, tempLength);

    try {
      inflater.inflate(chunkData);
    } catch (DataFormatException dataformatexception) {
      chunkData = null;
    } catch (OutOfMemoryError error) {
      System.gc();
      try {
        inflater.end();

        inflater = new Inflater();
        inflater.setInput(compressedChunkData, 0, tempLength);

        inflater.inflate(chunkData);
      } catch (DataFormatException dataformatexception) {
        chunkData = null;
      } catch (OutOfMemoryError error2) {
        chunkData = null;
      }
    } finally {
      inflater.end();
    }
  }
  protected void runtest(String name) {
    // Try to ensure we start off with a reasonably clean slate.
    System.gc();
    System.runFinalization();

    checkPoint(null);

    Testlet t = null;
    try {
      Class k = Class.forName(name);

      Object o = k.newInstance();
      if (!(o instanceof Testlet)) return;

      t = (Testlet) o;
    } catch (Throwable ex) {
      String d = "FAIL: uncaught exception loading " + name;
      if (verbose) d += ": " + ex.toString();
      System.out.println(d);
      debug(ex);
      ++failures;
      ++total;
    }

    if (t != null) {
      description = name;
      try {
        t.test(this);
      } catch (Throwable ex) {
        String d =
            ("FAIL: "
                + description
                + ": uncaught exception at "
                + ((last_check == null) ? "" : ("\"" + last_check + "\""))
                + " number "
                + (count + 1));
        if (verbose) d += ": " + ex.toString();
        System.out.println(d);
        debug(ex);
        ++failures;
        ++total;
      }
    }
  }
Esempio n. 18
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.
Esempio n. 19
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";
 }
Esempio n. 20
0
 private static void serverRunning() {
   System.out.println("Server Running");
   ServerTimer timer = new ServerTimer(60);
   Thread thread = new Thread(timer);
   thread.start();
   // System.out.println("Waiting for timer");
   while (!timer.finished()) ;
   timer.shutDown();
   // System.out.println("Migration !");
   timer = null;
   System.gc();
   try {
     game.setMoving(true);
     serverCall();
   } catch (RemoteException e) {
     System.out.println("Failed to modify game");
     System.exit(1);
   } catch (Exception ex) {
     System.out.println("Failed to call");
   }
 }
Esempio n. 21
0
  private static void serverCall() throws Exception {
    String sentence = "move";
    String line;

    while (!gameStopped) {
      System.out.print("");
    }
    playing = false;
    try {
      setDiscussion();
    } catch (Exception ex) {
      System.out.println("Failed to discuss with clients");
    }

    BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
    try {
      InetAddress inetAddress = InetAddress.getByName(serverInfo.getNext().getIpAddr());
      Socket clientSocket = new Socket(inetAddress, serverInfo.getNext().getPort());
      DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream());
      BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
      sendInfo(out);
      line = in.readLine();
      while (!game.getUnbinding()) ;
      Naming.unbind("rmi://" + serverInfo.getIpAddr() + ":1099/I_InfoGame");
      out.writeBytes("Unbinding finished\n");
      line = in.readLine();
      clientSocket.close();
    } catch (RemoteException e) {
      System.out.println("Failed get info from game");
      System.exit(1);
    } catch (Exception ex) {
      System.out.println("Failed to socket with waiting server");
    }
    discussion.shutDown();
    discussion = null;
    game = null;
    System.gc();
    serverWaiting();
  }
 @Scheduled(fixedDelay = SCHEDULED_CHECK)
 public void checkActiveClients() {
   Set<String> users = user_vidNameMap.keySet();
   Iterator<String> it = users.iterator();
   long time = System.currentTimeMillis();
   int count = 0;
   while (it.hasNext()) {
     count++;
     String user = it.next();
     if (user == null) continue;
     if (userAliveMap.containsKey(user)) {
       if (userAliveMap.get(user).longValue() < time) {
         removeUser(user);
         userAliveMap.remove(user);
       }
     } else {
       throw new RuntimeException("user in user-vid map but not in user-alive map");
     }
   }
   // System.out.println("Debug: Scheduled Check count:"+count+" user
   // count:"+user_vidNameMap.size());
   System.gc();
 }
Esempio n. 23
0
    public static void main(String args[])
    {
        try
        {
            Object parameters[] = parseArguments(args);
            File f = (File)parameters[0];
            File f1 = (File)parameters[1];
            Socket s = (Socket)parameters[2];
            double len = (double)f.length() / 1024D;
            System.out.println((new StringBuilder("Starting: ")).append(len).append(" kb").toString());
            startReport();
            for(int j = 1; j < 4; j++)
            {
                logSeries(j);
                int ms = 0x100000 * j;
                for(int i = 5; i < 11; i++)
                {
                    int rs = 1024 * i;
                    int ws = 1024 * i;
                    System.gc();
                    start = System.currentTimeMillis();
                    copyStreamConservative(new FileInputStream(f), new FileOutputStream(f1), rs);
                    end = System.currentTimeMillis();
                    time = end - start;
                    logTestResult(time, len, ms, rs, ws);
                }

            }

            endReport();
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
    }
Esempio n. 24
0
 public SerializationTest1(String s) {
   super(s);
   lastValue = 100D;
   series = new TimeSeries("Random Data");
   TimeSeriesCollection timeseriescollection = new TimeSeriesCollection(series);
   JFreeChart jfreechart = createChart(timeseriescollection);
   JFreeChart jfreechart1 = null;
   try {
     ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream();
     ObjectOutputStream objectoutputstream = new ObjectOutputStream(bytearrayoutputstream);
     objectoutputstream.writeObject(jfreechart);
     objectoutputstream.close();
     jfreechart = null;
     Object obj = null;
     series = null;
     System.gc();
     ObjectInputStream objectinputstream =
         new ObjectInputStream(new ByteArrayInputStream(bytearrayoutputstream.toByteArray()));
     jfreechart1 = (JFreeChart) objectinputstream.readObject();
     objectinputstream.close();
   } catch (Exception exception) {
     exception.printStackTrace();
   }
   XYPlot xyplot = (XYPlot) jfreechart1.getPlot();
   TimeSeriesCollection timeseriescollection1 = (TimeSeriesCollection) xyplot.getDataset();
   series = timeseriescollection1.getSeries(0);
   ChartPanel chartpanel = new ChartPanel(jfreechart1);
   JButton jbutton = new JButton("Add New Data Item");
   jbutton.setActionCommand("ADD_DATA");
   jbutton.addActionListener(this);
   JPanel jpanel = new JPanel(new BorderLayout());
   jpanel.add(chartpanel);
   jpanel.add(jbutton, "South");
   chartpanel.setPreferredSize(new Dimension(500, 270));
   setContentPane(jpanel);
 }
Esempio n. 25
0
  // Parse Node Info from into hash table of all node info
  // Schema :
  // create table Nodes (
  //     NodeName String,
  //     Cluster  String
  // );
  private void parseNodeInfo(Hashtable all_nodes, Statement stmt, String community, String node)
      throws SQLException {
    // Query for all Node/Cluster info and populate 'all_nodes' hashtable

    String sql = "select Node, Name from Organizations";

    if (community != null && node != null) {
      sql = sql + " where Community='" + community + "' and Node='" + node + "'";
    } else if (community != null) {
      sql = sql + " where Community='" + community + "'";
    } else if (node != null) {
      sql = sql + " where Node='" + node + "'";
    }

    System.out.println(sql);
    ResultSet rset = stmt.executeQuery(sql);
    int number = 0;
    while (rset.next()) {
      number++;
      String node_name = rset.getString("Node");
      String cluster_name = rset.getString("Name");
      try {
        Vector current_node_clusters = (Vector) all_nodes.get(node_name);
        if (current_node_clusters == null) {
          current_node_clusters = new Vector();
          all_nodes.put(node_name, current_node_clusters);
        }
        current_node_clusters.addElement(cluster_name);
      } catch (Exception nullPointer) {
        System.out.println("WARNING:  Cluster " + cluster_name + " does not have a node!!!");
      }
    }
    System.out.println("Query returned " + number + " results");
    rset = null;
    System.gc();
  }
Esempio n. 26
0
 public void JGFtidyup() {
   System.gc();
 }
Esempio n. 27
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()
Esempio n. 28
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());
 }
Esempio n. 29
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()
Esempio n. 30
0
  // Parse database tables to create organization info, including
  // organization details (from Organizations table)
  // roles (from Roles table)
  // support relationships (from Relationships table)
  // Schema:
  // create table Organizations (
  //   Name String,
  //   UIC String,
  //   UTC String,
  //   SRC String,
  //   Superior String,
  //   Echelon String,
  //   Agency String,
  //   Service String,
  //   Nomenclature String,
  //   Prototype String,
  // );
  // create table Roles (
  //    Organization String,
  //    Role String -- Capable Role for Organization
  // );
  // create table Relationships (
  //    Organization String,
  //    Supported String, -- Supported Organization
  //    Role String -- Support Role
  // );
  private void parseOrganizationInfo(
      Hashtable all_organizations, Statement stmt, String community, String node)
      throws SQLException {
    Double echelon;
    int number = 0;
    /*
    String sql = "select Name, UIC, UTC, SRC, Superior, Echelon, Agency, Service, Nomenclature, "
        +"Prototype, Location, Longitude, Latitude, Organizations.GeolocCode, InstallationTypeCode, "
        +"CountryStateCode, CountryStateName, IcaoCode, ReserveOrg from Organizations, "
        +"LocationMaster where Organizations.GeolocCode=LocationMaster.GeolocCode" ;
    */

    String sql =
        "select Name, UIC, UTC, SRC, Superior, Echelon, Agency, Service, Nomenclature, "
            + "Prototype, ReserveOrg from Organizations";

    if (community != null && node != null) {
      sql =
          sql
              + " where Organizations.Community='"
              + community
              + "' and Organizations.Node='"
              + node
              + "'";
    } else if (community != null) {
      sql = sql + " where Organizations.Community='" + community + "'";
    } else if (node != null) {
      sql = sql + " where Organizations.Node='" + node + "'";
    }
    System.out.println(sql);

    ResultSet rset = stmt.executeQuery(sql);

    while (rset.next()) {
      number++;
      String current_organization = rset.getString("Name");
      String testEchelon = rset.getString("Echelon");
      if (testEchelon == null) {
        echelon = new Double(-1);
      } else {
        echelon = new Double(testEchelon);
      }
      boolean reserve = false;
      int res = rset.getInt("ReserveOrg");
      if (res == 0) {
        reserve = false;
      } else {
        reserve = true;
      }

      OrganizationData org_data =
          new OrganizationData(
              current_organization,
              rset.getString("UIC"), // UIC
              rset.getString("UTC"), // UTC
              rset.getString("SRC"), // SRC
              rset.getString("Superior"), // Superior
              echelon, // Echelon
              rset.getString("Agency"), // Agency
              rset.getString("Service"), // Service
              rset.getString("Nomenclature"), // Nomenclature
              rset.getString("Prototype"), // Prototype
              reserve); // isReserve
      all_organizations.put(current_organization, org_data);
    }
    System.out.println("Query returned " + number + " results");

    rset = null;
    System.gc();

    // Query for the Assigned Location
    sql =
        "select Name, Location, Longitude, Latitude, AssignedLoc, InstallationTypeCode, "
            + "CountryStateCode, CountryStateName, IcaoCode, ReserveOrg from Organizations, "
            + "LocationMaster where Organizations.AssignedLoc=LocationMaster.GeolocCode";

    if (community != null && node != null) {
      sql =
          sql
              + " and Organizations.Community='"
              + community
              + "' and Organizations.Node='"
              + node
              + "'";
    } else if (community != null) {
      sql = sql + " and Organizations.Community='" + community + "'";
    } else if (node != null) {
      sql = sql + " and Organizations.Node='" + node + "'";
    }

    System.out.println(sql);

    rset = stmt.executeQuery(sql);

    while (rset.next()) {
      number++;
      String current_organization = rset.getString("Name");
      OrganizationData data = (OrganizationData) all_organizations.get(current_organization);
      // initialize the assigned location
      data.initAssignedLoc(
          rset.getString("Location"),
          rset.getString("Longitude"),
          rset.getString("Latitude"),
          rset.getString("AssignedLoc"),
          rset.getString("InstallationTypeCode"),
          rset.getString("CountryStateCode"),
          rset.getString("CountryStateName"),
          rset.getString("IcaoCode"));
    }
    System.out.println("Query returned " + number + " results");

    rset = null;
    System.gc();

    // Query for the home location
    sql =
        "select Name, Location, Longitude, Latitude, HomeLoc, InstallationTypeCode, "
            + "CountryStateCode, CountryStateName, IcaoCode, ReserveOrg from Organizations, "
            + "LocationMaster where Organizations.HomeLoc=LocationMaster.GeolocCode";

    if (community != null && node != null) {
      sql =
          sql
              + " and Organizations.Community='"
              + community
              + "' and Organizations.Node='"
              + node
              + "'";
    } else if (community != null) {
      sql = sql + " and Organizations.Community='" + community + "'";
    } else if (node != null) {
      sql = sql + " and Organizations.Node='" + node + "'";
    }

    System.out.println(sql);

    rset = stmt.executeQuery(sql);

    while (rset.next()) {
      number++;
      String current_organization = rset.getString("Name");
      OrganizationData data = (OrganizationData) all_organizations.get(current_organization);
      // initialize the Home location
      data.initHomeLoc(
          rset.getString("Location"),
          rset.getString("Longitude"),
          rset.getString("Latitude"),
          rset.getString("HomeLoc"),
          rset.getString("InstallationTypeCode"),
          rset.getString("CountryStateCode"),
          rset.getString("CountryStateName"),
          rset.getString("IcaoCode"));
    }
    System.out.println("Query returned " + number + " results");

    rset = null;
    System.gc();

    // Query for all Organization/Role info

    sql =
        "select Organization, Role from Roles, Organizations"
            + " where Organizations.Name=Roles.Organization ";
    number = 0;
    if (community != null && node != null) {
      sql =
          sql
              + " and Organizations.Community='"
              + community
              + "' and Organizations.Node='"
              + node
              + "'";
    } else if (community != null) {
      sql = sql + " and Organizations.Community='" + community + "'";
    } else if (node != null) {
      sql = sql + " and Organizations.Node='" + node + "'";
    }

    System.out.println(sql);
    rset = stmt.executeQuery(sql);

    while (rset.next()) {
      number++;
      String current_organization = (String) rset.getString("Organization");
      OrganizationData org_data = (OrganizationData) all_organizations.get(current_organization);
      if (org_data == null) {
        System.out.println("No organization defined : " + current_organization);
        System.exit(0);
      }
      org_data.addRole(rset.getString("Role")); // Role
    }
    System.out.println("Query returned " + number + " results");

    rset = null;
    System.gc();

    sql =
        "Select SupportingOrg, SupportedOrg, Role from Relationships, Organizations"
            + " where Relationships.SupportingOrg=Organizations.Name";

    if (community != null && node != null) {
      sql =
          sql
              + " and Organizations.Community='"
              + community
              + "'"
              + " and Organizations.Node='"
              + node
              + "'";
    } else if (community != null) {
      sql = sql + " and Organizations.Community='" + community + "'";

    } else if (node != null) {
      sql = sql + " and Organizations.Node='" + node + "'";
    }

    System.out.println(sql);
    rset = stmt.executeQuery(sql);

    number = 0;
    rset = stmt.executeQuery(sql);
    while (rset.next()) {
      number++;
      String current_organization = (String) rset.getString("SupportingOrg");
      OrganizationData org_data = (OrganizationData) all_organizations.get(current_organization);
      if (org_data == null) {
        System.out.println("No organization defined : " + current_organization);
        System.exit(0);
      }
      SupportRelation support =
          new SupportRelation(
              current_organization,
              rset.getString("SupportedOrg"), // Supported Org
              rset.getString("Role")); // Role
      org_data.addSupportRelation(support);
    }

    System.out.println("Query returned " + number + " results");

    rset = null;
    System.gc();

    // get the CSSCapabilities
    sql =
        "select CSSCapability.Cluster, Capability, QTY, Period"
            + " from CSSCapability, Organizations"
            + " where CSSCapability.Cluster=Organizations.Name";

    if (community != null && node != null) {
      sql =
          sql
              + " and Organizations.Community='"
              + community
              + "' and Organizations.Node='"
              + node
              + "'";
    } else if (community != null) {
      sql = sql + " and Organizations.Community='" + community + "'";
    } else if (node != null) {
      sql = sql + " and Organizations.Node='" + node + "'";
    }

    System.out.println(sql);
    number = 0;
    rset = stmt.executeQuery(sql);
    while (rset.next()) {
      number++;
      String current_organization = (String) rset.getString("Cluster");
      OrganizationData org_data = (OrganizationData) all_organizations.get(current_organization);
      if (org_data == null) {
        System.out.println("No organization defined : " + current_organization);
        System.exit(0);
      }
      CSSCapabilities CSSCap =
          new CSSCapabilities(
              current_organization,
              rset.getString("Capability"), // Capability
              rset.getString("QTY"), // Count
              rset.getString("Period"));
      org_data.addCSSCapabilities(CSSCap);
    }
    System.out.println("Query returned " + number + " results");

    rset = null;
    System.gc();
  }