Java Code Examples for com.facebook.imageutils.JfifUtil

The following examples show how to use com.facebook.imageutils.JfifUtil. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@Override
protected void onNewResultImpl(
    CloseableReference<PooledByteBuffer> newResult, boolean isLast) {
  final ImageFormat imageFormat =
      ImageFormatChecker.getImageFormat_WrapIOException(newResult.get().getStream());
  mMetaDataBuilder.reset();
  mMetaDataBuilder.setImageFormat(imageFormat);
  if (imageFormat == ImageFormat.JPEG && isLast) {
    mMetaDataBuilder.setRotationAngle(getRotationAngle(newResult));
    Rect dimensions = JfifUtil.getDimensions(newResult.get().getStream());
    if (dimensions != null) {
      mMetaDataBuilder.setWidth(dimensions.width());
      mMetaDataBuilder.setHeight(dimensions.height());
    }
  }
  mConsumer.onNewResult(Pair.create(newResult, mMetaDataBuilder.build()), isLast);
}
 
Example 2
Source Project: fresco   Source File: AddImageTransformMetaDataProducerTest.java    License: MIT License 6 votes vote down vote up
@Before
public void setUp() {
  MockitoAnnotations.initMocks(this);
  PowerMockito.mockStatic(ImageFormatChecker.class, JfifUtil.class, BitmapUtil.class);

  mAddMetaDataProducer = new AddImageTransformMetaDataProducer(mInputProducer);

  mIntermediateResultBufferRef = CloseableReference.of(mock(PooledByteBuffer.class));
  mFinalResultBufferRef = CloseableReference.of(mock(PooledByteBuffer.class));

  mIntermediateResult = new EncodedImage(mIntermediateResultBufferRef);
  mFinalResult = new EncodedImage(mFinalResultBufferRef);

  mAddMetaDataConsumer = null;
  doAnswer(
          new Answer() {
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable {
              mAddMetaDataConsumer = (Consumer<EncodedImage>) invocation.getArguments()[0];
              return null;
            }
          })
      .when(mInputProducer)
      .produceResults(any(Consumer.class), any(ProducerContext.class));
  mAddMetaDataProducer.produceResults(mConsumer, mProducerContext);
}
 
Example 3
Source Project: fresco   Source File: AddImageTransformMetaDataProducerTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testOnNewResultNotLast_DimensionsNotFound() {
  int rotationAngle = 180;
  int orientation = 1;
  when(ImageFormatChecker.getImageFormat_WrapIOException(any(InputStream.class)))
      .thenReturn(DefaultImageFormats.JPEG);
  when(JfifUtil.getAutoRotateAngleFromOrientation(orientation)).thenReturn(rotationAngle);
  when(JfifUtil.getOrientation(any(InputStream.class))).thenReturn(orientation);
  when(BitmapUtil.decodeDimensionsAndColorSpace(any(InputStream.class)))
      .thenReturn(new ImageMetaData(-1, -1, null));
  mAddMetaDataConsumer.onNewResult(mIntermediateResult, Consumer.NO_FLAGS);
  ArgumentCaptor<EncodedImage> argumentCaptor = ArgumentCaptor.forClass(EncodedImage.class);
  verify(mConsumer).onNewResult(argumentCaptor.capture(), eq(Consumer.NO_FLAGS));
  EncodedImage encodedImage = argumentCaptor.getValue();
  assertTrue(EncodedImage.isValid(encodedImage));
  assertEquals(-1, encodedImage.getRotationAngle());
  assertEquals(-1, encodedImage.getWidth());
  assertEquals(-1, encodedImage.getHeight());
}
 
Example 4
Source Project: fresco   Source File: AddImageTransformMetaDataProducerTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testOnNewResultNotLast_RotationNotFound() {
  when(ImageFormatChecker.getImageFormat_WrapIOException(any(InputStream.class)))
      .thenReturn(DefaultImageFormats.JPEG);
  when(JfifUtil.getOrientation(any(InputStream.class))).thenReturn(0);
  when(BitmapUtil.decodeDimensionsAndColorSpace(any(InputStream.class)))
      .thenReturn(new ImageMetaData(-1, -1, null));
  mAddMetaDataConsumer.onNewResult(mIntermediateResult, Consumer.NO_FLAGS);
  ArgumentCaptor<EncodedImage> argumentCaptor = ArgumentCaptor.forClass(EncodedImage.class);
  verify(mConsumer).onNewResult(argumentCaptor.capture(), eq(Consumer.NO_FLAGS));
  EncodedImage encodedImage = argumentCaptor.getValue();
  assertTrue(EncodedImage.isValid(encodedImage));
  assertEquals(-1, encodedImage.getRotationAngle());
  assertEquals(-1, encodedImage.getWidth());
  assertEquals(-1, encodedImage.getHeight());
}
 
Example 5
Source Project: fresco   Source File: AddImageTransformMetaDataProducerTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testOnNewResultNotLastAndJpeg() {
  int rotationAngle = 180;
  int orientation = 1;
  int width = 10;
  int height = 20;
  when(ImageFormatChecker.getImageFormat_WrapIOException(any(InputStream.class)))
      .thenReturn(DefaultImageFormats.JPEG);
  when(JfifUtil.getAutoRotateAngleFromOrientation(orientation)).thenReturn(rotationAngle);
  when(JfifUtil.getOrientation(any(InputStream.class))).thenReturn(orientation);
  when(BitmapUtil.decodeDimensionsAndColorSpace(any(InputStream.class)))
      .thenReturn(new ImageMetaData(width, height, null));
  mAddMetaDataConsumer.onNewResult(mFinalResult, Consumer.IS_LAST);
  ArgumentCaptor<EncodedImage> argumentCaptor = ArgumentCaptor.forClass(EncodedImage.class);
  verify(mConsumer).onNewResult(argumentCaptor.capture(), eq(Consumer.IS_LAST));
  EncodedImage encodedImage = argumentCaptor.getValue();
  assertTrue(EncodedImage.isValid(encodedImage));
  assertEquals(DefaultImageFormats.JPEG, encodedImage.getImageFormat());
  assertEquals(rotationAngle, encodedImage.getRotationAngle());
  assertEquals(width, encodedImage.getWidth());
  assertEquals(height, encodedImage.getHeight());
}
 
Example 6
Source Project: fresco   Source File: AddImageTransformMetaDataProducerTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testOnNewResultLastAndJpeg() {
  int rotationAngle = 180;
  int orientation = 1;
  int width = 10;
  int height = 20;
  when(ImageFormatChecker.getImageFormat_WrapIOException(any(InputStream.class)))
      .thenReturn(DefaultImageFormats.JPEG);
  when(JfifUtil.getAutoRotateAngleFromOrientation(orientation)).thenReturn(rotationAngle);
  when(JfifUtil.getOrientation(any(InputStream.class))).thenReturn(orientation);
  when(BitmapUtil.decodeDimensionsAndColorSpace(any(InputStream.class)))
      .thenReturn(new ImageMetaData(width, height, null));
  mAddMetaDataConsumer.onNewResult(mFinalResult, Consumer.IS_LAST);
  ArgumentCaptor<EncodedImage> argumentCaptor = ArgumentCaptor.forClass(EncodedImage.class);
  verify(mConsumer).onNewResult(argumentCaptor.capture(), eq(Consumer.IS_LAST));
  EncodedImage encodedImage = argumentCaptor.getValue();
  assertTrue(EncodedImage.isValid(encodedImage));
  assertEquals(DefaultImageFormats.JPEG, encodedImage.getImageFormat());
  assertEquals(rotationAngle, encodedImage.getRotationAngle());
  assertEquals(width, encodedImage.getWidth());
  assertEquals(height, encodedImage.getHeight());
}
 
Example 7
Source Project: FimiX8-RE   Source File: SecurePreferencesOld.java    License: MIT License 5 votes vote down vote up
@Deprecated
private static String generateAesKeyValue() throws NoSuchAlgorithmException {
    SecureRandom random = new SecureRandom();
    KeyGenerator generator = KeyGenerator.getInstance(AES_KEY_ALG);
    try {
        generator.init(256, random);
    } catch (Exception e) {
        try {
            generator.init(JfifUtil.MARKER_SOFn, random);
        } catch (Exception e2) {
            generator.init(128, random);
        }
    }
    return encode(generator.generateKey().getEncoded());
}
 
Example 8
/**
 * Creates a bitmap from encoded JPEG bytes. Supports a partial JPEG image.
 *
 * @param pooledByteBufferRef the reference to the encoded bytes
 * @param length the number of encoded bytes in the buffer
 * @return the bitmap
 * @throws java.lang.OutOfMemoryError if the Bitmap cannot be allocated
 */
CloseableReference<Bitmap> decodeJPEGFromPooledByteBuffer(
    CloseableReference<PooledByteBuffer> pooledByteBufferRef,
    int length) {
  final PooledByteBuffer pooledByteBuffer = pooledByteBufferRef.get();
  final InputStream jpegBufferInputStream = pooledByteBuffer.getStream();
  jpegBufferInputStream.mark(Integer.MAX_VALUE);

  boolean isJpegComplete;
  try {
    jpegBufferInputStream.skip(length - 2);
    isJpegComplete = (jpegBufferInputStream.read() == JfifUtil.MARKER_FIRST_BYTE) &&
        (jpegBufferInputStream.read() == JfifUtil.MARKER_EOI);
    jpegBufferInputStream.reset();
  } catch (IOException ioe) {
    throw new RuntimeException(ioe);
  }

  InputStream jpegDataStream = jpegBufferInputStream;
  if (pooledByteBuffer.size() > length) {
    jpegDataStream = new LimitedInputStream(jpegDataStream, length);
  }
  if (!isJpegComplete) {
    jpegDataStream = new TailAppendingInputStream(jpegDataStream, EOI_TAIL);
  }
  return doDecodeStaticImage(jpegDataStream);
}
 
Example 9
private ImageTransformMetaData getImageTransformMetaData(
    PooledByteBuffer imageRef,
    ExifInterface exifInterface) {
  ImageTransformMetaData.Builder builder = ImageTransformMetaData.newBuilder()
      .setImageFormat(ImageFormat.JPEG);
  builder.setRotationAngle(getRotationAngle(exifInterface));
  Rect dimensions = JfifUtil.getDimensions(imageRef.getStream());
  if (dimensions != null) {
    builder.setWidth(dimensions.width());
    builder.setHeight(dimensions.height());
  }
  return builder.build();
}
 
Example 10
/**
 * Not every marker is followed by associated segment
 */
private static boolean doesMarkerStartSegment(int markerSecondByte) {
  if (markerSecondByte == JfifUtil.MARKER_TEM) {
    return false;
  }

  if (markerSecondByte >= JfifUtil.MARKER_RST0 && markerSecondByte <= JfifUtil.MARKER_RST7) {
    return false;
  }

  return markerSecondByte != JfifUtil.MARKER_EOI && markerSecondByte != JfifUtil.MARKER_SOI;
}
 
Example 11
Source Project: fresco   Source File: EncodedImage.java    License: MIT License 5 votes vote down vote up
/**
 * Returns true if the image is a JPEG or DNG and its data is already complete at the specified
 * length, false otherwise.
 */
public boolean isCompleteAt(int length) {
  if (mImageFormat != DefaultImageFormats.JPEG && mImageFormat != DefaultImageFormats.DNG) {
    return true;
  }
  // If the image is backed by FileInputStreams return true since they will always be complete.
  if (mInputStreamSupplier != null) {
    return true;
  }
  // The image should be backed by a ByteBuffer
  Preconditions.checkNotNull(mPooledByteBufferRef);
  PooledByteBuffer buf = mPooledByteBufferRef.get();
  return (buf.read(length - 2) == (byte) JfifUtil.MARKER_FIRST_BYTE)
      && (buf.read(length - 1) == (byte) JfifUtil.MARKER_EOI);
}
 
Example 12
Source Project: fresco   Source File: EncodedImage.java    License: MIT License 5 votes vote down vote up
/** Sets the encoded image meta data. */
public void parseMetaData() {
  final ImageFormat imageFormat =
      ImageFormatChecker.getImageFormat_WrapIOException(getInputStream());
  mImageFormat = imageFormat;
  // BitmapUtil.decodeDimensions has a bug where it will return 100x100 for some WebPs even though
  // those are not its actual dimensions
  final Pair<Integer, Integer> dimensions;
  if (DefaultImageFormats.isWebpFormat(imageFormat)) {
    dimensions = readWebPImageSize();
  } else {
    dimensions = readImageMetaData().getDimensions();
  }
  if (imageFormat == DefaultImageFormats.JPEG && mRotationAngle == UNKNOWN_ROTATION_ANGLE) {
    // Load the JPEG rotation angle only if we have the dimensions
    if (dimensions != null) {
      mExifOrientation = JfifUtil.getOrientation(getInputStream());
      mRotationAngle = JfifUtil.getAutoRotateAngleFromOrientation(mExifOrientation);
    }
  } else if (imageFormat == DefaultImageFormats.HEIF
      && mRotationAngle == UNKNOWN_ROTATION_ANGLE) {
    mExifOrientation = HeifExifUtil.getOrientation(getInputStream());
    mRotationAngle = JfifUtil.getAutoRotateAngleFromOrientation(mExifOrientation);
  } else if (mRotationAngle == UNKNOWN_ROTATION_ANGLE) {
    mRotationAngle = 0;
  }
}
 
Example 13
Source Project: fresco   Source File: EncodedImageTest.java    License: MIT License 5 votes vote down vote up
@Test
public void testIsJpegCompleteAt_Complete() {
  byte[] encodedBytes = new byte[ENCODED_BYTES_LENGTH];
  encodedBytes[ENCODED_BYTES_LENGTH - 2] = (byte) JfifUtil.MARKER_FIRST_BYTE;
  encodedBytes[ENCODED_BYTES_LENGTH - 1] = (byte) JfifUtil.MARKER_EOI;
  PooledByteBuffer buf = new TrivialPooledByteBuffer(encodedBytes);
  EncodedImage encodedImage = new EncodedImage(CloseableReference.of(buf));
  encodedImage.setImageFormat(DefaultImageFormats.JPEG);
  assertTrue(encodedImage.isCompleteAt(ENCODED_BYTES_LENGTH));
}
 
Example 14
Source Project: fresco   Source File: LocalContentUriThumbnailFetchProducer.java    License: MIT License 5 votes vote down vote up
private static int getRotationAngle(String pathname) {
  if (pathname != null) {
    try {
      ExifInterface exif = new ExifInterface(pathname);
      return JfifUtil.getAutoRotateAngleFromOrientation(
          exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL));
    } catch (IOException ioe) {
      FLog.e(TAG, ioe, "Unable to retrieve thumbnail rotation for %s", pathname);
    }
  }
  return 0;
}
 
Example 15
Source Project: fresco   Source File: ProgressiveJpegParser.java    License: MIT License 5 votes vote down vote up
/** Not every marker is followed by associated segment */
private static boolean doesMarkerStartSegment(int markerSecondByte) {
  if (markerSecondByte == JfifUtil.MARKER_TEM) {
    return false;
  }

  if (markerSecondByte >= JfifUtil.MARKER_RST0 && markerSecondByte <= JfifUtil.MARKER_RST7) {
    return false;
  }

  return markerSecondByte != JfifUtil.MARKER_EOI && markerSecondByte != JfifUtil.MARKER_SOI;
}
 
Example 16
Source Project: fresco   Source File: ArtDecoderTest.java    License: MIT License 5 votes vote down vote up
private void jpegTestCase(boolean complete, int dataLength) {
  if (complete) {
    mEncodedBytes[dataLength - 2] = (byte) JfifUtil.MARKER_FIRST_BYTE;
    mEncodedBytes[dataLength - 1] = (byte) JfifUtil.MARKER_EOI;
  }
  CloseableReference<Bitmap> result =
      mArtDecoder.decodeJPEGFromEncodedImage(
          mEncodedImage, DEFAULT_BITMAP_CONFIG, null, dataLength);
  verifyDecodedFromStream();
  verifyNoLeaks();
  verifyDecodedBytes(complete, dataLength);
  closeAndVerifyClosed(result);
}
 
Example 17
Source Project: fresco   Source File: ArtDecoderTest.java    License: MIT License 5 votes vote down vote up
private void verifyDecodedBytes(boolean complete, int length) {
  byte[] decodedBytes = getDecodedBytes();
  assertArrayEquals(
      Arrays.copyOfRange(mEncodedBytes, 0, length), Arrays.copyOfRange(decodedBytes, 0, length));
  if (complete) {
    assertEquals(length, decodedBytes.length);
  } else {
    assertEquals(length + 2, decodedBytes.length);
    assertEquals((byte) JfifUtil.MARKER_FIRST_BYTE, decodedBytes[length]);
    assertEquals((byte) JfifUtil.MARKER_EOI, decodedBytes[length + 1]);
  }
}
 
Example 18
Source Project: fresco   Source File: LocalExifThumbnailProducerTest.java    License: MIT License 5 votes vote down vote up
@Before
public void setUp() throws IOException {
  MockitoAnnotations.initMocks(this);
  PowerMockito.mockStatic(JfifUtil.class, BitmapUtil.class);
  mTestExecutorService = new TestExecutorService(new FakeClock());

  mTestLocalExifThumbnailProducer =
      new TestLocalExifThumbnailProducer(
          mTestExecutorService, mPooledByteBufferFactory, mContentResolver);

  when(mProducerContext.getImageRequest()).thenReturn(mImageRequest);
  when(mImageRequest.getSourceUri()).thenReturn(mUri);
  when(mProducerContext.getProducerListener()).thenReturn(mProducerListener);

  mThumbnailBytes = new byte[100];
  when(mExifInterface.hasThumbnail()).thenReturn(true);
  when(mExifInterface.getThumbnail()).thenReturn(mThumbnailBytes);
  when(mPooledByteBufferFactory.newByteBuffer(mThumbnailBytes)).thenReturn(mThumbnailByteBuffer);

  when(mExifInterface.getAttribute(ExifInterface.TAG_ORIENTATION))
      .thenReturn(Integer.toString(ORIENTATION));
  when(JfifUtil.getAutoRotateAngleFromOrientation(ORIENTATION)).thenReturn(ANGLE);
  when(BitmapUtil.decodeDimensions(any(InputStream.class))).thenReturn(new Pair(WIDTH, HEIGHT));

  doAnswer(
          new Answer() {
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable {
              mCapturedEncodedImage =
                  EncodedImage.cloneOrNull((EncodedImage) invocation.getArguments()[0]);
              return null;
            }
          })
      .when(mConsumer)
      .onNewResult(notNull(EncodedImage.class), anyInt());
}
 
Example 19
Source Project: fresco   Source File: DalvikPurgeableDecoder.java    License: MIT License 5 votes vote down vote up
@VisibleForTesting
public static boolean endsWithEOI(CloseableReference<PooledByteBuffer> bytesRef, int length) {
  PooledByteBuffer buffer = bytesRef.get();
  return length >= 2
      && buffer.read(length - 2) == (byte) JfifUtil.MARKER_FIRST_BYTE
      && buffer.read(length - 1) == (byte) JfifUtil.MARKER_EOI;
}
 
Example 20
private static void putEOI(byte[] imageBytes, int offset) {
  // TODO 5884402: remove dependency on JfifUtil
  imageBytes[offset] = (byte) JfifUtil.MARKER_FIRST_BYTE;
  imageBytes[offset + 1] = (byte) JfifUtil.MARKER_EOI;
}
 
Example 21
private static boolean endsWithEOI(final byte[] imageBytes, int length) {
  // TODO 5884402: remove dependency on JfifUtil
  return length >= 2 &&
      imageBytes[length - 2] == (byte) JfifUtil.MARKER_FIRST_BYTE &&
      imageBytes[length - 1] == (byte) JfifUtil.MARKER_EOI;
}
 
Example 22
private int getRotationAngle(final ExifInterface exifInterface) {
  return JfifUtil.getAutoRotateAngleFromOrientation(
      Integer.parseInt(exifInterface.getAttribute(ExifInterface.TAG_ORIENTATION)));
}
 
Example 23
private int getRotationAngle(final CloseableReference<PooledByteBuffer> inputRef) {
  return JfifUtil.getAutoRotateAngleFromOrientation(
      JfifUtil.getOrientation(inputRef.get().getStream()));
}
 
Example 24
/**
 * Parses more data from inputStream.
 *
 * @param inputStream instance of buffered pooled byte buffer input stream
 */
private boolean doParseMoreData(final InputStream inputStream) {
  final int oldBestScanNumber = mBestScanNumber;
  try {
    int nextByte;
    while (mParserState != NOT_A_JPEG && (nextByte = inputStream.read()) != -1) {
      mBytesParsed++;

      switch (mParserState) {
        case READ_FIRST_JPEG_BYTE:
          if (nextByte == JfifUtil.MARKER_FIRST_BYTE) {
            mParserState = READ_SECOND_JPEG_BYTE;
          } else {
            mParserState = NOT_A_JPEG;
          }
          break;

        case READ_SECOND_JPEG_BYTE:
          if (nextByte == JfifUtil.MARKER_SOI) {
            mParserState = READ_MARKER_FIRST_BYTE_OR_ENTROPY_DATA;
          } else {
            mParserState = NOT_A_JPEG;
          }
          break;

        case READ_MARKER_FIRST_BYTE_OR_ENTROPY_DATA:
          if (nextByte == JfifUtil.MARKER_FIRST_BYTE) {
            mParserState = READ_MARKER_SECOND_BYTE;
          }
          break;

        case READ_MARKER_SECOND_BYTE:
          if (nextByte == JfifUtil.MARKER_FIRST_BYTE) {
            mParserState = READ_MARKER_SECOND_BYTE;
          } else if (nextByte == JfifUtil.MARKER_ESCAPE_BYTE) {
            mParserState = READ_MARKER_FIRST_BYTE_OR_ENTROPY_DATA;
          } else {
            if (nextByte == JfifUtil.MARKER_SOS || nextByte == JfifUtil.MARKER_EOI) {
              newScanOrImageEndFound(mBytesParsed - 2);
            }

            if (doesMarkerStartSegment(nextByte)) {
              mParserState = READ_SIZE_FIRST_BYTE;
            } else {
              mParserState = READ_MARKER_FIRST_BYTE_OR_ENTROPY_DATA;
            }
          }
          break;

        case READ_SIZE_FIRST_BYTE:
          mParserState = READ_SIZE_SECOND_BYTE;
          break;

        case READ_SIZE_SECOND_BYTE:
          final int size = (mLastByteRead << 8) + nextByte;
          // We need to jump after the end of the segment - skip size-2 next bytes.
          // We might want to skip more data than is available to read, in which case we will
          // consume entire data in inputStream and exit this function before entering another
          // iteration of the loop.
          final int bytesToSkip = size - 2;
          StreamUtil.skip(inputStream, bytesToSkip);
          mBytesParsed += bytesToSkip;
          mParserState = READ_MARKER_FIRST_BYTE_OR_ENTROPY_DATA;
          break;

        case NOT_A_JPEG:
        default:
          Preconditions.checkState(false);
      }

      mLastByteRead = nextByte;
    }
  } catch (IOException ioe) {
    // does not happen, input stream returned by pooled byte buffer does not throw IOExceptions
    Throwables.propagate(ioe);
  }
  return mParserState != NOT_A_JPEG && mBestScanNumber != oldBestScanNumber;
}
 
Example 25
Source Project: fresco   Source File: LocalExifThumbnailProducer.java    License: MIT License 4 votes vote down vote up
private int getRotationAngle(final ExifInterface exifInterface) {
  return JfifUtil.getAutoRotateAngleFromOrientation(
      Integer.parseInt(exifInterface.getAttribute(ExifInterface.TAG_ORIENTATION)));
}
 
Example 26
Source Project: fresco   Source File: ProgressiveJpegParser.java    License: MIT License 4 votes vote down vote up
/**
 * Parses more data from inputStream.
 *
 * @param inputStream instance of buffered pooled byte buffer input stream
 */
private boolean doParseMoreData(final InputStream inputStream) {
  final int oldBestScanNumber = mBestScanNumber;
  try {
    int nextByte;
    while (mParserState != NOT_A_JPEG && (nextByte = inputStream.read()) != -1) {
      mBytesParsed++;
      if (mEndMarkerRead) {
        // There should be no more data after the EOI marker, just in case there is lets
        // bail out instead of trying to parse the unknown data
        mParserState = NOT_A_JPEG;
        mEndMarkerRead = false;
        return false;
      }
      switch (mParserState) {
        case READ_FIRST_JPEG_BYTE:
          if (nextByte == JfifUtil.MARKER_FIRST_BYTE) {
            mParserState = READ_SECOND_JPEG_BYTE;
          } else {
            mParserState = NOT_A_JPEG;
          }
          break;

        case READ_SECOND_JPEG_BYTE:
          if (nextByte == JfifUtil.MARKER_SOI) {
            mParserState = READ_MARKER_FIRST_BYTE_OR_ENTROPY_DATA;
          } else {
            mParserState = NOT_A_JPEG;
          }
          break;

        case READ_MARKER_FIRST_BYTE_OR_ENTROPY_DATA:
          if (nextByte == JfifUtil.MARKER_FIRST_BYTE) {
            mParserState = READ_MARKER_SECOND_BYTE;
          }
          break;

        case READ_MARKER_SECOND_BYTE:
          if (nextByte == JfifUtil.MARKER_FIRST_BYTE) {
            mParserState = READ_MARKER_SECOND_BYTE;
          } else if (nextByte == JfifUtil.MARKER_ESCAPE_BYTE) {
            mParserState = READ_MARKER_FIRST_BYTE_OR_ENTROPY_DATA;
          } else if (nextByte == JfifUtil.MARKER_EOI) {
            mEndMarkerRead = true;
            newScanOrImageEndFound(mBytesParsed - 2);
            // There should be no data after the EOI marker, but in case there is, let's process
            // the next byte as a first marker byte.
            mParserState = READ_MARKER_FIRST_BYTE_OR_ENTROPY_DATA;
          } else {
            if (nextByte == JfifUtil.MARKER_SOS) {
              newScanOrImageEndFound(mBytesParsed - 2);
            }

            if (doesMarkerStartSegment(nextByte)) {
              mParserState = READ_SIZE_FIRST_BYTE;
            } else {
              mParserState = READ_MARKER_FIRST_BYTE_OR_ENTROPY_DATA;
            }
          }
          break;

        case READ_SIZE_FIRST_BYTE:
          mParserState = READ_SIZE_SECOND_BYTE;
          break;

        case READ_SIZE_SECOND_BYTE:
          final int size = (mLastByteRead << 8) + nextByte;
          // We need to jump after the end of the segment - skip size-2 next bytes.
          // We might want to skip more data than is available to read, in which case we will
          // consume entire data in inputStream and exit this function before entering another
          // iteration of the loop.
          final int bytesToSkip = size - 2;
          StreamUtil.skip(inputStream, bytesToSkip);
          mBytesParsed += bytesToSkip;
          mParserState = READ_MARKER_FIRST_BYTE_OR_ENTROPY_DATA;
          break;

        case NOT_A_JPEG:
        default:
          Preconditions.checkState(false);
      }

      mLastByteRead = nextByte;
    }
  } catch (IOException ioe) {
    // does not happen, input stream returned by pooled byte buffer does not throw IOExceptions
    Throwables.propagate(ioe);
  }
  return mParserState != NOT_A_JPEG && mBestScanNumber != oldBestScanNumber;
}
 
Example 27
Source Project: fresco   Source File: KitKatPurgeableDecoder.java    License: MIT License 4 votes vote down vote up
private static void putEOI(byte[] imageBytes, int offset) {
  // TODO 5884402: remove dependency on JfifUtil
  imageBytes[offset] = (byte) JfifUtil.MARKER_FIRST_BYTE;
  imageBytes[offset + 1] = (byte) JfifUtil.MARKER_EOI;
}