List of usage examples for java.util ListIterator nextIndex
int nextIndex();
From source file:org.squale.squalecommon.enterpriselayer.facade.quality.QualityResultFacade.java
/** * Permet de rcuprer les notes associs a une pratique ainsi que les regles avec le nombre de fois que elle a t * transgresse//from w ww .j a va 2s .c o m * * @param pAudits liste des AuditDTOs * @param pProject ComponentDTO relatif a un projet * @param pPratice pratique * @return ResultsDTO avec les deux Map renseignes ResultsMap : <br/> * -- Cl : null -- Valeur : Liste d'AuditDTO <br/> * -- Cl : ComponentDTO -- Valeurs : notes associes aux audits dans le mme ordre que la liste d'audit de * type java.lang.Float<br/> * PracticeMap : n lignes de la forme suivante :<br/> * -- Cl : AuditDTO -- Valeur : map de <RuleCheckingDTO,java.lang.Integer> * @throws JrafEnterpriseException exception Jraf */ public static ResultsDTO getRuleChecking(List pAudits, ComponentDTO pProject, PracticeRuleDTO pPratice) throws JrafEnterpriseException { // Initialisation ISession session = null; // session Hibernate List auditIds = initAuditIds(pAudits); // liste des identifiants des AuditDTO Long projectId = new Long(pProject.getID()); ResultsDTO results = null; // retour de la methode Map practiceMap = new HashMap(); // Map du nombre de violation sur une rgle Collection measures = null; RuleCheckingTransgressionBO measure = null; // Initialisation des Daos RuleCheckingTransgressionDAOImpl measureDAO = RuleCheckingTransgressionDAOImpl.getInstance(); try { session = PERSISTENTPROVIDER.getSession(); Long treKey = new Long(pPratice.getId()); results = getQResultsByAudit(pAudits, treKey, pProject); ListIterator auditIdsIterator = auditIds.listIterator(); Long currentID = null; // On construit la liste des types de mesures lies la pratique // On rcupre la pratique en base pour avoir la formule PracticeRuleBO ruleWithFormula = (PracticeRuleBO) QualityRuleDAOImpl.getInstance().get(session, new Long(pPratice.getId())); AbstractFormulaBO formula = ruleWithFormula.getFormula(); Collection measuresKind = buildClassesMeasureKind(formula.getMeasureKinds(), formula.getComponentLevel()); while (auditIdsIterator.hasNext()) { // recuperer les mesures Ruleschecking des diffrents audits currentID = (Long) (auditIdsIterator.next()); measures = measureDAO.load(session, projectId, currentID); if (measures.size() == 0) { LOG.error(QualityResultFacade.class.getName() + ".getRuleChecking" + "mesures de rulechecking sont nulles"); } // Map contenant tous les rsultats, cel permet de // fusionner des donnes issues de diffrents outils Map allResults = new HashMap(); // On parcours les mesures jusqu' pouvoir insrer les rgles // dans la map des pratiques for (Iterator it = measures.iterator(); it.hasNext();) { measure = (RuleCheckingTransgressionBO) it.next(); // Si la mesure est prise en compte dans le calcul de la note // on ajoute les rsultats associs if (measuresKind.contains(measure.getClass())) { Map resultsRulesChecking = makeRulesCheckingDTO(measure, pPratice.getName()); // On insre les rgles dans la map des pratiques allResults.putAll(resultsRulesChecking); } } AuditDTO auditDTO = (AuditDTO) pAudits.get(auditIdsIterator.nextIndex() - 1); practiceMap.put(auditDTO, allResults); } // affectation de la map au ResultsDTO results.setIntRepartitionPracticeMap(practiceMap); } catch (JrafDaoException e) { LOG.error(QualityResultFacade.class.getName() + ".getRuleChecking", e); } finally { FacadeHelper.closeSession(session, QualityResultFacade.class.getName() + ".getRuleChecking"); } return results; }
From source file:org.apache.fop.layoutmgr.AbstractBreaker.java
/** * Justifies the boxes and returns them as a new KnuthSequence. * @param blockList block list to justify * @param alg reference to the algorithm instance * @param availableBPD the available BPD * @return the effective list/* w w w.ja va 2 s. c o m*/ */ private BlockSequence justifyBoxes // CSOK: MethodLength (BlockSequence blockList, PageBreakingAlgorithm alg, int availableBPD) { int optimalPageCount; alg.setConstantLineWidth(availableBPD); optimalPageCount = alg.findBreakingPoints(blockList, /*availableBPD,*/ 1, true, BreakingAlgorithm.ALL_BREAKS); log.debug("PLM> optimalPageCount= " + optimalPageCount); // ListIterator<KnuthElement> sequenceIterator = blockList.listIterator(); ListIterator<PageBreakPosition> breakIterator = alg.getPageBreaks().listIterator(); KnuthElement thisElement = null; PageBreakPosition thisBreak; int adjustedDiff; // difference already adjusted while (breakIterator.hasNext()) { thisBreak = breakIterator.next(); if (log.isDebugEnabled()) { log.debug("| first page: break= " + thisBreak.getLeafPos() + " difference= " + thisBreak.difference + " ratio= " + thisBreak.bpdAdjust); } adjustedDiff = 0; // glue and penalty items at the beginning of the page must // be ignored: // the first element returned by sequenceIterator.next() // inside the // while loop must be a box KnuthElement firstElement; while (sequenceIterator.hasNext()) { firstElement = sequenceIterator.next(); if (!firstElement.isBox()) { log.debug("PLM> ignoring glue or penalty element " + "at the beginning of the sequence"); if (firstElement.isGlue()) { ((BlockLevelLayoutManager) firstElement.getLayoutManager()) .discardSpace((KnuthGlue) firstElement); } } else { break; } } sequenceIterator.previous(); // scan the sub-sequence representing a page, // collecting information about potential adjustments MinOptMax lineNumberMaxAdjustment = MinOptMax.ZERO; MinOptMax spaceMaxAdjustment = MinOptMax.ZERO; LinkedList<KnuthGlue> blockSpacesList = new LinkedList<KnuthGlue>(); LinkedList<KnuthGlue> unconfirmedList = new LinkedList<KnuthGlue>(); LinkedList<KnuthGlue> adjustableLinesList = new LinkedList<KnuthGlue>(); boolean bBoxSeen = false; while (sequenceIterator.hasNext() && sequenceIterator.nextIndex() <= thisBreak.getLeafPos()) { thisElement = sequenceIterator.next(); if (thisElement.isGlue()) { // glue elements are used to represent adjustable // lines // and adjustable spaces between blocks KnuthGlue thisGlue = (KnuthGlue) thisElement; Adjustment adjustment = thisGlue.getAdjustmentClass(); if (adjustment.equals(Adjustment.SPACE_BEFORE_ADJUSTMENT) || adjustment.equals(Adjustment.SPACE_AFTER_ADJUSTMENT)) { // potential space adjustment // glue items before the first box or after the // last one // must be ignored unconfirmedList.add(thisGlue); } else if (adjustment.equals(Adjustment.LINE_NUMBER_ADJUSTMENT)) { // potential line number adjustment lineNumberMaxAdjustment = lineNumberMaxAdjustment.plusMax(thisElement.getStretch()); lineNumberMaxAdjustment = lineNumberMaxAdjustment.minusMin(thisElement.getShrink()); adjustableLinesList.add(thisGlue); } else if (adjustment.equals(Adjustment.LINE_HEIGHT_ADJUSTMENT)) { // potential line height adjustment } } else if (thisElement.isBox()) { if (!bBoxSeen) { // this is the first box met in this page bBoxSeen = true; } else { while (!unconfirmedList.isEmpty()) { // glue items in unconfirmedList were not after // the last box // in this page; they must be added to // blockSpaceList KnuthGlue blockSpace = unconfirmedList.removeFirst(); spaceMaxAdjustment = spaceMaxAdjustment.plusMax(blockSpace.getStretch()); spaceMaxAdjustment = spaceMaxAdjustment.minusMin(blockSpace.getShrink()); blockSpacesList.add(blockSpace); } } } } log.debug("| line number adj= " + lineNumberMaxAdjustment); log.debug("| space adj = " + spaceMaxAdjustment); if (thisElement.isPenalty() && thisElement.getWidth() > 0) { log.debug(" mandatory variation to the number of lines!"); ((BlockLevelLayoutManager) thisElement.getLayoutManager()) .negotiateBPDAdjustment(thisElement.getWidth(), thisElement); } if (thisBreak.bpdAdjust != 0 && (thisBreak.difference > 0 && thisBreak.difference <= spaceMaxAdjustment.getMax()) || (thisBreak.difference < 0 && thisBreak.difference >= spaceMaxAdjustment.getMin())) { // modify only the spaces between blocks adjustedDiff += adjustBlockSpaces(blockSpacesList, thisBreak.difference, (thisBreak.difference > 0 ? spaceMaxAdjustment.getMax() : -spaceMaxAdjustment.getMin())); log.debug("single space: " + (adjustedDiff == thisBreak.difference || thisBreak.bpdAdjust == 0 ? "ok" : "ERROR")); } else if (thisBreak.bpdAdjust != 0) { adjustedDiff += adjustLineNumbers(adjustableLinesList, thisBreak.difference, (thisBreak.difference > 0 ? lineNumberMaxAdjustment.getMax() : -lineNumberMaxAdjustment.getMin())); adjustedDiff += adjustBlockSpaces(blockSpacesList, thisBreak.difference - adjustedDiff, ((thisBreak.difference - adjustedDiff) > 0 ? spaceMaxAdjustment.getMax() : -spaceMaxAdjustment.getMin())); log.debug("lines and space: " + (adjustedDiff == thisBreak.difference || thisBreak.bpdAdjust == 0 ? "ok" : "ERROR")); } } // create a new sequence: the new elements will contain the // Positions // which will be used in the addAreas() phase BlockSequence effectiveList = new BlockSequence(blockList.getStartOn(), blockList.getDisplayAlign()); effectiveList.addAll(getCurrentChildLM().getChangedKnuthElements( blockList.subList(0, blockList.size() - blockList.ignoreAtEnd), /* 0, */0)); //effectiveList.add(new KnuthPenalty(0, -KnuthElement.INFINITE, // false, new Position(this), false)); effectiveList.endSequence(); ElementListObserver.observe(effectiveList, "breaker-effective", null); alg.getPageBreaks().clear(); //Why this? return effectiveList; }
From source file:com.idega.builder.business.BuilderLogic.java
private void filterForPermission(List<Integer> groupIds, PresentationObject obj, PresentationObjectContainer parentObject, int index, IWContext iwc) { if (!iwc.hasViewPermission(groupIds, obj)) { logger.severe(obj + ": removed"); parentObject.getChildren().remove(index); parentObject.getChildren().add(index, PresentationObject.NULL_CLONE_OBJECT); } else if (obj.isContainer()) { if (obj instanceof Table) { Table tab = (Table) obj;/*from w ww .jav a2s . co m*/ int cols = tab.getColumns(); int rows = tab.getRows(); for (int x = 1; x <= cols; x++) { for (int y = 1; y <= rows; y++) { PresentationObjectContainer moc = tab.containerAt(x, y); if (moc != null) { List l = moc.getChildren(); if (l != null) { ListIterator iterT = l.listIterator(); while (iterT.hasNext()) { int index2 = iterT.nextIndex(); Object itemT = iterT.next(); if (itemT instanceof PresentationObject) { filterForPermission(groupIds, (PresentationObject) itemT, moc, index2, iwc); } } } } } } } else { List list = obj.getChildren(); if (list != null) { ListIterator iter = list.listIterator(); while (iter.hasNext()) { int index2 = iter.nextIndex(); PresentationObject item = (PresentationObject) iter.next(); filterForPermission(groupIds, item, (PresentationObjectContainer) obj, index2, iwc); } } } } }
From source file:com.idega.builder.business.BuilderLogic.java
public PresentationObject getTransformedObject(Page currentPage, String pageKey, UIComponent obj, int index, PresentationObjectContainer parent, String parentKey, IWContext iwc) { IWResourceBundle iwrb = getBuilderBundle().getResourceBundle(iwc); XMLElement pasted = (XMLElement) iwc.getSessionAttribute(CLIPBOARD); boolean clipboardEmpty = (pasted == null); //We can either be working with pure UIComponents or PresentationObjects boolean isPresentationObject = obj instanceof PresentationObject; //Some very special cases, added the boolean to make it faster /*if (isPresentationObject && obj instanceof Image) { obj = transformImage(pageKey, obj, iwc); }/*w ww . j a v a 2 s .c om*/ else*/ if (isPresentationObject && ((PresentationObject) obj).isContainer()) { if (obj instanceof Table) { getTransformedTable(currentPage, pageKey, obj, iwc, clipboardEmpty); } else { List list = obj.getChildren(); if (list != null && !list.isEmpty()) { ListIterator iter = list.listIterator(); while (iter.hasNext()) { int index2 = iter.nextIndex(); UIComponent item = (UIComponent) iter.next(); /** * If parent is Table */ if (index == -1) { getTransformedObject(currentPage, pageKey, item, index2, (PresentationObjectContainer) obj, parentKey, iwc); } else { String newParentKey = null; //Ugly Hack of handling the regions inside HTML template based pages. This needs to change. //TODO: Remove this instanceof case, to make that possible then the getICObjectInstanceID // method needs to be changed to return String if (obj instanceof HtmlPageRegion) { HtmlPageRegion region = (HtmlPageRegion) obj; //newParentKey is normally an ICObjectInstanceId or -1 to mark the top page //but here we make a workaround. newParentKey = region.getRegionId(); } else { newParentKey = getInstanceId(obj); } getTransformedObject(currentPage, pageKey, item, index2, (PresentationObjectContainer) obj, newParentKey, iwc); } } } if (index != -1) { Page curr = getPageCacher().getComponentBasedPage(getCurrentIBPage(iwc)).getNewPage(iwc); PresentationObjectContainer container = ((PresentationObjectContainer) obj); String instanceId = getInstanceId(obj); if (instanceId == null) { instanceId = obj.getId(); } String regionLabel = container.getLabel(); String addModuleUri = getUriToAddModuleWindow(regionLabel); if (curr.getIsExtendingTemplate()) { if (container.getBelongsToParent()) { if (!container.isLocked()) { Layer marker = getLabelMarker(instanceId, regionLabel); addButtonsLayer(marker, addModuleUri, regionLabel, iwrb, marker.getId()); container.add(marker); } } else { Layer marker = getLabelMarker(instanceId, regionLabel); Layer buttons = addButtonsLayer(marker, addModuleUri, regionLabel, iwrb, marker.getId()); container.add(marker); if (curr.getIsTemplate()) { buttons.add(getLabelIcon(instanceId, iwc, regionLabel)); if (container.isLocked()) { buttons.add(getLockedIcon(instanceId, iwc, regionLabel)); } else { buttons.add(getUnlockedIcon(instanceId, iwc)); } } } } else { Layer marker = getLabelMarker(instanceId, regionLabel); Layer buttons = addButtonsLayer(marker, addModuleUri, regionLabel, iwrb, marker.getId()); container.add(marker); if (curr.getIsTemplate()) { marker.add(getLabelIcon(instanceId, iwc, regionLabel)); if (container.isLocked()) { buttons.add(getLockedIcon(instanceId, iwc, regionLabel)); } else { buttons.add(getUnlockedIcon(instanceId, iwc)); } } } } } } PresentationObject transformed = null; if ((isPresentationObject && ((PresentationObject) obj).getUseBuilderObjectControl()) || !isPresentationObject) { if (index != -1) { boolean lastModuleInRegion = false; if (index >= parent.getChildCount()) { lastModuleInRegion = true; } else if (index == (parent.getChildCount() - 1)) { lastModuleInRegion = true; } boolean objectFromCurrentPage = true; try { IBXMLPage page = getIBXMLPage(pageKey); objectFromCurrentPage = getIBXMLWriter().findModule(page, getInstanceId(obj)) != null; } catch (Exception e) { e.printStackTrace(); } transformed = new IBObjectControl(obj, parent, parentKey, iwc, index, lastModuleInRegion, objectFromCurrentPage); if (index < parent.getChildCount()) { parent.set(index, transformed); } else { parent.add(transformed); index++; } } return transformed; } if (isPresentationObject) { return (PresentationObject) obj; } return null; }
From source file:net.pms.dlna.DLNAMediaInfo.java
public void parse(InputFile inputFile, Format ext, int type, boolean thumbOnly) { int i = 0;//from w ww. j a va 2s. c om while (isParsing()) { if (i == 5) { setMediaparsed(true); break; } try { Thread.sleep(1000); } catch (InterruptedException e) { } i++; } if (isMediaparsed()) { return; } if (inputFile != null) { if (inputFile.getFile() != null) { setSize(inputFile.getFile().length()); } else { setSize(inputFile.getSize()); } ProcessWrapperImpl pw = null; boolean ffmpeg_parsing = true; if (type == Format.AUDIO || ext instanceof AudioAsVideo) { ffmpeg_parsing = false; DLNAMediaAudio audio = new DLNAMediaAudio(); if (inputFile.getFile() != null) { try { AudioFile af = AudioFileIO.read(inputFile.getFile()); AudioHeader ah = af.getAudioHeader(); if (ah != null && !thumbOnly) { int length = ah.getTrackLength(); int rate = ah.getSampleRateAsNumber(); if (ah.getEncodingType().toLowerCase().contains("flac 24")) { audio.setBitsperSample(24); } audio.setSampleFrequency("" + rate); setDuration((double) length); setBitrate((int) ah.getBitRateAsNumber()); audio.getAudioProperties().setNumberOfChannels(2); if (ah.getChannels() != null && ah.getChannels().toLowerCase().contains("mono")) { audio.getAudioProperties().setNumberOfChannels(1); } else if (ah.getChannels() != null && ah.getChannels().toLowerCase().contains("stereo")) { audio.getAudioProperties().setNumberOfChannels(2); } else if (ah.getChannels() != null) { audio.getAudioProperties().setNumberOfChannels(Integer.parseInt(ah.getChannels())); } audio.setCodecA(ah.getEncodingType().toLowerCase()); if (audio.getCodecA().contains("(windows media")) { audio.setCodecA(audio.getCodecA() .substring(0, audio.getCodecA().indexOf("(windows media")).trim()); } } Tag t = af.getTag(); if (t != null) { if (t.getArtworkList().size() > 0) { setThumb(t.getArtworkList().get(0).getBinaryData()); } else { if (configuration.getAudioThumbnailMethod() > 0) { setThumb(CoverUtil.get().getThumbnailFromArtistAlbum( configuration.getAudioThumbnailMethod() == 1 ? CoverUtil.AUDIO_AMAZON : CoverUtil.AUDIO_DISCOGS, audio.getArtist(), audio.getAlbum())); } } if (!thumbOnly) { audio.setAlbum(t.getFirst(FieldKey.ALBUM)); audio.setArtist(t.getFirst(FieldKey.ARTIST)); audio.setSongname(t.getFirst(FieldKey.TITLE)); String y = t.getFirst(FieldKey.YEAR); try { if (y.length() > 4) { y = y.substring(0, 4); } audio.setYear(Integer.parseInt(((y != null && y.length() > 0) ? y : "0"))); y = t.getFirst(FieldKey.TRACK); audio.setTrack(Integer.parseInt(((y != null && y.length() > 0) ? y : "1"))); audio.setGenre(t.getFirst(FieldKey.GENRE)); } catch (Throwable e) { logger.debug("Error parsing unimportant metadata: " + e.getMessage()); } } } } catch (Throwable e) { logger.debug("Error parsing audio file: {} - {}", e.getMessage(), e.getCause() != null ? e.getCause().getMessage() : ""); ffmpeg_parsing = false; } if (audio.getSongname() == null || audio.getSongname().length() == 0) { audio.setSongname(inputFile.getFile().getName()); } if (!ffmpeg_parsing) { getAudioTracksList().add(audio); } } } if (type == Format.IMAGE && inputFile.getFile() != null) { try { ffmpeg_parsing = false; ImageInfo info = Sanselan.getImageInfo(inputFile.getFile()); setWidth(info.getWidth()); setHeight(info.getHeight()); setBitsPerPixel(info.getBitsPerPixel()); String formatName = info.getFormatName(); if (formatName.startsWith("JPEG")) { setCodecV("jpg"); IImageMetadata meta = Sanselan.getMetadata(inputFile.getFile()); if (meta != null && meta instanceof JpegImageMetadata) { JpegImageMetadata jpegmeta = (JpegImageMetadata) meta; TiffField tf = jpegmeta.findEXIFValue(TiffConstants.EXIF_TAG_MODEL); if (tf != null) { setModel(tf.getStringValue().trim()); } tf = jpegmeta.findEXIFValue(TiffConstants.EXIF_TAG_EXPOSURE_TIME); if (tf != null) { setExposure((int) (1000 * tf.getDoubleValue())); } tf = jpegmeta.findEXIFValue(TiffConstants.EXIF_TAG_ORIENTATION); if (tf != null) { setOrientation(tf.getIntValue()); } tf = jpegmeta.findEXIFValue(TiffConstants.EXIF_TAG_ISO); if (tf != null) { // Galaxy Nexus jpg pictures may contain multiple values, take the first int[] isoValues = tf.getIntArrayValue(); setIso(isoValues[0]); } } } else if (formatName.startsWith("PNG")) { setCodecV("png"); } else if (formatName.startsWith("GIF")) { setCodecV("gif"); } else if (formatName.startsWith("TIF")) { setCodecV("tiff"); } setContainer(getCodecV()); } catch (Throwable e) { logger.info("Error parsing image ({}) with Sanselan, switching to FFmpeg.", inputFile.getFile().getAbsolutePath()); } } if (configuration.getImageThumbnailsEnabled() && type != Format.VIDEO && type != Format.AUDIO) { try { File thumbDir = new File(configuration.getTempFolder(), THUMBNAIL_DIRECTORY_NAME); logger.trace("Generating thumbnail for: {}", inputFile.getFile().getAbsolutePath()); if (!thumbDir.exists() && !thumbDir.mkdirs()) { logger.warn("Could not create thumbnail directory: {}", thumbDir.getAbsolutePath()); } else { File thumbFile = new File(thumbDir, inputFile.getFile().getName() + ".jpg"); String thumbFilename = thumbFile.getAbsolutePath(); logger.trace("Creating (temporary) thumbnail: {}", thumbFilename); // Create the thumbnail image using the Thumbnailator library final Builder<File> thumbnail = Thumbnails.of(inputFile.getFile()); thumbnail.size(320, 180); thumbnail.outputFormat("jpg"); thumbnail.outputQuality(1.0f); try { thumbnail.toFile(thumbFilename); } catch (IIOException e) { logger.debug("Error generating thumbnail for: " + inputFile.getFile().getName()); logger.debug("The full error was: " + e); } File jpg = new File(thumbFilename); if (jpg.exists()) { InputStream is = new FileInputStream(jpg); int sz = is.available(); if (sz > 0) { setThumb(new byte[sz]); is.read(getThumb()); } is.close(); if (!jpg.delete()) { jpg.deleteOnExit(); } } } } catch (UnsupportedFormatException ufe) { logger.debug("Thumbnailator does not support the format of {}: {}", inputFile.getFile().getAbsolutePath(), ufe.getMessage()); } catch (Exception e) { logger.debug("Thumbnailator could not generate a thumbnail for: {}", inputFile.getFile().getAbsolutePath(), e); } } if (ffmpeg_parsing) { if (!thumbOnly || !configuration.isUseMplayerForVideoThumbs()) { pw = getFFmpegThumbnail(inputFile); } String input = "-"; boolean dvrms = false; if (inputFile.getFile() != null) { input = ProcessUtil.getShortFileNameIfWideChars(inputFile.getFile().getAbsolutePath()); dvrms = inputFile.getFile().getAbsolutePath().toLowerCase().endsWith("dvr-ms"); } if (!ffmpeg_failure && !thumbOnly) { if (input.equals("-")) { input = "pipe:"; } boolean matchs = false; ArrayList<String> lines = (ArrayList<String>) pw.getResults(); int langId = 0; int subId = 0; ListIterator<String> FFmpegMetaData = lines.listIterator(); for (String line : lines) { FFmpegMetaData.next(); line = line.trim(); if (line.startsWith("Output")) { matchs = false; } else if (line.startsWith("Input")) { if (line.indexOf(input) > -1) { matchs = true; setContainer(line.substring(10, line.indexOf(",", 11)).trim()); } else { matchs = false; } } else if (matchs) { if (line.indexOf("Duration") > -1) { StringTokenizer st = new StringTokenizer(line, ","); while (st.hasMoreTokens()) { String token = st.nextToken().trim(); if (token.startsWith("Duration: ")) { String durationStr = token.substring(10); int l = durationStr.substring(durationStr.indexOf(".") + 1).length(); if (l < 4) { durationStr = durationStr + "00".substring(0, 3 - l); } if (durationStr.indexOf("N/A") > -1) { setDuration(null); } else { setDuration(parseDurationString(durationStr)); } } else if (token.startsWith("bitrate: ")) { String bitr = token.substring(9); int spacepos = bitr.indexOf(" "); if (spacepos > -1) { String value = bitr.substring(0, spacepos); String unit = bitr.substring(spacepos + 1); setBitrate(Integer.parseInt(value)); if (unit.equals("kb/s")) { setBitrate(1024 * getBitrate()); } if (unit.equals("mb/s")) { setBitrate(1048576 * getBitrate()); } } } } } else if (line.indexOf("Audio:") > -1) { StringTokenizer st = new StringTokenizer(line, ","); int a = line.indexOf("("); int b = line.indexOf("):", a); DLNAMediaAudio audio = new DLNAMediaAudio(); audio.setId(langId++); if (a > -1 && b > a) { audio.setLang(line.substring(a + 1, b)); } else { audio.setLang(DLNAMediaLang.UND); } // Get TS IDs a = line.indexOf("[0x"); b = line.indexOf("]", a); if (a > -1 && b > a + 3) { String idString = line.substring(a + 3, b); try { audio.setId(Integer.parseInt(idString, 16)); } catch (NumberFormatException nfe) { logger.debug("Error parsing Stream ID: " + idString); } } while (st.hasMoreTokens()) { String token = st.nextToken().trim(); Integer nChannels; if (token.startsWith("Stream")) { audio.setCodecA(token.substring(token.indexOf("Audio: ") + 7)); } else if (token.endsWith("Hz")) { audio.setSampleFrequency(token.substring(0, token.indexOf("Hz")).trim()); } else if ((nChannels = audioChannelLayout.get(token)) != null) { audio.getAudioProperties().setNumberOfChannels(nChannels); } else if (token.matches("\\d+(?:\\s+channels?)")) { // implicitly anchored at both ends e.g. ^ ... $ // setNumberOfChannels(String) parses the number out of the string audio.getAudioProperties().setNumberOfChannels(token); } else if (token.equals("s32")) { audio.setBitsperSample(32); } else if (token.equals("s24")) { audio.setBitsperSample(24); } else if (token.equals("s16")) { audio.setBitsperSample(16); } } int FFmpegMetaDataNr = FFmpegMetaData.nextIndex(); if (FFmpegMetaDataNr > -1) { line = lines.get(FFmpegMetaDataNr); } if (line.indexOf("Metadata:") > -1) { FFmpegMetaDataNr = FFmpegMetaDataNr + 1; line = lines.get(FFmpegMetaDataNr); while (line.indexOf(" ") == 0) { if (line.toLowerCase().indexOf("title :") > -1) { int aa = line.indexOf(": "); int bb = line.length(); if (aa > -1 && bb > aa) { audio.setFlavor(line.substring(aa + 2, bb)); break; } } else { FFmpegMetaDataNr = FFmpegMetaDataNr + 1; line = lines.get(FFmpegMetaDataNr); } } } getAudioTracksList().add(audio); } else if (line.indexOf("Video:") > -1) { StringTokenizer st = new StringTokenizer(line, ","); while (st.hasMoreTokens()) { String token = st.nextToken().trim(); if (token.startsWith("Stream")) { setCodecV(token.substring(token.indexOf("Video: ") + 7)); } else if ((token.indexOf("tbc") > -1 || token.indexOf("tb(c)") > -1)) { // A/V sync issues with newest FFmpeg, due to the new tbr/tbn/tbc outputs // Priority to tb(c) String frameRateDoubleString = token.substring(0, token.indexOf("tb")) .trim(); try { if (!frameRateDoubleString.equals(getFrameRate())) {// tbc taken into account only if different than tbr Double frameRateDouble = Double.parseDouble(frameRateDoubleString); setFrameRate( String.format(Locale.ENGLISH, "%.2f", frameRateDouble / 2)); } } catch (NumberFormatException nfe) { // Could happen if tbc is "1k" or something like that, no big deal logger.debug( "Could not parse frame rate \"" + frameRateDoubleString + "\""); } } else if ((token.indexOf("tbr") > -1 || token.indexOf("tb(r)") > -1) && getFrameRate() == null) { setFrameRate(token.substring(0, token.indexOf("tb")).trim()); } else if ((token.indexOf("fps") > -1 || token.indexOf("fps(r)") > -1) && getFrameRate() == null) { // dvr-ms ? setFrameRate(token.substring(0, token.indexOf("fps")).trim()); } else if (token.indexOf("x") > -1) { String resolution = token.trim(); if (resolution.indexOf(" [") > -1) { resolution = resolution.substring(0, resolution.indexOf(" [")); } try { setWidth(Integer .parseInt(resolution.substring(0, resolution.indexOf("x")))); } catch (NumberFormatException nfe) { logger.debug("Could not parse width from \"" + resolution.substring(0, resolution.indexOf("x")) + "\""); } try { setHeight(Integer .parseInt(resolution.substring(resolution.indexOf("x") + 1))); } catch (NumberFormatException nfe) { logger.debug("Could not parse height from \"" + resolution.substring(resolution.indexOf("x") + 1) + "\""); } } } } else if (line.indexOf("Subtitle:") > -1 && !line.contains("tx3g")) { DLNAMediaSubtitle lang = new DLNAMediaSubtitle(); lang.setType((line.contains("dvdsub") && Platform.isWindows() ? SubtitleType.VOBSUB : SubtitleType.UNKNOWN)); int a = line.indexOf("("); int b = line.indexOf("):", a); if (a > -1 && b > a) { lang.setLang(line.substring(a + 1, b)); } else { lang.setLang(DLNAMediaLang.UND); } lang.setId(subId++); int FFmpegMetaDataNr = FFmpegMetaData.nextIndex(); if (FFmpegMetaDataNr > -1) { line = lines.get(FFmpegMetaDataNr); } if (line.indexOf("Metadata:") > -1) { FFmpegMetaDataNr = FFmpegMetaDataNr + 1; line = lines.get(FFmpegMetaDataNr); while (line.indexOf(" ") == 0) { if (line.toLowerCase().indexOf("title :") > -1) { int aa = line.indexOf(": "); int bb = line.length(); if (aa > -1 && bb > aa) { lang.setFlavor(line.substring(aa + 2, bb)); break; } } else { FFmpegMetaDataNr = FFmpegMetaDataNr + 1; line = lines.get(FFmpegMetaDataNr); } } } getSubtitleTracksList().add(lang); } } } } if (!thumbOnly && getContainer() != null && inputFile.getFile() != null && getContainer().equals("mpegts") && isH264() && getDurationInSeconds() == 0) { // Parse the duration try { int length = MpegUtil.getDurationFromMpeg(inputFile.getFile()); if (length > 0) { setDuration((double) length); } } catch (IOException e) { logger.trace("Error retrieving length: " + e.getMessage()); } } if (configuration.isUseMplayerForVideoThumbs() && type == Format.VIDEO && !dvrms) { try { getMplayerThumbnail(inputFile); String frameName = "" + inputFile.hashCode(); frameName = configuration.getTempFolder() + "/mplayer_thumbs/" + frameName + "00000001/00000001.jpg"; frameName = frameName.replace(',', '_'); File jpg = new File(frameName); if (jpg.exists()) { InputStream is = new FileInputStream(jpg); int sz = is.available(); if (sz > 0) { setThumb(new byte[sz]); is.read(getThumb()); } is.close(); if (!jpg.delete()) { jpg.deleteOnExit(); } // Try and retry if (!jpg.getParentFile().delete() && !jpg.getParentFile().delete()) { logger.debug("Failed to delete \"" + jpg.getParentFile().getAbsolutePath() + "\""); } } } catch (IOException e) { logger.debug("Caught exception", e); } } if (type == Format.VIDEO && pw != null && getThumb() == null) { InputStream is; try { is = pw.getInputStream(0); int sz = is.available(); if (sz > 0) { setThumb(new byte[sz]); is.read(getThumb()); } is.close(); if (sz > 0 && !net.pms.PMS.isHeadless()) { BufferedImage image = ImageIO.read(new ByteArrayInputStream(getThumb())); if (image != null) { Graphics g = image.getGraphics(); g.setColor(Color.WHITE); g.setFont(new Font("Arial", Font.PLAIN, 14)); int low = 0; if (getWidth() > 0) { if (getWidth() == 1920 || getWidth() == 1440) { g.drawString("1080p", 0, low += 18); } else if (getWidth() == 1280) { g.drawString("720p", 0, low += 18); } } ByteArrayOutputStream out = new ByteArrayOutputStream(); ImageIO.write(image, "jpeg", out); setThumb(out.toByteArray()); } } } catch (IOException e) { logger.debug("Error while decoding thumbnail: " + e.getMessage()); } } } finalize(type, inputFile); setMediaparsed(true); } }