index
int64
0
0
repo_id
stringlengths
26
205
file_path
stringlengths
51
246
content
stringlengths
8
433k
__index_level_0__
int64
0
10k
0
Create_ds/aws-sdk-java-v2/services/ec2/src/test/java/software/amazon/awssdk/services/ec2/transform
Create_ds/aws-sdk-java-v2/services/ec2/src/test/java/software/amazon/awssdk/services/ec2/transform/internal/GeneratePreSignUrlInterceptorTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.ec2.transform.internal; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; import static software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute.AWS_CREDENTIALS; import java.net.URI; import java.time.Clock; import java.time.Instant; import java.time.ZoneId; import java.time.ZonedDateTime; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.services.ec2.model.CopySnapshotRequest; @RunWith(MockitoJUnitRunner.class) public class GeneratePreSignUrlInterceptorTest { private static final GeneratePreSignUrlInterceptor INTERCEPTOR = new GeneratePreSignUrlInterceptor(); @Mock private Context.ModifyHttpRequest mockContext; @Test public void copySnapshotRequest_httpsProtocolAddedToEndpoint() { SdkHttpFullRequest request = SdkHttpFullRequest.builder() .uri(URI.create("https://ec2.us-west-2.amazonaws.com")) .method(SdkHttpMethod.POST) .build(); CopySnapshotRequest ec2Request = CopySnapshotRequest.builder() .sourceRegion("us-west-2") .destinationRegion("us-east-2") .build(); when(mockContext.httpRequest()).thenReturn(request); when(mockContext.request()).thenReturn(ec2Request); ExecutionAttributes attrs = new ExecutionAttributes(); attrs.putAttribute(AWS_CREDENTIALS, AwsBasicCredentials.create("foo", "bar")); SdkHttpRequest modifiedRequest = INTERCEPTOR.modifyHttpRequest(mockContext, attrs); String presignedUrl = modifiedRequest.rawQueryParameters().get("PresignedUrl").get(0); assertThat(presignedUrl).startsWith("https://"); } @Test public void copySnapshotRequest_generatesCorrectPresignedUrl() { // Expected URL was derived by first making a request to EC2 using // valid credentials and a KMS encrypted snapshot and verifying that // the snapshot was copied to the destination region, also encrypted. // Then the same code was used to make a second request, changing only // the credentials and snapshot ID. String expectedPresignedUrl = "https://ec2.us-west-2.amazonaws.com?Action=CopySnapshot" + "&Version=2016-11-15" + "&DestinationRegion=us-east-1" + "&SourceRegion=us-west-2" + "&SourceSnapshotId=SNAPSHOT_ID" + "&X-Amz-Algorithm=AWS4-HMAC-SHA256" + "&X-Amz-Date=20200107T205609Z" + "&X-Amz-SignedHeaders=host" + "&X-Amz-Expires=604800" + "&X-Amz-Credential=akid%2F20200107%2Fus-west-2%2Fec2%2Faws4_request" + "&X-Amz-Signature=c1f5e34834292a86ff2b46b5e97cebaf2967b09641b4e2e60a382a37d137a03b"; ZoneId utcZone = ZoneId.of("UTC").normalized(); // Same signing date as the one used for the request above Instant signingInstant = ZonedDateTime.of(2020, 1, 7, 20, 56, 9, 0, utcZone).toInstant(); Clock signingClock = Clock.fixed(signingInstant, utcZone); GeneratePreSignUrlInterceptor interceptor = new GeneratePreSignUrlInterceptor(signingClock); // These details don't really affect the test as they're not used in generating the signed URL SdkHttpFullRequest request = SdkHttpFullRequest.builder() .uri(URI.create("https://ec2.us-west-2.amazonaws.com")) .method(SdkHttpMethod.POST) .build(); CopySnapshotRequest ec2Request = CopySnapshotRequest.builder() .sourceRegion("us-west-2") .destinationRegion("us-east-1") .sourceSnapshotId("SNAPSHOT_ID") .build(); when(mockContext.httpRequest()).thenReturn(request); when(mockContext.request()).thenReturn(ec2Request); ExecutionAttributes attrs = new ExecutionAttributes(); attrs.putAttribute(AWS_CREDENTIALS, AwsBasicCredentials.create("akid", "skid")); SdkHttpRequest modifiedRequest = interceptor.modifyHttpRequest(mockContext, attrs); String generatedPresignedUrl = modifiedRequest.rawQueryParameters().get("PresignedUrl").get(0); assertThat(generatedPresignedUrl).isEqualTo(expectedPresignedUrl); } }
4,900
0
Create_ds/aws-sdk-java-v2/services/ec2/src/main/java/software/amazon/awssdk/services/ec2/transform
Create_ds/aws-sdk-java-v2/services/ec2/src/main/java/software/amazon/awssdk/services/ec2/transform/internal/TimestampFormatInterceptor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.ec2.transform.internal; import java.util.List; import java.util.regex.Pattern; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.services.ec2.model.DescribeSpotFleetRequestHistoryRequest; import software.amazon.awssdk.services.ec2.model.RequestSpotFleetRequest; /** * A request handler that strips out millisecond precision from requests to * RequestSpotFleet and DescribeSpotFleetRequestHistory, which don't expect * timestamps to be so precise. */ @SdkInternalApi public final class TimestampFormatInterceptor implements ExecutionInterceptor { private static final Pattern PATTERN = Pattern.compile("\\.\\d\\d\\dZ"); private static final String START_TIME = "StartTime"; private static final String VALID_FROM = "SpotFleetRequestConfig.ValidFrom"; private static final String VALID_UNTIL = "SpotFleetRequestConfig.ValidUntil"; @Override public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { SdkHttpRequest request = context.httpRequest(); Object original = context.request(); if (original instanceof DescribeSpotFleetRequestHistoryRequest) { List<String> startTime = request.firstMatchingRawQueryParameters(START_TIME); if (startTime != null && !startTime.isEmpty()) { return request.toBuilder() .putRawQueryParameter(START_TIME, sanitize(startTime.get(0))) .build(); } } else if (original instanceof RequestSpotFleetRequest) { List<String> validFrom = request.firstMatchingRawQueryParameters(VALID_FROM); List<String> validUntil = request.firstMatchingRawQueryParameters(VALID_UNTIL); return request.toBuilder().applyMutation(builder -> { if (validFrom != null && !validFrom.isEmpty()) { builder.putRawQueryParameter(VALID_FROM, sanitize(validFrom.get(0))); } if (validUntil != null && !validUntil.isEmpty()) { builder.putRawQueryParameter(VALID_UNTIL, sanitize(validUntil.get(0))); } }).build(); } return request; } private String sanitize(String input) { return PATTERN.matcher(input).replaceFirst("Z"); } }
4,901
0
Create_ds/aws-sdk-java-v2/services/ec2/src/main/java/software/amazon/awssdk/services/ec2/transform
Create_ds/aws-sdk-java-v2/services/ec2/src/main/java/software/amazon/awssdk/services/ec2/transform/internal/GeneratePreSignUrlInterceptor.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.services.ec2.transform.internal; import static software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute.AWS_CREDENTIALS; import static software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME; import java.net.URI; import java.time.Clock; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.SdkTestInternalApi; import software.amazon.awssdk.auth.credentials.AwsCredentials; import software.amazon.awssdk.auth.credentials.CredentialUtils; import software.amazon.awssdk.auth.signer.Aws4Signer; import software.amazon.awssdk.auth.signer.params.Aws4PresignerParams; import software.amazon.awssdk.awscore.util.AwsHostNameUtils; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.client.config.SdkClientOption; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.protocols.query.AwsEc2ProtocolFactory; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.ec2.Ec2Client; import software.amazon.awssdk.services.ec2.model.CopySnapshotRequest; import software.amazon.awssdk.services.ec2.transform.CopySnapshotRequestMarshaller; import software.amazon.awssdk.utils.CompletableFutureUtils; /** * ExecutionInterceptor that generates a pre-signed URL for copying encrypted snapshots */ @SdkInternalApi public final class GeneratePreSignUrlInterceptor implements ExecutionInterceptor { private static final URI CUSTOM_ENDPOINT_LOCALHOST = URI.create("http://localhost"); private static final AwsEc2ProtocolFactory PROTOCOL_FACTORY = AwsEc2ProtocolFactory .builder() // Need an endpoint to marshall but this will be overwritten in modifyHttpRequest .clientConfiguration(SdkClientConfiguration.builder() .option(SdkClientOption.ENDPOINT, CUSTOM_ENDPOINT_LOCALHOST) .build()) .build(); private static final CopySnapshotRequestMarshaller MARSHALLER = new CopySnapshotRequestMarshaller(PROTOCOL_FACTORY); private final Clock testClock; // for testing only public GeneratePreSignUrlInterceptor() { testClock = null; } @SdkTestInternalApi GeneratePreSignUrlInterceptor(Clock testClock) { this.testClock = testClock; } @Override public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { SdkHttpRequest request = context.httpRequest(); SdkRequest originalRequest = context.request(); if (originalRequest instanceof CopySnapshotRequest) { CopySnapshotRequest originalCopySnapshotRequest = (CopySnapshotRequest) originalRequest; // Return if presigned url is already specified by the user. if (originalCopySnapshotRequest.presignedUrl() != null) { return request; } String serviceName = "ec2"; // The source regions where the snapshot currently resides. String sourceRegion = originalCopySnapshotRequest.sourceRegion(); String sourceSnapshotId = originalCopySnapshotRequest .sourceSnapshotId(); /* * The region where the snapshot has to be copied from the source. * The original copy snap shot request will have the end point set * as the destination region in the client before calling this * request. */ String destinationRegion = originalCopySnapshotRequest.destinationRegion(); if (destinationRegion == null) { destinationRegion = AwsHostNameUtils.parseSigningRegion(request.host(), serviceName) .orElseThrow(() -> new IllegalArgumentException("Could not determine region for " + request.host())) .id(); } URI endPointSource = createEndpoint(sourceRegion, serviceName); SdkHttpFullRequest requestForPresigning = generateRequestForPresigning( sourceSnapshotId, sourceRegion, destinationRegion) .toBuilder() .uri(endPointSource) .method(SdkHttpMethod.GET) .build(); Aws4Signer signer = Aws4Signer.create(); Aws4PresignerParams signingParams = getPresignerParams(executionAttributes, sourceRegion, serviceName); SdkHttpFullRequest presignedRequest = signer.presign(requestForPresigning, signingParams); return request.toBuilder() .putRawQueryParameter("DestinationRegion", destinationRegion) .putRawQueryParameter("PresignedUrl", presignedRequest.getUri().toString()) .build(); } return request; } private Aws4PresignerParams getPresignerParams(ExecutionAttributes attributes, String signingRegion, String signingName) { return Aws4PresignerParams.builder() .signingRegion(Region.of(signingRegion)) .signingName(signingName) .awsCredentials(resolveCredentials(attributes)) .signingClockOverride(testClock) .build(); } // TODO(sra-identity-and-auth): add test case for SELECTED_AUTH_SCHEME case private AwsCredentials resolveCredentials(ExecutionAttributes attributes) { return attributes.getOptionalAttribute(SELECTED_AUTH_SCHEME) .map(selectedAuthScheme -> selectedAuthScheme.identity()) .map(identityFuture -> CompletableFutureUtils.joinLikeSync(identityFuture)) .filter(identity -> identity instanceof AwsCredentialsIdentity) .map(identity -> { AwsCredentialsIdentity awsCredentialsIdentity = (AwsCredentialsIdentity) identity; return CredentialUtils.toCredentials(awsCredentialsIdentity); }).orElse(attributes.getAttribute(AWS_CREDENTIALS)); } /** * Generates a Request object for the pre-signed URL. */ private SdkHttpFullRequest generateRequestForPresigning(String sourceSnapshotId, String sourceRegion, String destinationRegion) { CopySnapshotRequest copySnapshotRequest = CopySnapshotRequest.builder() .sourceSnapshotId(sourceSnapshotId) .sourceRegion(sourceRegion) .destinationRegion(destinationRegion) .build(); return MARSHALLER.marshall(copySnapshotRequest); } private URI createEndpoint(String regionName, String serviceName) { Region region = Region.of(regionName); if (region == null) { throw SdkClientException.builder() .message("{" + serviceName + ", " + regionName + "} was not " + "found in region metadata. Update to latest version of SDK and try again.") .build(); } URI endpoint = Ec2Client.serviceMetadata().endpointFor(region); if (endpoint.getScheme() == null) { return URI.create("https://" + endpoint); } return endpoint; } }
4,902
0
Create_ds/aws-sdk-java-v2/build-tools/src/main/java/software/amazon/awssdk/buildtools
Create_ds/aws-sdk-java-v2/build-tools/src/main/java/software/amazon/awssdk/buildtools/checkstyle/NoIgnoreAnnotationsCheck.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.buildtools.checkstyle; import com.puppycrawl.tools.checkstyle.api.AbstractCheck; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.utils.AnnotationUtil; /** * Checks if a class uses the @Ignore annotation. Avoid disabling tests and work to * resolve issues with the test instead. * * For manual tests and exceptional circumstances, use the commentation feature CHECKSTYLE: OFF * to mark a test as ignored. */ public class NoIgnoreAnnotationsCheck extends AbstractCheck { private static final String IGNORE_ANNOTATION = "Ignore"; @Override public int[] getDefaultTokens() { return getRequiredTokens(); } @Override public int[] getAcceptableTokens() { return getRequiredTokens(); } @Override public int[] getRequiredTokens() { return new int[] {TokenTypes.CLASS_DEF, TokenTypes.METHOD_DEF}; } @Override public void visitToken(DetailAST ast) { if (!AnnotationUtil.containsAnnotation(ast, IGNORE_ANNOTATION)) { return; } log(ast, "@Ignore annotation is not allowed"); } }
4,903
0
Create_ds/aws-sdk-java-v2/build-tools/src/main/java/software/amazon/awssdk/buildtools
Create_ds/aws-sdk-java-v2/build-tools/src/main/java/software/amazon/awssdk/buildtools/checkstyle/SdkIllegalImportCheck.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.buildtools.checkstyle; import com.puppycrawl.tools.checkstyle.api.AbstractCheck; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.FullIdent; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.utils.CommonUtil; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Pattern; /** * Checks if a class has illegal imports */ public class SdkIllegalImportCheck extends AbstractCheck { private final List<Pattern> illegalPackagesRegexps = new ArrayList<>(); private final List<String> illegalPackages = new ArrayList<>(); private Pattern classNameToCheck; private Pattern packageToCheck; private boolean containsIllegalImport = false; private boolean classMatched = false; private boolean classPackageMatched = false; public void setClassNameToCheck(String classNameToCheck) { this.classNameToCheck = CommonUtil.createPattern(classNameToCheck); } public void setPackageToCheck(String packageToCheckRegexp) { this.packageToCheck = CommonUtil.createPattern(packageToCheckRegexp); } public final void setIllegalPkgs(String... from) { illegalPackages.clear(); illegalPackages.addAll(Arrays.asList(from)); illegalPackagesRegexps.clear(); for (String illegalPkg : illegalPackages) { illegalPackagesRegexps.add(CommonUtil.createPattern("^" + illegalPkg)); } } @Override public int[] getDefaultTokens() { return getRequiredTokens(); } @Override public int[] getAcceptableTokens() { return getRequiredTokens(); } @Override public int[] getRequiredTokens() { return new int[] {TokenTypes.PACKAGE_DEF, TokenTypes.CLASS_DEF, TokenTypes.IMPORT, TokenTypes.STATIC_IMPORT}; } @Override public void beginTree(DetailAST rootAST) { containsIllegalImport = false; classMatched = false; classPackageMatched = false; } @Override public void finishTree(DetailAST rootAST) { // Set matched to true if no class package regex provided if (packageToCheck == null) { classPackageMatched = true; } if (containsIllegalImport && classMatched && classPackageMatched) { log(rootAST, "Illegal imports found " + illegalPackagesRegexps); } } @Override public void visitToken(DetailAST ast) { FullIdent importedPackage = null; FullIdent classPackage = null; switch (ast.getType()) { case TokenTypes.PACKAGE_DEF: classPackage = FullIdent.createFullIdent(ast.findFirstToken(TokenTypes.DOT)); break; case TokenTypes.CLASS_DEF: String className = ast.findFirstToken(TokenTypes.IDENT).getText(); if (classNameToCheck.matcher(className).matches()) { classMatched = true; } break; case TokenTypes.IMPORT: importedPackage = FullIdent.createFullIdentBelow(ast); break; case TokenTypes.STATIC_IMPORT: importedPackage = FullIdent.createFullIdent(ast.getFirstChild().getNextSibling()); break; } if (packageToCheck != null && classPackage != null && packageToCheck.matcher(classPackage.getText()).matches()) { classPackageMatched = true; } if (importedPackage!= null && isIllegalImport(importedPackage.getText())) { containsIllegalImport = true; } } private boolean isIllegalImport(String importText) { for (Pattern pattern : illegalPackagesRegexps) { if (pattern.matcher(importText).matches()) { return true; } } return false; } }
4,904
0
Create_ds/aws-sdk-java-v2/build-tools/src/main/java/software/amazon/awssdk/buildtools
Create_ds/aws-sdk-java-v2/build-tools/src/main/java/software/amazon/awssdk/buildtools/checkstyle/PluralEnumNames.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.buildtools.checkstyle; import com.puppycrawl.tools.checkstyle.api.AbstractCheck; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * A rule that disallows plurality in enum names (eg. it should be "Property.MY_PROPERTY", not "Properties.MY_PROPERTY"). This * also applies the validation to "pseudo-enums", classes with public static fields. */ public class PluralEnumNames extends AbstractCheck { private static final List<String> PLURAL_ENDINGS = Arrays.asList("S", "s"); private static final List<String> NON_PLURAL_ENDINGS = Collections.singletonList("Status"); @Override public int[] getDefaultTokens() { return getRequiredTokens(); } @Override public int[] getRequiredTokens() { return new int[] { TokenTypes.CLASS_DEF, TokenTypes.ENUM_DEF }; } @Override public int[] getAcceptableTokens() { return getRequiredTokens(); } @Override public void visitToken(DetailAST ast) { String classOrEnumName = ast.findFirstToken(TokenTypes.IDENT).getText(); if (isPlural(classOrEnumName) && isPluralDisallowed(ast)) { log(ast, "Enum or class name should be singular, not plural (Property.VALUE not Properties.VALUE)."); } } private boolean isPlural(String className) { return PLURAL_ENDINGS.stream().anyMatch(className::endsWith) && NON_PLURAL_ENDINGS.stream().noneMatch(className::endsWith); } private boolean isPluralDisallowed(DetailAST ast) { return isEnum(ast) || hasPublicStaticField(ast); } private boolean isEnum(DetailAST ast) { return ast.getType() == TokenTypes.ENUM_DEF; } private boolean hasPublicStaticField(DetailAST ast) { DetailAST classBody = ast.findFirstToken(TokenTypes.OBJBLOCK); DetailAST maybeVariableDefinition = classBody.getFirstChild(); String className = ast.findFirstToken(TokenTypes.IDENT).getText(); // Filter out util classes if (className.endsWith("Utils")) { return false; } while (maybeVariableDefinition != null) { if (maybeVariableDefinition.getType() == TokenTypes.VARIABLE_DEF) { DetailAST modifiers = maybeVariableDefinition.findFirstToken(TokenTypes.MODIFIERS); if (modifiers != null && isPublic(modifiers) && isStatic(modifiers)) { return true; } } maybeVariableDefinition = maybeVariableDefinition.getNextSibling(); } return false; } private boolean isPublic(DetailAST modifiers) { return modifiers.findFirstToken(TokenTypes.LITERAL_PUBLIC) != null; } private boolean isStatic(DetailAST modifiers) { return modifiers.findFirstToken(TokenTypes.LITERAL_STATIC) != null; } }
4,905
0
Create_ds/aws-sdk-java-v2/build-tools/src/main/java/software/amazon/awssdk/buildtools
Create_ds/aws-sdk-java-v2/build-tools/src/main/java/software/amazon/awssdk/buildtools/checkstyle/MissingSdkAnnotationCheck.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.buildtools.checkstyle; import com.puppycrawl.tools.checkstyle.api.AbstractCheck; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.utils.AnnotationUtil; import com.puppycrawl.tools.checkstyle.utils.ScopeUtil; import java.util.Arrays; import java.util.List; /** * A rule that checks if sdk annotation is missing on any non-test classes. Inner classes are ignored. */ public class MissingSdkAnnotationCheck extends AbstractCheck { private static final List<String> SDK_ANNOTATIONS = Arrays.asList("SdkPublicApi", "SdkInternalApi", "SdkProtectedApi"); @Override public int[] getDefaultTokens() { return getRequiredTokens(); } @Override public int[] getAcceptableTokens() { return getRequiredTokens(); } @Override public int[] getRequiredTokens() { return new int[] { TokenTypes.CLASS_DEF, TokenTypes.INTERFACE_DEF }; } @Override public void visitToken(DetailAST ast) { if (!ScopeUtil.isOuterMostType(ast) || SDK_ANNOTATIONS.stream().anyMatch(a -> AnnotationUtil.containsAnnotation (ast, a))) { return; } log(ast, "SDK annotation is missing on this class. eg: @SdkProtectedApi"); } }
4,906
0
Create_ds/aws-sdk-java-v2/build-tools/src/main/java/software/amazon/awssdk/buildtools
Create_ds/aws-sdk-java-v2/build-tools/src/main/java/software/amazon/awssdk/buildtools/checkstyle/UnnecessaryFinalOnLocalVariableCheck.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.buildtools.checkstyle; import com.puppycrawl.tools.checkstyle.api.AbstractCheck; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.utils.ScopeUtil; /** * A rule that disallows unnecessary 'final' on local variables */ public class UnnecessaryFinalOnLocalVariableCheck extends AbstractCheck { @Override public int[] getDefaultTokens() { return getRequiredTokens(); } @Override public int[] getAcceptableTokens() { return getRequiredTokens(); } @Override public int[] getRequiredTokens() { return new int[] { TokenTypes.VARIABLE_DEF }; } @Override public void visitToken(DetailAST ast) { if (ScopeUtil.isLocalVariableDef(ast) && ast.findFirstToken(TokenTypes.MODIFIERS) .findFirstToken(TokenTypes.FINAL) != null) { log(ast, "final should be removed from local variable"); } } }
4,907
0
Create_ds/aws-sdk-java-v2/build-tools/src/main/java/software/amazon/awssdk/buildtools
Create_ds/aws-sdk-java-v2/build-tools/src/main/java/software/amazon/awssdk/buildtools/checkstyle/SdkPublicMethodNameCheck.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.buildtools.checkstyle; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.checks.naming.MethodNameCheck; import com.puppycrawl.tools.checkstyle.utils.AnnotationUtil; /** * Sdk Method Name check to check only public methods in the classes with {@code @SdkPublicApi} annotation. */ public final class SdkPublicMethodNameCheck extends MethodNameCheck { /** * {@link Override Override} annotation name. */ private static final String OVERRIDE = "Override"; private static final String SDK_PUBLIC_API = "SdkPublicApi"; @Override public int[] getDefaultTokens() { return getRequiredTokens(); } @Override public int[] getAcceptableTokens() { return getRequiredTokens(); } @Override public int[] getRequiredTokens() { return new int[] { TokenTypes.METHOD_DEF }; } @Override public void visitToken(DetailAST ast) { // Get class classDef DetailAST classDef = ast.getParent().getParent(); try { if (!AnnotationUtil.containsAnnotation(ast, OVERRIDE) && AnnotationUtil.containsAnnotation(classDef, SDK_PUBLIC_API)) { super.visitToken(ast); } } catch (NullPointerException ex) { //If that method is in an anonymous class, it will throw NPE, ignoring those. } } @Override protected boolean mustCheckName(DetailAST ast) { return ast.findFirstToken(TokenTypes.MODIFIERS) .findFirstToken(TokenTypes.LITERAL_PUBLIC) != null; } }
4,908
0
Create_ds/aws-sdk-java-v2/build-tools/src/main/java/software/amazon/awssdk/buildtools
Create_ds/aws-sdk-java-v2/build-tools/src/main/java/software/amazon/awssdk/buildtools/checkstyle/NonJavaBaseModuleCheck.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.buildtools.checkstyle; import com.puppycrawl.tools.checkstyle.api.AbstractCheck; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.FullIdent; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.regex.Pattern; /** * Verify that we're not using classes in rt.jar that aren't exported via the java.base module. * * If anything fails this check, it increases our module dependencies. If you absolutely must use one of these * (e.g. java.beans) because it's fundamental to your functionality, you can suppress this checkstyle rule via * {@link #setLegalPackages(String...)}, but know that it is not free - you're essentially adding a dependency * for customers that use the module path. */ public class NonJavaBaseModuleCheck extends AbstractCheck { private static final List<String> ILLEGAL_PACKAGES = Arrays.asList( "java", "javax", "sun", "apple", "com.apple", "com.oracle"); private static final Set<String> LEGAL_PACKAGES = new HashSet<>(Arrays.asList( "java.io", "java.lang", "java.lang.annotation", "java.lang.invoke", "java.lang.module", "java.lang.ref", "java.lang.reflect", "java.math", "java.net", "java.net.spi", "java.nio", "java.nio.channels", "java.nio.channels.spi", "java.nio.charset", "java.nio.charset.spi", "java.nio.file", "java.nio.file.attribute", "java.nio.file.spi", "java.security", "java.security.acl", "java.security.cert", "java.security.interfaces", "java.security.spec", "java.text", "java.text.spi", "java.time", "java.time.chrono", "java.time.format", "java.time.temporal", "java.time.zone", "java.util", "java.util.concurrent", "java.util.concurrent.atomic", "java.util.concurrent.locks", "java.util.function", "java.util.jar", "java.util.regex", "java.util.spi", "java.util.stream", "java.util.jar", "java.util.zip", "javax.crypto", "javax.crypto.interfaces", "javax.crypto.spec", "javax.net", "javax.net.ssl", "javax.security.auth", "javax.security.auth.callback", "javax.security.auth.login", "javax.security.auth.spi", "javax.security.auth.x500", "javax.security.cert")); private static final Pattern CLASSNAME_START_PATTERN = Pattern.compile("[A-Z]"); private String currentSdkPackage; private HashMap<String, Set<String>> additionalLegalPackagesBySdkPackage = new HashMap<>(); /** * Additional legal packages are formatted as "sdk.package.name:jdk.package.name,sdk.package.name2:jdk.package.name2". * Multiple SDK packages can be repeated. */ public void setLegalPackages(String... legalPackages) { for (String additionalLegalPackage : legalPackages) { String[] splitPackage = additionalLegalPackage.split(":", 2); if (splitPackage.length != 2) { throw new IllegalArgumentException("Invalid legal package definition '" + additionalLegalPackage + "'. Expected" + " format is sdk.package.name:jdk.package.name"); } this.additionalLegalPackagesBySdkPackage.computeIfAbsent(splitPackage[0], k -> new HashSet<>()) .add(splitPackage[1]); } } @Override public int[] getDefaultTokens() { return getRequiredTokens(); } @Override public int[] getAcceptableTokens() { return getRequiredTokens(); } @Override public int[] getRequiredTokens() { return new int[] { TokenTypes.IMPORT, TokenTypes.STATIC_IMPORT, TokenTypes.PACKAGE_DEF }; } @Override public void visitToken(DetailAST ast) { if (ast.getType() == TokenTypes.PACKAGE_DEF) { handlePackageDefToken(ast); return; } handleImportToken(ast); } private void handlePackageDefToken(DetailAST ast) { this.currentSdkPackage = FullIdent.createFullIdent(ast.getLastChild().getPreviousSibling()).getText(); } private void handleImportToken(DetailAST ast) { FullIdent importIdentifier; if (ast.getType() == TokenTypes.IMPORT) { importIdentifier = FullIdent.createFullIdentBelow(ast); } else { importIdentifier = FullIdent.createFullIdent(ast.getFirstChild().getNextSibling()); } String importText = importIdentifier.getText(); if (isIllegalImport(importText) && !isLegalImport(importText)) { log(ast, "Import '" + importText + "' uses a JDK class that is not in java.base. This essentially adds an " + "additional module dependency. Don't suppress this rule unless it's absolutely required, and only " + "suppress the specific package you need via checkstyle.xml instead of suppressing the entire rule."); } } private boolean isIllegalImport(String importText) { for (String illegalPackage : ILLEGAL_PACKAGES) { if (importText.startsWith(illegalPackage + ".")) { return true; } } return false; } private boolean isLegalImport(String importText) { String importPackageWithTrailingDot = CLASSNAME_START_PATTERN.split(importText, 2)[0]; String importPackage = importText.substring(0, importPackageWithTrailingDot.length() - 1); if (LEGAL_PACKAGES.contains(importPackage)) { return true; } if (additionalLegalPackagesBySdkPackage.entrySet() .stream() .anyMatch(e -> currentSdkPackage.startsWith(e.getKey()) && e.getValue().contains(importPackage))) { return true; } return false; } }
4,909
0
Create_ds/aws-sdk-java-v2/build-tools/src/main/java/software/amazon/awssdk/buildtools
Create_ds/aws-sdk-java-v2/build-tools/src/main/java/software/amazon/awssdk/buildtools/findbugs/DisallowMethodCall.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.buildtools.findbugs; import edu.umd.cs.findbugs.BugInstance; import edu.umd.cs.findbugs.BugReporter; import edu.umd.cs.findbugs.ba.SignatureParser; import edu.umd.cs.findbugs.bcel.OpcodeStackDetector; import edu.umd.cs.findbugs.classfile.MethodDescriptor; import java.util.AbstractMap.SimpleEntry; import java.util.HashSet; import java.util.Map.Entry; import java.util.Set; import org.apache.bcel.Const; /** * Blocks usage of disallowed methods in the SDK. */ public class DisallowMethodCall extends OpcodeStackDetector { private static final Set<Entry<String, String>> PROHIBITED_METHODS = new HashSet<>(); private final BugReporter bugReporter; static { PROHIBITED_METHODS.add(new SimpleEntry<>("software/amazon/awssdk/http/SdkHttpHeaders", "headers")); PROHIBITED_METHODS.add(new SimpleEntry<>("software/amazon/awssdk/http/SdkHttpResponse", "headers")); PROHIBITED_METHODS.add(new SimpleEntry<>("software/amazon/awssdk/http/SdkHttpRequest", "headers")); PROHIBITED_METHODS.add(new SimpleEntry<>("software/amazon/awssdk/http/SdkHttpFullRequest", "headers")); PROHIBITED_METHODS.add(new SimpleEntry<>("software/amazon/awssdk/http/SdkHttpFullResponse", "headers")); PROHIBITED_METHODS.add(new SimpleEntry<>("software/amazon/awssdk/http/SdkHttpFullRequest$Builder", "headers")); PROHIBITED_METHODS.add(new SimpleEntry<>("software/amazon/awssdk/http/SdkHttpFullResponse$Builder", "headers")); PROHIBITED_METHODS.add(new SimpleEntry<>("software/amazon/awssdk/http/SdkHttpRequest", "rawQueryParameters")); PROHIBITED_METHODS.add(new SimpleEntry<>("software/amazon/awssdk/http/SdkHttpFullRequest", "rawQueryParameters")); PROHIBITED_METHODS.add(new SimpleEntry<>("software/amazon/awssdk/http/SdkHttpFullRequest$Builder", "rawQueryParameters")); } public DisallowMethodCall(BugReporter bugReporter) { this.bugReporter = bugReporter; } @Override public void sawOpcode(int code) { switch (code) { case Const.INVOKEVIRTUAL: case Const.INVOKESPECIAL: case Const.INVOKESTATIC: case Const.INVOKEINTERFACE: handleMethodCall(code); return; default: // Ignore - not a method call. } } private void handleMethodCall(int code) { MethodDescriptor method = getMethodDescriptorOperand(); SignatureParser signature = new SignatureParser(method.getSignature()); Entry<String, String> calledMethod = new SimpleEntry<>(method.getSlashedClassName(), method.getName()); if (PROHIBITED_METHODS.contains(calledMethod) && signature.getNumParameters() == 0) { bugReporter.reportBug(new BugInstance(this, "SDK_BAD_METHOD_CALL", NORMAL_PRIORITY) .addClassAndMethod(this) .addSourceLine(this, getPC())); } } }
4,910
0
Create_ds/aws-sdk-java-v2/build-tools/src/main/java/software/amazon/awssdk/buildtools
Create_ds/aws-sdk-java-v2/build-tools/src/main/java/software/amazon/awssdk/buildtools/findbugs/ToBuilderIsCorrect.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.buildtools.findbugs; import static java.util.Collections.emptyList; import edu.umd.cs.findbugs.BugInstance; import edu.umd.cs.findbugs.BugReporter; import edu.umd.cs.findbugs.OpcodeStack; import edu.umd.cs.findbugs.ba.XField; import edu.umd.cs.findbugs.ba.XMethod; import edu.umd.cs.findbugs.bcel.OpcodeStackDetector; import edu.umd.cs.findbugs.classfile.analysis.AnnotationValue; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.bcel.Const; import org.apache.bcel.classfile.Field; import org.apache.bcel.classfile.JavaClass; import org.apache.bcel.classfile.Method; /** * A FindBugs/SpotBugs rule for verifying that implementations of * software.amazon.awssdk.utils.builder.ToCopyableBuilder and CopyableBuilder are correct. */ public class ToBuilderIsCorrect extends OpcodeStackDetector { private final BugReporter bugReporter; /** * All implementations of CopyableBuilder encountered in the module. */ private final Map<String, JavaClass> builders = new HashMap<>(); /** * All implementations of ToCopyableBuilder encountered in the module. */ private final Map<String, JavaClass> buildables = new HashMap<>(); /** * The fields in CopyableBuilder implementations that are expected to be copied. * * Keys: The builder FQCN, Values: the fields in the builder */ private final Map<String, List<String>> builderFields = new HashMap<>(); /** * The fields in CopyableBuilder implementations that are not expected to be copied. These are configured on the toBuilder * method using the @ToBuilderIgnoreField annotation. * * Keys: The builder FQCN, Values: the fields to ignore */ private final Map<String, List<String>> ignoredFields = new HashMap<>(); /** * The implementations of CopyableBuilder that are not validated. These are determined automatically, e.g. because the * class inherits its toBuilder implementation from a parent class. */ private final Set<String> ignoredBuildables = new HashSet<>(); /** * Which fields are modified in a builder's constructor. This is used when a buildable uses a builder's constructor to copy * over fields. * * Key 1: The builder FQCN, Key 2: The constructor signature, Values: the fields modified in the constructor */ private final Map<String, Map<String, List<String>>> builderConstructorModifiedFields = new HashMap<>(); /** * Which fields are modified in a buildable's toBuilder method. This is used when a buildable invokes methods on the * builder to copy over fields. * * Key 1: The buildable FQCN, Key 2: the invoked builder FQCN, Values: the fields modified in the * toBuilder */ private final Map<String, Map<String, List<String>>> toBuilderModifiedFields = new HashMap<>(); /** * Which constructors are invoked from a buildable's toBuilder method. This is used when a buildable uses a builder's * constructor to copy over fields. * * Key 1: The buildable FQCN, Key 2: the invoked builder FQCN, Values: the signature of the constructor invoked by the * toBuilder method. */ private final Map<String, Map<String, String>> constructorsInvokedFromToBuilder = new HashMap<>(); /** * Which builder constructors reference which other builder constructors. This is used when a buildable uses a builder's * constructor to copy over fields, and that constructor delegates some copying to another internal constructor. * * Key 1: The builder FQCN, Key 2: the invoking constructor signature, Value: the target constructor signature. */ private final Map<String, Map<String, String>> crossConstructorReferences = new HashMap<>(); /** * Which classes or interfaces a builder extends. This is used to determine what builder is being modified when it is * invoked virtually from a toBuilder implementation. * * Key: The builder FQCN, Value: the FQCN parent classes and interfaces (including transitive) */ private final Map<String, Set<String>> builderParents = new HashMap<>(); /** * Whether the current class being assessed is a builder. */ private boolean isBuilder = false; /** * Whether the current class being assessed is a buildable. */ private boolean isBuildable = false; /** * Whether the current method being assessed is a builder's constructor. */ private boolean inBuilderConstructor = false; /** * Whether the current method being assessed is a buildable's toBuilder. */ private boolean inBuildableToBuilder = false; public ToBuilderIsCorrect(BugReporter bugReporter) { this.bugReporter = bugReporter; } /** * Determine whether we should visit the provided class. We only visit builders and buildables. */ @Override public boolean shouldVisit(JavaClass obj) { isBuilder = false; isBuildable = false; inBuilderConstructor = false; inBuildableToBuilder = false; try { if (obj.isInterface()) { return false; } JavaClass[] parentInterfaces = obj.getAllInterfaces(); Set<String> parents = Stream.concat(Arrays.stream(parentInterfaces), Arrays.stream(obj.getSuperClasses())) .map(JavaClass::getClassName) .collect(Collectors.toSet()); for (JavaClass i : parentInterfaces) { if (i.getClassName().equals("software.amazon.awssdk.utils.builder.CopyableBuilder")) { builders.put(obj.getClassName(), obj); builderParents.put(obj.getClassName(), parents); isBuilder = true; } if (i.getClassName().equals("software.amazon.awssdk.utils.builder.ToCopyableBuilder")) { buildables.put(obj.getClassName(), obj); isBuildable = true; } } if (isBuildable && isBuilder) { System.err.println(obj.getClassName() + " implements both CopyableBuilder and ToCopyableBuilder."); bugReporter.reportBug(new BugInstance(this, "BAD_TO_BUILDER", NORMAL_PRIORITY) .addClass(obj)); visitAfter(obj); return false; } return isBuildable || isBuilder; } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } @Override public void visit(Field obj) { if (isBuilder && !obj.isStatic()) { builderFields.computeIfAbsent(getDottedClassName(), c -> new ArrayList<>()).add(obj.getName()); } } @Override public void visit(Method method) { if (isBuilder && method.getName().equals(Const.CONSTRUCTOR_NAME)) { // This is a builder constructor builderConstructorModifiedFields.computeIfAbsent(getDottedClassName(), n1 -> new HashMap<>()) .computeIfAbsent(method.getSignature(), n -> new ArrayList<>()); crossConstructorReferences.computeIfAbsent(getDottedClassName(), n1 -> new HashMap<>()); inBuildableToBuilder = false; inBuilderConstructor = true; if (method.isPublic()) { System.err.println(getDottedClassName() + getMethodSig() + " must not be public."); bugReporter.reportBug(new BugInstance(this, "BAD_TO_BUILDER", NORMAL_PRIORITY) .addClassAndMethod(getXMethod())); } } else if (isBuildable && method.getName().equals("toBuilder") && method.getSignature().startsWith("()")) { // This is a buildable toBuilder constructorsInvokedFromToBuilder.computeIfAbsent(getDottedClassName(), n -> new HashMap<>()); toBuilderModifiedFields.computeIfAbsent(getDottedClassName(), n -> new HashMap<>()); inBuildableToBuilder = true; inBuilderConstructor = false; registerIgnoredFields(); } else { inBuildableToBuilder = false; inBuilderConstructor = false; } } /** * Register ignored fields specified in the current method's ToBuilderIgnoreField annotation. */ private void registerIgnoredFields() { for (AnnotationValue annotation : getXMethod().getAnnotations()) { if (annotation.getAnnotationClass() .getDottedClassName() .equals("software.amazon.awssdk.annotations.ToBuilderIgnoreField")) { Object value = annotation.getValue("value"); for (Object ignoredField : (Object[]) value) { ignoredFields.computeIfAbsent(getDottedClassName(), n -> new ArrayList<>()) .add((String) ignoredField); } } } } @Override public void sawOpcode(int seen) { if (inBuilderConstructor) { sawOpCodeInBuilderConstructor(seen); } else if (inBuildableToBuilder) { sawOpCodeInBuildableToBuilder(seen); } } private void sawOpCodeInBuilderConstructor(int seen) { // In builder constructor if (seen == Const.PUTFIELD && !isEmptyAllocation()) { // Writing directly to a field, but not with an empty value that was just constructed (likely empty maps, lists, // etc.) addConstructorModifiedField(getXFieldOperand().getName()); } else if (seen == Const.INVOKEVIRTUAL || seen == Const.INVOKEINTERFACE) { XField field = getStack().getStackItem(1).getXField(); if (field != null && field.getClassName().equals(getDottedClassName())) { // We're invoking a method on one of our fields. We just assume that counts as updating it (e.g. Map.putAll). addConstructorModifiedField(field.getName()); } } else if (seen == Const.INVOKESPECIAL && getDottedClassName().equals(getDottedClassConstantOperand()) && getNameConstantOperand().equals(Const.CONSTRUCTOR_NAME)) { // Invoking another constructor on this builder crossConstructorReferences.get(getDottedClassName()) .put(getXMethod().getSignature(), getSigConstantOperand()); } } /** * Return true if the value on the top of the stack is a newly-allocated object, created from a zero-arg method. If so, we * assume it's just allocating something empty (e.g. new HashMap(), new ArrayList(), etc.) */ private boolean isEmptyAllocation() { OpcodeStack.Item topOfStack = getStack().getStackItem(0); XMethod returnValueOf = topOfStack.getReturnValueOf(); if (returnValueOf == null) { return false; } return topOfStack.isNewlyAllocated() && returnValueOf.getSignature().startsWith("()"); } private void addConstructorModifiedField(String field) { builderConstructorModifiedFields.get(getDottedClassName()) .get(getXMethod().getSignature()) .add(field); } private void sawOpCodeInBuildableToBuilder(int seen) { // In toBuilder method if (seen == Const.INVOKESPECIAL && getNameConstantOperand().equals(Const.CONSTRUCTOR_NAME)) { // Invoking a constructor, possibly on a builder constructorsInvokedFromToBuilder.get(getDottedClassName()) .put(getDottedClassConstantOperand(), getSigConstantOperand()); } else if (seen == Const.INVOKEVIRTUAL || seen == Const.INVOKEINTERFACE) { // Invoking a method, possibly on a builder toBuilderModifiedFields.get(getDottedClassName()) .computeIfAbsent(getDottedClassConstantOperand(), n -> new ArrayList<>()) .add(getNameConstantOperand()); } else if (seen == Const.INVOKESPECIAL && getNameConstantOperand().equals("toBuilder")) { // Invoking another toBuilder. We make an assumption that it's doing the work instead of this buildable. ignoredBuildables.add(getDottedClassName()); } } @Override public void report() { buildables.forEach((buildableClassName, buildableClass) -> { // Find how toBuilder invokes the builder if (ignoredBuildables.contains(buildableClassName)) { // Skip validating this buildable because it delegates its toBuilder call to another buildable. } else if (invokesBuilderViaMethods(buildableClassName)) { validateBuilderViaMethods(buildableClassName, buildableClass); } else if (invokesBuilderViaConstructor(buildableClassName)) { validateBuilderConstructor(buildableClassName, buildableClass); } else { System.err.println(buildableClassName + ".toBuilder() does not invoke a constructor or method on a builder. A " + "toBuilder() method must either invoke a builder constructor or call builder() and " + "configure the fields on the builder."); bugReporter.reportBug(new BugInstance(this, "BAD_TO_BUILDER", NORMAL_PRIORITY) .addClass(buildableClass)); } }); } private boolean invokesBuilderViaConstructor(String buildableClassName) { Map<String, String> constructors = constructorsInvokedFromToBuilder.get(buildableClassName); if (constructors == null) { return false; } return constructors.keySet().stream().anyMatch(builders::containsKey); } private boolean invokesBuilderViaMethods(String buildableClassName) { Map<String, List<String>> methods = toBuilderModifiedFields.get(buildableClassName); if (methods == null) { return false; } return methods.keySet() .stream() .anyMatch(builderClass -> builders.containsKey(builderClass) || builderParents.values() .stream() .anyMatch(parents -> parents.contains(builderClass))); } private void validateBuilderConstructor(String buildableClassName, JavaClass buildableClass) { Map<String, String> invokedConstructors = constructorsInvokedFromToBuilder.get(buildableClassName); // Remove and ignore any non-builder constructors the buildable invoked. invokedConstructors.keySet().removeIf(builderClass -> !builders.containsKey(builderClass)); if (invokedConstructors.size() > 1) { System.err.println(buildableClassName + ".toBuilder() invokes multiple builder constructors: " + invokedConstructors); bugReporter.reportBug(new BugInstance(this, "BAD_TO_BUILDER", NORMAL_PRIORITY) .addClass(buildableClass)); } // Find the constructor implementation that we actually invoked, along with all of the constructors that were // transitively called Map.Entry<String, String> invokedConstructor = invokedConstructors.entrySet().iterator().next(); String builder = invokedConstructor.getKey(); String calledConstructor = invokedConstructor.getValue(); List<String> allInvokedConstructors = getAllInvokedConstructors(builder, calledConstructor); if (!builders.containsKey(builder)) { System.err.println(buildableClassName + ".toBuilder() invokes the constructor of an unknown type: " + builder); bugReporter.reportBug(new BugInstance(this, "BAD_TO_BUILDER", NORMAL_PRIORITY) .addClass(buildableClass)); } // Find which fields we modified in those constructors Set<String> builderFieldsForBuilder = new HashSet<>(builderFields.getOrDefault(builder, new ArrayList<>())); Map<String, List<String>> allConstructors = builderConstructorModifiedFields.get(builder); allInvokedConstructors.forEach(constructorSignature -> { List<String> modifiedFields = allConstructors.get(constructorSignature); if (modifiedFields == null) { System.err.println(buildableClassName + ".toBuilder() invokes an unknown constructor: " + builder + constructorSignature); bugReporter.reportBug(new BugInstance(this, "BAD_TO_BUILDER", NORMAL_PRIORITY) .addClass(builders.get(builder))); return; } modifiedFields.forEach(builderFieldsForBuilder::remove); }); // Subtract ignored fields ignoredFields.getOrDefault(buildableClassName, emptyList()).forEach(builderFieldsForBuilder::remove); // Anything left is unmodified if (!builderFieldsForBuilder.isEmpty()) { System.err.println(buildableClassName + ".toBuilder() does not update all of the builder's fields. " + "Missing fields: " + builderFieldsForBuilder + ". This check does not currently " + "consider transitive method calls. If this is a false positive, you can ignore this field by " + "annotating the toBuilder method with @ToBuilderIgnoreField and specifying the fields to " + "ignore."); bugReporter.reportBug(new BugInstance(this, "BAD_TO_BUILDER", NORMAL_PRIORITY) .addClass(builders.get(builder))); } } private List<String> getAllInvokedConstructors(String builder, String signature) { List<String> result = new ArrayList<>(); while (signature != null) { result.add(signature); signature = crossConstructorReferences.get(builder).get(signature); } return result; } private void validateBuilderViaMethods(String buildableClassName, JavaClass buildableClass) { // Find which methods were invoked in the builder Map<String, List<String>> invokedMethodsByClass = toBuilderModifiedFields.get(buildableClassName); invokedMethodsByClass.forEach((invokedClass, invokedMethods) -> { // Create a best-guess on what buildable implementation we're actually working with (based on the parent interface // we might be working with) String concreteClass = resolveParentToConcrete(invokedClass); if (builders.containsKey(concreteClass)) { // We're invoking these methods on a known builder. Assume the method name matches the field name and validate // based on that. List<String> concreteClassBuilderFields = builderFields.getOrDefault(concreteClass, new ArrayList<>()); Set<String> builderFieldsForBuilder = new HashSet<>(concreteClassBuilderFields); invokedMethods.forEach(builderFieldsForBuilder::remove); ignoredFields.getOrDefault(buildableClassName, emptyList()).forEach(builderFieldsForBuilder::remove); if (!builderFieldsForBuilder.isEmpty()) { System.err.println(buildableClassName + ".toBuilder() does not update all of the builder's fields. " + "Missing fields: " + builderFieldsForBuilder + ". This check does not currently " + "consider transitive method calls."); bugReporter.reportBug(new BugInstance(this, "BAD_TO_BUILDER", NORMAL_PRIORITY) .addClass(buildableClass)); } } }); } private String resolveParentToConcrete(String parent) { return builderParents.entrySet() .stream() .filter(parents -> parents.getValue().contains(parent)) .map(parents -> parents.getKey()) .findAny() .orElse(parent); } }
4,911
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/test/java/com/amazonaws/kinesisvideo
Create_ds/amazon-kinesis-video-streams-parser-library/src/test/java/com/amazonaws/kinesisvideo/parser/TestResourceUtil.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser; import org.apache.commons.lang3.Validate; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLClassLoader; import java.nio.ByteBuffer; import java.nio.file.Files; import java.nio.file.Paths; import static java.nio.file.Files.newInputStream; /** * Class used by the test classes to get acess to input test files */ public class TestResourceUtil { public static InputStream getTestInputStream(String name) throws IOException { //First check if we are running in maven. InputStream inputStream = ClassLoader.getSystemResourceAsStream(name); if (inputStream == null) { inputStream = newInputStream(Paths.get("testdata", name)); } Validate.isTrue(inputStream != null, "Could not read input file " + name); return inputStream; } public static byte[] getTestInputByteArray(String name) throws IOException { //First check if we are running in maven. InputStream inputStream = ClassLoader.getSystemResourceAsStream(name); if (inputStream == null) { inputStream = Files.newInputStream(Paths.get("testdata", name)); } Validate.isTrue(inputStream != null, "Could not read input file " + name); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte []buf = new byte [8192]; int readBytes; do { readBytes = inputStream.read(buf); if (readBytes > 0) { outputStream.write(buf, 0, readBytes); } }while (readBytes >= 0); return outputStream.toByteArray(); } /** * Utility debug method to print the class path. * Useful for verifying test setup in different build systems. */ public static void printClassPath() { ClassLoader cl = ClassLoader.getSystemClassLoader(); URL[] urls = ((URLClassLoader)cl).getURLs(); for(URL url: urls){ System.out.println(url.getFile()); } } }
4,912
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/test/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/test/java/com/amazonaws/kinesisvideo/parser/mkv/StreamingMkvReaderTest.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.mkv; import com.amazonaws.kinesisvideo.parser.TestResourceUtil; import com.amazonaws.kinesisvideo.parser.ebml.EBMLTypeInfo; import com.amazonaws.kinesisvideo.parser.ebml.InputStreamParserByteSource; import com.amazonaws.kinesisvideo.parser.ebml.MkvTypeInfos; import com.amazonaws.kinesisvideo.parser.mkv.visitors.CompositeMkvElementVisitor; import com.amazonaws.kinesisvideo.parser.mkv.visitors.CountVisitor; import com.amazonaws.kinesisvideo.parser.mkv.visitors.ElementSizeAndOffsetVisitor; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.List; import java.util.Optional; /** * Tests for {@link StreamingMkvReader}. */ public class StreamingMkvReaderTest { @Test public void testClustersMkvAllElementsWithoutPath() throws IOException, MkvElementVisitException { InputStreamParserByteSource parserByteSource = getClustersByteSource(); StreamingMkvReader streamReader = new StreamingMkvReader(false, new ArrayList<>(), parserByteSource); CountVisitor visitor = readAllReturnedElements(streamReader); assertCountsOfTypes(visitor, 1, 8, 444, 1); } @Test public void testClustersMkvAllElementsWithPath() throws IOException, MkvElementVisitException { InputStreamParserByteSource parserByteSource = getClustersByteSource(); StreamingMkvReader streamReader = StreamingMkvReader.createDefault(parserByteSource); CountVisitor visitor = readAllReturnedElements(streamReader); assertCountsOfTypes(visitor, 1, 8, 444, 1); } private void assertCountsOfTypes(CountVisitor visitor, int numSegments, int numClusters, int numFrames, int tagsPerSegment) { Assert.assertEquals(numSegments, visitor.getCount(MkvTypeInfos.EBML)); Assert.assertEquals(numSegments, visitor.getCount(MkvTypeInfos.SEGMENT)); Assert.assertEquals(numClusters, visitor.getCount(MkvTypeInfos.CLUSTER)); Assert.assertEquals(numClusters, visitor.getCount(MkvTypeInfos.TIMECODE)); Assert.assertEquals(numSegments, visitor.getCount(MkvTypeInfos.TIMECODESCALE)); Assert.assertEquals(0, visitor.getCount(MkvTypeInfos.DURATION)); Assert.assertEquals(numFrames, visitor.getCount(MkvTypeInfos.SIMPLEBLOCK)); Assert.assertEquals(numSegments, visitor.getCount(MkvTypeInfos.TRACKS)); Assert.assertEquals(numSegments, visitor.getCount(MkvTypeInfos.TRACKNUMBER)); Assert.assertEquals(numSegments*tagsPerSegment, visitor.getCount(MkvTypeInfos.TAG)); } @Test public void testGetDataOutputMkvTagNameWithPathFileWrite() throws IOException { InputStreamParserByteSource parserByteSource = getInputStreamParserByteSource("output_get_media.mkv"); List<EBMLTypeInfo> mkvTypeInfosToRead = new ArrayList<>(); mkvTypeInfosToRead.add(MkvTypeInfos.TAGNAME); StreamingMkvReader streamReader = new StreamingMkvReader(true, mkvTypeInfosToRead, parserByteSource); Path tmpFilePath = Files.createTempFile("StreamingMkvOutputGetMedia","output.txt"); int count = 0; try (BufferedWriter writer = Files.newBufferedWriter(tmpFilePath, StandardCharsets.US_ASCII, StandardOpenOption.WRITE, StandardOpenOption.CREATE)) { while (streamReader.mightHaveNext()) { Optional<MkvElement> mkvElement = streamReader.nextIfAvailable(); if (mkvElement.isPresent()) { if (mkvElement.get().getClass().equals(MkvDataElement.class)) { count++; } String elementString = mkvElement.toString(); writer.write(elementString, 0, elementString.length()); writer.newLine(); } } } finally { Files.delete(tmpFilePath); } Assert.assertEquals(5*12, count); } @Test public void testGetDataOutputMkvTagNameWithPath() throws IOException { InputStreamParserByteSource parserByteSource = getInputStreamParserByteSource("output_get_media.mkv"); List<EBMLTypeInfo> mkvTypeInfosToRead = new ArrayList<>(); mkvTypeInfosToRead.add(MkvTypeInfos.TAGNAME); StreamingMkvReader streamReader = new StreamingMkvReader(true, mkvTypeInfosToRead, parserByteSource); int count = 0; while (streamReader.mightHaveNext()) { Optional<MkvElement> mkvElement = streamReader.nextIfAvailable(); if (mkvElement.isPresent()) { if (mkvElement.get().getClass().equals(MkvDataElement.class)) { count++; } } } Assert.assertEquals(5 * 12, count); } @Test public void testGetDataOutputMkvAllElementsWithPath() throws IOException, MkvElementVisitException { InputStreamParserByteSource parserByteSource = getInputStreamParserByteSource("output_get_media.mkv"); StreamingMkvReader streamReader = StreamingMkvReader.createDefault(parserByteSource); CountVisitor visitor = readAllReturnedElements(streamReader); assertCountsOfTypes(visitor, 5, 5, 300, 5); } @Test public void testClustersMkvSimpleBlockWithPath() throws IOException, MkvElementVisitException { InputStreamParserByteSource parserByteSource = getClustersByteSource(); List<EBMLTypeInfo> mkvTypeInfosToRead = new ArrayList<>(); mkvTypeInfosToRead.add(MkvTypeInfos.SIMPLEBLOCK); StreamingMkvReader streamReader = new StreamingMkvReader(true, mkvTypeInfosToRead, parserByteSource); CountVisitor visitor = readAllReturnedElements(streamReader); Assert.assertEquals(444, visitor.getCount(MkvTypeInfos.SIMPLEBLOCK)); } @Test public void testClustersMkvIdAndOffset() throws IOException, MkvElementVisitException { InputStreamParserByteSource parserByteSource = getClustersByteSource(); StreamingMkvReader streamReader = StreamingMkvReader.createDefault(parserByteSource); Path tempOutputFile = Files.createTempFile("StreamingMkvClusters","offset.txt"); try (BufferedWriter writer = Files.newBufferedWriter(tempOutputFile, StandardCharsets.US_ASCII, StandardOpenOption.WRITE, StandardOpenOption.CREATE)) { ElementSizeAndOffsetVisitor offsetVisitor = new ElementSizeAndOffsetVisitor(writer); while (streamReader.mightHaveNext()) { Optional<MkvElement> mkvElement = streamReader.nextIfAvailable(); if (mkvElement.isPresent()) { mkvElement.get().accept(offsetVisitor); } } } finally { //Comment this out if the test fails and you need the partial output Files.delete(tempOutputFile); } } private CountVisitor readAllReturnedElements(StreamingMkvReader streamReader) throws MkvElementVisitException { List<EBMLTypeInfo> typeInfosToRead = new ArrayList<>(); typeInfosToRead.add(MkvTypeInfos.EBML); typeInfosToRead.add(MkvTypeInfos.SEGMENT); typeInfosToRead.add(MkvTypeInfos.CLUSTER); typeInfosToRead.add(MkvTypeInfos.TIMECODE); typeInfosToRead.add(MkvTypeInfos.TIMECODESCALE); typeInfosToRead.add(MkvTypeInfos.SIMPLEBLOCK); typeInfosToRead.add(MkvTypeInfos.TAGS); typeInfosToRead.add(MkvTypeInfos.TAG); typeInfosToRead.add(MkvTypeInfos.TRACKS); typeInfosToRead.add(MkvTypeInfos.TRACKNUMBER); CountVisitor countVisitor = new CountVisitor(typeInfosToRead); CompositeMkvElementVisitor compositeTestVisitor = new CompositeMkvElementVisitor(countVisitor, new TestDataElementVisitor()); while(streamReader.mightHaveNext()) { Optional<MkvElement> mkvElement = streamReader.nextIfAvailable(); if(mkvElement.isPresent()) { mkvElement.get().accept(compositeTestVisitor); } } return countVisitor; } private static class TestDataElementVisitor extends MkvElementVisitor { private Optional <MkvDataElement> previousDataElement = Optional.empty(); @Override public void visit(MkvStartMasterElement startMasterElement) throws MkvElementVisitException { assertNullPreviousDataElement(); } @Override public void visit(MkvEndMasterElement endMasterElement) throws MkvElementVisitException { assertNullPreviousDataElement(); } @Override public void visit(MkvDataElement dataElement) throws MkvElementVisitException { assertNullPreviousDataElement(); Assert.assertFalse(dataElement.isMaster()); Assert.assertNotNull(dataElement); Assert.assertNotNull(dataElement.getDataBuffer()); Assert.assertEquals(dataElement.getDataSize(), dataElement.getDataBuffer().limit()); previousDataElement = Optional.of(dataElement); } private void assertNullPreviousDataElement() { if (previousDataElement.isPresent()) { Assert.assertNull(previousDataElement.get().getDataBuffer()); } } } private InputStreamParserByteSource getClustersByteSource() throws IOException { final String fileName = "clusters.mkv"; return getInputStreamParserByteSource(fileName); } private InputStreamParserByteSource getInputStreamParserByteSource(String fileName) throws IOException { final InputStream in = TestResourceUtil.getTestInputStream(fileName); return new InputStreamParserByteSource(in); } }
4,913
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/test/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/test/java/com/amazonaws/kinesisvideo/parser/mkv/EBMLParserForMkvTypeInfosTest.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.mkv; import com.amazonaws.kinesisvideo.parser.TestResourceUtil; import com.amazonaws.kinesisvideo.parser.ebml.EBMLParser; import com.amazonaws.kinesisvideo.parser.ebml.InputStreamParserByteSource; import com.amazonaws.kinesisvideo.parser.ebml.TestEBMLParserCallback; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.io.InputStream; /** * Test to see that the elements in a typical input mkv file are recogized by the {@link MkvTypeInfoProvider}. */ public class EBMLParserForMkvTypeInfosTest { private EBMLParser parser; private TestEBMLParserCallback parserCallback; @Before public void setup() throws IllegalAccessException { parserCallback = new TestEBMLParserCallback(); MkvTypeInfoProvider typeInfoProvider = new MkvTypeInfoProvider(); typeInfoProvider.load(); parser = new EBMLParser(typeInfoProvider, parserCallback); } @Test public void testClustersMkv() throws IOException { final String fileName = "clusters.mkv"; final InputStream in = TestResourceUtil.getTestInputStream(fileName); InputStreamParserByteSource parserByteSource = new InputStreamParserByteSource(in); while(!parserByteSource.eof()) { parser.parse(parserByteSource); } parser.closeParser(); } }
4,914
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/test/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/test/java/com/amazonaws/kinesisvideo/parser/mkv/MkvValueTest.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.mkv; import org.junit.Assert; import org.junit.Test; import java.nio.ByteBuffer; /** * Tests for MkvValue equality */ public class MkvValueTest { @Test public void integerTest() { MkvValue<Integer> val1 = new MkvValue<>(2, 1); MkvValue<Integer> val2 = new MkvValue<>(2, 1); Assert.assertTrue(val1.equals(val2)); MkvValue<Integer> val3 = new MkvValue<>(3, 1); Assert.assertFalse(val1.equals(val3)); MkvValue<Integer> val4 = new MkvValue<>(2, 2); Assert.assertFalse(val1.equals(val4)); } @Test public void byteBufferTest() { ByteBuffer buf1 = ByteBuffer.wrap(new byte[] {(byte) 0x32, (byte) 0x45, (byte) 0x73 }); ByteBuffer buf2 = ByteBuffer.wrap(new byte[] {(byte) 0x32, (byte) 0x45, (byte) 0x73 }); MkvValue<ByteBuffer> val1 = new MkvValue<>(buf1, buf1.limit()); MkvValue<ByteBuffer> val2 = new MkvValue<>(buf2, buf2.limit()); Assert.assertTrue(val1.equals(val2)); //Even if a buffer has been partially read, equality should still succeed buf2.get(); Assert.assertTrue(val1.equals(val2)); ByteBuffer buf3 = ByteBuffer.wrap(new byte[] {(byte) 0x28}); MkvValue val3 = new MkvValue(buf3, buf3.limit()); Assert.assertFalse(val1.equals(val3)); } }
4,915
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/test/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/test/java/com/amazonaws/kinesisvideo/parser/mkv/ElementSizeAndOffsetVisitorTest.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.mkv; import com.amazonaws.kinesisvideo.parser.TestResourceUtil; import com.amazonaws.kinesisvideo.parser.ebml.InputStreamParserByteSource; import com.amazonaws.kinesisvideo.parser.mkv.visitors.ElementSizeAndOffsetVisitor; import org.junit.Test; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.Optional; /** * Test for ElementSizeAndOffsetVisitor. */ public class ElementSizeAndOffsetVisitorTest { @Test public void basicTest() throws IOException, MkvElementVisitException { final String fileName = "clusters.mkv"; final InputStream in = TestResourceUtil.getTestInputStream(fileName); StreamingMkvReader offsetReader = new StreamingMkvReader(false, new ArrayList<>(), new InputStreamParserByteSource(in)); Path tmpFilePath = Files.createTempFile("basicTest:"+fileName+":","offset"); try (BufferedWriter writer = Files.newBufferedWriter(tmpFilePath, StandardCharsets.US_ASCII, StandardOpenOption.WRITE, StandardOpenOption.CREATE)) { ElementSizeAndOffsetVisitor offsetVisitor = new ElementSizeAndOffsetVisitor(writer); while(offsetReader.mightHaveNext()) { Optional<MkvElement> mkvElement = offsetReader.nextIfAvailable(); if (mkvElement.isPresent()) { mkvElement.get().accept(offsetVisitor); } } } finally { Files.delete(tmpFilePath); } } }
4,916
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/test/java/com/amazonaws/kinesisvideo/parser/mkv
Create_ds/amazon-kinesis-video-streams-parser-library/src/test/java/com/amazonaws/kinesisvideo/parser/mkv/visitors/CopyVisitorTest.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.mkv.visitors; import com.amazonaws.kinesisvideo.parser.TestResourceUtil; import com.amazonaws.kinesisvideo.parser.ebml.InputStreamParserByteSource; import com.amazonaws.kinesisvideo.parser.mkv.MkvElementVisitException; import com.amazonaws.kinesisvideo.parser.mkv.StreamingMkvReader; import org.junit.Assert; import org.junit.Test; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; public class CopyVisitorTest { @Test public void testOneCopy() throws IOException, MkvElementVisitException { testOneCopyForFile("clusters.mkv"); } @Test public void testOneCopyGetMediaOutput() throws IOException, MkvElementVisitException { testOneCopyForFile("output_get_media.mkv"); } @Test public void testTwoCopiesAtOnce() throws IOException, MkvElementVisitException { testTwoCopiesAtOnceForFile("clusters.mkv"); } @Test public void testTwoCopiesAtOnceGetMediaOutput() throws IOException, MkvElementVisitException { testTwoCopiesAtOnceForFile("output_get_media.mkv"); } private void testTwoCopiesAtOnceForFile(String fileName) throws IOException, MkvElementVisitException { byte [] inputBytes = TestResourceUtil.getTestInputByteArray(fileName); ByteArrayOutputStream outputStream1 = new ByteArrayOutputStream(); ByteArrayOutputStream outputStream2 = new ByteArrayOutputStream(); try (CopyVisitor copyVisitor1 = new CopyVisitor(outputStream1)) { try (CopyVisitor copyVisitor2 = new CopyVisitor(outputStream2)) { StreamingMkvReader.createDefault(getInputStreamParserByteSource(fileName)) .apply(new CompositeMkvElementVisitor(copyVisitor1, copyVisitor2)); } } Assert.assertArrayEquals(inputBytes, outputStream1.toByteArray()); Assert.assertArrayEquals(inputBytes, outputStream2.toByteArray()); } private void testOneCopyForFile(String fileName) throws IOException, MkvElementVisitException { byte [] inputBytes = TestResourceUtil.getTestInputByteArray(fileName); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try (CopyVisitor copyVisitor = new CopyVisitor(outputStream)) { StreamingMkvReader.createDefault(getInputStreamParserByteSource(fileName)).apply(copyVisitor); } Assert.assertArrayEquals(inputBytes, outputStream.toByteArray()); } private InputStreamParserByteSource getInputStreamParserByteSource(String fileName) throws IOException { final InputStream in = TestResourceUtil.getTestInputStream(fileName); return new InputStreamParserByteSource(in); } }
4,917
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/test/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/test/java/com/amazonaws/kinesisvideo/parser/utilities/OutputSegmentMergerTest.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.utilities; import com.amazonaws.kinesisvideo.parser.TestResourceUtil; import com.amazonaws.kinesisvideo.parser.ebml.EBMLTypeInfo; import com.amazonaws.kinesisvideo.parser.ebml.InputStreamParserByteSource; import com.amazonaws.kinesisvideo.parser.ebml.MkvTypeInfos; import com.amazonaws.kinesisvideo.parser.mkv.MkvElement; import com.amazonaws.kinesisvideo.parser.mkv.MkvElementVisitException; import com.amazonaws.kinesisvideo.parser.mkv.StreamingMkvReader; import com.amazonaws.kinesisvideo.parser.mkv.visitors.CountVisitor; import com.amazonaws.kinesisvideo.parser.mkv.visitors.ElementSizeAndOffsetVisitor; import org.apache.commons.lang3.time.StopWatch; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import java.io.BufferedWriter; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.concurrent.TimeUnit; /** * Tests for OutputSegmentMerger */ public class OutputSegmentMergerTest { /** * This test merges the separate Mkv chunks generated by Kinesis Video GetMedia into one stream * as long as the chunks have the same EBML header and tracks. * It does a few things: * 1.Reads output_get_media.mkv that contains the output of get media call with 32 chunks as 32 Mkvstreaams. * 2.Merges it into one stream with 32 mkv clusters (fragments) * 3.It parses the merged stream to count the number of ebml headers, segments, clusters using * the {@link CountVisitor}. * Validates that the right number are present. * 4.Writes the merged output to a tmp file mergedoutput.mkv. mkvinfo can parse this successfully unliked the source * output_get_media.mkv. * 5.The test then parses the merged output again to print out the elements, their offsets in the merged mkv and * size of the element in bytes. It uses the {@link ElementSizeAndOffsetVisitor} to do this. */ @Test public void mergeTracksAndEBML() throws IOException, MkvElementVisitException { final List<EBMLTypeInfo> typeInfosToMergeOn = new ArrayList<>(); typeInfosToMergeOn.add(MkvTypeInfos.TRACKS); typeInfosToMergeOn.add(MkvTypeInfos.EBML); //Test that the merge works correctly. final byte [] outputBytes = mergeTestInternal(typeInfosToMergeOn); //TODO: enable to write the merged output to a file. /* Path tmpFileName = Files.createTempFile("OutputSegmentMergerMergeTracksAndEBML", "mergedoutput.mkv"); Files.write(tmpFileName, outputBytes, StandardOpenOption.WRITE, StandardOpenOption.CREATE); */ //Write out the element id, offset and data sizes of the various elements. writeOutIdAndOffset(outputBytes); } @Test public void mergeWithTimeCodeBackwards() throws IOException, MkvElementVisitException { //Read all the inputBytes so that we can compare with output bytes later. final byte [] inputBytes = TestResourceUtil.getTestInputByteArray("output_get_media.mkv"); final InputStream in = getInputStreamForDoubleBytes(inputBytes); //Stream to receive the merged output. final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); //Do the actual merge. final OutputSegmentMerger merger = OutputSegmentMerger.createDefault(outputStream); final StreamingMkvReader mkvStreamReader = StreamingMkvReader.createDefault(new InputStreamParserByteSource(in)); while(mkvStreamReader.mightHaveNext()) { final Optional<MkvElement> mkvElement = mkvStreamReader.nextIfAvailable(); if (mkvElement.isPresent()) { mkvElement.get().accept(merger); } } final byte[] outputBytes = outputStream.toByteArray(); Assert.assertFalse(Arrays.equals(inputBytes, outputBytes)); //Count different types of elements present in the merged stream. final CountVisitor countVisitor = getCountVisitorResult(outputBytes); //Validate that there are two EBML headers and segment and tracks //but there are 64 clusters and tracks as expected. Assert.assertEquals(2, countVisitor.getCount(MkvTypeInfos.EBML)); Assert.assertEquals(2, countVisitor.getCount(MkvTypeInfos.EBMLVERSION)); Assert.assertEquals(2, countVisitor.getCount(MkvTypeInfos.SEGMENT)); Assert.assertEquals(10, countVisitor.getCount(MkvTypeInfos.CLUSTER)); Assert.assertEquals(10, countVisitor.getCount(MkvTypeInfos.TIMECODE)); Assert.assertEquals(2, countVisitor.getCount(MkvTypeInfos.TRACKS)); Assert.assertEquals(2, countVisitor.getCount(MkvTypeInfos.TRACKNUMBER)); Assert.assertEquals(600, countVisitor.getCount(MkvTypeInfos.SIMPLEBLOCK)); Assert.assertEquals(120, countVisitor.getCount(MkvTypeInfos.TAGNAME)); } @Test public void packClustersWithSparseData() throws IOException, MkvElementVisitException { //Read all the inputBytes so that we can compare with output bytes later. final byte [] inputBytes = TestResourceUtil.getTestInputByteArray("output_get_media_sparse_fragments.mkv"); //Stream to receive the merged output. final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); //Do the actual merge. final OutputSegmentMerger merger = OutputSegmentMerger.create(outputStream, OutputSegmentMerger.Configuration.builder() .packClusters(true) .build()); final StreamingMkvReader mkvStreamReader = StreamingMkvReader.createDefault(new InputStreamParserByteSource(new ByteArrayInputStream(inputBytes))); while(mkvStreamReader.mightHaveNext()) { final Optional<MkvElement> mkvElement = mkvStreamReader.nextIfAvailable(); if (mkvElement.isPresent()) { mkvElement.get().accept(merger); } } final byte[] outputBytes = outputStream.toByteArray(); final byte [] expectedOutputBytes = TestResourceUtil.getTestInputByteArray("output_get_media_sparse_fragments_merged.mkv"); Assert.assertArrayEquals(expectedOutputBytes, outputBytes); } @Test public void stopWithTimeCodeBackwards() throws IOException, MkvElementVisitException { //Read all the inputBytes so that we can compare with output bytes later. final String fileName = "output-get-media-non-increasing-timecode.mkv"; final CountVisitor countVisitor = runMergerToStopAtFirstNonMatchingSegment(fileName); //Validate that there is only one EBML header and segment and tracks, //only 1 cluster and other elements as expected Assert.assertEquals(1, countVisitor.getCount(MkvTypeInfos.EBML)); Assert.assertEquals(1, countVisitor.getCount(MkvTypeInfos.EBMLVERSION)); Assert.assertEquals(1, countVisitor.getCount(MkvTypeInfos.SEGMENT)); Assert.assertEquals(1, countVisitor.getCount(MkvTypeInfos.CLUSTER)); Assert.assertEquals(1, countVisitor.getCount(MkvTypeInfos.TIMECODE)); Assert.assertEquals(1, countVisitor.getCount(MkvTypeInfos.TRACKS)); Assert.assertEquals(1, countVisitor.getCount(MkvTypeInfos.TRACKNUMBER)); Assert.assertEquals(30, countVisitor.getCount(MkvTypeInfos.SIMPLEBLOCK)); Assert.assertEquals(59, countVisitor.getCount(MkvTypeInfos.TAGNAME)); } @Test public void stopWithTimeCodeEqual() throws IOException, MkvElementVisitException { //Read all the inputBytes so that we can compare with output bytes later. final String fileName = "output-get-media-equal-timecode.mkv"; final CountVisitor countVisitor = runMergerToStopAtFirstNonMatchingSegment(fileName); //Validate that there is only one EBML header and segment and tracks, //only 1 cluster and other elements as expected Assert.assertEquals(1, countVisitor.getCount(MkvTypeInfos.EBML)); Assert.assertEquals(1, countVisitor.getCount(MkvTypeInfos.EBMLVERSION)); Assert.assertEquals(1, countVisitor.getCount(MkvTypeInfos.SEGMENT)); Assert.assertEquals(1, countVisitor.getCount(MkvTypeInfos.CLUSTER)); Assert.assertEquals(1, countVisitor.getCount(MkvTypeInfos.TIMECODE)); Assert.assertEquals(1, countVisitor.getCount(MkvTypeInfos.TRACKS)); Assert.assertEquals(1, countVisitor.getCount(MkvTypeInfos.TRACKNUMBER)); Assert.assertEquals(120, countVisitor.getCount(MkvTypeInfos.SIMPLEBLOCK)); Assert.assertEquals(12, countVisitor.getCount(MkvTypeInfos.TAGNAME)); } private CountVisitor runMergerToStopAtFirstNonMatchingSegment(final String fileName) throws IOException, MkvElementVisitException { final byte [] inputBytes = TestResourceUtil.getTestInputByteArray(fileName); final InputStream in = getInputStreamForDoubleBytes(inputBytes); //Stream to receive the merged output. final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); //Do the actual merge. final OutputSegmentMerger merger = OutputSegmentMerger.createToStopAtFirstNonMatchingSegment(outputStream); final StreamingMkvReader mkvStreamReader = StreamingMkvReader.createDefault(new InputStreamParserByteSource(in)); while (!merger.isDone() && mkvStreamReader.mightHaveNext()) { final Optional<MkvElement> mkvElement = mkvStreamReader.nextIfAvailable(); if (mkvElement.isPresent()) { mkvElement.get().accept(merger); } } Assert.assertTrue(merger.isDone()); final byte[] outputBytes = outputStream.toByteArray(); Assert.assertFalse(Arrays.equals(inputBytes, outputBytes)); //Count different types of elements present in the merged stream. return getCountVisitorResult(outputBytes); } @Test public void mergeWithStopAfterFirstSegment() throws IOException, MkvElementVisitException { //Read all the inputBytes so that we can compare with output bytes later. final CountVisitor countVisitor = runMergerToStopAtFirstNonMatchingSegment("output_get_media.mkv"); //Validate that there is only one EBML header and segment and tracks //but there are 32 clusters and tracks as expected. assertCountsAfterMerge(countVisitor); } private InputStream getInputStreamForDoubleBytes(final byte[] inputBytes) throws IOException { final ByteArrayOutputStream doubleStream = new ByteArrayOutputStream(); doubleStream.write(inputBytes); doubleStream.write(inputBytes); //Reading again purely to show that the OutputSegmentMerger works even with streams //where all the data is not in memory. return new ByteArrayInputStream(doubleStream.toByteArray()); } private byte [] mergeTestInternal(final List<EBMLTypeInfo> typeInfosToMergeOn) throws IOException, MkvElementVisitException { //Read all the inputBytes so that we can compare with output bytes later. final byte [] inputBytes = TestResourceUtil.getTestInputByteArray("output_get_media.mkv"); //Reading again purely to show that the OutputSegmentMerger works even with streams //where all the data is not in memory. final InputStream in = TestResourceUtil.getTestInputStream("output_get_media.mkv"); //Stream to receive the merged output. final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); //Do the actual merge. final OutputSegmentMerger merger = OutputSegmentMerger.create(outputStream, OutputSegmentMerger.Configuration.builder() .typeInfosToMergeOn(typeInfosToMergeOn) .build()); final StreamingMkvReader mkvStreamReader = StreamingMkvReader.createDefault(new InputStreamParserByteSource(in)); while (mkvStreamReader.mightHaveNext()) { final Optional<MkvElement> mkvElement = mkvStreamReader.nextIfAvailable(); if (mkvElement.isPresent()) { mkvElement.get().accept(merger); } } final byte []outputBytes = outputStream.toByteArray(); Assert.assertFalse(Arrays.equals(inputBytes, outputBytes)); //Count different types of elements present in the merged stream. final CountVisitor countVisitor = getCountVisitorResult(outputBytes); //Validate that there is only one EBML header and segment and tracks //but there are 5 clusters and tracks as expected. assertCountsAfterMerge(countVisitor); return outputBytes; } private void assertCountsAfterMerge(final CountVisitor countVisitor) { Assert.assertEquals(1, countVisitor.getCount(MkvTypeInfos.EBML)); Assert.assertEquals(1, countVisitor.getCount(MkvTypeInfos.EBMLVERSION)); Assert.assertEquals(1, countVisitor.getCount(MkvTypeInfos.SEGMENT)); Assert.assertEquals(5, countVisitor.getCount(MkvTypeInfos.CLUSTER)); Assert.assertEquals(5, countVisitor.getCount(MkvTypeInfos.TIMECODE)); Assert.assertEquals(1, countVisitor.getCount(MkvTypeInfos.TRACKS)); Assert.assertEquals(1, countVisitor.getCount(MkvTypeInfos.TRACKNUMBER)); Assert.assertEquals(300, countVisitor.getCount(MkvTypeInfos.SIMPLEBLOCK)); Assert.assertEquals(60, countVisitor.getCount(MkvTypeInfos.TAGNAME)); } private CountVisitor getCountVisitorResult(final byte[] outputBytes) throws MkvElementVisitException { final ByteArrayInputStream verifyStream = new ByteArrayInputStream(outputBytes); //List of elements to count. final List<EBMLTypeInfo> typesToCount = new ArrayList<>(); typesToCount.add(MkvTypeInfos.EBML); typesToCount.add(MkvTypeInfos.EBMLVERSION); typesToCount.add(MkvTypeInfos.SEGMENT); typesToCount.add(MkvTypeInfos.CLUSTER); typesToCount.add(MkvTypeInfos.TIMECODE); typesToCount.add(MkvTypeInfos.SIMPLEBLOCK); typesToCount.add(MkvTypeInfos.TRACKS); typesToCount.add(MkvTypeInfos.TRACKNUMBER); typesToCount.add(MkvTypeInfos.TAGNAME); //Create a visitor that counts the occurrences of the element. final CountVisitor countVisitor = new CountVisitor(typesToCount); final StreamingMkvReader verifyStreamReader = StreamingMkvReader.createDefault(new InputStreamParserByteSource(verifyStream)); //Run the visitor over the stream. while(verifyStreamReader.mightHaveNext()) { final Optional<MkvElement> mkvElement = verifyStreamReader.nextIfAvailable(); if (mkvElement.isPresent()) { mkvElement.get().accept(countVisitor); } } Assert.assertTrue(countVisitor.doEndAndStartMasterElementsMatch()); return countVisitor; } @Ignore @Test public void perfTest() throws IOException, MkvElementVisitException { final byte [] inputBytes = TestResourceUtil.getTestInputByteArray("output_get_media.mkv"); final int numIterations = 1000; final StopWatch timer = new StopWatch(); timer.start(); for (int i = 0; i < numIterations; i++) { try (final ByteArrayInputStream in = new ByteArrayInputStream(inputBytes); final ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { final OutputSegmentMerger merger = OutputSegmentMerger.createDefault(outputStream); final StreamingMkvReader mkvStreamReader = StreamingMkvReader.createWithMaxContentSize(new InputStreamParserByteSource(in), 32000); while(mkvStreamReader.mightHaveNext()) { final Optional<MkvElement> mkvElement = mkvStreamReader.nextIfAvailable(); if (mkvElement.isPresent()) { mkvElement.get().accept(merger); } } } } timer.stop(); final long totalTimeMillis = timer.getTime(); final double totalTimeSeconds = totalTimeMillis/(double )TimeUnit.SECONDS.toMillis(1); final double mergeRate = (double )(inputBytes.length)*numIterations/(totalTimeSeconds*1024*1024); System.out.println("Total time "+totalTimeMillis+" ms "+" Merging rate "+mergeRate+" MB/s"); } @Test public void basicTest() throws IOException, MkvElementVisitException { final byte [] inputBytes = TestResourceUtil.getTestInputByteArray("output_get_media.mkv"); final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); final ByteArrayInputStream in = new ByteArrayInputStream(inputBytes); final OutputSegmentMerger merger = OutputSegmentMerger.create(outputStream, OutputSegmentMerger.Configuration.builder() .typeInfosToMergeOn(new ArrayList<>()) .build()); final StreamingMkvReader mkvStreamReader = StreamingMkvReader.createDefault(new InputStreamParserByteSource(in)); while (mkvStreamReader.mightHaveNext()) { final Optional<MkvElement> mkvElement = mkvStreamReader.nextIfAvailable(); if (mkvElement.isPresent()) { mkvElement.get().accept(merger); } } Assert.assertEquals(5, merger.getClustersCount()); Assert.assertEquals(5, merger.getSegmentsCount()); Assert.assertEquals(300, merger.getSimpleBlocksCount()); final byte [] outputBytes = outputStream.toByteArray(); Assert.assertArrayEquals(inputBytes, outputBytes); final CountVisitor countVisitor = getCountVisitorResult(outputBytes); Assert.assertEquals(5, countVisitor.getCount(MkvTypeInfos.EBML)); Assert.assertEquals(5, countVisitor.getCount(MkvTypeInfos.EBMLVERSION)); Assert.assertEquals(5, countVisitor.getCount(MkvTypeInfos.SEGMENT)); Assert.assertEquals(5, countVisitor.getCount(MkvTypeInfos.CLUSTER)); Assert.assertEquals(5, countVisitor.getCount(MkvTypeInfos.TIMECODE)); Assert.assertEquals(5, countVisitor.getCount(MkvTypeInfos.TRACKS)); Assert.assertEquals(5, countVisitor.getCount(MkvTypeInfos.TRACKNUMBER)); Assert.assertEquals(300, countVisitor.getCount(MkvTypeInfos.SIMPLEBLOCK)); Assert.assertEquals(60, countVisitor.getCount(MkvTypeInfos.TAGNAME)); } @Test public void mergeEBMLHeaders() throws IOException, MkvElementVisitException { final List<EBMLTypeInfo> typeInfosToMergeOn = new ArrayList<>(); typeInfosToMergeOn.add(MkvTypeInfos.EBML); mergeTestInternal(typeInfosToMergeOn); } @Test public void mergeTracks() throws IOException, MkvElementVisitException { final List<EBMLTypeInfo> typeInfosToMergeOn = new ArrayList<>(); typeInfosToMergeOn.add(MkvTypeInfos.TRACKS); mergeTestInternal(typeInfosToMergeOn); } private void writeOutIdAndOffset(final byte[] outputBytes) throws IOException, MkvElementVisitException { final ByteArrayInputStream offsetStream = new ByteArrayInputStream(outputBytes); final StreamingMkvReader offsetReader = StreamingMkvReader.createDefault(new InputStreamParserByteSource(offsetStream)); //Write the element name, offset and size to a file. final Path tempFile = Files.createTempFile("Merger","offset"); try (final BufferedWriter writer = Files.newBufferedWriter(tempFile, StandardCharsets.US_ASCII, StandardOpenOption.WRITE, StandardOpenOption.CREATE)) { final ElementSizeAndOffsetVisitor offsetVisitor = new ElementSizeAndOffsetVisitor(writer); while (offsetReader.mightHaveNext()) { final Optional<MkvElement> mkvElement = offsetReader.nextIfAvailable(); if (mkvElement.isPresent()) { mkvElement.get().accept(offsetVisitor); } } } finally { Files.delete(tempFile); } } }
4,918
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/test/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/test/java/com/amazonaws/kinesisvideo/parser/utilities/FragmentMetadataVisitorTest.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.utilities; import com.amazonaws.kinesisvideo.parser.TestResourceUtil; import com.amazonaws.kinesisvideo.parser.ebml.InputStreamParserByteSource; import com.amazonaws.kinesisvideo.parser.ebml.MkvTypeInfos; import com.amazonaws.kinesisvideo.parser.mkv.MkvEndMasterElement; import com.amazonaws.kinesisvideo.parser.mkv.StreamingMkvReader; import com.amazonaws.kinesisvideo.parser.mkv.visitors.CompositeMkvElementVisitor; import com.amazonaws.kinesisvideo.parser.mkv.Frame; import com.amazonaws.kinesisvideo.parser.mkv.MkvDataElement; import com.amazonaws.kinesisvideo.parser.mkv.MkvElement; import com.amazonaws.kinesisvideo.parser.mkv.MkvElementVisitException; import com.amazonaws.kinesisvideo.parser.mkv.MkvValue; import com.amazonaws.kinesisvideo.parser.utilities.FragmentMetadataVisitor.BasicMkvTagProcessor; import org.junit.Assert; import org.junit.Test; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Set; /** * Test class to test {@link FragmentMetadataVisitor}. */ public class FragmentMetadataVisitorTest { @Test public void basicTest() throws IOException, MkvElementVisitException { final InputStream in = TestResourceUtil.getTestInputStream("output_get_media.mkv"); List<String> continuationTokens = new ArrayList<>(); continuationTokens.add("91343852333181432392682062607743920146159169392"); continuationTokens.add("91343852333181432397633822764885441725874549018"); continuationTokens.add("91343852333181432402585582922026963247510532162"); final BasicMkvTagProcessor tagProcessor = new BasicMkvTagProcessor(); final FragmentMetadataVisitor fragmentVisitor = FragmentMetadataVisitor.create(Optional.of(tagProcessor)); StreamingMkvReader mkvStreamReader = StreamingMkvReader.createDefault(new InputStreamParserByteSource(in)); int segmentCount = 0; while(mkvStreamReader.mightHaveNext()) { Optional<MkvElement> mkvElement = mkvStreamReader.nextIfAvailable(); if (mkvElement.isPresent()) { mkvElement.get().accept(fragmentVisitor); if (MkvTypeInfos.SIMPLEBLOCK.equals(mkvElement.get().getElementMetaData().getTypeInfo())) { MkvDataElement dataElement = (MkvDataElement) mkvElement.get(); Frame frame = ((MkvValue<Frame>)dataElement.getValueCopy()).getVal(); MkvTrackMetadata trackMetadata = fragmentVisitor.getMkvTrackMetadata(frame.getTrackNumber()); assertTrackAndFragmentInfo(fragmentVisitor, frame, trackMetadata); } if (MkvTypeInfos.SEGMENT.equals(mkvElement.get().getElementMetaData().getTypeInfo())) { if (mkvElement.get() instanceof MkvEndMasterElement) { if (segmentCount < continuationTokens.size()) { Optional<String> continuationToken = fragmentVisitor.getContinuationToken(); Assert.assertTrue(continuationToken.isPresent()); Assert.assertEquals(continuationTokens.get(segmentCount), continuationToken.get()); } Assert.assertTrue(fragmentVisitor.getCurrentFragmentMetadata().isPresent()); final List<MkvTag> tags = tagProcessor.getTags(); Assert.assertEquals(7, tags.size()); Assert.assertEquals("COMPATIBLE_BRANDS", tags.get(0).getTagName()); Assert.assertEquals("isomavc1mp42", tags.get(0).getTagValue()); Assert.assertEquals("MAJOR_BRAND", tags.get(1).getTagName()); Assert.assertEquals("M4V ", tags.get(1).getTagValue()); Assert.assertEquals("MINOR_VERSION", tags.get(2).getTagName()); Assert.assertEquals("1", tags.get(2).getTagValue()); Assert.assertEquals("ENCODER", tags.get(3).getTagName()); Assert.assertEquals("Lavf57.71.100", tags.get(3).getTagValue()); Assert.assertEquals("HANDLER_NAME", tags.get(4).getTagName()); Assert.assertEquals("ETI ISO Video Media Handler", tags.get(4).getTagValue()); Assert.assertEquals("ENCODER", tags.get(5).getTagName()); Assert.assertEquals("Elemental H.264", tags.get(5).getTagValue()); Assert.assertEquals("DURATION", tags.get(6).getTagName()); Assert.assertEquals("00:00:10.000000000\u0000\u0000", tags.get(6).getTagValue()); segmentCount++; tagProcessor.clear(); } } } } } private void assertTrackAndFragmentInfo(FragmentMetadataVisitor fragmentVisitor, Frame frame, MkvTrackMetadata trackMetadata) { Assert.assertEquals(frame.getTrackNumber(), trackMetadata.getTrackNumber().longValue()); Assert.assertEquals(360L, trackMetadata.getPixelHeight().get().longValue()); Assert.assertEquals(640L, trackMetadata.getPixelWidth().get().longValue()); Assert.assertEquals("V_MPEG4/ISO/AVC", trackMetadata.getCodecId()); Assert.assertTrue(fragmentVisitor.getCurrentFragmentMetadata().isPresent()); Assert.assertTrue(fragmentVisitor.getCurrentFragmentMetadata().get().isSuccess()); Assert.assertEquals(0, fragmentVisitor.getCurrentFragmentMetadata().get().getErrorId()); Assert.assertNull(fragmentVisitor.getCurrentFragmentMetadata().get().getErrorCode()); if (fragmentVisitor.getPreviousFragmentMetadata().isPresent()) { Assert.assertTrue(fragmentVisitor.getPreviousFragmentMetadata() .get() .getFragmentNumber() .compareTo(fragmentVisitor.getCurrentFragmentMetadata().get().getFragmentNumber()) < 0); } } @Test public void withOutputSegmentMergerTest() throws IOException, MkvElementVisitException { final FragmentMetadataVisitor fragmentVisitor = FragmentMetadataVisitor.create(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); OutputSegmentMerger outputSegmentMerger = OutputSegmentMerger.createDefault(outputStream); CompositeMkvElementVisitor compositeVisitor = new TestCompositeVisitor(fragmentVisitor, outputSegmentMerger); final InputStream in = TestResourceUtil.getTestInputStream("output_get_media.mkv"); StreamingMkvReader mkvStreamReader = StreamingMkvReader.createDefault(new InputStreamParserByteSource(in)); while (mkvStreamReader.mightHaveNext()) { Optional<MkvElement> mkvElement = mkvStreamReader.nextIfAvailable(); if (mkvElement.isPresent()) { mkvElement.get().accept(compositeVisitor); if (MkvTypeInfos.SIMPLEBLOCK.equals(mkvElement.get().getElementMetaData().getTypeInfo())) { MkvDataElement dataElement = (MkvDataElement) mkvElement.get(); Frame frame = ((MkvValue<Frame>) dataElement.getValueCopy()).getVal(); Assert.assertTrue(frame.getFrameData().limit() > 0); MkvTrackMetadata trackMetadata = fragmentVisitor.getMkvTrackMetadata(frame.getTrackNumber()); assertTrackAndFragmentInfo(fragmentVisitor, frame, trackMetadata); } } } } @Test public void testFragmentNumbers_NoClusterData() throws IOException, MkvElementVisitException { final FragmentMetadataVisitor fragmentVisitor = FragmentMetadataVisitor.create(); String testFile = "empty-mkv-with-tags.mkv"; Set<String> expectedFragmentNumbers = new HashSet<>( Arrays.asList( "91343852338378294813695855977007281634605393997" )); final InputStream inputStream = TestResourceUtil.getTestInputStream(testFile); Set<String> visitedFragmentNumbers = new HashSet<>(); StreamingMkvReader mkvStreamReader = StreamingMkvReader.createDefault(new InputStreamParserByteSource(inputStream)); while (mkvStreamReader.mightHaveNext()) { Optional<MkvElement> mkvElement = mkvStreamReader.nextIfAvailable(); if (mkvElement.isPresent()) { mkvElement.get().accept(fragmentVisitor); Optional<FragmentMetadata> fragmentMetadata = fragmentVisitor.getCurrentFragmentMetadata(); if (fragmentMetadata.isPresent()) { String fragmentNumber = fragmentMetadata.get().getFragmentNumberString(); visitedFragmentNumbers.add(fragmentNumber); } } } Assert.assertEquals(expectedFragmentNumbers, visitedFragmentNumbers); } /** * Validating the fragment metadata visitor returns the set of tags in the right order from the test file. * The test file contains mix of multiple clusters and tags. */ @Test public void testMkvTags_MixedCluster() throws IOException, MkvElementVisitException { final BasicMkvTagProcessor tagProcessor = new BasicMkvTagProcessor(); final FragmentMetadataVisitor fragmentVisitor = FragmentMetadataVisitor.create(Optional.of(tagProcessor)); String testFile = "test_mixed_tags.mkv"; boolean firstCluster = true; final InputStream inputStream = TestResourceUtil.getTestInputStream(testFile); StreamingMkvReader mkvStreamReader = StreamingMkvReader.createDefault(new InputStreamParserByteSource(inputStream)); while (mkvStreamReader.mightHaveNext()) { Optional<MkvElement> mkvElement = mkvStreamReader.nextIfAvailable(); if (mkvElement.isPresent()) { mkvElement.get().accept(fragmentVisitor); if (MkvTypeInfos.SEGMENT.equals(mkvElement.get().getElementMetaData().getTypeInfo()) && mkvElement.get() instanceof MkvEndMasterElement) { final List<MkvTag> tags = tagProcessor.getTags(); Assert.assertEquals(firstCluster ? 10 : 5, tags.size()); for (int i = 0; i < tags.size(); i++) { Assert.assertEquals(String.format("testTag_%s", i % 5), tags.get(i).getTagName()); Assert.assertEquals(String.format("testTag_%s_Value", i % 5), tags.get(i).getTagValue()); } tagProcessor.clear(); firstCluster = false; } } } } /** * Validating the fragment metadata visitor returns the set of tags in the right order from the test file. * The test file contains no clusters only EBML header, Segment and a set of tags. */ @Test public void testMkvTags_NoCluster() throws IOException, MkvElementVisitException { final BasicMkvTagProcessor tagProcessor = new BasicMkvTagProcessor(); final FragmentMetadataVisitor fragmentVisitor = FragmentMetadataVisitor.create(Optional.of(tagProcessor)); String testFile = "test_tags_empty_cluster.mkv"; final InputStream inputStream = TestResourceUtil.getTestInputStream(testFile); StreamingMkvReader mkvStreamReader = StreamingMkvReader.createDefault(new InputStreamParserByteSource(inputStream)); while (mkvStreamReader.mightHaveNext()) { Optional<MkvElement> mkvElement = mkvStreamReader.nextIfAvailable(); if (mkvElement.isPresent()) { mkvElement.get().accept(fragmentVisitor); if (MkvTypeInfos.SEGMENT.equals(mkvElement.get().getElementMetaData().getTypeInfo()) && mkvElement.get() instanceof MkvEndMasterElement) { final List<MkvTag> tags = tagProcessor.getTags(); Assert.assertEquals(5, tags.size()); for (int i = 0; i < tags.size(); i++) { Assert.assertEquals(String.format("testTag_%s", i), tags.get(i).getTagName()); Assert.assertEquals(String.format("testTag_%s_Value", i), tags.get(i).getTagValue()); } tagProcessor.clear(); } } } } @Test public void testFragmentMetadata_NoFragementMetadata_withWebm() throws IOException, MkvElementVisitException { final FragmentMetadataVisitor fragmentMetadataVisitor = FragmentMetadataVisitor.create(); final String testFile = "big-buck-bunny_trailer.webm"; int metadataCount = 0; final StreamingMkvReader mkvStreamReader = StreamingMkvReader .createDefault(new InputStreamParserByteSource(TestResourceUtil.getTestInputStream(testFile))); while (mkvStreamReader.mightHaveNext()) { Optional<MkvElement> mkvElement = mkvStreamReader.nextIfAvailable(); if (mkvElement.isPresent()) { mkvElement.get().accept(fragmentMetadataVisitor); Optional<FragmentMetadata> fragmentMetadata = fragmentMetadataVisitor.getCurrentFragmentMetadata(); if(fragmentMetadata.isPresent()) { metadataCount ++; } } } Assert.assertEquals(0, metadataCount); } @Test public void testFragmentMetadata_NoFragementMetadata_withMkv() throws IOException, MkvElementVisitException { final FragmentMetadataVisitor fragmentMetadataVisitor = FragmentMetadataVisitor.create(); final String testFile = "clusters.mkv"; int metadataCount = 0; final StreamingMkvReader mkvStreamReader = StreamingMkvReader .createDefault(new InputStreamParserByteSource(TestResourceUtil.getTestInputStream(testFile))); while (mkvStreamReader.mightHaveNext()) { Optional<MkvElement> mkvElement = mkvStreamReader.nextIfAvailable(); if (mkvElement.isPresent()) { mkvElement.get().accept(fragmentMetadataVisitor); Optional<FragmentMetadata> fragmentMetadata = fragmentMetadataVisitor.getCurrentFragmentMetadata(); if(fragmentMetadata.isPresent()) { metadataCount ++; } } } Assert.assertEquals(0, metadataCount); } private static class TestCompositeVisitor extends CompositeMkvElementVisitor { public TestCompositeVisitor(FragmentMetadataVisitor fragmentMetadataVisitor, OutputSegmentMerger merger) { super(fragmentMetadataVisitor, merger); } } }
4,919
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/test/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/test/java/com/amazonaws/kinesisvideo/parser/utilities/H264FrameDecoderTest.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.utilities; import com.amazonaws.kinesisvideo.parser.TestResourceUtil; import com.amazonaws.kinesisvideo.parser.ebml.InputStreamParserByteSource; import com.amazonaws.kinesisvideo.parser.ebml.MkvTypeInfos; import com.amazonaws.kinesisvideo.parser.mkv.MkvElementVisitException; import com.amazonaws.kinesisvideo.parser.mkv.StreamingMkvReader; import com.amazonaws.kinesisvideo.parser.mkv.visitors.CompositeMkvElementVisitor; import com.amazonaws.kinesisvideo.parser.mkv.visitors.CountVisitor; import org.junit.Assert; import org.junit.Test; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.Optional; public class H264FrameDecoderTest { @Test public void frameDecodeCountTest() throws IOException, MkvElementVisitException { final InputStream in = TestResourceUtil.getTestInputStream("kinesis_video_renderer_example_output.mkv"); final byte[] codecPrivateData = new byte[]{ 0x01, 0x64, 0x00, 0x28, (byte) 0xff, (byte) 0xe1, 0x00, 0x0e, 0x27, 0x64, 0x00, 0x28, (byte) 0xac, 0x2b, 0x40, 0x50, 0x1e, (byte) 0xd0, 0x0f, 0x12, 0x26, (byte) 0xa0, 0x01, 0x00, 0x04, 0x28, (byte) 0xee, 0x1f, 0x2c }; final H264FrameDecoder frameDecoder = new H264FrameDecoder(); final StreamingMkvReader mkvStreamReader = StreamingMkvReader.createDefault(new InputStreamParserByteSource(in)); final CountVisitor countVisitor = CountVisitor.create(MkvTypeInfos.CLUSTER, MkvTypeInfos.SEGMENT, MkvTypeInfos.SIMPLEBLOCK, MkvTypeInfos.TRACKS); mkvStreamReader.apply(new CompositeMkvElementVisitor(countVisitor, FrameVisitor.create(frameDecoder))); Assert.assertEquals(8, countVisitor.getCount(MkvTypeInfos.TRACKS)); Assert.assertEquals(8, countVisitor.getCount(MkvTypeInfos.CLUSTER)); Assert.assertEquals(444, countVisitor.getCount(MkvTypeInfos.SIMPLEBLOCK)); Assert.assertEquals(444, frameDecoder.getFrameCount()); final ByteBuffer codecPrivateDataFromFrame = frameDecoder.getCodecPrivateData(); Assert.assertEquals(ByteBuffer.wrap(codecPrivateData), codecPrivateDataFromFrame); } @Test public void frameDecodeForDifferentResolution() throws Exception { final InputStream in = TestResourceUtil.getTestInputStream("vogels_330.mkv"); final H264FrameDecoder frameDecoder = new H264FrameDecoder(); final StreamingMkvReader mkvStreamReader = StreamingMkvReader.createDefault(new InputStreamParserByteSource(in)); final CountVisitor countVisitor = CountVisitor.create(MkvTypeInfos.CLUSTER, MkvTypeInfos.SEGMENT, MkvTypeInfos.SIMPLEBLOCK, MkvTypeInfos.TRACKS); final FrameVisitorTest.TestFrameProcessor frameProcessor = new FrameVisitorTest.TestFrameProcessor(); mkvStreamReader.apply(new CompositeMkvElementVisitor(countVisitor, FrameVisitor.create(frameDecoder, Optional.empty(), Optional.of(1L)), FrameVisitor.create(frameProcessor, Optional.empty(), Optional.of(2L)))); Assert.assertEquals(1, countVisitor.getCount(MkvTypeInfos.TRACKS)); Assert.assertEquals(9, countVisitor.getCount(MkvTypeInfos.CLUSTER)); Assert.assertEquals(2334, countVisitor.getCount(MkvTypeInfos.SIMPLEBLOCK)); // Total frames Assert.assertEquals(909, frameDecoder.getFrameCount()); // Video frames Assert.assertEquals(1425, frameProcessor.getFramesCount()); // Audio frames } }
4,920
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/test/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/test/java/com/amazonaws/kinesisvideo/parser/utilities/H264FrameRendererTest.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.utilities; import com.amazonaws.kinesisvideo.parser.TestResourceUtil; import com.amazonaws.kinesisvideo.parser.ebml.InputStreamParserByteSource; import com.amazonaws.kinesisvideo.parser.ebml.MkvTypeInfos; import com.amazonaws.kinesisvideo.parser.examples.KinesisVideoFrameViewer; import com.amazonaws.kinesisvideo.parser.mkv.MkvElementVisitException; import com.amazonaws.kinesisvideo.parser.mkv.StreamingMkvReader; import com.amazonaws.kinesisvideo.parser.mkv.visitors.CompositeMkvElementVisitor; import com.amazonaws.kinesisvideo.parser.mkv.visitors.CountVisitor; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.modules.junit4.PowerMockRunner; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.InputStream; import static org.mockito.Matchers.any; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.powermock.api.mockito.PowerMockito.mock; @RunWith(PowerMockRunner.class) public class H264FrameRendererTest { @Test public void frameRenderCountTest() throws IOException, MkvElementVisitException { final InputStream in = TestResourceUtil.getTestInputStream("kinesis_video_renderer_example_output.mkv"); final KinesisVideoFrameViewer kinesisVideoFrameViewer = mock(KinesisVideoFrameViewer.class); doNothing().when(kinesisVideoFrameViewer).update(any(BufferedImage.class)); H264FrameRenderer frameRenderer = H264FrameRenderer.create(kinesisVideoFrameViewer); StreamingMkvReader mkvStreamReader = StreamingMkvReader.createDefault(new InputStreamParserByteSource(in)); CountVisitor countVisitor = CountVisitor.create(MkvTypeInfos.CLUSTER, MkvTypeInfos.SEGMENT, MkvTypeInfos.SIMPLEBLOCK); mkvStreamReader.apply(new CompositeMkvElementVisitor(countVisitor, FrameVisitor.create(frameRenderer))); Assert.assertEquals(444, frameRenderer.getFrameCount()); verify(kinesisVideoFrameViewer, times(444)).update(any(BufferedImage.class)); } }
4,921
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/test/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/test/java/com/amazonaws/kinesisvideo/parser/utilities/FrameVisitorTest.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.utilities; import com.amazonaws.kinesisvideo.parser.TestResourceUtil; import com.amazonaws.kinesisvideo.parser.ebml.InputStreamParserByteSource; import com.amazonaws.kinesisvideo.parser.mkv.Frame; import com.amazonaws.kinesisvideo.parser.mkv.StreamingMkvReader; import lombok.Getter; import lombok.NonNull; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.io.InputStream; import java.math.BigInteger; import java.util.Optional; public class FrameVisitorTest { private static final int VIDEO_FRAMES_COUNT = 909; private static final int AUDIO_FRAMES_COUNT = 1425; private static final int SIMPLE_BLOCKS_COUNT_MKV = VIDEO_FRAMES_COUNT + AUDIO_FRAMES_COUNT; private static final long TIMESCALE = 1000000; private static final long LAST_FRAGMENT_TIMECODE = 28821; @Getter public static final class TestFrameProcessor implements FrameVisitor.FrameProcessor { private long framesCount = 0L; private long timescale = 0L; private long fragmentTimecode = 0L; @Override public void process(@NonNull final Frame frame, @NonNull final MkvTrackMetadata trackMetadata, final @NonNull Optional<FragmentMetadata> fragmentMetadata, final @NonNull Optional<FragmentMetadataVisitor.MkvTagProcessor> tagProcessor, final @NonNull Optional<BigInteger> timescale, final @NonNull Optional<BigInteger> fragmentTimecode) { this.timescale = timescale.get().longValue(); this.fragmentTimecode = fragmentTimecode.get().longValue(); framesCount++; } } private FrameVisitor frameVisitor; private TestFrameProcessor frameProcessor; private StreamingMkvReader streamingMkvReader; @Before public void setUp() throws Exception { frameProcessor = new TestFrameProcessor(); frameVisitor = FrameVisitor.create(frameProcessor); } @Test public void testWithMkvVideo() throws Exception { streamingMkvReader = StreamingMkvReader.createDefault(getClustersByteSource("vogels_480.mkv")); streamingMkvReader.apply(frameVisitor); Assert.assertEquals(SIMPLE_BLOCKS_COUNT_MKV, frameProcessor.getFramesCount()); Assert.assertEquals(TIMESCALE, frameProcessor.getTimescale()); Assert.assertEquals(LAST_FRAGMENT_TIMECODE, frameProcessor.getFragmentTimecode()); } @Test public void testForVideoFrames() throws Exception { frameVisitor = FrameVisitor.create(frameProcessor, Optional.empty(), Optional.of(1L)); streamingMkvReader = StreamingMkvReader.createDefault(getClustersByteSource("vogels_480.mkv")); streamingMkvReader.apply(frameVisitor); Assert.assertEquals(VIDEO_FRAMES_COUNT, frameProcessor.getFramesCount()); Assert.assertEquals(TIMESCALE, frameProcessor.getTimescale()); Assert.assertEquals(LAST_FRAGMENT_TIMECODE, frameProcessor.getFragmentTimecode()); } @Test public void testForAudioFrames() throws Exception { frameVisitor = FrameVisitor.create(frameProcessor, Optional.empty(), Optional.of(2L)); streamingMkvReader = StreamingMkvReader.createDefault(getClustersByteSource("vogels_480.mkv")); streamingMkvReader.apply(frameVisitor); Assert.assertEquals(AUDIO_FRAMES_COUNT, frameProcessor.getFramesCount()); Assert.assertEquals(TIMESCALE, frameProcessor.getTimescale()); Assert.assertEquals(LAST_FRAGMENT_TIMECODE, frameProcessor.getFragmentTimecode()); } private InputStreamParserByteSource getClustersByteSource(final String name) throws IOException { return getInputStreamParserByteSource(name); } private InputStreamParserByteSource getInputStreamParserByteSource(final String fileName) throws IOException { final InputStream in = TestResourceUtil.getTestInputStream(fileName); return new InputStreamParserByteSource(in); } }
4,922
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/test/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/test/java/com/amazonaws/kinesisvideo/parser/utilities/SimpleFrameVisitorTest.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.utilities; import com.amazonaws.kinesisvideo.parser.TestResourceUtil; import com.amazonaws.kinesisvideo.parser.ebml.EBMLElementMetaData; import com.amazonaws.kinesisvideo.parser.ebml.InputStreamParserByteSource; import com.amazonaws.kinesisvideo.parser.ebml.MkvTypeInfos; import com.amazonaws.kinesisvideo.parser.mkv.Frame; import com.amazonaws.kinesisvideo.parser.mkv.MkvDataElement; import com.amazonaws.kinesisvideo.parser.mkv.MkvElementVisitException; import com.amazonaws.kinesisvideo.parser.mkv.MkvElementVisitor; import com.amazonaws.kinesisvideo.parser.mkv.StreamingMkvReader; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.reflect.Whitebox; import java.io.IOException; import java.io.InputStream; @RunWith(PowerMockRunner.class) @PrepareForTest({SimpleFrameVisitor.class}) public class SimpleFrameVisitorTest { private int frameProcessCount; private int nullFrameCount; private static int SIMPLE_BLOCKS_COUNT_WEBM = 2308; private static int SIMPLE_BLOCKS_COUNT_MKV = 444; private final class TestFrameProcessor implements SimpleFrameVisitor.FrameProcessor { @Override public void process(final Frame frame, long clusterTimeCode, long timeCodeScale) { frameProcessCount++; if(frame == null) { nullFrameCount++; } } } @Mock private MkvDataElement mockDataElement; @Mock private EBMLElementMetaData mockElementMetaData; private SimpleFrameVisitor frameVisitor; private StreamingMkvReader streamingMkvReader; @Before public void setUp() throws Exception { frameVisitor = SimpleFrameVisitor .create(new TestFrameProcessor()); } @Test public void testWithWebmVideo() throws Exception { streamingMkvReader = StreamingMkvReader .createDefault(getClustersByteSource("big-buck-bunny_trailer.webm")); streamingMkvReader.apply(frameVisitor); Assert.assertEquals(SIMPLE_BLOCKS_COUNT_WEBM, frameProcessCount); Assert.assertEquals(nullFrameCount, 0); MkvElementVisitor internal = Whitebox.getInternalState(frameVisitor, "frameVisitorInternal"); long timeCode = Whitebox.getInternalState(internal, "clusterTimeCode"); long timeCodeScale = Whitebox.getInternalState(internal, "timeCodeScale"); Assert.assertNotEquals(-1, timeCode); Assert.assertNotEquals(-1, timeCodeScale); } @Test public void testWithMkvVideo() throws Exception { streamingMkvReader = StreamingMkvReader.createDefault(getClustersByteSource("clusters.mkv")); streamingMkvReader.apply(frameVisitor); Assert.assertEquals(SIMPLE_BLOCKS_COUNT_MKV, frameProcessCount); Assert.assertEquals(nullFrameCount, 0); MkvElementVisitor internal = Whitebox.getInternalState(frameVisitor, "frameVisitorInternal"); long timeCode = Whitebox.getInternalState(internal, "clusterTimeCode"); long timeCodeScale = Whitebox.getInternalState(internal, "timeCodeScale"); Assert.assertNotEquals(-1, timeCode); Assert.assertNotEquals(-1, timeCodeScale); } @Test(expected = MkvElementVisitException.class) public void testWhenNoTimeCode() throws Exception { MkvElementVisitor internal = Whitebox.getInternalState(frameVisitor, "frameVisitorInternal"); Whitebox.setInternalState(internal, "timeCodeScale", 1); PowerMockito.when(mockDataElement.getElementMetaData()).thenReturn(mockElementMetaData); PowerMockito.when(mockElementMetaData.getTypeInfo()).thenReturn(MkvTypeInfos.SIMPLEBLOCK); internal.visit(mockDataElement); } @Test(expected = MkvElementVisitException.class) public void testWhenNoTimeCodeScale() throws Exception { MkvElementVisitor internal = Whitebox.getInternalState(frameVisitor, "frameVisitorInternal"); Whitebox.setInternalState(internal, "clusterTimeCode", 1); PowerMockito.when(mockDataElement.getElementMetaData()).thenReturn(mockElementMetaData); PowerMockito.when(mockElementMetaData.getTypeInfo()).thenReturn(MkvTypeInfos.SIMPLEBLOCK); internal.visit(mockDataElement); } private InputStreamParserByteSource getClustersByteSource(String name) throws IOException { return getInputStreamParserByteSource(name); } private InputStreamParserByteSource getInputStreamParserByteSource(String fileName) throws IOException { final InputStream in = TestResourceUtil.getTestInputStream(fileName); return new InputStreamParserByteSource(in); } }
4,923
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/test/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/test/java/com/amazonaws/kinesisvideo/parser/utilities/FrameRendererTest.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.utilities; import com.amazonaws.kinesisvideo.parser.TestResourceUtil; import com.amazonaws.kinesisvideo.parser.ebml.EBMLTypeInfo; import com.amazonaws.kinesisvideo.parser.ebml.InputStreamParserByteSource; import com.amazonaws.kinesisvideo.parser.ebml.MkvTypeInfos; import com.amazonaws.kinesisvideo.parser.examples.KinesisVideoFrameViewer; import com.amazonaws.kinesisvideo.parser.mkv.*; import com.amazonaws.kinesisvideo.parser.mkv.visitors.CompositeMkvElementVisitor; import com.amazonaws.kinesisvideo.parser.mkv.visitors.CountVisitor; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; public class FrameRendererTest { // long running test @Test public void frameCountTest() throws IOException, MkvElementVisitException { final InputStream in = TestResourceUtil.getTestInputStream("kinesis_video_renderer_example_output.mkv"); byte[] codecPrivateData = new byte[]{ 0x01, 0x64, 0x00, 0x28, (byte) 0xff, (byte) 0xe1, 0x00, 0x0e, 0x27, 0x64, 0x00, 0x28, (byte) 0xac, 0x2b, 0x40, 0x50, 0x1e, (byte) 0xd0, 0x0f, 0x12, 0x26, (byte) 0xa0, 0x01, 0x00, 0x04, 0x28, (byte) 0xee, 0x1f, 0x2c }; H264FrameRenderer frameRenderer = H264FrameRenderer.create(new KinesisVideoFrameViewer(0, 0)); StreamingMkvReader mkvStreamReader = StreamingMkvReader.createDefault(new InputStreamParserByteSource(in)); CountVisitor countVisitor = CountVisitor.create( MkvTypeInfos.CLUSTER, MkvTypeInfos.SEGMENT, MkvTypeInfos.SIMPLEBLOCK, MkvTypeInfos.TRACKS); mkvStreamReader.apply(new CompositeMkvElementVisitor(countVisitor, FrameVisitor.create(frameRenderer))); Assert.assertEquals(8, countVisitor.getCount(MkvTypeInfos.TRACKS)); Assert.assertEquals(8, countVisitor.getCount(MkvTypeInfos.CLUSTER)); Assert.assertEquals(444, countVisitor.getCount(MkvTypeInfos.SIMPLEBLOCK)); Assert.assertEquals(444, frameRenderer.getFrameCount()); ByteBuffer codecPrivateDataFromFrame = frameRenderer.getCodecPrivateData(); Assert.assertEquals(ByteBuffer.wrap(codecPrivateData), codecPrivateDataFromFrame); } /** * Test jcodec decoding a frame from an mkv that has a pixel width/height that isn't a multiple of 16 */ @Test public void frameCountTest2() throws IOException, MkvElementVisitException { final InputStream in = TestResourceUtil.getTestInputStream("output_get_media.mkv"); byte[] codecPrivateData = new byte[]{ 0x01, 0x4d, 0x40, 0x1e, 0x03, 0x01, 0x00, 0x27, 0x27, 0x4d, 0x40, 0x1e, (byte) 0xb9, 0x10, 0x14, 0x05, (byte) 0xff, 0x2e, 0x02, (byte) 0xd4, 0x04, 0x04, 0x07, (byte) 0xc0, 0x00, 0x00, 0x03, 0x00, 0x40, 0x00, 0x00, 0x0f, 0x38, (byte) 0xa0, 0x00, 0x3d, 0x09, 0x00, 0x07, (byte) 0xa1, 0x3b, (byte) 0xde, (byte) 0xe0, 0x3e, 0x11, 0x08, (byte) 0xd4, 0x01, 0x00, 0x04, 0x28, (byte) 0xfe, 0x3c, (byte) 0x80 }; H264FrameRenderer frameRenderer = H264FrameRenderer.create(new KinesisVideoFrameViewer(0, 0)); StreamingMkvReader mkvStreamReader = StreamingMkvReader.createDefault(new InputStreamParserByteSource(in)); CountVisitor countVisitor = CountVisitor.create( MkvTypeInfos.CLUSTER, MkvTypeInfos.SEGMENT, MkvTypeInfos.SIMPLEBLOCK, MkvTypeInfos.TRACKS); mkvStreamReader.apply(new CompositeMkvElementVisitor(countVisitor, FrameVisitor.create(frameRenderer))); Assert.assertEquals(5, countVisitor.getCount(MkvTypeInfos.TRACKS)); Assert.assertEquals(5, countVisitor.getCount(MkvTypeInfos.CLUSTER)); Assert.assertEquals(300, countVisitor.getCount(MkvTypeInfos.SIMPLEBLOCK)); Assert.assertEquals(300, frameRenderer.getFrameCount()); ByteBuffer codecPrivateDataFromFrame = frameRenderer.getCodecPrivateData(); Assert.assertEquals(ByteBuffer.wrap(codecPrivateData), codecPrivateDataFromFrame); } }
4,924
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/test/java/com/amazonaws/kinesisvideo/parser/utilities
Create_ds/amazon-kinesis-video-streams-parser-library/src/test/java/com/amazonaws/kinesisvideo/parser/utilities/consumer/MergedOutputPiperTest.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.utilities.consumer; import com.amazonaws.kinesisvideo.parser.TestResourceUtil; import com.amazonaws.kinesisvideo.parser.ebml.InputStreamParserByteSource; import com.amazonaws.kinesisvideo.parser.ebml.MkvTypeInfos; import com.amazonaws.kinesisvideo.parser.mkv.MkvElementVisitException; import com.amazonaws.kinesisvideo.parser.mkv.StreamingMkvReader; import com.amazonaws.kinesisvideo.parser.mkv.visitors.CountVisitor; import com.amazonaws.kinesisvideo.parser.utilities.FragmentMetadata; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.time.StopWatch; import org.junit.Assert; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.util.Optional; /** * Tests for MergedOutputPiper */ public class MergedOutputPiperTest { //Can be overridden by setting the environment variable PATH_TO_CAT private static final String DEFAULT_PATH_TO_CAT = "/bin/cat"; //Can be overridden by setting the environment variable PATH_TO_GSTREAMER private static final String DEFAULT_PATH_TO_GSTREAMER = "/usr/bin/gst-launch-1.0"; private boolean canRunBasicTest; private String pathToCat; private boolean canRunGStreamer; private String pathToGStreamer; private Optional<String> processedFragmentNumberString; @Before public void setup() { pathToCat = pathToExecutable("PATH_TO_CAT", DEFAULT_PATH_TO_CAT); canRunBasicTest = checkIfFileExists(pathToCat); pathToGStreamer = pathToExecutable("PATH_TO_GSTREAMER", DEFAULT_PATH_TO_GSTREAMER); canRunGStreamer = checkIfFileExists(pathToGStreamer); processedFragmentNumberString = Optional.empty(); } private String pathToExecutable(String environmentVariable, String defaultPath) { final String environmentVariableValue = System.getenv(environmentVariable); return StringUtils.isEmpty(environmentVariableValue) ? defaultPath : environmentVariableValue; } private boolean checkIfFileExists(String pathToFile) { return new File(pathToFile).exists(); } @Test public void testBasic() throws IOException, MkvElementVisitException { if (canRunBasicTest) { String fileName = "output_get_media.mkv"; runBasicTestForFile(fileName, "91343852333181432412489103236310005892133364608", 5); } } @Test public void testBasicNonIncreasingTimecode() throws IOException, MkvElementVisitException { if (canRunBasicTest) { String fileName = "output-get-media-non-increasing-timecode.mkv"; runBasicTestForFile(fileName, "91343852338381293673923423239754896920603583280", 1); } } @Ignore @Test public void testGStreamerVideoSink() throws IOException, MkvElementVisitException { if (canRunGStreamer) { Path tmpFilePathToStdout = Files.createTempFile("testGStreamer", "stdout"); Path tmpFilePathToStdErr = Files.createTempFile("testGStreamer", "stderr"); try { InputStream is = TestResourceUtil.getTestInputStream("output_get_media.mkv"); ProcessBuilder processBuilder = new ProcessBuilder().command(pathToGStreamer, "-v", "fdsrc", "!", "decodebin", "!", "videoconvert", "!", "autovideosink") .redirectOutput(tmpFilePathToStdout.toFile()) .redirectError(tmpFilePathToStdErr.toFile()); MergedOutputPiper piper = new MergedOutputPiper(processBuilder); piper.process(is, this::setProcessedFragmentNumberString); Assert.assertEquals("91343852333181432412489103236310005892133364608", processedFragmentNumberString.get()); Assert.assertEquals(5, piper.getMergedSegments()); } finally { Files.delete(tmpFilePathToStdout); Files.delete(tmpFilePathToStdErr); } } } @Test public void testGStreamerFileSink() throws IOException, MkvElementVisitException { if (canRunGStreamer) { Path tmpFilePathToStdout = Files.createTempFile("testGStreamerFileSink", "stdout"); Path tmpFilePathToStdErr = Files.createTempFile("testGStreamerFileSink", "stderr"); Path tmpFilePathToOutputFile = Files.createTempFile("testGStreamerFileSink", "output.mkv"); try { InputStream is = TestResourceUtil.getTestInputStream("output_get_media.mkv"); ProcessBuilder processBuilder = new ProcessBuilder().command(pathToGStreamer, "-v", "fdsrc", "!", "filesink", "location=" + tmpFilePathToOutputFile.toAbsolutePath().toString()) .redirectOutput(tmpFilePathToStdout.toFile()) .redirectError(tmpFilePathToStdErr.toFile()); MergedOutputPiper piper = new MergedOutputPiper(processBuilder); piper.process(is, this::setProcessedFragmentNumberString); CountVisitor countVisitor = CountVisitor.create(MkvTypeInfos.CLUSTER, MkvTypeInfos.SEGMENT, MkvTypeInfos.SIMPLEBLOCK); StreamingMkvReader.createDefault(new InputStreamParserByteSource(new FileInputStream( tmpFilePathToOutputFile.toFile()))).apply(countVisitor); Assert.assertEquals(5, countVisitor.getCount(MkvTypeInfos.CLUSTER)); Assert.assertEquals(1, countVisitor.getCount(MkvTypeInfos.SEGMENT)); Assert.assertEquals(300, countVisitor.getCount(MkvTypeInfos.SIMPLEBLOCK)); } finally { Files.delete(tmpFilePathToStdout); Files.delete(tmpFilePathToStdErr); Files.delete(tmpFilePathToOutputFile); } } } @Test public void testGStreamerFileSinkWithFactory() throws IOException, MkvElementVisitException { if (canRunGStreamer) { Path tmpFilePathToOutputFile = Files.createTempFile("testGStreamerFileSink", "output.mkv"); MergedOutputPiperFactory piperFactory = new MergedOutputPiperFactory(pathToGStreamer, "-v", "fdsrc", "!", "filesink", "location=" + tmpFilePathToOutputFile.toAbsolutePath().toString()); try { InputStream is = TestResourceUtil.getTestInputStream("output_get_media.mkv"); GetMediaResponseStreamConsumer piper = piperFactory.createConsumer(); Assert.assertTrue(piper.getClass().equals(MergedOutputPiper.class)); piper.process(is, this::setProcessedFragmentNumberString); CountVisitor countVisitor = CountVisitor.create(MkvTypeInfos.CLUSTER, MkvTypeInfos.SEGMENT, MkvTypeInfos.SIMPLEBLOCK); StreamingMkvReader.createDefault(new InputStreamParserByteSource(new FileInputStream( tmpFilePathToOutputFile.toFile()))).apply(countVisitor); Assert.assertEquals(5, countVisitor.getCount(MkvTypeInfos.CLUSTER)); Assert.assertEquals(1, countVisitor.getCount(MkvTypeInfos.SEGMENT)); Assert.assertEquals(300, countVisitor.getCount(MkvTypeInfos.SIMPLEBLOCK)); } finally { Files.delete(tmpFilePathToOutputFile); } } } private void runBasicTestForFile(String fileName, String expectedFragmentNumberToStartAfter, int expectedNumMergedSegments) throws IOException, MkvElementVisitException { StopWatch timer = new StopWatch(); timer.start(); InputStream is = TestResourceUtil.getTestInputStream(fileName); Path tmpFilePath = Files.createTempFile("basicTest:" + fileName + ":", "merged.mkv"); try { ProcessBuilder processBuilder = new ProcessBuilder().command(pathToCat).redirectOutput(tmpFilePath.toFile()); MergedOutputPiper piper = new MergedOutputPiper(processBuilder); piper.process(is, this::setProcessedFragmentNumberString); timer.stop(); Assert.assertEquals(expectedFragmentNumberToStartAfter, processedFragmentNumberString.get()); Assert.assertEquals(expectedNumMergedSegments, piper.getMergedSegments()); } finally { Files.delete(tmpFilePath); } } private Optional<String> setProcessedFragmentNumberString(FragmentMetadata f) { return processedFragmentNumberString = Optional.of(f.getFragmentNumberString()); } }
4,925
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/test/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/test/java/com/amazonaws/kinesisvideo/parser/examples/KinesisVideoExampleTest.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.examples; import com.amazonaws.auth.profile.ProfileCredentialsProvider; import com.amazonaws.kinesisvideo.parser.TestResourceUtil; import com.amazonaws.regions.Regions; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import java.io.IOException; /** * Test to execute Kinesis Video Example. * The test in this class are currently ignored for unit tests since they require access to Kinesis Video through * valid credentials. * These can be re-enabled as integration tests. * They can be executed on any machine with valid aws credentials for access to Kinesis Video. */ public class KinesisVideoExampleTest { @Ignore @Test public void testExample() throws InterruptedException, IOException { KinesisVideoExample example = KinesisVideoExample.builder().region(Regions.US_WEST_2) .streamName("myTestStream") .credentialsProvider(new ProfileCredentialsProvider()) .inputVideoStream(TestResourceUtil.getTestInputStream("vogels_480.mkv")) .build(); example.execute(); Assert.assertEquals(9, example.getFragmentsPersisted()); Assert.assertEquals(9, example.getFragmentsRead()); } @Ignore @Test public void testConsumerExample() throws InterruptedException, IOException { KinesisVideoExample example = KinesisVideoExample.builder().region(Regions.US_WEST_2) .streamName("myTestStream") .credentialsProvider(new ProfileCredentialsProvider()) // Use existing stream in KVS (with Producer sending) .noSampleInputRequired(true) .build(); example.execute(); } }
4,926
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/test/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/test/java/com/amazonaws/kinesisvideo/parser/examples/KinesisVideoGStreamerPiperExampleTest.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.examples; import com.amazonaws.auth.profile.ProfileCredentialsProvider; import com.amazonaws.kinesisvideo.parser.TestResourceUtil; import com.amazonaws.kinesisvideo.parser.ebml.InputStreamParserByteSource; import com.amazonaws.kinesisvideo.parser.ebml.MkvTypeInfos; import com.amazonaws.kinesisvideo.parser.mkv.MkvElementVisitException; import com.amazonaws.kinesisvideo.parser.mkv.StreamingMkvReader; import com.amazonaws.kinesisvideo.parser.mkv.visitors.CountVisitor; import com.amazonaws.regions.Regions; import lombok.Getter; import org.jcodec.common.Assert; import org.junit.Ignore; import org.junit.Test; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; /** * Test to execute Kinesis Video GStreamer Piper Example. * It passes in a pipeline that demuxes and remuxes the input mkv stream and writes to a file sink. * This can be used to demonstrate that the stream passed into the gstreamer pipeline is acceptable to it. */ public class KinesisVideoGStreamerPiperExampleTest { @Ignore @Test public void testExample() throws InterruptedException, IOException, MkvElementVisitException { final Path outputFilePath = Paths.get("output_from_gstreamer-"+System.currentTimeMillis()+".mkv"); String gStreamerPipelineArgument = "matroskademux ! matroskamux! filesink location=" + outputFilePath.toAbsolutePath().toString(); //Might need to update DEFAULT_PATH_TO_GSTREAMER variable in KinesisVideoGStreamerPiperExample class KinesisVideoGStreamerPiperExample example = KinesisVideoGStreamerPiperExample.builder().region(Regions.US_WEST_2) .streamName("myTestStream2") .credentialsProvider(new ProfileCredentialsProvider()) .inputVideoStream(TestResourceUtil.getTestInputStream("clusters.mkv")) .gStreamerPipelineArgument(gStreamerPipelineArgument) .build(); example.execute(); //Verify that the generated output file has the expected number of segments, clusters and simple blocks. CountVisitor countVisitor = CountVisitor.create(MkvTypeInfos.SEGMENT, MkvTypeInfos.CLUSTER, MkvTypeInfos.SIMPLEBLOCK); StreamingMkvReader.createDefault(new InputStreamParserByteSource(Files.newInputStream(outputFilePath))) .apply(countVisitor); Assert.assertEquals(1,countVisitor.getCount(MkvTypeInfos.SEGMENT)); Assert.assertEquals(8,countVisitor.getCount(MkvTypeInfos.CLUSTER)); Assert.assertEquals(444,countVisitor.getCount(MkvTypeInfos.SIMPLEBLOCK)); } }
4,927
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/test/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/test/java/com/amazonaws/kinesisvideo/parser/examples/KinesisVideoRendererExampleTest.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.examples; import com.amazonaws.auth.profile.ProfileCredentialsProvider; import com.amazonaws.kinesisvideo.parser.TestResourceUtil; import com.amazonaws.regions.Regions; import org.junit.Ignore; import org.junit.Test; import java.io.IOException; public class KinesisVideoRendererExampleTest { /* long running test */ @Ignore @Test public void testExample() throws InterruptedException, IOException { KinesisVideoRendererExample example = KinesisVideoRendererExample.builder().region(Regions.US_WEST_2) .streamName("render-example-stream") .credentialsProvider(new ProfileCredentialsProvider()) .inputVideoStream(TestResourceUtil.getTestInputStream("vogels_480.mkv")) .renderFragmentMetadata(false) .build(); example.execute(); } @Ignore @Test public void testDifferentResolution() throws InterruptedException, IOException { KinesisVideoRendererExample example = KinesisVideoRendererExample.builder().region(Regions.US_WEST_2) .streamName("render-example-stream") .credentialsProvider(new ProfileCredentialsProvider()) .inputVideoStream(TestResourceUtil.getTestInputStream("vogels_330.mkv")) .renderFragmentMetadata(false) .build(); example.execute(); } @Ignore @Test public void testConsumerExample() throws InterruptedException, IOException { KinesisVideoRendererExample example = KinesisVideoRendererExample.builder().region(Regions.US_WEST_2) .streamName("render-example-stream") .credentialsProvider(new ProfileCredentialsProvider()) // Display the tags in the frame viewer window .renderFragmentMetadata(true) // Use existing stream in KVS (with Producer sending) .noSampleInputRequired(true) .build(); example.execute(); } }
4,928
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/test/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/test/java/com/amazonaws/kinesisvideo/parser/examples/KinesisVideoRekognitionIntegrationExampleTest.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.examples; import java.io.IOException; import com.amazonaws.auth.profile.ProfileCredentialsProvider; import com.amazonaws.kinesisvideo.parser.TestResourceUtil; import com.amazonaws.kinesisvideo.parser.rekognition.pojo.RekognitionInput; import com.amazonaws.regions.Regions; import org.junit.Ignore; import org.junit.Test; /** * This examples demonstrates how to integrate KVS with Rekognition and draw bounding boxes for each frame. */ public class KinesisVideoRekognitionIntegrationExampleTest { /* long running test */ @Ignore @Test public void testExample() throws InterruptedException, IOException { // NOTE: Rekogntion Input needs ARN for both Kinesis Video Streams and Kinesis Data Streams. // For more info please refer https://docs.aws.amazon.com/rekognition/latest/dg/streaming-video.html RekognitionInput rekognitionInput = RekognitionInput.builder() .kinesisVideoStreamArn("<kvs-stream-arn>") .kinesisDataStreamArn("<kds-stream-arn>") .streamingProcessorName("<stream-processor-name>") // Refer how to add face collection : // https://docs.aws.amazon.com/rekognition/latest/dg/add-faces-to-collection-procedure.html .faceCollectionId("<face-collection-id>") .iamRoleArn("<iam-role>") .matchThreshold(0.08f) .build(); KinesisVideoRekognitionIntegrationExample example = KinesisVideoRekognitionIntegrationExample.builder() .region(Regions.US_WEST_2) .kvsStreamName("<kvs-stream-name>") .kdsStreamName("<kds-stream-name>") .rekognitionInput(rekognitionInput) .credentialsProvider(new ProfileCredentialsProvider()) // NOTE: If the input stream is not passed then the example assumes that the video fragments are // ingested using other mechanisms like GStreamer sample app or AmazonKinesisVideoDemoApp .inputStream(TestResourceUtil.getTestInputStream("bezos_vogels.mkv")) .build(); // The test file resolution is 1280p. example.setWidth(1280); example.setHeight(720); // This test might render frames with high latency until the rekognition results are returned. Change below // timeout to smaller value if the frames need to be rendered with low latency when rekognition results // are not present. example.setRekognitionMaxTimeoutInMillis(100); example.execute(30L); } }
4,929
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/test/java/com/amazonaws/kinesisvideo/parser/rekognition
Create_ds/amazon-kinesis-video-streams-parser-library/src/test/java/com/amazonaws/kinesisvideo/parser/rekognition/processor/RekognitionStreamProcessorTest.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.rekognition.processor; import com.amazonaws.auth.EnvironmentVariableCredentialsProvider; import com.amazonaws.auth.profile.ProfileCredentialsProvider; import com.amazonaws.kinesisvideo.parser.rekognition.pojo.RekognitionInput; import com.amazonaws.regions.Regions; import com.amazonaws.services.rekognition.model.CreateStreamProcessorResult; import com.amazonaws.services.rekognition.model.DescribeStreamProcessorResult; import com.amazonaws.services.rekognition.model.ListStreamProcessorsResult; import com.amazonaws.services.rekognition.model.StartStreamProcessorResult; import lombok.extern.slf4j.Slf4j; import org.junit.Assert; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; @Slf4j @Ignore // Used for controlling rekognition stream processor used in Rekognition integration examples. public class RekognitionStreamProcessorTest { RekognitionStreamProcessor streamProcessor; @Before public void testSetup() { final RekognitionInput rekognitionInput = RekognitionInput.builder() .kinesisVideoStreamArn("<kvs-stream-arn>") .kinesisDataStreamArn("<kds-stream-arn>") .streamingProcessorName("<stream-processor-name>") // Refer how to add face collection : // https://docs.aws.amazon.com/rekognition/latest/dg/add-faces-to-collection-procedure.html .faceCollectionId("<face-collection-id>") .iamRoleArn("<iam-role>") .matchThreshold(0.08f) .build(); streamProcessor = RekognitionStreamProcessor.create(Regions.US_WEST_2, new ProfileCredentialsProvider(), rekognitionInput); } @Test public void createStreamProcessor() { final CreateStreamProcessorResult result = streamProcessor.createStreamProcessor(); Assert.assertNotNull(result.getStreamProcessorArn()); } @Test public void startStreamProcessor() { final StartStreamProcessorResult result = streamProcessor.startStreamProcessor(); log.info("Result : {}", result); } @Test public void describeStreamProcessor() { final DescribeStreamProcessorResult result = streamProcessor.describeStreamProcessor(); log.info("Status for stream processor : {}", result.getStatus()); } @Test public void listStreamProcessor() { final ListStreamProcessorsResult result = streamProcessor.listStreamProcessor(); log.info("List StreamProcessors : {}", result); } }
4,930
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/test/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/test/java/com/amazonaws/kinesisvideo/parser/ebml/EBMLParserTest.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.ebml; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.OptionalLong; import static com.amazonaws.kinesisvideo.parser.ebml.EBMLUtils.UNKNOWN_LENGTH_VALUE; /** * Tests for the {@link EBMLParser}. */ public class EBMLParserTest { private EBMLParser parser; private TestEBMLParserCallback parserCallback; private boolean testRawBytesMatch = true; byte [] EBML_id_bytes = new byte [] { (byte )0x1A, (byte ) 0x45, (byte ) 0xDF, (byte ) 0xA3 }; byte [] EBML_ZERO_LENGTH_RAWBYTES = new byte [] { (byte )0x1A, (byte ) 0x45, (byte ) 0xDF, (byte ) 0xA3, (byte ) 0x80 }; byte [] EBMLVersion_id_bytes = new byte [] { (byte )0x42, (byte )0x86 }; byte [] EBMLReadVersion_id_bytes = new byte [] { (byte )0x42, (byte )0xF7 }; byte [] UNKNOWN_LENGTH = new byte [] { (byte) 0x01, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF}; byte [] SEGMENT_id_bytes = new byte[] { (byte) 0x18, (byte) 0x53, (byte) 0x80, (byte) 0x67}; byte [] SEEKHEAD_id_bytes = new byte[] { (byte) 0x11, (byte) 0x4D, (byte) 0x9B, (byte) 0x74}; byte [] SEEK_id_bytes = new byte[] { (byte) 0x4D, (byte) 0xBB}; byte [] SEEKID_id_bytes = new byte[] { (byte) 0x53, (byte) 0xAB}; byte [] SEEKPOSITION_id_bytes = new byte[] { (byte) 0x53, (byte) 0xAC}; byte [] COLOUR_id_bytes = new byte [] { (byte)0x55, (byte) 0xB0 }; byte [] MATRIX_COEFFICIENTS_id_bytes = new byte[] { (byte) 0x55, (byte) 0xB1 }; @Before public void setup() throws IllegalAccessException { parserCallback = new TestEBMLParserCallback(); parser = new EBMLParser(new TestEBMLTypeInfoProvider(), parserCallback); } @Test public void testEBMLElementInOneStep() throws IOException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); outputStream.write(EBML_ZERO_LENGTH_RAWBYTES); setExpectedCallbacksForEBMLElement(); callParser(outputStream, outputStream.size()); } private void setExpectedCallbacksForEBMLElement() { parserCallback.setCheckExpectedCallbacks(true); parserCallback.expectCallback(TestEBMLParserCallback.CallbackDescription.builder() .callbackType(TestEBMLParserCallback.CallbackDescription.CallbackType.START) .elementCount(0) .typeInfo(TestEBMLTypeInfoProvider.EBML) .numBytes(OptionalLong.of(0)) .bytes(EBML_ZERO_LENGTH_RAWBYTES) .build()) .expectCallback(createExpectedCallbackForEndEBML(0)); } @Test public void testEBMLElementInThreeSteps() throws IOException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); outputStream.write(EBML_ZERO_LENGTH_RAWBYTES); setExpectedCallbacksForEBMLElement(); callParser(outputStream, 2); } @Test public void testMasterElementOneChildElementSizeBasedTermination() throws IOException { ByteArrayOutputStream outputStream = setupTestForMasterElementWithOneChildAndElementSizedBasedTermination(); callParser(outputStream, outputStream.size()); } @Test public void testMasterElementOneChildElementSizeBasedTerminationMultipleChunks() throws IOException { ByteArrayOutputStream outputStream = setupTestForMasterElementWithOneChildAndElementSizedBasedTermination(); callParser(outputStream, 1); } @Test public void testMasterElementOneChildElementUnknownLength() throws IOException { ByteArrayOutputStream outputStream = setupTestForMasterElementWithOneChildAndUnknownlength(); callParser(outputStream, outputStream.size()); } @Test public void testMasterElementOneChildElementUnknownLengthMultipleChunks() throws IOException { ByteArrayOutputStream outputStream = setupTestForMasterElementWithOneChildAndUnknownlength(); callParser(outputStream, 3); } @Test public void testMasterElementWithUnknownLengthAndEndOfStream() throws IOException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte [] EBML_element_rawbytes = writeElement(EBML_id_bytes, UNKNOWN_LENGTH, outputStream); byte [] EBMLVersion_element_rawbytes = writeElement(EBMLVersion_id_bytes, wrapByte(0x83), outputStream); byte [] EBMLVersion_data_bytes = new byte[] {0x1, 0x4, 0xD}; outputStream.write(EBMLVersion_data_bytes); parserCallback.setCheckExpectedCallbacks(true); parserCallback.expectCallback(createExpectedCallbackForStartOfEBMLUnknownLength(EBML_element_rawbytes)); addExpectedCallbacksForEBMLVersion(EBMLVersion_element_rawbytes, EBMLVersion_data_bytes, 1) .expectCallback(createExpectedCallbackForEndEBML(0)); callParser(outputStream, outputStream.size()); parser.closeParser(); } @Test public void testInputStreamReturningEoF() throws IOException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte [] EBML_element_rawbytes = writeElement(EBML_id_bytes, UNKNOWN_LENGTH, outputStream); byte [] EBMLVersion_element_rawbytes = writeElement(EBMLVersion_id_bytes, wrapByte(0x83), outputStream); byte [] EBMLVersion_data_bytes = new byte[] {0x1, 0x4, 0xD}; outputStream.write(EBMLVersion_data_bytes, 0, 2); outputStream.close(); parserCallback.setCheckExpectedCallbacks(true); parserCallback.expectCallback(createExpectedCallbackForStartOfEBMLUnknownLength(EBML_element_rawbytes)) .expectCallback(TestEBMLParserCallback.CallbackDescription.builder() .callbackType(TestEBMLParserCallback.CallbackDescription.CallbackType.START) .typeInfo(TestEBMLTypeInfoProvider.EBMLVersion) .elementCount(1) .numBytes(OptionalLong.of(EBMLVersion_data_bytes.length)) .bytes(EBMLVersion_element_rawbytes) .build()) .expectCallback(TestEBMLParserCallback.CallbackDescription.builder() .callbackType(TestEBMLParserCallback.CallbackDescription.CallbackType.CONTENT) .typeInfo(TestEBMLTypeInfoProvider.EBMLVersion) .elementCount(1) .numBytes(OptionalLong.of(EBMLVersion_data_bytes.length)) .bytes(Arrays.copyOf(EBMLVersion_data_bytes, 2)) .build()) .expectCallback(TestEBMLParserCallback.CallbackDescription.builder() .callbackType(TestEBMLParserCallback.CallbackDescription.CallbackType.CONTENT) .typeInfo(TestEBMLTypeInfoProvider.EBMLVersion) .elementCount(1) .numBytes(OptionalLong.of(1)) .bytes(new byte[] {}) .build()) .expectCallback(TestEBMLParserCallback.CallbackDescription.builder() .callbackType(TestEBMLParserCallback.CallbackDescription.CallbackType.END) .typeInfo(TestEBMLTypeInfoProvider.EBMLVersion) .elementCount(1) .build()) .expectCallback(createExpectedCallbackForEndEBML(0)); callParser(outputStream, outputStream.size() + 1, true); Assert.assertTrue(parser.isEndOfStream()); Assert.assertTrue(parser.isClosed()); } /** * This test writes and parses * EBML with unknown length * EBMLVersion with 3 bytes * EBMLReadVersion with 2 bytes * SEGMENT with unknownlength * SEEKHEAD with unknownlength * CRC with 4 bytes * SEEK with data of 11 bytes * SEEKID with 2 bytes (id(2+1)+ 2 = 5 bytes) * SEEKPOSITION with 3 bytes (id(2+1) + 3 = 6 bytes) * EBML with 0 length * @throws IOException */ @Test public void testWithMultipleMasterElementsAndChildElements() throws IOException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); //EBML byte[] EBML_element_rawbytes = writeElement(EBML_id_bytes, UNKNOWN_LENGTH, outputStream); byte[] EBMLVersion_element_rawbytes = writeElement(EBMLVersion_id_bytes, wrapByte(0x83), outputStream); byte[] EBMLVersion_data_bytes = new byte[] { 0x1, 0x4, 0xD }; outputStream.write(EBMLVersion_data_bytes); byte[] EBMLReadVersion_element_rawbytes = writeElement(EBMLReadVersion_id_bytes, wrapByte(0x82), outputStream); byte[] EBMLReadVersion_data_bytes = new byte[] { 0x72, 0x1C }; outputStream.write(EBMLReadVersion_data_bytes); //SEGMENT byte[] SEGMENT_element_rawbytes = writeElement(SEGMENT_id_bytes, UNKNOWN_LENGTH, outputStream); byte[] SEEKHEAD_element_rawbytes = writeElement(SEEKHEAD_id_bytes, UNKNOWN_LENGTH, outputStream); byte[] CRC_element_rawbytes = writeElement(wrapByte(0xBF), wrapByte(0x84), outputStream); byte[] CRC_data_bytes = new byte[] { 0x12, 0x3C, 0x43, 0x4D }; outputStream.write(CRC_data_bytes); byte[] SEEK_element_rawbytes = writeElement(SEEK_id_bytes, wrapByte(0x8B), outputStream); byte[] SEEKID_element_rawbytes = writeElement(SEEKID_id_bytes, wrapByte(0x82), outputStream); byte[] SEEKID_data_bytes = new byte[] { 0x34, 0x35 }; outputStream.write(SEEKID_data_bytes); byte[] SEEKPOSITON_element_rawbytes = writeElement(SEEKPOSITION_id_bytes, wrapByte(0x83), outputStream); byte[] SEEKPOSITON_data_bytes = new byte[] { 0x36, 0x37, 0x38 }; outputStream.write(SEEKPOSITON_data_bytes); outputStream.write(EBML_ZERO_LENGTH_RAWBYTES); int chunkSize = 1; parserCallback.setCheckExpectedCallbacks(true); parserCallback.expectCallback(createExpectedCallbackForStartOfEBMLUnknownLength(EBML_element_rawbytes)); addExpectedCallbacksForBaseElement(TestEBMLTypeInfoProvider.EBMLVersion, EBMLVersion_element_rawbytes, EBMLVersion_data_bytes, 1, chunkSize); addExpectedCallbacksForBaseElement(TestEBMLTypeInfoProvider.EBMLReadVersion, EBMLReadVersion_element_rawbytes, EBMLReadVersion_data_bytes, 2, chunkSize).expectCallback(createExpectedCallbackForEndEBML(0)) .expectCallback(TestEBMLParserCallback.CallbackDescription.builder() .callbackType(TestEBMLParserCallback.CallbackDescription.CallbackType.START) .typeInfo(TestEBMLTypeInfoProvider.SEGMENT) .elementCount(3) .numBytes(OptionalLong.of(UNKNOWN_LENGTH_VALUE)) .bytes(SEGMENT_element_rawbytes) .build()) .expectCallback(TestEBMLParserCallback.CallbackDescription.builder() .callbackType(TestEBMLParserCallback.CallbackDescription.CallbackType.START) .typeInfo(TestEBMLTypeInfoProvider.SEEKHEAD) .elementCount(4) .numBytes(OptionalLong.of(UNKNOWN_LENGTH_VALUE)) .bytes(SEEKHEAD_element_rawbytes) .build()); addExpectedCallbacksForBaseElement(TestEBMLTypeInfoProvider.CRC, CRC_element_rawbytes, CRC_data_bytes, 5, chunkSize).expectCallback(TestEBMLParserCallback.CallbackDescription.builder() .callbackType(TestEBMLParserCallback.CallbackDescription.CallbackType.START) .typeInfo(TestEBMLTypeInfoProvider.SEEK) .elementCount(6) .numBytes(OptionalLong.of( SEEKID_element_rawbytes.length + SEEKID_data_bytes.length + SEEKPOSITON_element_rawbytes.length + SEEKPOSITON_data_bytes.length)) .bytes(SEEK_element_rawbytes) .build()); addExpectedCallbacksForBaseElement(TestEBMLTypeInfoProvider.SEEKID, SEEKID_element_rawbytes, SEEKID_data_bytes, 7, chunkSize); addExpectedCallbacksForBaseElement(TestEBMLTypeInfoProvider.SEEKPOSITION, SEEKPOSITON_element_rawbytes, SEEKPOSITON_data_bytes, 8, chunkSize).expectCallback(createExpectedCallbackForEndMasterElement(6, TestEBMLTypeInfoProvider.SEEK)) .expectCallback(createExpectedCallbackForEndMasterElement(4, TestEBMLTypeInfoProvider.SEEKHEAD)) .expectCallback(createExpectedCallbackForEndMasterElement(3, TestEBMLTypeInfoProvider.SEGMENT)) .expectCallback(TestEBMLParserCallback.CallbackDescription.builder() .callbackType(TestEBMLParserCallback.CallbackDescription.CallbackType.START) .elementCount(9) .typeInfo(TestEBMLTypeInfoProvider.EBML) .numBytes(OptionalLong.of(0)) .bytes(EBML_ZERO_LENGTH_RAWBYTES) .build()) .expectCallback(createExpectedCallbackForEndEBML(9)); callParser(outputStream, 1); } @Test public void unknownElementsTest() throws IOException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte [] EBML_element_rawbytes = writeElement(EBML_id_bytes, UNKNOWN_LENGTH, outputStream); byte [] EBMLVersion_element_rawbytes = writeElement(EBMLVersion_id_bytes, wrapByte(0x83), outputStream); byte [] EBMLVersion_data_bytes = new byte[] {0x1, 0x4, 0xD}; outputStream.write(EBMLVersion_data_bytes); //unknown elements byte [] COLOUR_element_rawbytes = writeElement(COLOUR_id_bytes, wrapByte(0x85),outputStream); byte [] MATRIX_COEFFICIENT_element_rawbytes = writeElement(MATRIX_COEFFICIENTS_id_bytes, wrapByte(0x82), outputStream); byte [] MATRIX_COEFFICIENT_data_bytes = new byte [] {0x1, 0x2}; outputStream.write(MATRIX_COEFFICIENT_data_bytes); outputStream.write(EBML_ZERO_LENGTH_RAWBYTES); parserCallback.setCheckExpectedCallbacks(true); parserCallback.expectCallback(createExpectedCallbackForStartOfEBMLUnknownLength(EBML_element_rawbytes)); addExpectedCallbacksForBaseElement(TestEBMLTypeInfoProvider.EBMLVersion, EBMLVersion_element_rawbytes, EBMLVersion_data_bytes, 1, 1).expectCallback(createExpectedCallbackForEndEBML(0)) .expectCallback(TestEBMLParserCallback.CallbackDescription.builder() .callbackType(TestEBMLParserCallback.CallbackDescription.CallbackType.START) .elementCount(3) .typeInfo(TestEBMLTypeInfoProvider.EBML) .numBytes(OptionalLong.of(0)) .bytes(EBML_ZERO_LENGTH_RAWBYTES) .build()) .expectCallback(createExpectedCallbackForEndEBML(3)); testRawBytesMatch = false; callParser(outputStream, 1); } private ByteArrayOutputStream setupTestForMasterElementWithOneChildAndUnknownlength() throws IOException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte [] EBML_element_rawbytes = writeElement(EBML_id_bytes, UNKNOWN_LENGTH, outputStream); byte [] EBMLVersion_element_rawbytes = writeElement(EBMLVersion_id_bytes, wrapByte(0x83), outputStream); byte [] EBMLVersion_data_bytes = new byte[] {0x1, 0x4, 0xD}; outputStream.write(EBMLVersion_data_bytes); outputStream.write(EBML_ZERO_LENGTH_RAWBYTES); parserCallback.setCheckExpectedCallbacks(true); parserCallback.expectCallback(createExpectedCallbackForStartOfEBMLUnknownLength(EBML_element_rawbytes)); addExpectedCallbacksForEBMLVersion(EBMLVersion_element_rawbytes, EBMLVersion_data_bytes, 1) .expectCallback(createExpectedCallbackForEndEBML(0)) .expectCallback(TestEBMLParserCallback.CallbackDescription.builder() .callbackType(TestEBMLParserCallback.CallbackDescription.CallbackType.START) .elementCount(2) .typeInfo(TestEBMLTypeInfoProvider.EBML) .numBytes(OptionalLong.of(0)) .bytes(EBML_ZERO_LENGTH_RAWBYTES) .build()) .expectCallback(createExpectedCallbackForEndEBML(2)); return outputStream; } private TestEBMLParserCallback.CallbackDescription createExpectedCallbackForEndEBML(long elementCount) { return createExpectedCallbackForEndMasterElement(elementCount, TestEBMLTypeInfoProvider.EBML); } private TestEBMLParserCallback.CallbackDescription createExpectedCallbackForEndMasterElement(long elementCount, EBMLTypeInfo typeInfo) { return TestEBMLParserCallback.CallbackDescription.builder() .callbackType(TestEBMLParserCallback.CallbackDescription.CallbackType.END) .typeInfo(typeInfo) .elementCount(elementCount) .build(); } private TestEBMLParserCallback addExpectedCallbacksForEBMLVersion(byte[] EBMLVersion_element_rawbytes, byte[] EBMLVersion_data_bytes, long elementCount) { return addExpectedCallbacksForBaseElement(TestEBMLTypeInfoProvider.EBMLVersion, EBMLVersion_element_rawbytes, EBMLVersion_data_bytes, elementCount, EBMLVersion_data_bytes.length); } private TestEBMLParserCallback addExpectedCallbacksForBaseElement(EBMLTypeInfo typeInfo, byte[] element_rawbytes, byte[] data_bytes, long elementCount, int chunkSize) { parserCallback.expectCallback(TestEBMLParserCallback.CallbackDescription.builder() .callbackType(TestEBMLParserCallback.CallbackDescription.CallbackType.START) .typeInfo(typeInfo) .elementCount(elementCount) .numBytes(OptionalLong.of(data_bytes.length)) .bytes(element_rawbytes) .build()); int count = 0; while (count < data_bytes.length) { int length = Math.min(chunkSize, data_bytes.length - count); parserCallback.expectCallback(TestEBMLParserCallback.CallbackDescription.builder() .callbackType(TestEBMLParserCallback.CallbackDescription.CallbackType.CONTENT) .typeInfo(typeInfo) .elementCount(elementCount) .numBytes(OptionalLong.of(length)) .bytes(Arrays.copyOfRange(data_bytes, count, count + length)) .build()); count += length; } return parserCallback .expectCallback(TestEBMLParserCallback.CallbackDescription.builder() .callbackType(TestEBMLParserCallback.CallbackDescription.CallbackType.END) .typeInfo(typeInfo) .elementCount(elementCount) .build()); } private TestEBMLParserCallback.CallbackDescription createExpectedCallbackForStartOfEBMLUnknownLength(byte[] EBML_element_rawbytes) { return TestEBMLParserCallback.CallbackDescription.builder() .callbackType(TestEBMLParserCallback.CallbackDescription.CallbackType.START) .typeInfo(TestEBMLTypeInfoProvider.EBML) .elementCount(0) .numBytes(OptionalLong.of(UNKNOWN_LENGTH_VALUE)) .bytes(EBML_element_rawbytes) .build(); } private ByteArrayOutputStream setupTestForMasterElementWithOneChildAndElementSizedBasedTermination() throws IOException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte [] EBML_element_rawbytes = writeElement(EBML_id_bytes, wrapByte(0x84), outputStream); byte [] EBMLVersion_element_rawbytes = writeElement(EBMLVersion_id_bytes, wrapByte(0x81), outputStream); byte [] EBMLVersion_data_bytes = new byte [] { (byte) 0x4}; outputStream.write(EBMLVersion_data_bytes); parserCallback.setCheckExpectedCallbacks(true); parserCallback.expectCallback(TestEBMLParserCallback.CallbackDescription.builder() .callbackType(TestEBMLParserCallback.CallbackDescription.CallbackType.START) .typeInfo(TestEBMLTypeInfoProvider.EBML) .elementCount(0) .numBytes(OptionalLong.of(4)) .bytes(EBML_element_rawbytes) .build()); addExpectedCallbacksForEBMLVersion(EBMLVersion_element_rawbytes, EBMLVersion_data_bytes, 1) .expectCallback(createExpectedCallbackForEndEBML(0)); return outputStream; } private static byte[] writeElement(byte[] id, byte[] size, ByteArrayOutputStream overAllOutputStream) throws IOException { ByteArrayOutputStream elementOutputStream = new ByteArrayOutputStream(); elementOutputStream.write(id); elementOutputStream.write(size); byte[] result = elementOutputStream.toByteArray(); overAllOutputStream.write(result); return result; } private static byte [] wrapByte(int data) { return new byte [] {(byte)data}; } private void callParser(ByteArrayOutputStream outputStream, int chunkSize) throws IOException { callParser(outputStream, chunkSize, false); } private void callParser(ByteArrayOutputStream outputStream, int chunkSize, boolean closeLast) throws IOException { byte [] data = outputStream.toByteArray(); int count = 0; while (count < data.length) { int length = Math.min(chunkSize, data.length - count); InputStream underlyingDataStream = new ByteArrayInputStream(data, count, length); InputStreamParserByteSource byteSource; if (closeLast && count + length >= data.length) { underlyingDataStream.close(); byteSource = new InputStreamParserByteSource(underlyingDataStream) { @Override public int available() { return super.available() + 1; } }; } else { byteSource = new InputStreamParserByteSource(underlyingDataStream); } parser.parse(byteSource); count += length; } if (!closeLast) { parser.closeParser(); } if(testRawBytesMatch) { Assert.assertArrayEquals(data, parserCallback.rawBytes()); } //TODO: enable later parserCallback.validateEmptyCallback(); } }
4,931
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/test/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/test/java/com/amazonaws/kinesisvideo/parser/ebml/TestEBMLTypeInfoProvider.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.ebml; import org.apache.commons.lang3.Validate; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.Map; import java.util.Optional; /** * A EBMLTypeInfoProvider for unit tests that provides only a very samll subset of the Mkv Elements. */ public class TestEBMLTypeInfoProvider implements EBMLTypeInfoProvider { public static final EBMLTypeInfo EBML = new EBMLTypeInfo.EBMLTypeInfoBuilder().id(0x1A45DFA3).name("EBML").level(0).type( EBMLTypeInfo.TYPE.MASTER).build(); public static final EBMLTypeInfo EBMLVersion = new EBMLTypeInfo.EBMLTypeInfoBuilder().id(0x4286).name("EBMLVersion").level(1).type( EBMLTypeInfo.TYPE.UINTEGER).build(); public static final EBMLTypeInfo EBMLReadVersion = new EBMLTypeInfo.EBMLTypeInfoBuilder().id(0x42F7).name("EBMLReadVersion").level(1).type( EBMLTypeInfo.TYPE.UINTEGER).build(); public static final EBMLTypeInfo CRC = new EBMLTypeInfo.EBMLTypeInfoBuilder().name("CRC-32").id(0xBF).level(-1).type( EBMLTypeInfo.TYPE.BINARY).build(); public static final EBMLTypeInfo SEGMENT = new EBMLTypeInfo.EBMLTypeInfoBuilder().name("Segment").level(0).id(0x18538067).type( EBMLTypeInfo.TYPE.MASTER).build(); public static final EBMLTypeInfo SEEKHEAD = new EBMLTypeInfo.EBMLTypeInfoBuilder().name("SeekHead").level(1).id(0x114D9B74).type( EBMLTypeInfo.TYPE.MASTER).build(); public static final EBMLTypeInfo SEEK = new EBMLTypeInfo.EBMLTypeInfoBuilder().name("Seek").level(2).id(0x4DBB).type( EBMLTypeInfo.TYPE.MASTER).build(); public static final EBMLTypeInfo SEEKID = new EBMLTypeInfo.EBMLTypeInfoBuilder().name("SeekID").level(3).id(0x53AB).type( EBMLTypeInfo.TYPE.BINARY).build(); public static final EBMLTypeInfo SEEKPOSITION = new EBMLTypeInfo.EBMLTypeInfoBuilder().name("SeekPosition").level(3).id(0x53AC).type( EBMLTypeInfo.TYPE.UINTEGER).build(); private Map<Integer,EBMLTypeInfo> typeInfoMap = new HashMap(); public TestEBMLTypeInfoProvider() throws IllegalAccessException { for (Field field : TestEBMLTypeInfoProvider.class.getDeclaredFields()) { if (Modifier.isStatic(field.getModifiers()) && field.getType().equals(EBMLTypeInfo.class)) { EBMLTypeInfo type = (EBMLTypeInfo )field.get(null); Validate.isTrue(!typeInfoMap.containsKey(type.getId())); typeInfoMap.put(type.getId(), type); } } } @Override public Optional<EBMLTypeInfo> getType(int id) { return Optional.ofNullable(typeInfoMap.get(id)); } }
4,932
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/test/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/test/java/com/amazonaws/kinesisvideo/parser/ebml/EBMLUtilsTest.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.ebml; import org.junit.Assert; import org.junit.Test; import java.math.BigInteger; import java.nio.ByteBuffer; import java.nio.ByteOrder; /** * Tests for the EBMLUtils class. */ public class EBMLUtilsTest { @Test public void readSignedInteger8bytes() { byte[] data = { (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFE }; runTestForNegativeTwo(data); } private void runTestForNegativeTwo(byte[] data) { ByteBuffer buffer = ByteBuffer.wrap(data); long value = EBMLUtils.readDataSignedInteger(buffer, data.length); Assert.assertEquals(-2, value); } @Test public void readSignedInteger7bytes() { byte[] data = { (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFE }; runTestForNegativeTwo(data); } @Test public void readSignedInteger2bytes() { byte[] data = { (byte) 0xFF, (byte) 0xFE }; runTestForNegativeTwo(data); } @Test public void readSignedInteger1byte() { byte[] data = { (byte) 0xFE }; runTestForNegativeTwo(data); } @Test public void readUnsignedIntegerSevenBytesOrLessTwoBytes() { byte[] data = { (byte) 0xFF, (byte) 0xFE }; ByteBuffer buffer = ByteBuffer.wrap(data); long value = EBMLUtils.readUnsignedIntegerSevenBytesOrLess(buffer, data.length); Assert.assertEquals(0xFFFE, value); } @Test public void readPositiveSignedInteger1byte() { byte[] data = { (byte) 0x7E }; ByteBuffer buffer = ByteBuffer.wrap(data); long value = EBMLUtils.readDataSignedInteger(buffer, data.length); Assert.assertEquals(0x7E, value); } @Test public void readUnsignedInteger() { ByteBuffer b = ByteBuffer.allocate(8); b.putLong(-309349387097750278L); b.order(ByteOrder.BIG_ENDIAN); b.rewind(); BigInteger unsigned = EBMLUtils.readDataUnsignedInteger(b, 8); Assert.assertTrue(unsigned.signum() > 0); b.rewind(); long value = EBMLUtils.readDataSignedInteger(b, 8); Assert.assertEquals(value, -309349387097750278L); System.out.println(unsigned.toString(16)); } //:-309349387097750278 }
4,933
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/test/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/test/java/com/amazonaws/kinesisvideo/parser/ebml/TestEBMLParserCallback.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.ebml; import lombok.Builder; import lombok.EqualsAndHashCode; import lombok.Setter; import lombok.ToString; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.Validate; import java.io.ByteArrayOutputStream; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.LinkedList; import java.util.OptionalLong; import java.util.Queue; /** * Implementation of {@link EBMLParserCallbacks} used for tests. */ @Slf4j public class TestEBMLParserCallback implements EBMLParserCallbacks { @Setter boolean checkExpectedCallbacks; ByteBuffer contentBuffer = ByteBuffer.allocate(10_000); ByteArrayOutputStream rawBytesOutput = new ByteArrayOutputStream(); Queue<CallbackDescription> callbackDescriptions = new LinkedList<>(); @Override public void onStartElement(EBMLElementMetaData elementMetaData, long elementDataSize, ByteBuffer idAndSizeRawBytes, ElementPathSupplier pathSupplier) { long elementNumber = elementMetaData.getElementNumber(); EBMLTypeInfo typeInfo = elementMetaData.getTypeInfo(); log.info("On Start: elementNumber " + elementNumber + " typeInfo " + typeInfo.toString() + " size " + elementDataSize); if (log.isDebugEnabled()) { log.debug("Rawbytes { " + hexDump(idAndSizeRawBytes) + " }"); } dumpByteBufferToRawOutput(idAndSizeRawBytes); if (checkExpectedCallbacks) { CallbackDescription expectedCallback = callbackDescriptions.remove(); CallbackDescription actualCallback = CallbackDescription.builder() .elementCount(elementNumber) .callbackType(CallbackDescription.CallbackType.START) .typeInfo(typeInfo) .numBytes(OptionalLong.of(elementDataSize)) .bytes(convertToByteArray(idAndSizeRawBytes)) .build(); Validate.isTrue(compareCallbackDescriptions(expectedCallback, actualCallback), getMismatchExpectationMessage(expectedCallback, actualCallback)); } } private static boolean compareCallbackDescriptions(CallbackDescription expectedCallback, CallbackDescription actualCallback) { return expectedCallback.equals(actualCallback) && expectedCallback.areBytesEqual(actualCallback.bytes); } @Override public void onPartialContent(EBMLElementMetaData elementMetaData, ParserBulkByteSource bulkByteSource, int bytesToRead) { contentBuffer.clear(); bulkByteSource.readBytes(contentBuffer, bytesToRead); contentBuffer.flip(); long elementNumber = elementMetaData.getElementNumber(); EBMLTypeInfo typeInfo = elementMetaData.getTypeInfo(); log.info("On PartialContent: elementCount " + elementNumber + " typeInfo " + typeInfo.toString() + " bytesToRead " + bytesToRead); if (log.isDebugEnabled()) { log.debug("Rawbytes { " + hexDump(contentBuffer) + " }"); } dumpByteBufferToRawOutput(contentBuffer); if (checkExpectedCallbacks) { CallbackDescription expectedCallback = callbackDescriptions.remove(); CallbackDescription actualCallback = CallbackDescription.builder() .callbackType(CallbackDescription.CallbackType.CONTENT) .elementCount(elementNumber) .typeInfo(typeInfo) .numBytes(OptionalLong.of(bytesToRead)) .bytes(convertToByteArray(contentBuffer)) .build(); Validate.isTrue(compareCallbackDescriptions(expectedCallback, actualCallback), getMismatchExpectationMessage(expectedCallback, actualCallback)); } } private String getMismatchExpectationMessage(CallbackDescription expectedCallback, CallbackDescription actualCallback) { return " ExpectedCallback " + expectedCallback + " ActualCallback " + actualCallback; } @Override public void onEndElement(EBMLElementMetaData elementMetaData, ElementPathSupplier pathSupplier) { long elementNumber = elementMetaData.getElementNumber(); EBMLTypeInfo typeInfo = elementMetaData.getTypeInfo(); log.info("On EndElement: elementNumber " + elementNumber + " typeInfo " + typeInfo.toString()); if (checkExpectedCallbacks) { CallbackDescription expectedCallback = callbackDescriptions.remove(); CallbackDescription actualCallback = CallbackDescription.builder() .callbackType(CallbackDescription.CallbackType.END) .elementCount(elementNumber) .typeInfo(typeInfo) .build(); Validate.isTrue(compareCallbackDescriptions(expectedCallback, actualCallback), getMismatchExpectationMessage(expectedCallback, actualCallback)); } } byte [] rawBytes() { return rawBytesOutput.toByteArray(); } void validateEmptyCallback() { Validate.isTrue(callbackDescriptions.isEmpty(), "remaining size "+callbackDescriptions.size()); } TestEBMLParserCallback expectCallback(CallbackDescription callbackDescription) { callbackDescriptions.add(callbackDescription); return this; } public static String hexDump(ByteBuffer byteBuffer) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < byteBuffer.limit(); i++) { builder.append(String.format("0x%02x ", byteBuffer.get(i))); } return builder.toString(); } private void dumpByteBufferToRawOutput(ByteBuffer byteBuffer) { rawBytesOutput.write(byteBuffer.array(), byteBuffer.position(), byteBuffer.limit() - byteBuffer.position()); } private byte[] convertToByteArray(ByteBuffer byteBuffer) { byte [] array = new byte[byteBuffer.limit() - byteBuffer.position()]; byteBuffer.get(array); return array; } @Builder @EqualsAndHashCode(doNotUseGetters=true,exclude = "bytes") @ToString static class CallbackDescription { enum CallbackType {START, CONTENT, END}; final CallbackType callbackType; EBMLTypeInfo typeInfo; long elementCount; @Builder.Default OptionalLong numBytes = OptionalLong.empty(); @Builder.Default byte[] bytes = null; boolean areBytesEqual(byte[] otherBytes) { return Arrays.equals(bytes, otherBytes); } } }
4,934
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/kinesis/KinesisDataStreamsWorker.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.kinesis; import java.net.InetAddress; import java.util.UUID; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.kinesisvideo.parser.rekognition.pojo.RekognizedFragmentsIndex; import com.amazonaws.regions.Regions; import com.amazonaws.services.kinesis.clientlibrary.interfaces.IRecordProcessorFactory; import com.amazonaws.services.kinesis.clientlibrary.lib.worker.InitialPositionInStream; import com.amazonaws.services.kinesis.clientlibrary.lib.worker.KinesisClientLibConfiguration; import com.amazonaws.services.kinesis.clientlibrary.lib.worker.Worker; import lombok.AccessLevel; import lombok.RequiredArgsConstructor; /** * Sample Amazon Kinesis Application. */ @RequiredArgsConstructor(access = AccessLevel.PRIVATE) public final class KinesisDataStreamsWorker implements Runnable { private static final String APPLICATION_NAME = "rekognition-kds-stream-application"; // Initial position in the stream when the application starts up for the first time. // Position can be one of LATEST (most recent data) or TRIM_HORIZON (oldest available data) private static final InitialPositionInStream SAMPLE_APPLICATION_INITIAL_POSITION_IN_STREAM = InitialPositionInStream.LATEST; private final Regions region; private final AWSCredentialsProvider credentialsProvider; private final String kdsStreamName; private final RekognizedFragmentsIndex rekognizedFragmentsIndex; public static KinesisDataStreamsWorker create(final Regions region, final AWSCredentialsProvider credentialsProvider, final String kdsStreamName, final RekognizedFragmentsIndex rekognizedFragmentsIndex) { return new KinesisDataStreamsWorker(region, credentialsProvider, kdsStreamName, rekognizedFragmentsIndex); } @Override public void run() { try { String workerId = InetAddress.getLocalHost().getCanonicalHostName() + ":" + UUID.randomUUID(); KinesisClientLibConfiguration kinesisClientLibConfiguration = new KinesisClientLibConfiguration(APPLICATION_NAME, kdsStreamName, credentialsProvider, workerId); kinesisClientLibConfiguration.withInitialPositionInStream(SAMPLE_APPLICATION_INITIAL_POSITION_IN_STREAM) .withRegionName(region.getName()); final IRecordProcessorFactory recordProcessorFactory = () -> new KinesisRecordProcessor(rekognizedFragmentsIndex, credentialsProvider); final Worker worker = new Worker(recordProcessorFactory, kinesisClientLibConfiguration); System.out.printf("Running %s to process stream %s as worker %s...", APPLICATION_NAME, kdsStreamName, workerId); int exitCode = 0; try { worker.run(); } catch (Throwable t) { System.err.println("Caught throwable while processing data."); t.printStackTrace(); exitCode = 1; } System.out.println("Exit code : " + exitCode); } catch (Exception e) { e.printStackTrace(); } } }
4,935
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/kinesis/KinesisRecordProcessor.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.kinesis; /* * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.util.List; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.kinesisvideo.parser.rekognition.pojo.DetectedFace; import com.amazonaws.kinesisvideo.parser.rekognition.pojo.FaceSearchResponse; import com.amazonaws.kinesisvideo.parser.rekognition.pojo.MatchedFace; import com.amazonaws.kinesisvideo.parser.rekognition.pojo.RekognitionOutput; import com.amazonaws.kinesisvideo.parser.rekognition.pojo.RekognizedFragmentsIndex; import com.amazonaws.kinesisvideo.parser.rekognition.pojo.RekognizedOutput; import com.amazonaws.services.kinesis.clientlibrary.exceptions.InvalidStateException; import com.amazonaws.services.kinesis.clientlibrary.exceptions.ShutdownException; import com.amazonaws.services.kinesis.clientlibrary.exceptions.ThrottlingException; import com.amazonaws.services.kinesis.clientlibrary.interfaces.IRecordProcessor; import com.amazonaws.services.kinesis.clientlibrary.interfaces.IRecordProcessorCheckpointer; import com.amazonaws.services.kinesis.clientlibrary.lib.worker.ShutdownReason; import com.amazonaws.services.kinesis.model.Record; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Processes records and checkpoints progress. */ public class KinesisRecordProcessor implements IRecordProcessor { private static final Log LOG = LogFactory.getLog(KinesisRecordProcessor.class); private String kinesisShardId; // Backoff and retry settings private static final long BACKOFF_TIME_IN_MILLIS = 3000L; private static final int NUM_RETRIES = 10; private static final String DELIMITER = "$"; // Checkpoint about once a minute private static final long CHECKPOINT_INTERVAL_MILLIS = 1000L; private long nextCheckpointTimeInMillis; private final CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder(); private final RekognizedFragmentsIndex rekognizedFragmentsIndex; private StringBuilder stringBuilder = new StringBuilder(); public KinesisRecordProcessor(final RekognizedFragmentsIndex rekognizedFragmentsIndex, final AWSCredentialsProvider awsCredentialsProvider) { this.rekognizedFragmentsIndex = rekognizedFragmentsIndex; } /** * {@inheritDoc} */ @Override public void initialize(final String shardId) { LOG.info("Initializing record processor for shard: " + shardId); this.kinesisShardId = shardId; } /** * {@inheritDoc} */ @Override public void processRecords(final List<Record> records, final IRecordProcessorCheckpointer checkpointer) { LOG.info("Processing " + records.size() + " records from " + kinesisShardId); // Process records and perform all exception handling. processRecordsWithRetries(records); // Checkpoint once every checkpoint interval. if (System.currentTimeMillis() > nextCheckpointTimeInMillis) { checkpoint(checkpointer); nextCheckpointTimeInMillis = System.currentTimeMillis() + CHECKPOINT_INTERVAL_MILLIS; } } /** * Process records performing retries as needed. Skip "poison pill" records. * * @param records Data records to be processed. */ private void processRecordsWithRetries(final List<Record> records) { for (final Record record : records) { boolean processedSuccessfully = false; for (int i = 0; i < NUM_RETRIES; i++) { try { processSingleRecord(record); processedSuccessfully = true; break; } catch (final Throwable t) { LOG.warn("Caught throwable while processing record " + record, t); } // backoff if we encounter an exception. try { Thread.sleep(BACKOFF_TIME_IN_MILLIS); } catch (final InterruptedException e) { LOG.debug("Interrupted sleep", e); } } if (!processedSuccessfully) { LOG.error("Couldn't process record " + record + ". Skipping the record."); } } } /** * Process a single record. * * @param record The record to be processed. */ private void processSingleRecord(final Record record) { String data = null; final ObjectMapper mapper = new ObjectMapper(); try { // For this app, we interpret the payload as UTF-8 chars. final ByteBuffer buffer = record.getData(); data = new String(buffer.array(), "UTF-8"); stringBuilder = stringBuilder.append(data).append(DELIMITER); final RekognitionOutput output = mapper.readValue(data, RekognitionOutput.class); // Get the fragment number from Rekognition Output final String fragmentNumber = output .getInputInformation() .getKinesisVideo() .getFragmentNumber(); final Double frameOffsetInSeconds = output .getInputInformation() .getKinesisVideo() .getFrameOffsetInSeconds(); final Double serverTimestamp = output .getInputInformation() .getKinesisVideo() .getServerTimestamp(); final Double producerTimestamp = output .getInputInformation() .getKinesisVideo() .getProducerTimestamp(); final double detectedTime = output.getInputInformation().getKinesisVideo().getServerTimestamp() + output.getInputInformation().getKinesisVideo().getFrameOffsetInSeconds() * 1000L; final RekognizedOutput rekognizedOutput = RekognizedOutput.builder() .fragmentNumber(fragmentNumber) .serverTimestamp(serverTimestamp) .producerTimestamp(producerTimestamp) .frameOffsetInSeconds(frameOffsetInSeconds) .detectedTime(detectedTime) .build(); // Add face search response final List<FaceSearchResponse> responses = output.getFaceSearchResponse(); for (final FaceSearchResponse response : responses) { final DetectedFace detectedFace = response.getDetectedFace(); final List<MatchedFace> matchedFaces = response.getMatchedFaces(); final RekognizedOutput.FaceSearchOutput faceSearchOutput = RekognizedOutput.FaceSearchOutput.builder() .detectedFace(detectedFace) .matchedFaceList(matchedFaces) .build(); rekognizedOutput.addFaceSearchOutput(faceSearchOutput); } // Add it to the index rekognizedFragmentsIndex.add(fragmentNumber, producerTimestamp.longValue(), serverTimestamp.longValue(), rekognizedOutput); } catch (final NumberFormatException e) { LOG.info("Record does not match sample record format. Ignoring record with data; " + data); } catch (final UnsupportedEncodingException e) { e.printStackTrace(); } catch (final JsonParseException e) { e.printStackTrace(); } catch (final JsonMappingException e) { e.printStackTrace(); } catch (final IOException e) { e.printStackTrace(); } } /** * {@inheritDoc} */ @Override public void shutdown(final IRecordProcessorCheckpointer checkpointer, final ShutdownReason reason) { LOG.info("Shutting down record processor for shard: " + kinesisShardId); // Important to checkpoint after reaching end of shard, so we can start processing data from child shards. if (reason == ShutdownReason.TERMINATE) { checkpoint(checkpointer); } } /** Checkpoint with retries. * @param checkpointer */ private void checkpoint(final IRecordProcessorCheckpointer checkpointer) { LOG.info("Checkpointing shard " + kinesisShardId); for (int i = 0; i < NUM_RETRIES; i++) { try { checkpointer.checkpoint(); break; } catch (final ShutdownException se) { // Ignore checkpoint if the processor instance has been shutdown (fail over). LOG.info("Caught shutdown exception, skipping checkpoint.", se); break; } catch (final ThrottlingException e) { // Backoff and re-attempt checkpoint upon transient failures if (i >= (NUM_RETRIES - 1)) { LOG.error("Checkpoint failed after " + (i + 1) + "attempts.", e); break; } else { LOG.info("Transient issue when checkpointing - attempt " + (i + 1) + " of " + NUM_RETRIES, e); } } catch (final InvalidStateException e) { // This indicates an issue with the DynamoDB table (check for table, provisioned IOPS). LOG.error("Cannot save checkpoint to the DynamoDB table used by the Amazon Kinesis Client Library.", e); break; } try { Thread.sleep(BACKOFF_TIME_IN_MILLIS); } catch (final InterruptedException e) { LOG.debug("Interrupted sleep", e); } } } }
4,936
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/mkv/MkvElementVisitException.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.mkv; /** * An exception class that represents exceptions generated when a visitor is used process a MkvElement. */ public class MkvElementVisitException extends Exception { public MkvElementVisitException(String message, Exception cause) { super(message, cause); } }
4,937
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/mkv/MkvElementVisitor.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.mkv; /** * Base visitor for visiting the different types of elements vended by a {\link StreamingMkvReader}. */ public abstract class MkvElementVisitor { public abstract void visit(MkvStartMasterElement startMasterElement) throws MkvElementVisitException; public abstract void visit(MkvEndMasterElement endMasterElement) throws MkvElementVisitException; public abstract void visit(MkvDataElement dataElement) throws MkvElementVisitException; public boolean isDone() { return false; } }
4,938
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/mkv/Frame.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.mkv; import com.amazonaws.kinesisvideo.parser.ebml.EBMLUtils; import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.ToString; import org.apache.commons.lang3.Validate; import java.nio.ByteBuffer; /** * Class that captures the meta-data and data for a frame in a Kinesis Video Stream. * This is based on the content of a SimpleBlock in Mkv. */ @Getter @AllArgsConstructor(access=AccessLevel.PRIVATE) @Builder(toBuilder = true) @ToString(exclude = {"frameData"}) public class Frame { private final long trackNumber; private final int timeCode; private final boolean keyFrame; private final boolean invisible; private final boolean discardable; private final Lacing lacing; private final ByteBuffer frameData; public enum Lacing { NO, XIPH, EBML, FIXED_SIZE} /** * Create a frame object for the provided data buffer. * Do not create a copy of the data buffer while creating the frame object. * @param simpleBlockDataBuffer The data buffer. * @return A frame containing the data buffer. */ public static Frame withoutCopy(ByteBuffer simpleBlockDataBuffer) { FrameBuilder builder = getBuilderWithCommonParams(simpleBlockDataBuffer); ByteBuffer frameData = simpleBlockDataBuffer.slice(); return builder.frameData(frameData).build(); } /** * Create a frame object for the provided data buffer. * Create a copy of the data buffer while creating the frame object. * @param simpleBlockDataBuffer The data buffer. * @return A frame containing a copy of the data buffer. */ public static Frame withCopy(ByteBuffer simpleBlockDataBuffer) { FrameBuilder builder = getBuilderWithCommonParams(simpleBlockDataBuffer); ByteBuffer frameData = ByteBuffer.allocate(simpleBlockDataBuffer.remaining()); frameData.put(simpleBlockDataBuffer); frameData.flip(); return builder.frameData(frameData).build(); } /** * Create a FrameBuilder * @param simpleBlockDataBuffer * @return */ private static FrameBuilder getBuilderWithCommonParams(ByteBuffer simpleBlockDataBuffer) { FrameBuilder builder = Frame.builder() .trackNumber(EBMLUtils.readEbmlInt(simpleBlockDataBuffer)) .timeCode((int) EBMLUtils.readDataSignedInteger(simpleBlockDataBuffer, 2)); final long flag = EBMLUtils.readUnsignedIntegerSevenBytesOrLess(simpleBlockDataBuffer, 1); builder.keyFrame((flag & (0x1 << 7)) > 0) .invisible((flag & (0x1 << 3)) > 0) .discardable((flag & 0x1) > 0); final int laceValue = (int) (flag & 0x3 << 1) >> 1; final Lacing lacing = getLacing(laceValue); builder.lacing(lacing); return builder; } private static Lacing getLacing(int laceValue) { switch(laceValue) { case 0: return Lacing.NO; case 1: return Lacing.XIPH; case 2: return Lacing.EBML; case 3: return Lacing.FIXED_SIZE; default: Validate.isTrue(false, "Invalid value of lacing "+laceValue); } throw new IllegalArgumentException("Invalid value of lacing "+laceValue); } }
4,939
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/mkv/StreamingMkvReader.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.mkv; import com.amazonaws.kinesisvideo.parser.ebml.EBMLParser; import com.amazonaws.kinesisvideo.parser.ebml.EBMLTypeInfo; import com.amazonaws.kinesisvideo.parser.ebml.ParserByteSource; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.Validate; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Optional; import java.util.OptionalInt; import java.util.Set; import java.util.function.Predicate; /** * This class is used to read mkv elements from an mkv stream in a non-blocking way. * This is a streaming mkv reader that provides mkv elements as they become completely available. * * mightHaveNext() returns true, when the reader might have more data. If it returns false, we know that * there can be no more data and we can stop reading. * * nextIfAvailable returns the next MkvElement if one is available, otherwise it returns Optional.absent() * There are three possible types of MkvElements: * 1. {@link MkvStartMasterElement} which represents the start of an Mkv master element. * 2. {@link MkvEndMasterElement} which represents the end of an Mkv master element. * 3. {@link MkvDataElement} which represents a non-master MKV element that contains actual data of a particular type. * * When nextIfAvailable returns a MkvDataElement, its data buffer containing the raw bytes of the element's content * can only be accessed before nextIfAvailable is called again. To retain the value of the MkvDataElement for later use * call getValueCopy() on it. It copies the raw bytes and interprets it based on the type of the MkvDataElement. * */ @Slf4j public class StreamingMkvReader { private final boolean requirePath; private final Set<EBMLTypeInfo> typeInfosToRead; private final ParserByteSource byteSource; private final EBMLParser parser; private final MkvStreamReaderCallback mkvStreamReaderCallback; private Optional<MkvDataElement> previousDataElement; StreamingMkvReader(boolean requirePath, Collection<EBMLTypeInfo> typeInfosToRead, ParserByteSource byteSource) { this(requirePath, typeInfosToRead, byteSource, OptionalInt.empty()); } StreamingMkvReader(boolean requirePath, Collection<EBMLTypeInfo> typeInfosToRead, ParserByteSource byteSource, OptionalInt maxContentBytesAtOnce) { this.requirePath = requirePath; typeInfosToRead.stream().forEach(t -> Validate.isTrue(t.getType() != EBMLTypeInfo.TYPE.MASTER)); this.typeInfosToRead = new HashSet(typeInfosToRead); this.byteSource = byteSource; this.mkvStreamReaderCallback = new MkvStreamReaderCallback(this.requirePath, elementFilter()); this.previousDataElement = Optional.empty(); MkvTypeInfoProvider typeInfoProvider = new MkvTypeInfoProvider(); try { typeInfoProvider.load(); } catch (IllegalAccessException e) { //TODO: fix this throw new RuntimeException("Could not load mkv info", e); } if (maxContentBytesAtOnce.isPresent()) { this.parser = new EBMLParser(typeInfoProvider, mkvStreamReaderCallback, maxContentBytesAtOnce.getAsInt()); } else { this.parser = new EBMLParser(typeInfoProvider, mkvStreamReaderCallback); } } public static StreamingMkvReader createDefault(ParserByteSource byteSource) { return new StreamingMkvReader(true, new ArrayList<>(), byteSource, OptionalInt.empty()); } public static StreamingMkvReader createWithMaxContentSize(ParserByteSource byteSource, int maxContentBytesAtOnce) { return new StreamingMkvReader(true, new ArrayList<>(), byteSource, OptionalInt.of(maxContentBytesAtOnce)); } public boolean mightHaveNext() { if (mkvStreamReaderCallback.hasElementsToReturn()) { log.debug("ReaderCallback has elements to return "); return true; } if( !byteSource.eof() && !parser.isClosed()) { return true; } else if (byteSource.eof()) { log.debug("byteSource has reached eof"); if(!parser.isClosed()) { log.debug("byteSource has reached eof and calling close on parser"); parser.closeParser(); return true; } } log.debug("No more elements to process byteSource.eof {} parser.isClosed {} ", byteSource.eof(), parser.isClosed()); return false; } public Optional<MkvElement> nextIfAvailable() { if (mkvStreamReaderCallback.hasElementsToReturn()) { if (log.isDebugEnabled()) { log.debug("ReaderCallback has elements to return. Return element from it."); } return getMkvElementToReturn(); } parser.parse(byteSource); return getMkvElementToReturn(); } /** * Method to apply a visitor in a loop to all the elements returns by a StreamingMkvReader. * This method polls for the next available element in a tight loop. * It might not be suitable in cases where the user wants to interleave some other activity between polling. * * @param visitor The visitor to apply. * @throws MkvElementVisitException If the visitor fails. */ public void apply(MkvElementVisitor visitor) throws MkvElementVisitException { while (this.mightHaveNext() && !visitor.isDone()) { Optional<MkvElement> mkvElementOptional = this.nextIfAvailable(); if (mkvElementOptional.isPresent()) { mkvElementOptional.get().accept(visitor); } } } private Optional<MkvElement> getMkvElementToReturn() { Optional<MkvElement> currentElement = mkvStreamReaderCallback.getMkvElementIfAvailable(); //Null out the data buffer of the previous data element before returning the next element. //We do this because the same data buffer gets reused for consecutive data elements and we //do not want users to mistakenly reuse data buffers on cached data elements. //They should use the getValueCopy to retain the data. if (currentElement.isPresent()) { if (previousDataElement.isPresent()) { previousDataElement.get().clearDataBuffer(); previousDataElement = Optional.empty(); } if (!currentElement.get().isMaster()) { previousDataElement = Optional.of((MkvDataElement) currentElement.get()); } } return currentElement; } private Predicate<EBMLTypeInfo> elementFilter() { if (typeInfosToRead.size() == 0) { return (t) -> t.getType() != EBMLTypeInfo.TYPE.MASTER; } else { return typeInfosToRead::contains; } } }
4,940
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/mkv/MkvTypeInfoProvider.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.mkv; import com.amazonaws.kinesisvideo.parser.ebml.EBMLTypeInfo; import com.amazonaws.kinesisvideo.parser.ebml.EBMLTypeInfoProvider; import com.amazonaws.kinesisvideo.parser.ebml.MkvTypeInfos; import org.apache.commons.lang3.Validate; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.Map; import java.util.Optional; /** * A class to provide the type information for the EBML elements used by Mkv. * This type information is used by the EBML parser. */ public class MkvTypeInfoProvider implements EBMLTypeInfoProvider { private final Map<Integer,EBMLTypeInfo> typeInfoMap = new HashMap(); public void load() throws IllegalAccessException { for (Field field : MkvTypeInfos.class.getDeclaredFields()) { if (Modifier.isStatic(field.getModifiers()) && field.getType().equals(EBMLTypeInfo.class)) { EBMLTypeInfo type = (EBMLTypeInfo )field.get(null); Validate.isTrue(!typeInfoMap.containsKey(type.getId())); typeInfoMap.put(type.getId(), type); } } } @Override public Optional<EBMLTypeInfo> getType(int id) { return Optional.ofNullable(typeInfoMap.get(id)); } }
4,941
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/mkv/FrameProcessException.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.mkv; public class FrameProcessException extends MkvElementVisitException { public FrameProcessException(String message, Exception cause) { super(message, cause); } }
4,942
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/mkv/MkvDataElement.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.mkv; import com.amazonaws.kinesisvideo.parser.ebml.EBMLElementMetaData; import com.amazonaws.kinesisvideo.parser.ebml.EBMLUtils; import com.amazonaws.kinesisvideo.parser.ebml.MkvTypeInfos; import lombok.AccessLevel; import lombok.Builder; import lombok.Getter; import lombok.ToString; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.Validate; import java.math.BigInteger; import java.nio.ByteBuffer; import java.nio.channels.WritableByteChannel; import java.nio.charset.StandardCharsets; import java.time.Instant; import java.util.List; /** * Class representing a non-master mkv element, that contains actual data in an mkv stream. * It includes the bytes containing the id and size of the element, the size of the data in the element. * When first vended by a {@link StreamingMkvReader} it also includes the raw bytes of the data element in the dataBuffer. * However, the data buffer can only be accessed before nextIfAvailable is called again on the StreamingMkvReader. * To retain the value of the MkvDataElement for later use call getValueCopy() on it. * It copies the raw bytes and interprets it based on the type of the MkvDataElement. */ @Getter @ToString(callSuper = true, exclude = {"dataBuffer","valueCopy", "idAndSizeRawBytes"}) @Slf4j public class MkvDataElement extends MkvElement { private static final int DATE_SIZE = 8; private static final Instant DATE_BASE_INSTANT = Instant.ofEpochSecond(978307200); private final long dataSize; private final ByteBuffer idAndSizeRawBytes; private ByteBuffer dataBuffer; @Getter(AccessLevel.NONE) private MkvValue valueCopy; @Builder private MkvDataElement(EBMLElementMetaData elementMetaData, List<EBMLElementMetaData> elementPath, ByteBuffer idAndSizeRawBytes, long dataSize, ByteBuffer dataBuffer) { super(elementMetaData, elementPath); this.dataSize = dataSize; this.dataBuffer = dataBuffer; this.idAndSizeRawBytes = idAndSizeRawBytes; } public MkvValue getValueCopy() { if (valueCopy == null) { createValueByCopyingBytes(); } return valueCopy; } private void createValueByCopyingBytes() { dataBuffer.rewind(); try { switch (elementMetaData.getTypeInfo().getType()) { case INTEGER: valueCopy = new MkvValue(EBMLUtils.readDataSignedInteger(dataBuffer, dataSize), dataSize); break; case UINTEGER: BigInteger unsignedValue = EBMLUtils.readDataUnsignedInteger(dataBuffer, dataSize); //We originally failed validation here, but users ran into streams where the //Track UID was negative. So, we changed this to an error log. if (unsignedValue.signum() < 0) { log.error("Uinteger has negative value {} ", unsignedValue); } valueCopy = new MkvValue(unsignedValue, dataSize); break; case FLOAT: Validate.isTrue(dataSize == Float.BYTES || dataSize == Double.BYTES, "Invalid size for float type" + dataSize); if (dataSize == Float.BYTES) { valueCopy = new MkvValue(dataBuffer.getFloat(), Float.BYTES); } else { valueCopy = new MkvValue(dataBuffer.getDouble(), Double.BYTES); } break; case STRING: valueCopy = new MkvValue(StandardCharsets.US_ASCII.decode(dataBuffer).toString(), dataSize); break; case UTF_8: valueCopy = new MkvValue(StandardCharsets.UTF_8.decode(dataBuffer).toString(), dataSize); break; case DATE: Validate.isTrue(dataSize == DATE_SIZE, "Date element size can only be 8 bytes not " + dataSize); long dateLongValue = EBMLUtils.readDataSignedInteger(dataBuffer, DATE_SIZE); valueCopy = new MkvValue(DATE_BASE_INSTANT.plusNanos(dateLongValue),dataSize); break; case BINARY: if (elementMetaData.getTypeInfo().equals(MkvTypeInfos.SIMPLEBLOCK)) { Frame frame = Frame.withCopy(dataBuffer); valueCopy = new MkvValue(frame, dataSize); } else { ByteBuffer buffer = ByteBuffer.allocate((int) dataSize); dataBuffer.get(buffer.array(), 0, (int) dataSize); valueCopy = new MkvValue(buffer, dataSize); } break; default: throw new IllegalArgumentException( "Cannot have value for ebml element type " + elementMetaData.getTypeInfo().getType()); } } finally { dataBuffer.rewind(); } } @Override public boolean isMaster() { return false; } @Override public void accept(MkvElementVisitor visitor) throws MkvElementVisitException { visitor.visit(this); } @Override public boolean equivalent(MkvElement other) { if (!typeEquals(other)) { return false; } MkvDataElement otherDataElement = (MkvDataElement) other; return this.dataSize == otherDataElement.dataSize && this.valueCopy.equals(otherDataElement.valueCopy); } @Override public void writeToChannel(WritableByteChannel outputChannel) throws MkvElementVisitException { writeByteBufferToChannel(idAndSizeRawBytes, outputChannel); writeByteBufferToChannel(dataBuffer, outputChannel); } public int getIdAndSizeRawBytesLength() { return idAndSizeRawBytes.limit(); } public int getDataBufferSize() { if (dataBuffer == null ) { return 0; } return dataBuffer.limit(); } void clearDataBuffer() { dataBuffer = null; } }
4,943
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/mkv/MkvStartMasterElement.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.mkv; import com.amazonaws.kinesisvideo.parser.ebml.EBMLElementMetaData; import lombok.Builder; import lombok.Getter; import lombok.ToString; import java.nio.ByteBuffer; import java.nio.channels.WritableByteChannel; import java.util.List; import static com.amazonaws.kinesisvideo.parser.ebml.EBMLUtils.UNKNOWN_LENGTH_VALUE; /** * Class representing the start of a mkv master element. * It includes the bytes containing the id and size of the element along with its {@link EBMLElementMetaData} * and its path (if specified). */ @Getter @ToString(callSuper = true, exclude = "idAndSizeRawBytes") public class MkvStartMasterElement extends MkvElement { private final long dataSize; private final ByteBuffer idAndSizeRawBytes = ByteBuffer.allocate(MAX_ID_AND_SIZE_BYTES); @Builder private MkvStartMasterElement(EBMLElementMetaData elementMetaData, List<EBMLElementMetaData> elementPath, long dataSize, ByteBuffer idAndSizeRawBytes) { super(elementMetaData, elementPath); this.dataSize = dataSize; this.idAndSizeRawBytes.put(idAndSizeRawBytes); this.idAndSizeRawBytes.flip(); idAndSizeRawBytes.rewind(); } @Override public boolean isMaster() { return true; } @Override public void accept(MkvElementVisitor visitor) throws MkvElementVisitException { visitor.visit(this); } @Override public boolean equivalent(MkvElement other) { return typeEquals(other) && this.dataSize == ((MkvStartMasterElement) other).dataSize; } public boolean isUnknownLength() { return dataSize == UNKNOWN_LENGTH_VALUE; } @Override public void writeToChannel(WritableByteChannel outputChannel) throws MkvElementVisitException { writeByteBufferToChannel(idAndSizeRawBytes, outputChannel); } public int getIdAndSizeRawBytesLength() { return idAndSizeRawBytes.limit(); } }
4,944
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/mkv/MkvElement.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.mkv; import com.amazonaws.kinesisvideo.parser.ebml.EBMLElementMetaData; import com.amazonaws.kinesisvideo.parser.ebml.EBMLUtils; import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.ToString; import org.apache.commons.lang3.Validate; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.WritableByteChannel; import java.util.List; /** * Common base class for all MkvElements */ @Getter @ToString @AllArgsConstructor(access = AccessLevel.PACKAGE) public abstract class MkvElement { protected static final int MAX_ID_AND_SIZE_BYTES = EBMLUtils.EBML_ID_MAX_BYTES + EBMLUtils.EBML_SIZE_MAX_BYTES; protected final EBMLElementMetaData elementMetaData; protected final List<EBMLElementMetaData> elementPath; protected boolean typeEquals(MkvElement other) { if (!other.getClass().equals(this.getClass())) { return false; } return elementMetaData.getTypeInfo().equals(other.getElementMetaData().getTypeInfo()); } public abstract boolean isMaster(); public abstract void accept(MkvElementVisitor visitor) throws MkvElementVisitException; public abstract boolean equivalent(MkvElement other); public void writeToChannel(WritableByteChannel outputChannel) throws MkvElementVisitException { } protected void writeByteBufferToChannel(ByteBuffer src, WritableByteChannel outputChannel) throws MkvElementVisitException { src.rewind(); int size = src.remaining(); try { int numBytes = outputChannel.write(src); Validate.isTrue(size == numBytes, "Output channel wrote " + size + " bytes instead of " + numBytes); } catch (IOException e) { throw new MkvElementVisitException("Writing to output channel failed", e); } finally { src.rewind(); } } }
4,945
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/mkv/MkvStreamReaderCallback.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.mkv; import com.amazonaws.kinesisvideo.parser.ebml.EBMLElementMetaData; import com.amazonaws.kinesisvideo.parser.ebml.EBMLParserCallbacks; import com.amazonaws.kinesisvideo.parser.ebml.EBMLTypeInfo; import com.amazonaws.kinesisvideo.parser.ebml.ParserBulkByteSource; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.Validate; import java.nio.ByteBuffer; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.Queue; import java.util.function.Predicate; /** * EBML parser callback used by the MKVStream reader */ @Slf4j @RequiredArgsConstructor class MkvStreamReaderCallback implements EBMLParserCallbacks{ //NOTE: if object creation rate becomes a performance bottleneck convert these to nullables private Optional<CurrentMkvDataElementInfo> currentMkvDataElementInfo = Optional.empty(); private final Queue<MkvElement> elementsToReturn = new ArrayDeque<>(); private final boolean shouldStoreElementPaths; private final Predicate<EBMLTypeInfo> elementFilter; //TODO: make this dynamic private static final int MAX_BUFFER_SIZE = 1_000_000; ByteBuffer readBuffer = ByteBuffer.allocate(MAX_BUFFER_SIZE); @Override public void onStartElement(EBMLElementMetaData elementMetaData, long elementDataSize, ByteBuffer idAndSizeRawBytes, ElementPathSupplier pathSupplier) { Validate.isTrue(!currentMkvDataElementInfo.isPresent()); if(elementMetaData.isMaster()) { log.debug("Start Master Element to return {} data size {} ", elementMetaData, elementDataSize); addMkvElementToReturn(MkvStartMasterElement.builder().elementMetaData(elementMetaData) .elementPath(getPath(pathSupplier)) .dataSize(elementDataSize) .idAndSizeRawBytes(idAndSizeRawBytes).build()); } else { if (elementDataSize > readBuffer.capacity()) { int sizeToAllocate = ((int )Math.ceil((double )elementDataSize/MAX_BUFFER_SIZE))*MAX_BUFFER_SIZE; log.debug("Resizing readBuffer to {}", sizeToAllocate); readBuffer = ByteBuffer.allocate(sizeToAllocate); } readBuffer.clear(); if (elementFilter.test(elementMetaData.getTypeInfo())) { log.debug("Data Element to start building {} data size {} ", elementMetaData, elementDataSize); List<EBMLElementMetaData> elementPath = getPath(pathSupplier); currentMkvDataElementInfo = Optional.of(new CurrentMkvDataElementInfo(elementMetaData, elementDataSize, elementPath, idAndSizeRawBytes)); } } } private List<EBMLElementMetaData> getPath(ElementPathSupplier pathSupplier) { List<EBMLElementMetaData> elementPath; if (shouldStoreElementPaths) { elementPath = pathSupplier.getAncestors(); } else { elementPath = new ArrayList<>(); } return elementPath; } @Override public void onPartialContent(EBMLElementMetaData elementMetaData, ParserBulkByteSource bulkByteSource, int bytesToRead) { Validate.isTrue(elementsToReturn.isEmpty()); if (elementFilter.test(elementMetaData.getTypeInfo())) { Validate.isTrue(currentMkvDataElementInfo.isPresent()); currentMkvDataElementInfo.get().validateExpectedElement(elementMetaData); log.debug("Data Element to start buffering data {} bytes to read {} ", elementMetaData, bytesToRead); } if(!elementMetaData.isMaster()) { bulkByteSource.readBytes(readBuffer, bytesToRead); } } @Override public void onEndElement(EBMLElementMetaData elementMetaData, ElementPathSupplier pathSupplier) { if(elementMetaData.isMaster()) { Validate.isTrue(!currentMkvDataElementInfo.isPresent()); log.debug("End Master Element to return {}", elementMetaData); addMkvElementToReturn(MkvEndMasterElement.builder() .elementMetaData(elementMetaData) .elementPath(getPath(pathSupplier)) .build()); } else { if (elementFilter.test(elementMetaData.getTypeInfo())) { Validate.isTrue(currentMkvDataElementInfo.isPresent()); log.debug("Data Element to return {} data size {} ", elementMetaData, readBuffer.position()); readBuffer.flip(); addMkvElementToReturn(currentMkvDataElementInfo.get().build(readBuffer)); currentMkvDataElementInfo = Optional.empty(); } } } @Override public boolean continueParsing() { return elementsToReturn.isEmpty(); } boolean hasElementsToReturn() { return !elementsToReturn.isEmpty(); } public Optional<MkvElement> getMkvElementIfAvailable() { if (elementsToReturn.isEmpty()) { return Optional.empty(); } return Optional.of(elementsToReturn.remove()); } private void addMkvElementToReturn(MkvElement elementToReturn) { this.elementsToReturn.add(elementToReturn); } private static class CurrentMkvDataElementInfo { private final EBMLElementMetaData elementMetadata; private final long dataSize; private final List<EBMLElementMetaData> elementPath; private final ByteBuffer idAndSizeRawBytes = ByteBuffer.allocate(MkvElement.MAX_ID_AND_SIZE_BYTES); CurrentMkvDataElementInfo(EBMLElementMetaData elementMetadata, long dataSize, List<EBMLElementMetaData> elementPath, ByteBuffer idAndSizeRawBytes) { this.elementMetadata = elementMetadata; this.dataSize = dataSize; this.elementPath = elementPath; //Copy the id and size raw bytes since these will be retained. this.idAndSizeRawBytes.put(idAndSizeRawBytes); this.idAndSizeRawBytes.flip(); idAndSizeRawBytes.rewind(); } MkvDataElement build(ByteBuffer data) { Validate.isTrue(data.limit() == dataSize); return MkvDataElement.builder() .elementMetaData(elementMetadata) .dataSize(dataSize) .idAndSizeRawBytes(idAndSizeRawBytes) .elementPath(elementPath) .dataBuffer(data) .build(); } public void validateExpectedElement(EBMLElementMetaData elementMetaData) { Validate.isTrue(elementMetaData.equals(this.elementMetadata)); } } }
4,946
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/mkv/MkvEndMasterElement.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.mkv; import com.amazonaws.kinesisvideo.parser.ebml.EBMLElementMetaData; import lombok.Builder; import lombok.ToString; import java.util.List; /** * Class representing the end of a mkv master element. * It contains the metadata {@link EBMLElementMetaData} and the path if specified. */ @ToString(callSuper = true) public class MkvEndMasterElement extends MkvElement { @Builder private MkvEndMasterElement(EBMLElementMetaData elementMetaData, List<EBMLElementMetaData> elementPath) { super(elementMetaData, elementPath); } @Override public boolean isMaster() { return true; } @Override public void accept(MkvElementVisitor visitor) throws MkvElementVisitException { visitor.visit(this); } @Override public boolean equivalent(MkvElement other) { return typeEquals(other); } }
4,947
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/mkv/MkvValue.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.mkv; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NonNull; import java.nio.ByteBuffer; /** * A class to contain the values of MKV elements. */ @AllArgsConstructor public class MkvValue<T extends Object> { @NonNull private final T val; @Getter private final long originalDataSize; public T getVal() { if (ByteBuffer.class.isAssignableFrom(val.getClass())) { ByteBuffer byteBufferVal = (ByteBuffer)val; byteBufferVal.rewind(); } return val; } public boolean equals(Object otherObj) { if (otherObj == null) { return false; } if (!otherObj.getClass().equals(this.getClass())) { return false; } MkvValue other = (MkvValue) otherObj; if (!val.getClass().equals(other.val.getClass())) { return false; } if (originalDataSize != other.originalDataSize) { return false; } return getVal().equals(other.getVal()); } @Override public int hashCode() { int result = val.hashCode(); result = 31 * result + (int) (originalDataSize ^ (originalDataSize >>> 32)); return result; } }
4,948
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/mkv
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/mkv/visitors/CountVisitor.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.mkv.visitors; import com.amazonaws.kinesisvideo.parser.ebml.EBMLTypeInfo; import com.amazonaws.kinesisvideo.parser.mkv.MkvDataElement; import com.amazonaws.kinesisvideo.parser.mkv.MkvElement; import com.amazonaws.kinesisvideo.parser.mkv.MkvElementVisitor; import com.amazonaws.kinesisvideo.parser.mkv.MkvEndMasterElement; import com.amazonaws.kinesisvideo.parser.mkv.MkvStartMasterElement; import lombok.extern.slf4j.Slf4j; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; /** * A visitor used to count elements of a particular type */ @Slf4j public class CountVisitor extends MkvElementVisitor { private final Set<EBMLTypeInfo> typesToCount = new HashSet<>(); private final Map<EBMLTypeInfo, Integer> typeCount = new HashMap<>(); private final Map<EBMLTypeInfo, Integer> endMasterCount = new HashMap<>(); public CountVisitor(Collection<EBMLTypeInfo> typesToCount) { this.typesToCount.addAll(typesToCount); this.typesToCount.stream().forEach(t -> typeCount.put(t, 0)); this.typesToCount.stream() .filter(t -> t.getType().equals(EBMLTypeInfo.TYPE.MASTER)) .forEach(t -> endMasterCount.put(t, 0)); } public static CountVisitor create(EBMLTypeInfo... typesToCount) { List<EBMLTypeInfo> typeInfoList = new ArrayList<>(); for (EBMLTypeInfo typeToCount : typesToCount) { typeInfoList.add(typeToCount); } return new CountVisitor(typeInfoList); } @Override public void visit(MkvStartMasterElement startMasterElement) { incrementTypeCount(startMasterElement); } @Override public void visit(MkvEndMasterElement endMasterElement) { incrementCount(endMasterElement, endMasterCount); } @Override public void visit(MkvDataElement dataElement) { incrementTypeCount(dataElement); } public int getCount(EBMLTypeInfo typeInfo) { return typeCount.getOrDefault(typeInfo, 0); } public boolean doEndAndStartMasterElementsMatch() { List<EBMLTypeInfo> mismatchedStartAndEnd = typeCount.entrySet().stream().filter(e -> e.getKey().getType().equals(EBMLTypeInfo.TYPE.MASTER)).filter(e -> typeCount.get(e.getKey()) != endMasterCount.get(e.getKey())).map(Map.Entry::getKey).collect( Collectors.toList()); if (!mismatchedStartAndEnd.isEmpty()) { log.warn(" Some end and master element counts did not match: "); mismatchedStartAndEnd.stream().forEach(t -> log.warn("Element {} start count {} end count {}", t, typeCount.get(t), endMasterCount.get(t))); return false; } return true; } private void incrementTypeCount(MkvElement mkvElement) { incrementCount(mkvElement, typeCount); } private void incrementCount(MkvElement mkvElement, Map<EBMLTypeInfo, Integer> mapToUpdate) { if (typesToCount.contains(mkvElement.getElementMetaData().getTypeInfo())) { log.debug("Element {} to Count found", mkvElement); int oldValue = mapToUpdate.get(mkvElement.getElementMetaData().getTypeInfo()); mapToUpdate.put(mkvElement.getElementMetaData().getTypeInfo(), oldValue + 1); } } }
4,949
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/mkv
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/mkv/visitors/ElementSizeAndOffsetVisitor.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.mkv.visitors; import com.amazonaws.kinesisvideo.parser.ebml.MkvTypeInfos; import com.amazonaws.kinesisvideo.parser.mkv.Frame; import com.amazonaws.kinesisvideo.parser.mkv.MkvDataElement; import com.amazonaws.kinesisvideo.parser.mkv.MkvElement; import com.amazonaws.kinesisvideo.parser.mkv.MkvElementVisitException; import com.amazonaws.kinesisvideo.parser.mkv.MkvElementVisitor; import com.amazonaws.kinesisvideo.parser.mkv.MkvEndMasterElement; import com.amazonaws.kinesisvideo.parser.mkv.MkvStartMasterElement; import com.amazonaws.kinesisvideo.parser.mkv.MkvValue; import lombok.RequiredArgsConstructor; import java.io.BufferedWriter; import java.io.IOException; import java.math.BigInteger; /** * It logs the offsets and element sizes to a writer. * It is useful for looking into mkv streams, where mkvinfo fails. */ @RequiredArgsConstructor public class ElementSizeAndOffsetVisitor extends MkvElementVisitor { private final BufferedWriter writer; private long offsetCount = 0; @Override public void visit(MkvStartMasterElement startMasterElement) throws MkvElementVisitException { StringBuilder builder = new StringBuilder(); appendOffset(startMasterElement, builder); appendCommonParts(startMasterElement, builder); builder.append(" element header size ") .append(startMasterElement.getIdAndSizeRawBytesLength()) .append(" element data size "); if (startMasterElement.isUnknownLength()) { builder.append("unknown"); } else { builder.append(startMasterElement.getDataSize()); } offsetCount += startMasterElement.getIdAndSizeRawBytesLength(); buildAndWrite(builder); } @Override public void visit(MkvEndMasterElement endMasterElement) { } @Override public void visit(MkvDataElement dataElement) throws MkvElementVisitException { StringBuilder builder = createStringBuilderWithOffset(dataElement); appendCommonParts(dataElement, builder); builder.append(" element header size ") .append(dataElement.getIdAndSizeRawBytesLength()) .append(" element data size ") .append(dataElement.getDataSize()); offsetCount += dataElement.getIdAndSizeRawBytesLength(); offsetCount += dataElement.getDataSize(); buildAndWrite(builder); if (MkvTypeInfos.SIMPLEBLOCK.equals(dataElement.getElementMetaData().getTypeInfo())) { //Print out the frame information. MkvValue<Frame> frameValue = dataElement.getValueCopy(); Frame frame = frameValue.getVal(); buildAndWrite(createStringBuilderWithOffset(dataElement).append("Frame data (size): ") .append(frame.getFrameData().limit()) .append(" ") .append(frame.toString())); } else if (MkvTypeInfos.TAGNAME.equals(dataElement.getElementMetaData().getTypeInfo())) { MkvValue<String> tagName= dataElement.getValueCopy(); buildAndWrite(createStringBuilderWithOffset(dataElement).append("Tag Name :").append(tagName.getVal())); } else if (MkvTypeInfos.TIMECODE.equals(dataElement.getElementMetaData().getTypeInfo())) { MkvValue<BigInteger> timeCode = dataElement.getValueCopy(); buildAndWrite(createStringBuilderWithOffset(dataElement).append("TimeCode :") .append(timeCode.getVal().toString())); } } private StringBuilder createStringBuilderWithOffset(MkvDataElement dataElement) { StringBuilder frameStringBuilder = new StringBuilder(); appendOffset(dataElement, frameStringBuilder); return frameStringBuilder; } private void appendCommonParts(MkvElement mkvElement, StringBuilder builder) { builder.append("Element ") .append(mkvElement.getElementMetaData().getTypeInfo().getName()) .append(" elementNumber ") .append(mkvElement.getElementMetaData().getElementNumber()) .append(" offset ") .append(offsetCount); } private void appendOffset(MkvElement element, StringBuilder builder) { int level = Math.max(0, element.getElementMetaData().getTypeInfo().getLevel()); for (int i = 0; i < level; i++) { builder.append(" "); } } private void buildAndWrite(StringBuilder builder) throws MkvElementVisitException { try { String s = builder.toString(); writer.write(s, 0, s.length()); writer.newLine(); } catch (IOException e) { throw new MkvElementVisitException("Failure in ElementSizeAndOffsetVisitor ", e); } } }
4,950
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/mkv
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/mkv/visitors/CompositeMkvElementVisitor.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.mkv.visitors; import com.amazonaws.kinesisvideo.parser.mkv.MkvDataElement; import com.amazonaws.kinesisvideo.parser.mkv.MkvElement; import com.amazonaws.kinesisvideo.parser.mkv.MkvElementVisitException; import com.amazonaws.kinesisvideo.parser.mkv.MkvElementVisitor; import com.amazonaws.kinesisvideo.parser.mkv.MkvEndMasterElement; import com.amazonaws.kinesisvideo.parser.mkv.MkvStartMasterElement; import lombok.AccessLevel; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import java.util.ArrayList; import java.util.List; /** * Class represents a composite visitor made out of multiple visitors. * */ @RequiredArgsConstructor(access = AccessLevel.PROTECTED) @Slf4j public class CompositeMkvElementVisitor extends MkvElementVisitor { protected final List<MkvElementVisitor> childVisitors; public CompositeMkvElementVisitor(MkvElementVisitor... visitors){ childVisitors = new ArrayList<>(); for (MkvElementVisitor visitor : visitors) { childVisitors.add(visitor); } } @Override public void visit(MkvStartMasterElement startMasterElement) throws MkvElementVisitException { visitAll(startMasterElement); } @Override public void visit(MkvEndMasterElement endMasterElement) throws MkvElementVisitException { visitAll(endMasterElement); } @Override public void visit(MkvDataElement dataElement) throws MkvElementVisitException { visitAll(dataElement); } @Override public boolean isDone() { return childVisitors.stream().anyMatch(MkvElementVisitor::isDone); } private void visitAll(MkvElement element) throws MkvElementVisitException { for (MkvElementVisitor childVisitor : childVisitors) { if (log.isDebugEnabled()) { log.debug("Composite visitor calling {} on element {}", childVisitor.getClass().toString(), element.toString()); } element.accept(childVisitor); } } }
4,951
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/mkv
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/mkv/visitors/CopyVisitor.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.mkv.visitors; import com.amazonaws.kinesisvideo.parser.mkv.MkvDataElement; import com.amazonaws.kinesisvideo.parser.mkv.MkvElementVisitException; import com.amazonaws.kinesisvideo.parser.mkv.MkvElementVisitor; import com.amazonaws.kinesisvideo.parser.mkv.MkvEndMasterElement; import com.amazonaws.kinesisvideo.parser.mkv.MkvStartMasterElement; import java.io.Closeable; import java.io.IOException; import java.io.OutputStream; import java.nio.channels.Channels; import java.nio.channels.WritableByteChannel; /** * This visitor can be used to copy the ray bytes of elements to an output stream. * It can be used to create a copy of an mkv stream being parsed. * It is particularly useful for debugging as part of a {@link CompositeMkvElementVisitor} since it allows creating * a copy of an input stream while also processing it in parallel. * * For start master elements, it copies the element header, namely its id and size. * For data elements, it copies the element header as well as the data bytes. * For end master elements, there are no raw bytes to copy. */ public class CopyVisitor extends MkvElementVisitor implements Closeable { private final WritableByteChannel outputChannel; public CopyVisitor(OutputStream outputStream) { this.outputChannel = Channels.newChannel(outputStream); } @Override public void visit(MkvStartMasterElement startMasterElement) throws MkvElementVisitException { startMasterElement.writeToChannel(outputChannel); } @Override public void visit(MkvEndMasterElement endMasterElement) throws MkvElementVisitException { } @Override public void visit(MkvDataElement dataElement) throws MkvElementVisitException { dataElement.writeToChannel(outputChannel); } @Override public void close() throws IOException { outputChannel.close(); } }
4,952
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/utilities/H264FrameEncoder.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.utilities; import com.amazonaws.kinesisvideo.parser.examples.lambda.EncodedFrame; import lombok.extern.slf4j.Slf4j; import org.jcodec.codecs.h264.H264Encoder; import org.jcodec.codecs.h264.H264Utils; import org.jcodec.codecs.h264.encode.H264FixedRateControl; import org.jcodec.codecs.h264.io.model.PictureParameterSet; import org.jcodec.codecs.h264.io.model.SeqParameterSet; import org.jcodec.codecs.h264.io.model.SliceType; import org.jcodec.codecs.h264.mp4.AvcCBox; import org.jcodec.common.VideoEncoder; import org.jcodec.common.model.ColorSpace; import org.jcodec.common.model.Picture; import org.jcodec.common.model.Size; import org.jcodec.scale.AWTUtil; import java.awt.image.BufferedImage; import java.io.IOException; import java.nio.ByteBuffer; import static java.util.Arrays.asList; /** * H264 Frame Encoder class which uses JCodec encoder to encode frames. */ @Slf4j public class H264FrameEncoder { private Picture toEncode; private H264Encoder encoder; private SeqParameterSet sps; private PictureParameterSet pps; private ByteBuffer out; private byte[] cpd; private int frameNumber; public H264FrameEncoder(final int width, final int height, final int bitRate) { this.encoder = new H264Encoder(new H264FixedRateControl(bitRate)); this.out = ByteBuffer.allocate(width * height * 6); this.frameNumber = 0; final Size size = new Size(width, height); sps = this.encoder.initSPS(size); pps = this.encoder.initPPS(); final ByteBuffer spsBuffer = ByteBuffer.allocate(512); this.sps.write(spsBuffer); spsBuffer.flip(); final ByteBuffer serialSps = ByteBuffer.allocate(512); this.sps.write(serialSps); serialSps.flip(); H264Utils.escapeNALinplace(serialSps); final ByteBuffer serialPps = ByteBuffer.allocate(512); this.pps.write(serialPps); serialPps.flip(); H264Utils.escapeNALinplace(serialPps); final ByteBuffer serialAvcc = ByteBuffer.allocate(512); final AvcCBox avcC = AvcCBox.createAvcCBox(this.sps.profileIdc, 0, this.sps.levelIdc, 4, asList(serialSps), asList(serialPps)); avcC.doWrite(serialAvcc); serialAvcc.flip(); cpd = new byte[serialAvcc.remaining()]; serialAvcc.get(cpd); } public EncodedFrame encodeFrame(final BufferedImage bi) { // Perform conversion from buffered image to pic out.clear(); toEncode = AWTUtil.fromBufferedImage(bi, ColorSpace.YUV420J); // First frame is treated as I Frame (IDR Frame) final SliceType sliceType = this.frameNumber == 0 ? SliceType.I : SliceType.P; log.debug("Encoding frame no: {}, frame type : {}", frameNumber, sliceType); final boolean idr = this.frameNumber == 0; // Encode image into H.264 frame, the result is stored in 'out' buffer final ByteBuffer data = encoder.doEncodeFrame(toEncode, out, idr, this.frameNumber++, sliceType); return EncodedFrame.builder() .byteBuffer(data) .isKeyFrame(idr) .cpd(ByteBuffer.wrap(cpd)) .build(); } public void setFrameNumber(final int frameNumber) { this.frameNumber = frameNumber; } public SeqParameterSet getSps() { return sps; } public PictureParameterSet getPps() { return pps; } public byte[] getCodecPrivateData() { return cpd.clone(); } public int getKeyInterval() { return encoder.getKeyInterval(); } }
4,953
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/utilities/MkvTrackMetadata.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.utilities; import com.amazonaws.kinesisvideo.parser.mkv.MkvElement; import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.ToString; import java.math.BigInteger; import java.nio.ByteBuffer; import java.util.List; import java.util.Optional; /** * Class that captures the meta-data for a particular track in the mkv response. */ @AllArgsConstructor(access = AccessLevel.PRIVATE) @Builder @Getter @ToString(exclude = {"codecPrivateData", "allElementsInTrack"}) public class MkvTrackMetadata { private BigInteger trackNumber; @Builder.Default private Optional<BigInteger> trackUID = Optional.empty(); @Builder.Default private String trackName = ""; @Builder.Default private String codecId = ""; @Builder.Default private String codecName = ""; private ByteBuffer codecPrivateData; // Video track specific @Builder.Default private Optional<BigInteger> pixelWidth = Optional.empty(); @Builder.Default private Optional<BigInteger> pixelHeight = Optional.empty(); // Audio track specific @Builder.Default private Optional<Double> samplingFrequency = Optional.empty(); @Builder.Default private Optional<BigInteger> channels = Optional.empty(); @Builder.Default private Optional<BigInteger> bitDepth = Optional.empty(); private List<MkvElement> allElementsInTrack; }
4,954
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/utilities/SimpleFrameVisitor.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.utilities; import com.amazonaws.kinesisvideo.parser.ebml.MkvTypeInfos; import com.amazonaws.kinesisvideo.parser.mkv.Frame; import com.amazonaws.kinesisvideo.parser.mkv.MkvElementVisitException; import com.amazonaws.kinesisvideo.parser.mkv.MkvElementVisitor; import com.amazonaws.kinesisvideo.parser.mkv.MkvValue; import com.amazonaws.kinesisvideo.parser.mkv.visitors.CompositeMkvElementVisitor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.NotImplementedException; import org.apache.commons.lang3.Validate; import java.math.BigInteger; /** * Fragment metdata tags will not be present as there is no tag when the data (mkv/webm) is not * retrieved from Kinesis video. * As a result, user cannot get the timestamp from fragment metadata tags. * This class is used to provide a FrameVisitor to process frame as well as time elements for timestamp. **/ @Slf4j public class SimpleFrameVisitor extends CompositeMkvElementVisitor { private final FrameVisitorInternal frameVisitorInternal; private final FrameProcessor frameProcessor; private SimpleFrameVisitor(FrameProcessor frameProcessor) { this.frameProcessor = frameProcessor; frameVisitorInternal = new FrameVisitorInternal(); childVisitors.add(frameVisitorInternal); } public static SimpleFrameVisitor create(FrameProcessor frameProcessor) { return new SimpleFrameVisitor(frameProcessor); } public interface FrameProcessor { default void process(Frame frame, long clusterTimeCode, long timeCodeScale) { throw new NotImplementedException("Default FrameVisitor with No Fragement MetaData"); } } private class FrameVisitorInternal extends MkvElementVisitor { private long clusterTimeCode = -1; private long timeCodeScale = -1; @Override public void visit(com.amazonaws.kinesisvideo.parser.mkv.MkvStartMasterElement startMasterElement) throws com.amazonaws.kinesisvideo.parser.mkv.MkvElementVisitException { } @Override public void visit(com.amazonaws.kinesisvideo.parser.mkv.MkvEndMasterElement endMasterElement) throws com.amazonaws.kinesisvideo.parser.mkv.MkvElementVisitException { } @Override public void visit(com.amazonaws.kinesisvideo.parser.mkv.MkvDataElement dataElement) throws com.amazonaws.kinesisvideo.parser.mkv.MkvElementVisitException { if (MkvTypeInfos.TIMECODE.equals(dataElement.getElementMetaData().getTypeInfo())) { clusterTimeCode = ((BigInteger) dataElement.getValueCopy().getVal()).longValue(); } if (MkvTypeInfos.TIMECODESCALE.equals(dataElement.getElementMetaData().getTypeInfo())) { timeCodeScale = ((BigInteger) dataElement.getValueCopy().getVal()).longValue(); } if (MkvTypeInfos.SIMPLEBLOCK.equals(dataElement.getElementMetaData().getTypeInfo())) { if (clusterTimeCode == -1 || timeCodeScale == -1) { throw new MkvElementVisitException("No timeCodeScale or timeCode found", new RuntimeException()); } final MkvValue<Frame> frame = dataElement.getValueCopy(); Validate.notNull(frame); frameProcessor.process(frame.getVal(), clusterTimeCode, timeCodeScale); } } } }
4,955
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/utilities/FragmentMetadataVisitor.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.utilities; import com.amazonaws.kinesisvideo.parser.ebml.EBMLElementMetaData; import com.amazonaws.kinesisvideo.parser.ebml.EBMLTypeInfo; import com.amazonaws.kinesisvideo.parser.ebml.MkvTypeInfos; import com.amazonaws.kinesisvideo.parser.mkv.MkvDataElement; import com.amazonaws.kinesisvideo.parser.mkv.MkvElement; import com.amazonaws.kinesisvideo.parser.mkv.MkvElementVisitException; import com.amazonaws.kinesisvideo.parser.mkv.MkvElementVisitor; import com.amazonaws.kinesisvideo.parser.mkv.MkvEndMasterElement; import com.amazonaws.kinesisvideo.parser.mkv.MkvStartMasterElement; import com.amazonaws.kinesisvideo.parser.mkv.MkvValue; import com.amazonaws.kinesisvideo.parser.mkv.visitors.CompositeMkvElementVisitor; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.NotImplementedException; import org.apache.commons.lang3.Validate; import java.math.BigInteger; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.OptionalLong; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; /** * This class captures the fragment and track meta-data from the GetMedia output. * It uses multiple visitors to capture all the tags, track information as well as detecting the start and end * of segments and clusters. */ @Slf4j public class FragmentMetadataVisitor extends CompositeMkvElementVisitor { private static final String MILLIS_BEHIND_NOW_KEY = "AWS_KINESISVIDEO_MILLIS_BEHIND_NOW"; private static final String CONTINUATION_TOKEN_KEY = "AWS_KINESISVIDEO_CONTINUATION_TOKEN"; private static final EBMLTypeInfo[] TRACK_TYPES = new EBMLTypeInfo [] { MkvTypeInfos.TRACKNUMBER, MkvTypeInfos.TRACKUID, MkvTypeInfos.NAME, MkvTypeInfos.CODECID, MkvTypeInfos.CODECNAME, MkvTypeInfos.CODECPRIVATE, MkvTypeInfos.PIXELWIDTH, MkvTypeInfos.PIXELHEIGHT }; private static final String AWS_KINESISVIDEO_TAGNAME_PREFIX = "AWS_KINESISVIDEO"; public interface MkvTagProcessor { default void process(MkvTag mkvTag, Optional<FragmentMetadata> currentFragmentMetadata) { throw new NotImplementedException("Default FragmentMetadataVisitor.MkvTagProcessor"); } default void clear() { throw new NotImplementedException("Default FragmentMetadataVisitor.MkvTagProcessor"); } } private final MkvChildElementCollector tagCollector; private final MkvChildElementCollector trackCollector; private final StateMachineVisitor stateMachineVisitor; private final Optional<MkvTagProcessor> mkvTagProcessor; private final Set<EBMLTypeInfo> trackTypesForTrackMetadata = new HashSet(); @Getter private Optional<FragmentMetadata> previousFragmentMetadata = Optional.empty(); @Getter private Optional<FragmentMetadata> currentFragmentMetadata = Optional.empty(); private OptionalLong millisBehindNow = OptionalLong.empty(); private Optional<String> continuationToken = Optional.empty(); private final Map<BigInteger, MkvTrackMetadata> trackMetadataMap = new HashMap(); private String tagName = null; private String tagValue = null; private FragmentMetadataVisitor(List<MkvElementVisitor> childVisitors, MkvChildElementCollector tagCollector, MkvChildElementCollector trackCollector, Optional<MkvTagProcessor> mkvTagProcessor) { super(childVisitors); Validate.isTrue(tagCollector.getParentTypeInfo().equals(MkvTypeInfos.TAGS)); Validate.isTrue(trackCollector.getParentTypeInfo().equals(MkvTypeInfos.TRACKS)); this.tagCollector = tagCollector; this.trackCollector = trackCollector; this.stateMachineVisitor = new StateMachineVisitor(); this.childVisitors.add(stateMachineVisitor); this.mkvTagProcessor = mkvTagProcessor; for (EBMLTypeInfo trackType : TRACK_TYPES) { this.trackTypesForTrackMetadata.add(trackType); } } public static FragmentMetadataVisitor create() { return create(Optional.empty()); } public static FragmentMetadataVisitor create(Optional<MkvTagProcessor> mkvTagProcessor) { final List<MkvElementVisitor> childVisitors = new ArrayList<>(); final MkvChildElementCollector tagCollector = new MkvChildElementCollector(MkvTypeInfos.TAGS); final MkvChildElementCollector trackCollector = new MkvChildElementCollector(MkvTypeInfos.TRACKS); childVisitors.add(tagCollector); childVisitors.add(trackCollector); return new FragmentMetadataVisitor(childVisitors, tagCollector, trackCollector, mkvTagProcessor); } enum State {NEW, PRE_CLUSTER, IN_CLUSTER, POST_CLUSTER} private class StateMachineVisitor extends MkvElementVisitor { State state = State.NEW; @Override public void visit(MkvStartMasterElement startMasterElement) throws MkvElementVisitException { switch (state) { case NEW: if (MkvTypeInfos.SEGMENT.equals(startMasterElement.getElementMetaData().getTypeInfo())) { log.debug("Segment start {} changing state to PRE_CLUSTER", startMasterElement); resetCollectedData(); state = State.PRE_CLUSTER; } break; case PRE_CLUSTER: if (MkvTypeInfos.CLUSTER.equals(startMasterElement.getElementMetaData().getTypeInfo())) { log.debug("Cluster start {} changing state to IN_CLUSTER", startMasterElement); collectPreClusterInfo(); state = State.IN_CLUSTER; } break; default: break; } } @Override public void visit(MkvEndMasterElement endMasterElement) throws MkvElementVisitException { switch (state) { case IN_CLUSTER: if (MkvTypeInfos.CLUSTER.equals(endMasterElement.getElementMetaData().getTypeInfo())) { state = State.POST_CLUSTER; } break; case POST_CLUSTER: if (MkvTypeInfos.SEGMENT.equals(endMasterElement.getElementMetaData().getTypeInfo())) { log.debug("Segment end {} changing state to NEW", endMasterElement); state = State.NEW; } break; case PRE_CLUSTER: if (MkvTypeInfos.SEGMENT.equals(endMasterElement.getElementMetaData().getTypeInfo())) { log.warn("Segment end {} while in PRE_CLUSTER. Collecting cluster info", endMasterElement); collectPreClusterInfo(); } break; default: break; } // If any tags section finishes, try to update the millisbehind latest and continuation token // since there can be multiple in the same segment. if (MkvTypeInfos.TAGS.equals(endMasterElement.getElementMetaData().getTypeInfo())) { if (log.isDebugEnabled()) { log.debug("TAGS end {}, potentially updating millisbehindlatest and continuation token", endMasterElement); } setMillisBehindLatestAndContinuationToken(); } } @Override public void visit(MkvDataElement dataElement) throws MkvElementVisitException { if (mkvTagProcessor.isPresent()) { if (MkvTypeInfos.TAGNAME.equals(dataElement.getElementMetaData().getTypeInfo())) { tagName = getMkvElementStringVal(dataElement); } else if (MkvTypeInfos.TAGSTRING.equals(dataElement.getElementMetaData().getTypeInfo())) { tagValue = getMkvElementStringVal(dataElement); } if (tagName != null && tagValue != null) { // Only process non-internal tags if (!tagName.startsWith(AWS_KINESISVIDEO_TAGNAME_PREFIX)) { mkvTagProcessor.get().process(new MkvTag(tagName, tagValue), currentFragmentMetadata); } // Empty the values for new tag tagName = null; tagValue = null; } } } } public MkvTrackMetadata getMkvTrackMetadata(long trackNumber) { return trackMetadataMap.get(BigInteger.valueOf(trackNumber)); } public OptionalLong getMillisBehindNow() { return millisBehindNow; } public Optional<String> getContinuationToken() { return continuationToken; } private void setMillisBehindLatestAndContinuationToken() { final Map<String, String> tagNameToTagValueMap = getTagNameToValueMap(); //Do not overwrite an existing value with Optional.absent String millisBehindString = tagNameToTagValueMap.get(MILLIS_BEHIND_NOW_KEY); if (millisBehindString != null) { millisBehindNow = (OptionalLong.of(Long.parseLong(millisBehindString))); currentFragmentMetadata.ifPresent(f -> f.setMillisBehindNow(millisBehindNow)); } String continutationTokenString = tagNameToTagValueMap.get(CONTINUATION_TOKEN_KEY); if (continutationTokenString != null) { continuationToken = Optional.of(continutationTokenString); currentFragmentMetadata.ifPresent(f -> f.setContinuationToken(continuationToken)); } } private void collectPreClusterInfo() { final Map<String, String> tagNameToTagValueMap = getTagNameToValueMap(); currentFragmentMetadata = Optional.ofNullable(FragmentMetadata.createFromtagNametoValueMap(tagNameToTagValueMap)); final Map<Long, List<MkvElement>> trackEntryElementNumberToMkvElement = getTrackEntryMap(); trackEntryElementNumberToMkvElement.values().stream().forEach(this::createTrackMetadata); } private Map<Long, List<MkvElement>> getTrackEntryMap() { final Map<Long,List<MkvElement>> trackEntryElementNumberToMkvElement = new HashMap<>(); List<MkvElement> trackElements = trackCollector.copyOfCollection(); trackElements .stream() .filter(e -> MkvTypeInfos.TRACKENTRY.equals(e.getElementMetaData().getTypeInfo())) .forEach(e -> trackEntryElementNumberToMkvElement.put(e.getElementMetaData().getElementNumber(), new ArrayList<>())); trackElements.stream() .filter(e -> e.getElementMetaData().getTypeInfo().getLevel() > MkvTypeInfos.TRACKENTRY.getLevel()) .forEach(e -> { EBMLElementMetaData trackEntryParent = e.getElementPath().get(MkvTypeInfos.TRACKENTRY.getLevel()); Validate.isTrue(MkvTypeInfos.TRACKENTRY.equals(trackEntryParent.getTypeInfo())); trackEntryElementNumberToMkvElement.get(trackEntryParent.getElementNumber()).add(e); }); return trackEntryElementNumberToMkvElement; } private void createTrackMetadata(List<MkvElement> trackEntryPropertyLists) { Map<EBMLTypeInfo, MkvElement> metaDataProperties = trackEntryPropertyLists.stream() .filter(e -> trackTypesForTrackMetadata.contains(e.getElementMetaData().getTypeInfo())) .collect(Collectors.toMap(e -> e.getElementMetaData().getTypeInfo(), Function.identity())); MkvTrackMetadata mkvTrackMetadata = MkvTrackMetadata.builder() .trackNumber(getUnsignedLongVal(metaDataProperties, MkvTypeInfos.TRACKNUMBER)) .trackUID(getUnsignedLongValOptional(metaDataProperties, MkvTypeInfos.TRACKUID)) .trackName(getStringVal(metaDataProperties, MkvTypeInfos.NAME)) .codecId(getStringVal(metaDataProperties, MkvTypeInfos.CODECID)) .codecName(getStringVal(metaDataProperties, MkvTypeInfos.CODECNAME)) .codecPrivateData(getByteBuffer(metaDataProperties, MkvTypeInfos.CODECPRIVATE)) .pixelWidth(getUnsignedLongValOptional(metaDataProperties, MkvTypeInfos.PIXELWIDTH)) .pixelHeight(getUnsignedLongValOptional(metaDataProperties, MkvTypeInfos.PIXELHEIGHT)) .samplingFrequency(getFloatingPointValOptional(metaDataProperties, MkvTypeInfos.SAMPLINGFREQUENCY)) .channels(getUnsignedLongValOptional(metaDataProperties, MkvTypeInfos.CHANNELS)) .bitDepth(getUnsignedLongValOptional(metaDataProperties, MkvTypeInfos.BITDEPTH)) .allElementsInTrack(trackEntryPropertyLists) .build(); trackMetadataMap.put(mkvTrackMetadata.getTrackNumber(), mkvTrackMetadata); } private static String getStringVal(Map<EBMLTypeInfo, MkvElement> metaDataProperties, EBMLTypeInfo key) { MkvElement element = metaDataProperties.get(key); if (element == null) { return null; } MkvDataElement dataElement = (MkvDataElement)element; Validate.isTrue(EBMLTypeInfo.TYPE.STRING.equals(dataElement.getElementMetaData().getTypeInfo().getType()) || EBMLTypeInfo.TYPE.UTF_8.equals(dataElement.getElementMetaData().getTypeInfo().getType())); return ((MkvValue<String>)dataElement.getValueCopy()).getVal(); } private static Optional<BigInteger> getUnsignedLongValOptional(Map<EBMLTypeInfo, MkvElement> metaDataProperties, EBMLTypeInfo key) { return Optional.ofNullable(getUnsignedLongVal(metaDataProperties, key)); } private static BigInteger getUnsignedLongVal(Map<EBMLTypeInfo, MkvElement> metaDataProperties, EBMLTypeInfo key) { MkvElement element = metaDataProperties.get(key); if (element == null) { return null; } MkvDataElement dataElement = (MkvDataElement) element; Validate.isTrue(EBMLTypeInfo.TYPE.UINTEGER.equals(dataElement.getElementMetaData().getTypeInfo().getType())); return ((MkvValue<BigInteger>) dataElement.getValueCopy()).getVal(); } private static Optional<Double> getFloatingPointValOptional(Map<EBMLTypeInfo, MkvElement> metaDataProperties, EBMLTypeInfo key) { return Optional.ofNullable(getFloatingPointVal(metaDataProperties, key)); } private static Double getFloatingPointVal(Map<EBMLTypeInfo, MkvElement> metaDataProperties, EBMLTypeInfo key) { MkvElement element = metaDataProperties.get(key); if (element == null) { return null; } MkvDataElement dataElement = (MkvDataElement) element; Validate.isTrue(EBMLTypeInfo.TYPE.FLOAT.equals(dataElement.getElementMetaData().getTypeInfo().getType())); return ((MkvValue<Double>) dataElement.getValueCopy()).getVal(); } private static ByteBuffer getByteBuffer(Map<EBMLTypeInfo, MkvElement> metaDataProperties, EBMLTypeInfo key) { MkvElement element = metaDataProperties.get(key); if (element == null) { return null; } MkvDataElement dataElement = (MkvDataElement)element; Validate.isTrue(EBMLTypeInfo.TYPE.BINARY.equals(dataElement.getElementMetaData().getTypeInfo().getType())); return ((MkvValue<ByteBuffer>)dataElement.getValueCopy()).getVal(); } private Map<String, String> getTagNameToValueMap() { List<MkvElement> tagElements = tagCollector.copyOfCollection(); Map<String, Long> tagNameToParentElementNumber = tagElements.stream() .filter(e -> MkvTypeInfos.TAGNAME.equals(e.getElementMetaData().getTypeInfo())) .filter(e -> MkvTypeInfos.SIMPLETAG.equals(getParentElement(e).getTypeInfo())) .filter(e -> isTagFromKinesisVideo((MkvDataElement) e)) .collect(Collectors.toMap(this::getMkvElementStringVal, e -> getParentElement(e).getElementNumber(), (a,b)->b)); Map<Long, String> parentElementNumberToTagValue = tagElements.stream() .filter(e -> MkvTypeInfos.TAGSTRING.equals(e.getElementMetaData().getTypeInfo())) .filter(e -> MkvTypeInfos.SIMPLETAG.equals(getParentElement(e).getTypeInfo())) .collect(Collectors.toMap(e -> getParentElement(e).getElementNumber(), this::getMkvElementStringVal)); return tagNameToParentElementNumber.entrySet() .stream() .collect(Collectors.toMap(e -> e.getKey(), e -> parentElementNumberToTagValue.getOrDefault(e.getValue(),""))); } private static boolean isTagFromKinesisVideo(MkvDataElement e) { MkvValue<String> tagNameValue = e.getValueCopy(); return tagNameValue.getVal().startsWith(AWS_KINESISVIDEO_TAGNAME_PREFIX); } private String getMkvElementStringVal(MkvElement e) { return ((MkvValue<String>) ((MkvDataElement) e).getValueCopy()).getVal(); } private static EBMLElementMetaData getParentElement(MkvElement e) { return e.getElementPath().get(e.getElementPath().size()-1); } private void resetCollectedData() { previousFragmentMetadata = currentFragmentMetadata; currentFragmentMetadata = Optional.empty(); trackMetadataMap.clear(); tagName = tagValue = null; tagCollector.clearCollection(); trackCollector.clearCollection(); } public static final class BasicMkvTagProcessor implements FragmentMetadataVisitor.MkvTagProcessor { @Getter private List<MkvTag> tags = new ArrayList<>(); @Override public void process(MkvTag mkvTag, Optional<FragmentMetadata> currentFragmentMetadata) { tags.add(mkvTag); } @Override public void clear() { tags.clear(); } } }
4,956
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/utilities/H264BoundingBoxFrameRenderer.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.utilities; import java.awt.image.BufferedImage; import java.util.List; import java.util.Optional; import com.amazonaws.kinesisvideo.parser.examples.KinesisVideoBoundingBoxFrameViewer; import com.amazonaws.kinesisvideo.parser.mkv.Frame; import com.amazonaws.kinesisvideo.parser.mkv.FrameProcessException; import com.amazonaws.kinesisvideo.parser.rekognition.pojo.RekognizedFragmentsIndex; import com.amazonaws.kinesisvideo.parser.rekognition.pojo.RekognizedOutput; import lombok.Setter; import lombok.extern.slf4j.Slf4j; @Slf4j public class H264BoundingBoxFrameRenderer extends H264FrameRenderer { private static final int DEFAULT_MAX_TIMEOUT = 100; private static final int WAIT_TIMEOUT = 3; private static final int MILLIS_IN_SEC = 1000; private static final int OFFSET_DELTA_THRESHOLD = 10; private final KinesisVideoBoundingBoxFrameViewer kinesisVideoBoundingBoxFrameViewer; private final RekognizedFragmentsIndex rekognizedFragmentsIndex; private RekognizedOutput currentRekognizedOutput = null; @Setter private int maxTimeout = DEFAULT_MAX_TIMEOUT; private long keyFrameTimecode; private H264BoundingBoxFrameRenderer(final KinesisVideoBoundingBoxFrameViewer kinesisVideoBoundingBoxFrameViewer, final RekognizedFragmentsIndex rekognizedFragmentsIndex) { super(kinesisVideoBoundingBoxFrameViewer); this.kinesisVideoBoundingBoxFrameViewer = kinesisVideoBoundingBoxFrameViewer; this.rekognizedFragmentsIndex = rekognizedFragmentsIndex; } public static H264BoundingBoxFrameRenderer create(final KinesisVideoBoundingBoxFrameViewer kinesisVideoBoundingBoxFrameViewer, final RekognizedFragmentsIndex rekognizedFragmentsIndex) { return new H264BoundingBoxFrameRenderer(kinesisVideoBoundingBoxFrameViewer, rekognizedFragmentsIndex); } @Override public void process(final Frame frame, final MkvTrackMetadata trackMetadata, final Optional<FragmentMetadata> fragmentMetadata, final Optional<FragmentMetadataVisitor.MkvTagProcessor> tagProcessor) throws FrameProcessException { final BufferedImage bufferedImage = decodeH264Frame(frame, trackMetadata); final Optional<RekognizedOutput> rekognizedOutput = getRekognizedOutput(frame, fragmentMetadata); renderFrame(bufferedImage, rekognizedOutput); } private Optional<RekognizedOutput> getRekognizedOutput(final Frame frame, final Optional<FragmentMetadata> fragmentMetadata) { Optional<RekognizedOutput> rekognizedOutput = Optional.empty(); if (rekognizedFragmentsIndex != null && fragmentMetadata.isPresent()) { final String fragmentNumber = fragmentMetadata.get().getFragmentNumberString(); int timeout = 0; List<RekognizedOutput> rekognizedOutputs = null; // if rekognizedOutputs is null then Rekognition did not return the results for this fragment. // Wait until the results are received. while (true) { rekognizedOutputs = rekognizedFragmentsIndex.getRekognizedOutputList(fragmentNumber); if (rekognizedOutputs != null) { break; } else { timeout += waitForResults(WAIT_TIMEOUT); if (timeout >= maxTimeout) { log.warn("No rekognized result after waiting for {} ms ", timeout); break; } } } if (rekognizedOutputs != null) { // Currently Rekognition samples frames and calculates the frame offset from the fragment start time. // So, in order to match with rekognition results, we have to compute the same frame offset from the // beginning of the fragments. if (frame.isKeyFrame()) { keyFrameTimecode = frame.getTimeCode(); log.debug("Key frame timecode : {}", keyFrameTimecode); } final long frameOffset = (frame.getTimeCode() > keyFrameTimecode) ? frame.getTimeCode() - keyFrameTimecode : 0; log.debug("Current Fragment Number : {} Computed Frame offset : {}", fragmentNumber, frameOffset); if (log.isDebugEnabled()) { rekognizedOutputs .forEach(p -> log.debug("frameOffsetInSeconds from Rekognition : {}", p.getFrameOffsetInSeconds())); } // Check whether the computed offset matches the rekognized output frame offset. Rekognition // output is in seconds whereas the frame offset is calculated in milliseconds. // NOTE: Rekognition frame offset doesn't exactly match with the computed offset below. So // take the closest one possible within 10ms delta. rekognizedOutput = rekognizedOutputs.stream() .filter(p -> isOffsetDeltaWithinThreshold(frameOffset, p)) .findFirst(); // Remove from the index once the RekognizedOutput is processed. Else it would increase the memory // footprint and blow up the JVM. if (rekognizedOutput.isPresent()) { log.debug("Computed offset matched with retrieved offset. Delta : {}", Math.abs(frameOffset - (rekognizedOutput.get().getFrameOffsetInSeconds() * MILLIS_IN_SEC))); rekognizedOutputs.remove(rekognizedOutput.get()); if (rekognizedOutputs.isEmpty()) { log.debug("All frames processed for this fragment number : {}", fragmentNumber); rekognizedFragmentsIndex.remove(fragmentNumber); } } } } return rekognizedOutput; } private boolean isOffsetDeltaWithinThreshold(final long frameOffset, final RekognizedOutput output) { return Math.abs(frameOffset - (output.getFrameOffsetInSeconds() * MILLIS_IN_SEC)) <= OFFSET_DELTA_THRESHOLD; } void renderFrame(final BufferedImage bufferedImage, final Optional<RekognizedOutput> rekognizedOutput) { if (rekognizedOutput.isPresent()) { System.out.println("Rendering Rekognized sampled frame..."); kinesisVideoBoundingBoxFrameViewer.update(bufferedImage, rekognizedOutput.get()); currentRekognizedOutput = rekognizedOutput.get(); } else if (currentRekognizedOutput != null) { System.out.println("Rendering non-sampled frame with previous rekognized results..."); kinesisVideoBoundingBoxFrameViewer.update(bufferedImage, currentRekognizedOutput); } else { System.out.println("Rendering frame without any rekognized results..."); kinesisVideoBoundingBoxFrameViewer.update(bufferedImage); } } private long waitForResults(final long timeout) { final long startTime = System.currentTimeMillis(); try { log.info("No rekognized results for this fragment number. Waiting ...."); Thread.sleep(timeout); } catch (final InterruptedException e) { log.warn("Error while waiting for rekognized output !", e); } return System.currentTimeMillis() - startTime; } }
4,957
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/utilities/FrameRendererVisitor.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.utilities; import java.awt.image.BufferedImage; import java.nio.ByteBuffer; import java.util.List; import com.amazonaws.kinesisvideo.parser.examples.KinesisVideoFrameViewer; import com.amazonaws.kinesisvideo.parser.mkv.Frame; import com.amazonaws.kinesisvideo.parser.mkv.MkvDataElement; import com.amazonaws.kinesisvideo.parser.mkv.MkvElementVisitException; import com.amazonaws.kinesisvideo.parser.mkv.MkvElementVisitor; import com.amazonaws.kinesisvideo.parser.mkv.MkvEndMasterElement; import com.amazonaws.kinesisvideo.parser.mkv.MkvStartMasterElement; import com.amazonaws.kinesisvideo.parser.mkv.MkvValue; import com.amazonaws.kinesisvideo.parser.mkv.visitors.CompositeMkvElementVisitor; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.jcodec.codecs.h264.H264Decoder; import org.jcodec.codecs.h264.mp4.AvcCBox; import org.jcodec.common.model.ColorSpace; import org.jcodec.common.model.Picture; import org.jcodec.scale.AWTUtil; import org.jcodec.scale.Transform; import org.jcodec.scale.Yuv420jToRgb; import static org.jcodec.codecs.h264.H264Utils.splitMOVPacket; @Slf4j public class FrameRendererVisitor extends CompositeMkvElementVisitor { private final KinesisVideoFrameViewer kinesisVideoFrameViewer; private final FragmentMetadataVisitor fragmentMetadataVisitor; private final FrameVisitorInternal frameVisitorInternal; private final H264Decoder decoder = new H264Decoder(); private final Transform transform = new Yuv420jToRgb(); @Getter private int frameCount; private byte[] codecPrivateData; private FrameRendererVisitor(final FragmentMetadataVisitor fragmentMetadataVisitor, final KinesisVideoFrameViewer kinesisVideoFrameViewer) { super(fragmentMetadataVisitor); this.fragmentMetadataVisitor = fragmentMetadataVisitor; this.kinesisVideoFrameViewer = kinesisVideoFrameViewer; this.kinesisVideoFrameViewer.setVisible(true); this.frameVisitorInternal = new FrameVisitorInternal(); this.childVisitors.add(this.frameVisitorInternal); } public static FrameRendererVisitor create(final KinesisVideoFrameViewer kinesisVideoFrameViewer) { return new FrameRendererVisitor( com.amazonaws.kinesisvideo.parser.utilities.FragmentMetadataVisitor.create(), kinesisVideoFrameViewer); } public ByteBuffer getCodecPrivateData() { return ByteBuffer.wrap(codecPrivateData); } private class FrameVisitorInternal extends MkvElementVisitor { @Override public void visit(final MkvStartMasterElement startMasterElement) throws MkvElementVisitException { } @Override public void visit(final MkvEndMasterElement endMasterElement) throws MkvElementVisitException { } @Override public void visit(final MkvDataElement dataElement) throws MkvElementVisitException { log.info("Got data element: {}", dataElement.getElementMetaData().getTypeInfo().getName()); final String dataElementName = dataElement.getElementMetaData().getTypeInfo().getName(); if ("SimpleBlock".equals(dataElementName)) { final MkvValue<Frame> frame = dataElement.getValueCopy(); final ByteBuffer frameBuffer = frame.getVal().getFrameData(); final MkvTrackMetadata trackMetadata = fragmentMetadataVisitor.getMkvTrackMetadata( frame.getVal().getTrackNumber()); final int pixelWidth = trackMetadata.getPixelWidth().get().intValue(); final int pixelHeight = trackMetadata.getPixelHeight().get().intValue(); codecPrivateData = trackMetadata.getCodecPrivateData().array(); log.debug("Decoding frames ... "); // Read the bytes that appear to comprise the header // See: https://www.matroska.org/technical/specs/index.html#simpleblock_structure final Picture rgb = Picture.create(pixelWidth, pixelHeight, ColorSpace.RGB); final BufferedImage renderImage = new BufferedImage( pixelWidth, pixelHeight, BufferedImage.TYPE_3BYTE_BGR); final AvcCBox avcC = AvcCBox.parseAvcCBox(ByteBuffer.wrap(codecPrivateData)); decoder.addSps(avcC.getSpsList()); decoder.addPps(avcC.getPpsList()); final Picture buf = Picture.create(pixelWidth + ((16 - (pixelWidth % 16)) % 16), pixelHeight + ((16 - (pixelHeight % 16)) % 16), ColorSpace.YUV420J); final List<ByteBuffer> byteBuffers = splitMOVPacket(frameBuffer, avcC); final Picture pic = decoder.decodeFrameFromNals(byteBuffers, buf.getData()); if (pic != null) { // Work around for color issues in JCodec // https://github.com/jcodec/jcodec/issues/59 // https://github.com/jcodec/jcodec/issues/192 final byte[][] dataTemp = new byte[3][pic.getData().length]; dataTemp[0] = pic.getPlaneData(0); dataTemp[1] = pic.getPlaneData(2); dataTemp[2] = pic.getPlaneData(1); final Picture tmpBuf = Picture.createPicture(pixelWidth, pixelHeight, dataTemp, ColorSpace.YUV420J); transform.transform(tmpBuf, rgb); AWTUtil.toBufferedImage(rgb, renderImage); kinesisVideoFrameViewer.update(renderImage); frameCount++; } } } } }
4,958
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/utilities/H264FrameDecoder.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.utilities; import com.amazonaws.kinesisvideo.parser.mkv.Frame; import com.amazonaws.kinesisvideo.parser.mkv.FrameProcessException; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.jcodec.codecs.h264.H264Decoder; import org.jcodec.codecs.h264.mp4.AvcCBox; import org.jcodec.common.model.ColorSpace; import org.jcodec.common.model.Picture; import org.jcodec.scale.AWTUtil; import org.jcodec.scale.Transform; import org.jcodec.scale.Yuv420jToRgb; import java.awt.image.BufferedImage; import java.nio.ByteBuffer; import java.util.List; import java.util.Optional; import static org.jcodec.codecs.h264.H264Utils.splitMOVPacket; /** * H264 Frame Decoder class which uses JCodec decoder to decode frames. */ @Slf4j public class H264FrameDecoder implements FrameVisitor.FrameProcessor { private final H264Decoder decoder = new H264Decoder(); private final Transform transform = new Yuv420jToRgb(); @Getter private int frameCount; private byte[] codecPrivateData; @Override public void process(final Frame frame, final MkvTrackMetadata trackMetadata, final Optional<FragmentMetadata> fragmentMetadata) throws FrameProcessException { decodeH264Frame(frame, trackMetadata); } public BufferedImage decodeH264Frame(final Frame frame, final MkvTrackMetadata trackMetadata) { final ByteBuffer frameBuffer = frame.getFrameData(); final int pixelWidth = trackMetadata.getPixelWidth().get().intValue(); final int pixelHeight = trackMetadata.getPixelHeight().get().intValue(); codecPrivateData = trackMetadata.getCodecPrivateData().array(); log.debug("Decoding frames ... "); // Read the bytes that appear to comprise the header // See: https://www.matroska.org/technical/specs/index.html#simpleblock_structure final Picture rgb = Picture.create(pixelWidth, pixelHeight, ColorSpace.RGB); final BufferedImage bufferedImage = new BufferedImage(pixelWidth, pixelHeight, BufferedImage.TYPE_3BYTE_BGR); final AvcCBox avcC = AvcCBox.parseAvcCBox(ByteBuffer.wrap(codecPrivateData)); decoder.addSps(avcC.getSpsList()); decoder.addPps(avcC.getPpsList()); final Picture buf = Picture.create(pixelWidth + ((16 - (pixelWidth % 16)) % 16), pixelHeight + ((16 - (pixelHeight % 16)) % 16), ColorSpace.YUV420J); final List<ByteBuffer> byteBuffers = splitMOVPacket(frameBuffer, avcC); final Picture pic = decoder.decodeFrameFromNals(byteBuffers, buf.getData()); if (pic != null) { // Work around for color issues in JCodec // https://github.com/jcodec/jcodec/issues/59 // https://github.com/jcodec/jcodec/issues/192 final byte[][] dataTemp = new byte[3][pic.getData().length]; dataTemp[0] = pic.getPlaneData(0); dataTemp[1] = pic.getPlaneData(2); dataTemp[2] = pic.getPlaneData(1); final Picture tmpBuf = Picture.createPicture(pixelWidth, pixelHeight, dataTemp, ColorSpace.YUV420J); transform.transform(tmpBuf, rgb); AWTUtil.toBufferedImage(rgb, bufferedImage); frameCount++; } return bufferedImage; } public ByteBuffer getCodecPrivateData() { return ByteBuffer.wrap(codecPrivateData); } }
4,959
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/utilities/DynamoDBHelper.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.utilities; import com.amazonaws.ClientConfiguration; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.regions.Regions; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient; import com.amazonaws.services.dynamodbv2.model.AmazonDynamoDBException; import com.amazonaws.services.dynamodbv2.model.AttributeDefinition; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.dynamodbv2.model.AttributeValueUpdate; import com.amazonaws.services.dynamodbv2.model.CreateTableRequest; import com.amazonaws.services.dynamodbv2.model.CreateTableResult; import com.amazonaws.services.dynamodbv2.model.DescribeTableRequest; import com.amazonaws.services.dynamodbv2.model.GetItemRequest; import com.amazonaws.services.dynamodbv2.model.KeySchemaElement; import com.amazonaws.services.dynamodbv2.model.KeyType; import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput; import com.amazonaws.services.dynamodbv2.model.PutItemRequest; import com.amazonaws.services.dynamodbv2.model.PutItemResult; import com.amazonaws.services.dynamodbv2.model.ResourceNotFoundException; import com.amazonaws.services.dynamodbv2.model.ScalarAttributeType; import com.amazonaws.services.dynamodbv2.model.TableDescription; import com.amazonaws.services.dynamodbv2.model.UpdateItemRequest; import com.amazonaws.services.dynamodbv2.model.UpdateItemResult; import lombok.extern.slf4j.Slf4j; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * DynamoDB helper class to access FragmentCheckpoint table. Used by the KinesisVideoRekognitionLambdaExample to save * fragment checkpoints between successive lambda executions. */ @Slf4j public class DynamoDBHelper { private static final String TABLE_NAME = "FragmentCheckpoint"; private static final String KVS_STREAM_NAME = "KVSStreamName"; private static final String FRAGMENT_NUMBER = "FragmentNumber"; private static final String SERVER_TIME = "ServerTime"; private static final String PRODUCER_TIME = "ProducerTime"; private static final String UPDATED_TIME = "UpdatedTime"; private final AmazonDynamoDB ddbClient; public DynamoDBHelper(final Regions region, final AWSCredentialsProvider credentialsProvider) { final ClientConfiguration clientConfiguration = new ClientConfiguration() .withConnectionTimeout(ClientConfiguration.DEFAULT_CONNECTION_TIMEOUT) .withRetryPolicy(ClientConfiguration.DEFAULT_RETRY_POLICY) .withRequestTimeout(ClientConfiguration.DEFAULT_REQUEST_TIMEOUT) .withSocketTimeout(ClientConfiguration.DEFAULT_SOCKET_TIMEOUT); ddbClient = AmazonDynamoDBClient.builder() .withClientConfiguration(clientConfiguration) .withCredentials(credentialsProvider) .withRegion(region) .build(); } /** * Creates the FragmentCheckpoint table if it doesn't exist already. */ public void createTableIfDoesntExist() { // Check if table exists if (!checkIfTableExists()) { log.info("Creating table : {}", TABLE_NAME); final CreateTableRequest request = new CreateTableRequest() {{ setAttributeDefinitions( Collections.singletonList( new AttributeDefinition( KVS_STREAM_NAME, ScalarAttributeType.S))); setKeySchema( Collections.singletonList( new KeySchemaElement( KVS_STREAM_NAME, KeyType.HASH))); setProvisionedThroughput( new ProvisionedThroughput(1000L, 1000L)); setTableName(TABLE_NAME); }}; try { final CreateTableResult result = ddbClient.createTable(request); log.info("Table created : {}", result.getTableDescription()); } catch (final AmazonDynamoDBException e) { log.error("Error creating DDB table {}...", TABLE_NAME, e); throw e; } } } private boolean checkIfTableExists() { try { final DescribeTableRequest request = new DescribeTableRequest() {{ setTableName(TABLE_NAME); }}; final TableDescription table_info = ddbClient.describeTable(request).getTable(); log.info("Table exists : {}", table_info.getTableName()); return true; } catch (final ResourceNotFoundException e) { log.warn("{} table doesn't exist !", TABLE_NAME); } catch (final AmazonDynamoDBException e) { log.warn("Error while describing table!", e); } return false; } /** * Gets the FragmentCheckpoint item from the table for the specified stream name. * * @param streamName Input stream name * @return FragmentCheckpoint entry. null if any exception is thrown. */ public Map<String, AttributeValue> getItem(final String streamName) { try { final Map<String,AttributeValue> key = new HashMap<>(); key.put(KVS_STREAM_NAME, new AttributeValue().withS(streamName)); final GetItemRequest getItemRequest = new GetItemRequest() {{ setTableName(TABLE_NAME); setKey(key); }}; return ddbClient.getItem(getItemRequest).getItem(); } catch (final AmazonDynamoDBException e) { log.warn("Error while getting item from table!", e); } return null; } /** * Put item into FragmentCheckpoint table for the given input parameters * * @param streamName KVS Stream name * @param fragmentNumber Last processed fragment's fragment number * @param producerTime Last processed fragment's producer time * @param serverTime Last processed fragment's server time * @param updatedTime Time when the entry is going to be updated. */ public void putItem(final String streamName, final String fragmentNumber, final Long producerTime, final Long serverTime, final Long updatedTime) { try { final Map<String,AttributeValue> item = new HashMap<>(); item.put(KVS_STREAM_NAME, new AttributeValue().withS(streamName)); item.put(FRAGMENT_NUMBER, new AttributeValue().withS(fragmentNumber)); item.put(UPDATED_TIME, new AttributeValue().withN(updatedTime.toString())); item.put(PRODUCER_TIME, new AttributeValue().withN(producerTime.toString())); item.put(SERVER_TIME, new AttributeValue().withN(serverTime.toString())); final PutItemRequest putItemRequest = new PutItemRequest() {{ setTableName(TABLE_NAME); setItem(item); }}; final PutItemResult result = ddbClient.putItem(putItemRequest); log.info("Item saved : ", result.getAttributes()); } catch (final Exception e) { log.warn("Error while putting item into the table!", e); } } /** * Update item into FragmentCheckpoint table for the given input parameters * * @param streamName KVS Stream name * @param fragmentNumber Last processed fragment's fragment number * @param producerTime Last processed fragment's producer time * @param serverTime Last processed fragment's server time * @param updatedTime Time when the entry is going to be updated. */ public void updateItem(final String streamName, final String fragmentNumber, final Long producerTime, final Long serverTime, final Long updatedTime) { try { final Map<String,AttributeValue> key = new HashMap<>(); key.put(KVS_STREAM_NAME, new AttributeValue().withS(streamName)); final Map<String,AttributeValueUpdate> updates = new HashMap<>(); updates.put(FRAGMENT_NUMBER, new AttributeValueUpdate().withValue( new AttributeValue().withS(fragmentNumber))); updates.put(UPDATED_TIME, new AttributeValueUpdate().withValue( new AttributeValue().withN(updatedTime.toString()))); updates.put(PRODUCER_TIME, new AttributeValueUpdate().withValue( new AttributeValue().withN(producerTime.toString()))); updates.put(SERVER_TIME, new AttributeValueUpdate().withValue( new AttributeValue().withN(serverTime.toString()))); final UpdateItemRequest updateItemRequest = new UpdateItemRequest() {{ setTableName(TABLE_NAME); setKey(key); setAttributeUpdates(updates); }}; final UpdateItemResult result = ddbClient.updateItem(updateItemRequest); log.info("Item updated : {}", result.getAttributes()); } catch (final Exception e) { log.warn("Error while updating item in the table!", e); } } }
4,960
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/utilities/FragmentMetadata.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.utilities; import lombok.Getter; import lombok.Setter; import lombok.ToString; import org.apache.commons.lang3.Validate; import java.math.BigInteger; import java.util.Date; import java.util.Map; import java.util.Optional; import java.util.OptionalLong; import java.util.concurrent.TimeUnit; /** * Metadata for a Kinesis Video Fragment. */ @Getter @ToString public class FragmentMetadata { private static final String FRAGMENT_NUMBER_KEY = "AWS_KINESISVIDEO_FRAGMENT_NUMBER"; private static final String SERVER_SIDE_TIMESTAMP_KEY = "AWS_KINESISVIDEO_SERVER_TIMESTAMP"; private static final String PRODCUER_SIDE_TIMESTAMP_KEY = "AWS_KINESISVIDEO_PRODUCER_TIMESTAMP"; private static final String ERROR_CODE_KEY = "AWS_KINESISVIDEO_ERROR_CODE"; private static final String ERROR_ID_KEY = "AWS_KINESISVIDEO_ERROR_ID"; private static final long MILLIS_PER_SECOND = TimeUnit.SECONDS.toMillis(1); private final String fragmentNumberString; private final long serverSideTimestampMillis; private final long producerSideTimestampMillis; private final BigInteger fragmentNumber; private final boolean success; private final long errorId; private final String errorCode; @Setter private OptionalLong millisBehindNow = OptionalLong.empty(); @Setter private Optional<String> continuationToken = Optional.empty(); private FragmentMetadata(String fragmentNumberString, double serverSideTimestampSeconds, double producerSideTimestampSeconds) { this(fragmentNumberString, convertToMillis(serverSideTimestampSeconds), convertToMillis(producerSideTimestampSeconds), true, 0, null); } private FragmentMetadata(String fragmentNumberString, long errorId, String errorCode) { this(fragmentNumberString, -1, -1, false, errorId, errorCode); } private FragmentMetadata(String fragmentNumberString, long serverSideTimestampMillis, long producerSideTimestampMillis, boolean success, long errorId, String errorCode) { this.fragmentNumberString = fragmentNumberString; this.fragmentNumber = new BigInteger(fragmentNumberString); this.serverSideTimestampMillis = serverSideTimestampMillis; this.producerSideTimestampMillis = producerSideTimestampMillis; this.success = success; this.errorId = errorId; this.errorCode = errorCode; } private static long convertToMillis(double serverSideTimestampSeconds) { return (long) Math.ceil(serverSideTimestampSeconds * MILLIS_PER_SECOND); } static FragmentMetadata createFromtagNametoValueMap(final Map<String, String> tagNameToTagValueMap) { if (tagNameToTagValueMap.containsKey(SERVER_SIDE_TIMESTAMP_KEY)) { //This is a successful fragment. return new FragmentMetadata(getValueForTag(tagNameToTagValueMap, FRAGMENT_NUMBER_KEY), Double.parseDouble(getValueForTag(tagNameToTagValueMap, SERVER_SIDE_TIMESTAMP_KEY)), Double.parseDouble(getValueForTag(tagNameToTagValueMap, PRODCUER_SIDE_TIMESTAMP_KEY))); } else if (tagNameToTagValueMap.containsKey(FRAGMENT_NUMBER_KEY)) { return new FragmentMetadata(getValueForTag(tagNameToTagValueMap, FRAGMENT_NUMBER_KEY), Long.parseLong(getValueForTag(tagNameToTagValueMap, ERROR_ID_KEY)), getValueForTag(tagNameToTagValueMap, ERROR_CODE_KEY)); } return null; } private static String getValueForTag(Map<String, String> tagNameToTagValueMap, String tagName) { String tagVal = tagNameToTagValueMap.get(tagName); return Validate.notEmpty(tagVal, "tagName " + tagName); } public Date getServerSideTimestampAsDate() { return new Date(this.serverSideTimestampMillis); } public Date getProducerSideTimetampAsDate() { return new Date(this.producerSideTimestampMillis); } public boolean isCompleteFragment() { return millisBehindNow.isPresent() && continuationToken.isPresent(); } }
4,961
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/utilities/H264FrameRenderer.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.utilities; import java.awt.image.BufferedImage; import java.util.Optional; import com.amazonaws.kinesisvideo.parser.examples.KinesisVideoFrameViewer; import com.amazonaws.kinesisvideo.parser.mkv.Frame; import com.amazonaws.kinesisvideo.parser.mkv.FrameProcessException; import lombok.extern.slf4j.Slf4j; import static com.amazonaws.kinesisvideo.parser.utilities.BufferedImageUtil.addTextToImage; @Slf4j public class H264FrameRenderer extends H264FrameDecoder { private static final int PIXEL_TO_LEFT = 10; private static final int PIXEL_TO_TOP_LINE_1 = 20; private static final int PIXEL_TO_TOP_LINE_2 = 40; private final KinesisVideoFrameViewer kinesisVideoFrameViewer; protected H264FrameRenderer(final KinesisVideoFrameViewer kinesisVideoFrameViewer) { super(); this.kinesisVideoFrameViewer = kinesisVideoFrameViewer; this.kinesisVideoFrameViewer.setVisible(true); } public static H264FrameRenderer create(KinesisVideoFrameViewer kinesisVideoFrameViewer) { return new H264FrameRenderer(kinesisVideoFrameViewer); } @Override public void process(Frame frame, MkvTrackMetadata trackMetadata, Optional<FragmentMetadata> fragmentMetadata, Optional<FragmentMetadataVisitor.MkvTagProcessor> tagProcessor) throws FrameProcessException { final BufferedImage bufferedImage = decodeH264Frame(frame, trackMetadata); if (tagProcessor.isPresent()) { final FragmentMetadataVisitor.BasicMkvTagProcessor processor = (FragmentMetadataVisitor.BasicMkvTagProcessor) tagProcessor.get(); if (fragmentMetadata.isPresent()) { addTextToImage(bufferedImage, String.format("Fragment Number: %s", fragmentMetadata.get().getFragmentNumberString()), PIXEL_TO_LEFT, PIXEL_TO_TOP_LINE_1); } if (processor.getTags().size() > 0) { addTextToImage(bufferedImage, "Fragment Metadata: " + processor.getTags().toString(), PIXEL_TO_LEFT, PIXEL_TO_TOP_LINE_2); } else { addTextToImage(bufferedImage, "Fragment Metadata: No Metadata Available", PIXEL_TO_LEFT, PIXEL_TO_TOP_LINE_2); } } kinesisVideoFrameViewer.update(bufferedImage); } }
4,962
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/utilities/OutputSegmentMerger.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.utilities; import com.amazonaws.kinesisvideo.parser.ebml.EBMLTypeInfo; import com.amazonaws.kinesisvideo.parser.ebml.MkvTypeInfos; import com.amazonaws.kinesisvideo.parser.mkv.Frame; import com.amazonaws.kinesisvideo.parser.mkv.MkvDataElement; import com.amazonaws.kinesisvideo.parser.mkv.MkvElement; import com.amazonaws.kinesisvideo.parser.mkv.MkvElementVisitException; import com.amazonaws.kinesisvideo.parser.mkv.MkvElementVisitor; import com.amazonaws.kinesisvideo.parser.mkv.MkvEndMasterElement; import com.amazonaws.kinesisvideo.parser.mkv.MkvStartMasterElement; import com.amazonaws.kinesisvideo.parser.mkv.visitors.CompositeMkvElementVisitor; import com.amazonaws.kinesisvideo.parser.mkv.visitors.CountVisitor; import com.google.common.collect.ImmutableList; import lombok.Builder; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.Validate; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.math.BigInteger; import java.nio.ByteBuffer; import java.nio.channels.Channels; import java.nio.channels.WritableByteChannel; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import static com.amazonaws.kinesisvideo.parser.utilities.OutputSegmentMerger.MergeState.BUFFERING_CLUSTER_START; import static com.amazonaws.kinesisvideo.parser.utilities.OutputSegmentMerger.MergeState.EMITTING; /** * Merge the individual consecutive mkv streams output by a GetMedia call into one or more mkv streams. * Each mkv stream has one segment. * This class merges consecutive mkv streams as long as they share the same track and EBML information. * It merges based on the elements that are the child elements of the track and EBML master elements. * It collects all the child elements for each master element for each mkv stream. * It compares the collected child elements of each master element in one mkv stream * with the collected child elements of the same master element in the previous mkv stream. * If the test passes for both thr track and EBML master elements in an mkv stream, * its headers up to its first cluster are not emitted to the output stream, otherwise they are emitted. * All data within or after cluster is emitted. * * The Merger can also be configured for different merging behaviors. See {@link Configuration}. */ @Slf4j public class OutputSegmentMerger extends CompositeMkvElementVisitor { private final OutputStream outputStream; private final List<CollectorState> collectorStates; private final Configuration configuration; enum MergeState { NEW, BUFFERING_SEGMENT, BUFFERING_CLUSTER_START, EMITTING, DONE } private MergeState state = MergeState.NEW; private final MergeVisitor mergeVisitor = new MergeVisitor(); private final ByteArrayOutputStream bufferingSegmentStream = new ByteArrayOutputStream(); private WritableByteChannel bufferingSegmentChannel; private final ByteArrayOutputStream bufferingClusterStream = new ByteArrayOutputStream(); private WritableByteChannel bufferingClusterChannel; private final CountVisitor countVisitor; private final WritableByteChannel outputChannel; private long emittedSegments = 0; // fields for tracking cluster and cluster durations private Optional<BigInteger> lastClusterTimecode = Optional.empty(); private final List<Integer> clusterFrameTimeCodes = new ArrayList<>(); public static final List<EBMLTypeInfo> DEFAULT_MASTER_ELEMENTS_TO_MERGE_ON = ImmutableList.of( MkvTypeInfos.TRACKS, MkvTypeInfos.EBML ); private static final ByteBuffer SEGMENT_ELEMENT_WITH_UNKNOWN_LENGTH = ByteBuffer.wrap(new byte[] { (byte) 0x18, (byte) 0x53, (byte) 0x80, (byte) 0x67, (byte) 0x01, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF }); private static final ByteBuffer VOID_ELEMENT_WITH_SIZE_ONE = ByteBuffer.wrap(new byte [] { (byte) 0xEC, (byte) 0x81, (byte) 0x42 }); private OutputSegmentMerger(final OutputStream outputStream, final CountVisitor countVisitor, final Configuration configuration) { super(countVisitor); childVisitors.add(mergeVisitor); this.countVisitor = countVisitor; this.outputStream = outputStream; this.outputChannel = Channels.newChannel(this.outputStream); this.bufferingSegmentChannel = Channels.newChannel(bufferingSegmentStream); this.bufferingClusterChannel = Channels.newChannel(bufferingClusterStream); this.collectorStates = configuration.typeInfosToMergeOn.stream() .map(CollectorState::new) .collect(Collectors.toList()); this.configuration = configuration; } /** * Create an OutputSegmentMerger. * * @param outputStream The output stream to write the merged segments to. * @param configuration Configuration options for how to manage merging. * @return an OutputSegmentMerger that can be used to merge the segments from Kinesis Video that share a common header. */ public static OutputSegmentMerger create(final OutputStream outputStream, final Configuration configuration) { return new OutputSegmentMerger(outputStream, getCountVisitor(), configuration); } /** * Create an OutputSegmentMerger. * * @param outputStream The output stream to write the merged segments to. * @return an OutputSegmentMerger that can be used to merge the segments from Kinesis Video that share a common header. */ public static OutputSegmentMerger createDefault(final OutputStream outputStream) { return new OutputSegmentMerger(outputStream, getCountVisitor(), Configuration.builder().build()); } /** * Create an OutputSegmentMerger that stops emitting after detecting the first non matching segment. * * @param outputStream The output stream to write the merged segments to. * @return an OutputSegmentMerger that can be used to merge the segments from Kinesis Video that share a common header. * @deprecated Use {@link #create(OutputStream, Configuration)} instead. */ public static OutputSegmentMerger createToStopAtFirstNonMatchingSegment(final OutputStream outputStream) { return new OutputSegmentMerger(outputStream, getCountVisitor(), Configuration.builder() .stopAtFirstNonMatchingSegment(true) .build()); } /** * Configuration options for modifying the behavior of the {@link OutputSegmentMerger}. */ @Builder public static class Configuration { /** * When true, the Merger will stop emitting data after detecting the first segment that does not match the * previous segments. This is useful when the user wants the different merged mkv streams to go to different * destinations such as files. */ @Builder.Default private final boolean stopAtFirstNonMatchingSegment = false; /** * When true, the cluster timecodes will be modified to remove any gaps in the media between clusters. This is * useful for merging sparse streams. Also starts the first cluster with a timecode of 0. * * When false, the cluster timecodes are not altered. */ @Builder.Default private final boolean packClusters = false; /** * */ @Builder.Default private final List<EBMLTypeInfo> typeInfosToMergeOn = DEFAULT_MASTER_ELEMENTS_TO_MERGE_ON; } private static CountVisitor getCountVisitor() { return CountVisitor.create(MkvTypeInfos.CLUSTER, MkvTypeInfos.SEGMENT, MkvTypeInfos.SIMPLEBLOCK); } public int getClustersCount() { return countVisitor.getCount(MkvTypeInfos.CLUSTER); } public int getSegmentsCount() { return countVisitor.getCount(MkvTypeInfos.SEGMENT); } public int getSimpleBlocksCount() { return countVisitor.getCount(MkvTypeInfos.SIMPLEBLOCK); } @Override public boolean isDone() { return MergeState.DONE == state; } private class MergeVisitor extends MkvElementVisitor { @Override public void visit(final MkvStartMasterElement startMasterElement) throws MkvElementVisitException { try { switch (state) { case NEW: //Only the ebml header is expected in the new state Validate.isTrue(MkvTypeInfos.EBML.equals(startMasterElement.getElementMetaData().getTypeInfo()), "EBML should be the only expected element type when a new MKV stream is expected"); log.info("Detected start of EBML element, transitioning from {} to BUFFERING", state); //Change state to buffering and bufferAndCollect this element. state = MergeState.BUFFERING_SEGMENT; bufferAndCollect(startMasterElement); break; case BUFFERING_SEGMENT: //if it is the cluster start element check if the buffered elements should be emitted and // then change state to emitting, emit this the element as well. final EBMLTypeInfo startElementTypeInfo = startMasterElement.getElementMetaData().getTypeInfo(); if (MkvTypeInfos.CLUSTER.equals(startElementTypeInfo) || MkvTypeInfos.TAGS.equals( startElementTypeInfo)) { final boolean shouldEmitSegment = shouldEmitBufferedSegmentData(); if (shouldEmitSegment) { if (configuration.stopAtFirstNonMatchingSegment && emittedSegments >= 1) { log.info("Detected start of element {} transitioning from {} to DONE", startElementTypeInfo, state); state = MergeState.DONE; } else { emitBufferedSegmentData(true); resetChannels(); log.info("Detected start of element {} transitioning from {} to EMITTING", startElementTypeInfo, state); state = EMITTING; emit(startMasterElement); } } else { log.info("Detected start of element {} transitioning from {} to BUFFERING_CLUSTER_START", startElementTypeInfo, state); state = BUFFERING_CLUSTER_START; bufferAndCollect(startMasterElement); } } else { bufferAndCollect(startMasterElement); } break; case BUFFERING_CLUSTER_START: bufferAndCollect(startMasterElement); break; case EMITTING: emit(startMasterElement); break; case DONE: log.warn("OutputSegmentMerger is already done. It will not process any more elements."); break; } } catch (final IOException ie) { wrapIOException(ie); } } private void wrapIOException(final IOException ie) throws MkvElementVisitException { String exceptionMessage = "IOException in merge visitor "; if (lastClusterTimecode.isPresent()) { exceptionMessage += "in or immediately after cluster with timecode "+lastClusterTimecode.get(); } else { exceptionMessage += "in first cluster"; } throw new MkvElementVisitException(exceptionMessage, ie); } @Override public void visit(final MkvEndMasterElement endMasterElement) throws MkvElementVisitException { switch (state) { case NEW: Validate.isTrue(false, "Should not start with an EndMasterElement " + endMasterElement.toString()); break; case BUFFERING_SEGMENT: case BUFFERING_CLUSTER_START: collect(endMasterElement); break; case EMITTING: if (MkvTypeInfos.SEGMENT.equals(endMasterElement.getElementMetaData().getTypeInfo())) { log.info("Detected end of segment element, transitioning from {} to NEW", state); state = MergeState.NEW; resetCollectors(); } break; case DONE: log.warn("OutputSegmentMerger is already done. It will not process any more elements."); break; } } @Override public void visit(final MkvDataElement dataElement) throws MkvElementVisitException { try { switch (state) { case NEW: Validate.isTrue(false, "Should not start with a data element " + dataElement.toString()); break; case BUFFERING_SEGMENT: bufferAndCollect(dataElement); break; case BUFFERING_CLUSTER_START: if (MkvTypeInfos.TIMECODE.equals(dataElement.getElementMetaData().getTypeInfo())) { final BigInteger currentTimeCode = (BigInteger) dataElement.getValueCopy().getVal(); if (lastClusterTimecode.isPresent() && currentTimeCode.compareTo(lastClusterTimecode.get()) <= 0) { if (configuration.stopAtFirstNonMatchingSegment && emittedSegments >= 1) { log.info("Detected time code going back from {} to {}, state from {} to DONE", lastClusterTimecode, currentTimeCode, state); state = MergeState.DONE; } else { //emit buffered segment start emitBufferedSegmentData(true); } } if (!isDone()) { emitClusterStart(); resetChannels(); state = EMITTING; emitAdjustedTimeCode(dataElement); } } else { bufferAndCollect(dataElement); } break; case EMITTING: if (MkvTypeInfos.TIMECODE.equals(dataElement.getElementMetaData().getTypeInfo())) { emitAdjustedTimeCode(dataElement); } else if (MkvTypeInfos.SIMPLEBLOCK.equals(dataElement.getElementMetaData().getTypeInfo())) { emitFrame(dataElement); } else { emit(dataElement); } break; case DONE: log.warn("OutputSegmentMerger is already done. It will not process any more elements."); break; } } catch (final IOException ie) { wrapIOException(ie); } } @Override public boolean isDone() { return MergeState.DONE == state; } } private void emitClusterStart() throws IOException { bufferingClusterChannel.close(); final int numBytes = outputChannel.write(ByteBuffer.wrap(bufferingClusterStream.toByteArray())); log.debug("Wrote buffered cluster start data to output stream {} bytes", numBytes); } private void emitAdjustedTimeCode(final MkvDataElement timeCodeElement) throws MkvElementVisitException { if (configuration.packClusters) { final int dataSize = (int) timeCodeElement.getDataSize(); final BigInteger adjustedTimeCode; if (lastClusterTimecode.isPresent()) { // The timecode of the cluster should be the timecode of the previous cluster plus the previous cluster duration. // c.timecode = (c-1).timecode + (c-1).duration // However, neither the cluster nor the frames in the cluster have an explicit duration to use as the cluster // duration. So, we calculate the frame duration as the difference between frame timecodes, and then add // those durations to get the cluster duration. But this does not work for the last frame since there is // no frame after it to take the diff with. So, we just estimate the frame duration as the average of all // the other frame durations. // Sort cluster frame timecodes (this handles b-frames) Collections.sort(clusterFrameTimeCodes); // Get frame durations final List<Integer> frameDurations = new ArrayList<>(); for (int i = 1; i < clusterFrameTimeCodes.size(); i++) { frameDurations.add(clusterFrameTimeCodes.get(i) - clusterFrameTimeCodes.get(i -1)); } // Get average duration and add it to the other durations to account for the last frame final int averageFrameDuration; if (frameDurations.isEmpty()) { averageFrameDuration = 1; } else { averageFrameDuration = frameDurations.stream().mapToInt(Integer::intValue).sum() / frameDurations.size(); } frameDurations.add(averageFrameDuration); // Sum up the frame durations to get the cluster duration final int clusterDuration = frameDurations.stream().mapToInt(Integer::intValue).sum(); // Add duration to the previous cluster timecode adjustedTimeCode = lastClusterTimecode.get().add(BigInteger.valueOf(clusterDuration)); } else { // For the first cluster set the timecode to 0 adjustedTimeCode = BigInteger.valueOf(0L); } // When replacing the cluster timecode value, we want to use the same size data value so that parent element // sizes are not impacted. final byte[] newDataBytes = adjustedTimeCode.toByteArray(); Validate.isTrue(dataSize >= newDataBytes.length, "Adjusted timecode is not compatible with the existing data size"); final ByteBuffer newDataBuffer = ByteBuffer.allocate(dataSize); newDataBuffer.position(dataSize - newDataBytes.length); newDataBuffer.put(newDataBytes); newDataBuffer.rewind(); final MkvDataElement adjustedTimeCodeElement = MkvDataElement.builder() .idAndSizeRawBytes(timeCodeElement.getIdAndSizeRawBytes()) .elementMetaData(timeCodeElement.getElementMetaData()) .elementPath(timeCodeElement.getElementPath()) .dataSize(timeCodeElement.getDataSize()) .dataBuffer(newDataBuffer) .build(); emit(adjustedTimeCodeElement); lastClusterTimecode = Optional.of(adjustedTimeCode); // Since we are at the start of a new cluster, reset the frame state from the previous cluster. // Note: this could also be done directly on the "cluster start" event, but resetting the values here because // they are currently only used for cluster packing, so keeping cluster packing code together. clusterFrameTimeCodes.clear(); } else { emit(timeCodeElement); lastClusterTimecode = Optional.of((BigInteger) timeCodeElement.getValueCopy().getVal()); } } private void emitFrame(final MkvDataElement simpleBlockElement) throws MkvElementVisitException { if (configuration.packClusters) { final Frame frame = (Frame) simpleBlockElement.getValueCopy().getVal(); clusterFrameTimeCodes.add(frame.getTimeCode()); } emit(simpleBlockElement); } private void bufferAndCollect(final MkvStartMasterElement startMasterElement) throws IOException, MkvElementVisitException { Validate.isTrue(state == MergeState.BUFFERING_SEGMENT || state == MergeState.BUFFERING_CLUSTER_START, "Trying to buffer in wrong state " + state); //Buffer and collect if (MergeState.BUFFERING_SEGMENT == state) { if (!collectorStates.isEmpty() && MkvTypeInfos.SEGMENT.equals(startMasterElement.getElementMetaData() .getTypeInfo()) && !startMasterElement.isUnknownLength()) { //if the start master element belongs to a segment that has a defined length, //change it to one with an unknown length since we will be changing the length of the segment //element. SEGMENT_ELEMENT_WITH_UNKNOWN_LENGTH.rewind(); bufferingSegmentChannel.write(SEGMENT_ELEMENT_WITH_UNKNOWN_LENGTH); } else { startMasterElement.writeToChannel(bufferingSegmentChannel); } } else { startMasterElement.writeToChannel(bufferingClusterChannel); } this.sendElementToAllCollectors(startMasterElement); } private void bufferAndCollect(final MkvDataElement dataElement) throws MkvElementVisitException { Validate.isTrue(state == MergeState.BUFFERING_SEGMENT || state == MergeState.BUFFERING_CLUSTER_START, "Trying to buffer in wrong state " + state); if (MergeState.BUFFERING_SEGMENT == state) { writeToChannel(bufferingSegmentChannel, dataElement); } else { writeToChannel(bufferingClusterChannel, dataElement); } this.sendElementToAllCollectors(dataElement); } private static void writeToChannel(final WritableByteChannel byteChannel, final MkvDataElement dataElement) throws MkvElementVisitException { dataElement.writeToChannel(byteChannel); } private void emit(final MkvStartMasterElement startMasterElement) throws MkvElementVisitException { Validate.isTrue(state == EMITTING, "emitting in wrong state "+state); startMasterElement.writeToChannel(outputChannel); } private void emit(final MkvDataElement dataElement) throws MkvElementVisitException { Validate.isTrue(state == EMITTING, "emitting in wrong state "+state); dataElement.writeToChannel(outputChannel); } private void collect(final MkvEndMasterElement endMasterElement) throws MkvElementVisitException { //only trigger collectors since endelements do not have any data to buffer. this.sendElementToAllCollectors(endMasterElement); } private void sendElementToAllCollectors(final MkvElement dataElement) throws MkvElementVisitException { for (final CollectorState cs : collectorStates) { dataElement.accept(cs.getCollector()); } } private void emitBufferedSegmentData(final boolean shouldEmitSegmentData) throws IOException { bufferingSegmentChannel.close(); if (shouldEmitSegmentData) { final int numBytes = outputChannel.write(ByteBuffer.wrap(bufferingSegmentStream.toByteArray())); log.debug("Wrote buffered header data to output stream {} bytes",numBytes); emittedSegments++; } else { //We can merge the segments, so we dont need to write the buffered headers // However, we still need to introduce a dummy void element to prevent consumers //getting confused by two consecutive elements of the same type. VOID_ELEMENT_WITH_SIZE_ONE.rewind(); outputChannel.write(VOID_ELEMENT_WITH_SIZE_ONE); } } private void resetChannels() { bufferingSegmentStream.reset(); bufferingSegmentChannel = Channels.newChannel(bufferingSegmentStream); bufferingClusterStream.reset(); bufferingClusterChannel = Channels.newChannel(bufferingClusterStream); } private boolean shouldEmitBufferedSegmentData() { boolean doAllCollectorsMatchPreviousResults = false; if (!collectorStates.isEmpty()) { doAllCollectorsMatchPreviousResults = collectorStates.stream().allMatch(CollectorState::doCurrentAndOldResultsMatch); } log.info("Number of collectors {}. Did all collectors match previous results: {} ", collectorStates.size(), doAllCollectorsMatchPreviousResults); return !doAllCollectorsMatchPreviousResults; } private void resetCollectors() { collectorStates.forEach(CollectorState::reset); } private static class CollectorState { @Getter private final EBMLTypeInfo parentTypeInfo; @Getter private final MkvChildElementCollector collector; private List<MkvElement> previousResult = new ArrayList<>(); public CollectorState(final EBMLTypeInfo parentTypeInfo) { this.parentTypeInfo = parentTypeInfo; this.collector = new MkvChildElementCollector(parentTypeInfo); } public void reset() { previousResult = collector.copyOfCollection(); collector.clearCollection(); } boolean doCurrentAndOldResultsMatch() { return collector.equivalent(previousResult); } } }
4,963
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/utilities/BufferedImageUtil.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.utilities; import javax.annotation.Nonnull; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage; public final class BufferedImageUtil { private static final int DEFAULT_FONT_SIZE = 13; private static final Font DEFAULT_FONT = new Font(null, Font.CENTER_BASELINE, DEFAULT_FONT_SIZE); public static void addTextToImage(@Nonnull BufferedImage bufferedImage, String text, int pixelX, int pixelY) { Graphics graphics = bufferedImage.getGraphics(); graphics.setColor(Color.YELLOW); graphics.setFont(DEFAULT_FONT); for (String line : text.split(MkvTag.class.getSimpleName())) { graphics.drawString(line, pixelX, pixelY += graphics.getFontMetrics().getHeight()); } } }
4,964
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/utilities/MkvChildElementCollector.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.utilities; import com.amazonaws.kinesisvideo.parser.ebml.EBMLTypeInfo; import com.amazonaws.kinesisvideo.parser.mkv.MkvDataElement; import com.amazonaws.kinesisvideo.parser.mkv.MkvElement; import com.amazonaws.kinesisvideo.parser.mkv.MkvElementVisitor; import com.amazonaws.kinesisvideo.parser.mkv.MkvEndMasterElement; import com.amazonaws.kinesisvideo.parser.mkv.MkvStartMasterElement; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.Validate; import java.util.ArrayList; import java.util.List; /** * This collects and stores all the child elements for a particular master element. * For MkvDataElements, it copies the values and stores them to make sure they can * be accessed after the iterator for the mkvstream parser has moved on. */ @Slf4j public class MkvChildElementCollector extends MkvElementVisitor { @Getter private final EBMLTypeInfo parentTypeInfo; private final List<MkvElement> collectedElements = new ArrayList<>(); public MkvChildElementCollector(EBMLTypeInfo parentTypeInfo) { Validate.isTrue(parentTypeInfo.getType().equals(EBMLTypeInfo.TYPE.MASTER), "ChildElementCollectors can only collect children for master elements"); log.debug("MkvChildElementCollector for element {}", parentTypeInfo); this.parentTypeInfo = parentTypeInfo; } @Override public void visit(MkvStartMasterElement startMasterElement) { if (isParentType(startMasterElement) || shouldBeCollected(startMasterElement)) { //if this is the parent info itself, add it. log.debug("Add start master element {} to collector ", startMasterElement); collectedElements.add(startMasterElement); } } @Override public void visit(MkvEndMasterElement endMasterElement) { if (isParentType(endMasterElement) || shouldBeCollected(endMasterElement)) { //if this is the parent info itself, add it. log.debug("Add end master element {} to collector ", endMasterElement); collectedElements.add(endMasterElement); } } @Override public void visit(MkvDataElement dataElement) { if (shouldBeCollected(dataElement)) { log.debug("Copy value and add data element {} to collector ", dataElement); dataElement.getValueCopy(); collectedElements.add(dataElement); } } public List<MkvElement> copyOfCollection(){ return new ArrayList<>(collectedElements); } public void clearCollection() { collectedElements.clear(); } /** * Check if the collected children in this collector are the same as those from another collection ? * We are not checking for full equality since the element number embedded in the meta-data wll be different. * It compares the typeinfo and the saved values. * @param otherChildren The children of the other collector. * @return True if the typeinfo and the saved values of the children of the other collector are the same. */ public boolean equivalent(List<MkvElement> otherChildren) { if (collectedElements.size() != otherChildren.size()) { return false; } for (int i=0; i < collectedElements.size(); i++) { MkvElement collectedElement = collectedElements.get(i); MkvElement otherElement = otherChildren.get(i); if (!collectedElement.getClass().equals(otherElement.getClass())) { return false; } if (!collectedElement.equivalent(otherElement)) { return false; } } return true; } private boolean isParentType(MkvElement startMasterElement) { return startMasterElement.getElementMetaData().getTypeInfo().equals(parentTypeInfo); } //NOTE: check if this should be relaxed to only look for the parent anywhere in //the path. //TODO: deal with recursive element with search private boolean shouldBeCollected(MkvElement mkvElement) { if (mkvElement.getElementPath().size() <= parentTypeInfo.getLevel()) { //If the element belongs to a level lower than the parent's level, the path may be shorter //than the parent's level. We do not want to collect such elements. if (mkvElement.getElementMetaData().getTypeInfo().getLevel() > parentTypeInfo.getLevel()) { log.warn("Element {} has a path {} shorter than parent type's {} level but does not belong to " + "a lower level than the parent ", mkvElement.getElementMetaData().toString(), mkvElement.getElementPath().size(), parentTypeInfo.toString()); } return false; } return mkvElement.getElementPath().get(parentTypeInfo.getLevel()).getTypeInfo().equals(parentTypeInfo); } }
4,965
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/utilities/MkvTag.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.utilities; import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.ToString; /** * Class that captures MKV tag key/value string pairs */ @AllArgsConstructor(access = AccessLevel.PUBLIC) @Builder @Getter @ToString public class MkvTag { @Builder.Default private String tagName = ""; @Builder.Default private String tagValue = ""; }
4,966
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/utilities/FrameVisitor.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.utilities; import com.amazonaws.kinesisvideo.parser.ebml.MkvTypeInfos; import com.amazonaws.kinesisvideo.parser.mkv.Frame; import com.amazonaws.kinesisvideo.parser.mkv.FrameProcessException; import com.amazonaws.kinesisvideo.parser.mkv.MkvElementVisitor; import com.amazonaws.kinesisvideo.parser.mkv.MkvValue; import com.amazonaws.kinesisvideo.parser.mkv.visitors.CompositeMkvElementVisitor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.NotImplementedException; import org.apache.commons.lang3.Validate; import java.math.BigInteger; import java.util.Optional; @Slf4j public class FrameVisitor extends CompositeMkvElementVisitor { private final FragmentMetadataVisitor fragmentMetadataVisitor; private final FrameVisitorInternal frameVisitorInternal; private final FrameProcessor frameProcessor; private final Optional<Long> trackNumber; private final Optional<FragmentMetadataVisitor.MkvTagProcessor> tagProcessor; private Optional<BigInteger> timescale; private Optional<BigInteger> fragmentTimecode; private FrameVisitor(final FragmentMetadataVisitor fragmentMetadataVisitor, final Optional<FragmentMetadataVisitor.MkvTagProcessor> tagProcessor, final FrameProcessor frameProcessor, final Optional<Long> trackNumber) { super(fragmentMetadataVisitor); this.fragmentMetadataVisitor = fragmentMetadataVisitor; this.frameVisitorInternal = new FrameVisitorInternal(); this.childVisitors.add(this.frameVisitorInternal); this.frameProcessor = frameProcessor; this.tagProcessor = tagProcessor; this.trackNumber = trackNumber; this.timescale = Optional.empty(); this.fragmentTimecode = Optional.empty(); } public static FrameVisitor create(final FrameProcessor frameProcessor) { return new FrameVisitor(FragmentMetadataVisitor.create(), Optional.empty(), frameProcessor, Optional.empty()); } public static FrameVisitor create(final FrameProcessor frameProcessor, final Optional<FragmentMetadataVisitor.MkvTagProcessor> tagProcessor) { return new FrameVisitor(FragmentMetadataVisitor.create(tagProcessor), tagProcessor, frameProcessor, Optional.empty()); } public static FrameVisitor create(final FrameProcessor frameProcessor, final Optional<FragmentMetadataVisitor.MkvTagProcessor> tagProcessor, final Optional<Long> trackNumber) { return new FrameVisitor(FragmentMetadataVisitor.create(tagProcessor), tagProcessor, frameProcessor, trackNumber); } public void close() { frameProcessor.close(); } public interface FrameProcessor extends AutoCloseable { default void process(final Frame frame, final MkvTrackMetadata trackMetadata, final Optional<FragmentMetadata> fragmentMetadata) throws FrameProcessException { throw new NotImplementedException("Default FrameVisitor.FrameProcessor"); } default void process(final Frame frame, final MkvTrackMetadata trackMetadata, final Optional<FragmentMetadata> fragmentMetadata, final Optional<FragmentMetadataVisitor.MkvTagProcessor> tagProcessor) throws FrameProcessException { if (tagProcessor.isPresent()) { throw new NotImplementedException("Default FrameVisitor.FrameProcessor"); } else { process(frame, trackMetadata, fragmentMetadata); } } default void process(final Frame frame, final MkvTrackMetadata trackMetadata, final Optional<FragmentMetadata> fragmentMetadata, final Optional<FragmentMetadataVisitor.MkvTagProcessor> tagProcessor, final Optional<BigInteger> timescale, final Optional<BigInteger> fragmentTimecode) throws FrameProcessException { process(frame, trackMetadata, fragmentMetadata, tagProcessor); } @Override default void close() { //No op close. Derived classes should implement this method to meaningfully handle cleanup of the // resources. } } private class FrameVisitorInternal extends MkvElementVisitor { @Override public void visit(final com.amazonaws.kinesisvideo.parser.mkv.MkvStartMasterElement startMasterElement) throws com.amazonaws.kinesisvideo.parser.mkv.MkvElementVisitException { } @Override public void visit(final com.amazonaws.kinesisvideo.parser.mkv.MkvEndMasterElement endMasterElement) throws com.amazonaws.kinesisvideo.parser.mkv.MkvElementVisitException { if (tagProcessor.isPresent() && MkvTypeInfos.CLUSTER.equals(endMasterElement.getElementMetaData().getTypeInfo())) { tagProcessor.get().clear(); } } @Override public void visit(final com.amazonaws.kinesisvideo.parser.mkv.MkvDataElement dataElement) throws com.amazonaws.kinesisvideo.parser.mkv.MkvElementVisitException { if (MkvTypeInfos.TIMECODESCALE.equals(dataElement.getElementMetaData().getTypeInfo())) { timescale = Optional.of((BigInteger) dataElement.getValueCopy().getVal()); } if (MkvTypeInfos.TIMECODE.equals(dataElement.getElementMetaData().getTypeInfo())) { fragmentTimecode = Optional.of((BigInteger) dataElement.getValueCopy().getVal()); } if (MkvTypeInfos.SIMPLEBLOCK.equals(dataElement.getElementMetaData().getTypeInfo())) { final MkvValue<Frame> frame = dataElement.getValueCopy(); Validate.notNull(frame); final long frameTrackNo = frame.getVal().getTrackNumber(); final MkvTrackMetadata trackMetadata = fragmentMetadataVisitor.getMkvTrackMetadata(frameTrackNo); if (trackNumber.orElse(frameTrackNo) == frameTrackNo) { frameProcessor.process(frame.getVal(), trackMetadata, fragmentMetadataVisitor.getCurrentFragmentMetadata(), tagProcessor, timescale, fragmentTimecode); } } } } }
4,967
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/utilities/ProducerStreamUtil.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.utilities; import com.amazonaws.kinesisvideo.client.mediasource.CameraMediaSourceConfiguration; import com.amazonaws.kinesisvideo.common.exception.KinesisVideoException; import com.amazonaws.kinesisvideo.internal.client.mediasource.MediaSourceConfiguration; import com.amazonaws.kinesisvideo.internal.mediasource.bytes.BytesMediaSourceConfiguration; import com.amazonaws.kinesisvideo.producer.StreamInfo; import com.amazonaws.kinesisvideo.producer.Tag; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import static com.amazonaws.kinesisvideo.producer.Time.HUNDREDS_OF_NANOS_IN_AN_HOUR; import static com.amazonaws.kinesisvideo.producer.Time.HUNDREDS_OF_NANOS_IN_A_MILLISECOND; import static com.amazonaws.kinesisvideo.producer.Time.HUNDREDS_OF_NANOS_IN_A_SECOND; import static com.amazonaws.kinesisvideo.producer.Time.NANOS_IN_A_TIME_UNIT; public final class ProducerStreamUtil { private static final boolean NOT_ADAPTIVE = false; private static final boolean KEYFRAME_FRAGMENTATION = true; private static final boolean SDK_GENERATES_TIMECODES = false; private static final boolean RELATIVE_FRAGMENT_TIMECODES = false; private static final String NO_KMS_KEY_ID = null; private static final int VERSION_ZERO = 0; private static final long MAX_LATENCY_ZERO = 0L; private static final long NO_RETENTION = 0L; private static final boolean REQUEST_FRAGMENT_ACKS = true; private static final boolean RECOVER_ON_FAILURE = true; private static final long DEFAULT_GOP_DURATION = 2000L * HUNDREDS_OF_NANOS_IN_A_SECOND; private static final int DEFAULT_BITRATE = 2000000; private static final int DEFAULT_TIMESCALE = 10000; private static final int FRAMERATE_30 = 30; private static final int FRAME_RATE_25 = 25; private static final boolean USE_FRAME_TIMECODES = true; private static final boolean ABSOLUTE_TIMECODES = true; private static final boolean RELATIVE_TIMECODES = false; private static final boolean RECALCULATE_METRICS = true; /** * Default buffer duration for a stream */ public static final long DEFAULT_BUFFER_DURATION_IN_SECONDS = 40; /** * Default replay duration for a stream */ public static final long DEFAULT_REPLAY_DURATION_IN_SECONDS = 20; /** * Default connection staleness detection duration. */ public static final long DEFAULT_STALENESS_DURATION_IN_SECONDS = 20; public static StreamInfo toStreamInfo( final String streamName, final MediaSourceConfiguration mediaSourceConfiguration) throws KinesisVideoException { if (isCameraConfiguration(mediaSourceConfiguration)) { return getCameraStreamInfo(streamName, mediaSourceConfiguration); } else if (isBytesConfiguration(mediaSourceConfiguration)) { return getBytesStreamInfo(streamName, mediaSourceConfiguration); } else if (isImageFileConfiguration(mediaSourceConfiguration)) { return getImageFileStreamInfo(mediaSourceConfiguration, streamName); } throw new KinesisVideoException("Unable to create StreamInfo " + "from media source configuration"); } private static boolean isCameraConfiguration( final MediaSourceConfiguration mediaSourceConfiguration) { return CameraMediaSourceConfiguration.class .isAssignableFrom(mediaSourceConfiguration.getClass()); } private static boolean isBytesConfiguration( final MediaSourceConfiguration mediaSourceConfiguration) { return BytesMediaSourceConfiguration.class .isAssignableFrom(mediaSourceConfiguration.getClass()); } private static boolean isImageFileConfiguration(final MediaSourceConfiguration mediaSourceConfiguration) { return mediaSourceConfiguration.getClass().getSimpleName().equals("ImageFileMediaSourceConfiguration"); } private static StreamInfo getCameraStreamInfo( final String streamName, final MediaSourceConfiguration mediaSourceConfiguration) throws KinesisVideoException { final CameraMediaSourceConfiguration configuration = (CameraMediaSourceConfiguration) mediaSourceConfiguration; // Need to fix-up the content type as the Console playback only accepts video/h264 and will fail // if the mime type is video/avc which is the default in Android. String contentType = configuration.getEncoderMimeType(); if (contentType.equals("video/avc")) { contentType = "video/h264"; } return new StreamInfo(VERSION_ZERO, streamName, StreamInfo.StreamingType.STREAMING_TYPE_REALTIME, contentType, NO_KMS_KEY_ID, configuration.getRetentionPeriodInHours() * HUNDREDS_OF_NANOS_IN_AN_HOUR, NOT_ADAPTIVE, MAX_LATENCY_ZERO, DEFAULT_GOP_DURATION * HUNDREDS_OF_NANOS_IN_A_MILLISECOND, KEYFRAME_FRAGMENTATION, USE_FRAME_TIMECODES, configuration.getIsAbsoluteTimecode(), REQUEST_FRAGMENT_ACKS, RECOVER_ON_FAILURE, StreamInfo.codecIdFromContentType(configuration.getEncoderMimeType()), StreamInfo.createTrackName(configuration.getEncoderMimeType()), configuration.getBitRate(), configuration.getFrameRate(), DEFAULT_BUFFER_DURATION_IN_SECONDS * HUNDREDS_OF_NANOS_IN_A_SECOND, DEFAULT_REPLAY_DURATION_IN_SECONDS * HUNDREDS_OF_NANOS_IN_A_SECOND, DEFAULT_STALENESS_DURATION_IN_SECONDS * HUNDREDS_OF_NANOS_IN_A_SECOND, configuration.getTimeScale() / NANOS_IN_A_TIME_UNIT, RECALCULATE_METRICS, configuration.getCodecPrivateData(), getTags(), configuration.getNalAdaptationFlags()); } private static StreamInfo getBytesStreamInfo(final String streamName, final MediaSourceConfiguration mediaSourceConfiguration) throws KinesisVideoException { final BytesMediaSourceConfiguration configuration = (BytesMediaSourceConfiguration) mediaSourceConfiguration; return new StreamInfo(VERSION_ZERO, streamName, StreamInfo.StreamingType.STREAMING_TYPE_REALTIME, "application/octet-stream", NO_KMS_KEY_ID, configuration.getRetentionPeriodInHours() * HUNDREDS_OF_NANOS_IN_AN_HOUR, NOT_ADAPTIVE, MAX_LATENCY_ZERO, DEFAULT_GOP_DURATION * HUNDREDS_OF_NANOS_IN_A_MILLISECOND, KEYFRAME_FRAGMENTATION, USE_FRAME_TIMECODES, ABSOLUTE_TIMECODES, REQUEST_FRAGMENT_ACKS, RECOVER_ON_FAILURE, null, null, DEFAULT_BITRATE, FRAMERATE_30, DEFAULT_BUFFER_DURATION_IN_SECONDS * HUNDREDS_OF_NANOS_IN_A_SECOND, DEFAULT_REPLAY_DURATION_IN_SECONDS * HUNDREDS_OF_NANOS_IN_A_SECOND, DEFAULT_STALENESS_DURATION_IN_SECONDS * HUNDREDS_OF_NANOS_IN_A_SECOND, DEFAULT_TIMESCALE, RECALCULATE_METRICS, null, getTags(), StreamInfo.NalAdaptationFlags.NAL_ADAPTATION_FLAG_NONE); } private static StreamInfo getImageFileStreamInfo(final MediaSourceConfiguration configuration, final String streamName) throws KinesisVideoException { try { return (StreamInfo) configuration.getClass().getMethod("toStreamInfo", String.class) .invoke(configuration, streamName); } catch (final IllegalAccessException e) { throw new KinesisVideoException(e); } catch (final IllegalArgumentException e) { throw new KinesisVideoException(e); } catch (final InvocationTargetException e) { throw new KinesisVideoException(e); } catch (final NoSuchMethodException e) { throw new KinesisVideoException(e); } catch (final SecurityException e) { throw new KinesisVideoException(e); } } private static Tag[] getTags() { final List<Tag> tagList = new ArrayList<Tag>(); tagList.add(new Tag("device", "Test Device")); tagList.add(new Tag("stream", "Test Stream")); return tagList.toArray(new Tag[0]); } private ProducerStreamUtil() { // no-op } }
4,968
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/utilities
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/utilities/consumer/MergedOutputPiper.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.utilities.consumer; import com.amazonaws.kinesisvideo.parser.ebml.InputStreamParserByteSource; import com.amazonaws.kinesisvideo.parser.mkv.MkvElementVisitException; import com.amazonaws.kinesisvideo.parser.mkv.StreamingMkvReader; import com.amazonaws.kinesisvideo.parser.mkv.visitors.CompositeMkvElementVisitor; import com.amazonaws.kinesisvideo.parser.utilities.OutputSegmentMerger; import lombok.RequiredArgsConstructor; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * This class merges consecutive mkv streams and pipes the merged stream to the stdin of a child process. * It is meant to be used to pipe the output of a GetMedia* call to a processing application that can not deal * with having multiple consecutive mkv streams. Gstreamer is one such application that requires a merged stream. * A merged stream is where the consecutive mkv streams are merged as long as they share the same track * and EBML information and the cluster level timecodes in those streams keep increasing. * If a non-matching mkv stream is detected, the piper stops. */ @RequiredArgsConstructor public class MergedOutputPiper extends GetMediaResponseStreamConsumer { /** * The process builder to create the child proccess to which the merged output */ private final ProcessBuilder childProcessBuilder; private OutputSegmentMerger merger; private Process targetProcess; @Override public void process(final InputStream inputStream, FragmentMetadataCallback endOfFragmentCallback) throws MkvElementVisitException, IOException { targetProcess = childProcessBuilder.start(); try (OutputStream os = targetProcess.getOutputStream()) { merger = OutputSegmentMerger.createToStopAtFirstNonMatchingSegment(os); processWithFragmentEndCallbacks(inputStream, endOfFragmentCallback, merger); } } /** * Get the number of segments that were merged by the piper. * If the merger is done because the last segment it read cannot be merged, then the number of merged segments * is the number of segments read minus the last segment. * If the merger is not done then the number of merged segments is the number of read segments. * @return */ public int getMergedSegments() { if (merger.isDone()) { return merger.getSegmentsCount() - 1; } else { return merger.getSegmentsCount(); } } @Override public void close() { targetProcess.destroyForcibly(); } }
4,969
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/utilities
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/utilities/consumer/FragmentMetadataCallback.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.utilities.consumer; import com.amazonaws.kinesisvideo.parser.utilities.FragmentMetadata; /** * A callback that receives the fragment metadata of a fragment. */ @FunctionalInterface public interface FragmentMetadataCallback { void call(FragmentMetadata consumedFragment); }
4,970
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/utilities
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/utilities/consumer/FragmentProgressTracker.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.utilities.consumer; import com.amazonaws.kinesisvideo.parser.ebml.MkvTypeInfos; import com.amazonaws.kinesisvideo.parser.mkv.MkvDataElement; import com.amazonaws.kinesisvideo.parser.mkv.MkvElementVisitException; import com.amazonaws.kinesisvideo.parser.mkv.MkvElementVisitor; import com.amazonaws.kinesisvideo.parser.mkv.MkvEndMasterElement; import com.amazonaws.kinesisvideo.parser.mkv.MkvStartMasterElement; import com.amazonaws.kinesisvideo.parser.mkv.visitors.CompositeMkvElementVisitor; import com.amazonaws.kinesisvideo.parser.mkv.visitors.CountVisitor; import com.amazonaws.kinesisvideo.parser.utilities.FragmentMetadataVisitor; import lombok.RequiredArgsConstructor; /** * This class is used to track the progress in processing the output of a GetMedia call. * */ public class FragmentProgressTracker extends CompositeMkvElementVisitor { private final CountVisitor countVisitor; private FragmentProgressTracker(MkvElementVisitor processingVisitor, FragmentMetadataVisitor metadataVisitor, CountVisitor countVisitor, EndOfSegmentVisitor endOfSegmentVisitor) { super(metadataVisitor, processingVisitor, countVisitor, endOfSegmentVisitor); this.countVisitor = countVisitor; } public static FragmentProgressTracker create(MkvElementVisitor processingVisitor, FragmentMetadataCallback callback) { FragmentMetadataVisitor metadataVisitor = FragmentMetadataVisitor.create(); return new FragmentProgressTracker(processingVisitor, metadataVisitor, CountVisitor.create(MkvTypeInfos.CLUSTER, MkvTypeInfos.SEGMENT, MkvTypeInfos.SIMPLEBLOCK, MkvTypeInfos.TAG), new EndOfSegmentVisitor(metadataVisitor, callback)); } public int getClustersCount() { return countVisitor.getCount(MkvTypeInfos.CLUSTER); } public int getSegmentsCount() { return countVisitor.getCount(MkvTypeInfos.SEGMENT); } public int getSimpleBlocksCount() { return countVisitor.getCount(MkvTypeInfos.SIMPLEBLOCK); } @RequiredArgsConstructor private static class EndOfSegmentVisitor extends MkvElementVisitor { private final FragmentMetadataVisitor metadataVisitor; private final FragmentMetadataCallback endOfFragmentCallback; @Override public void visit(MkvStartMasterElement startMasterElement) throws MkvElementVisitException { } @Override public void visit(MkvEndMasterElement endMasterElement) throws MkvElementVisitException { if (MkvTypeInfos.SEGMENT.equals(endMasterElement.getElementMetaData().getTypeInfo())) { metadataVisitor.getCurrentFragmentMetadata().ifPresent(endOfFragmentCallback::call); } } @Override public void visit(MkvDataElement dataElement) throws MkvElementVisitException { } } }
4,971
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/utilities
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/utilities/consumer/GetMediaResponseStreamConsumer.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.utilities.consumer; import com.amazonaws.kinesisvideo.parser.ebml.InputStreamParserByteSource; import com.amazonaws.kinesisvideo.parser.mkv.MkvElementVisitException; import com.amazonaws.kinesisvideo.parser.mkv.MkvElementVisitor; import com.amazonaws.kinesisvideo.parser.mkv.StreamingMkvReader; import java.io.IOException; import java.io.InputStream; /** * This base class is used to consume the output of a GetMedia* call to Kinesis Video in a streaming fashion. * The first parameter for process method is the payload inputStream in a GetMediaResult returned by a call to GetMedia. * Implementations of the process method of this interface should block until all the data in the inputStream has been * processed or the process method decides to stop for some other reason. The FragmentMetadataCallback is invoked at * the end of every processed fragment. */ public abstract class GetMediaResponseStreamConsumer implements AutoCloseable { public abstract void process(InputStream inputStream, FragmentMetadataCallback callback) throws MkvElementVisitException, IOException; protected void processWithFragmentEndCallbacks(InputStream inputStream, FragmentMetadataCallback endOfFragmentCallback, MkvElementVisitor mkvElementVisitor) throws MkvElementVisitException { StreamingMkvReader.createDefault(new InputStreamParserByteSource(inputStream)) .apply(FragmentProgressTracker.create(mkvElementVisitor, endOfFragmentCallback)); } @Override public void close() { //No op close. Derived classes should implement this method to meaningfully handle cleanup of the resources. } }
4,972
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/utilities
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/utilities/consumer/GetMediaResponseStreamConsumerFactory.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.utilities.consumer; import java.io.IOException; /** * A base class used to create GetMediaResponseStreamConsumers. */ public abstract class GetMediaResponseStreamConsumerFactory { public abstract GetMediaResponseStreamConsumer createConsumer() throws IOException; }
4,973
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/utilities
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/utilities/consumer/MergedOutputPiperFactory.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.utilities.consumer; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Optional; /** * This factory class creates MergedOutputPiper consumers based on a particular target ProcessBuilder. */ public class MergedOutputPiperFactory extends GetMediaResponseStreamConsumerFactory { private final Optional<String> directoryOptional; private final List<String> commandList; private final boolean redirectOutputAndError; public MergedOutputPiperFactory(String... commands) { this(Optional.empty(), commands); } public MergedOutputPiperFactory(Optional<String> directoryOptional, String... commands) { this(directoryOptional, false, commands); } private MergedOutputPiperFactory(Optional<String> directoryOptional, boolean redirectOutputAndError, String... commands) { this.directoryOptional = directoryOptional; this.commandList = new ArrayList(); for (String command : commands) { commandList.add(command); } this.redirectOutputAndError = redirectOutputAndError; } public MergedOutputPiperFactory(Optional<String> directoryOptional, boolean redirectOutputAndError, List<String> commandList) { this.directoryOptional = directoryOptional; this.commandList = commandList; this.redirectOutputAndError = redirectOutputAndError; } @Override public GetMediaResponseStreamConsumer createConsumer() throws IOException{ ProcessBuilder builder = new ProcessBuilder().command(commandList); directoryOptional.ifPresent(d -> builder.directory(new File(d))); if (redirectOutputAndError) { builder.redirectOutput(Files.createFile(Paths.get(redirectedFileName("stdout"))).toFile()); builder.redirectError(Files.createFile(Paths.get(redirectedFileName("stderr"))).toFile()); } return new MergedOutputPiper(builder); } private String redirectedFileName(String suffix) { return "MergedOutputPiper-"+System.currentTimeMillis()+"-"+suffix; } }
4,974
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/examples/StreamOps.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.examples; import java.util.Optional; import java.util.concurrent.TimeUnit; import java.util.function.Predicate; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.regions.Regions; import com.amazonaws.services.kinesisvideo.AmazonKinesisVideo; import com.amazonaws.services.kinesisvideo.AmazonKinesisVideoClientBuilder; import com.amazonaws.services.kinesisvideo.model.CreateStreamRequest; import com.amazonaws.services.kinesisvideo.model.DeleteStreamRequest; import com.amazonaws.services.kinesisvideo.model.DescribeStreamRequest; import com.amazonaws.services.kinesisvideo.model.ResourceNotFoundException; import com.amazonaws.services.kinesisvideo.model.StreamInfo; import lombok.Builder; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.Validate; @Slf4j @Getter public class StreamOps extends KinesisVideoCommon { private static final long SLEEP_PERIOD_MILLIS = TimeUnit.SECONDS.toMillis(3); private static final int DATA_RETENTION_IN_HOURS = 48; private final String streamName; final AmazonKinesisVideo amazonKinesisVideo; @Builder public StreamOps(Regions region, String streamName, AWSCredentialsProvider credentialsProvider) { super(region, credentialsProvider, streamName); this.streamName = streamName; final AmazonKinesisVideoClientBuilder builder = AmazonKinesisVideoClientBuilder.standard(); configureClient(builder); this.amazonKinesisVideo = builder.build(); } /** * If the stream exists delete it and then recreate it. * Otherwise just create the stream. */ public void recreateStreamIfNecessary() throws InterruptedException { deleteStreamIfPresent(); //create the stream. amazonKinesisVideo.createStream(new CreateStreamRequest().withStreamName(streamName) .withDataRetentionInHours(DATA_RETENTION_IN_HOURS) .withMediaType("video/h264")); log.info("CreateStream called for stream {}", streamName); //wait for stream to become active. final Optional<StreamInfo> createdStreamInfo = waitForStateToMatch((s) -> s.isPresent() && "ACTIVE".equals(s.get().getStatus())); //some basic validations on the response of the create stream Validate.isTrue(createdStreamInfo.isPresent()); Validate.isTrue(createdStreamInfo.get().getDataRetentionInHours() == DATA_RETENTION_IN_HOURS); log.info("Stream {} created ARN {}", streamName, createdStreamInfo.get().getStreamARN()); } public void createStreamIfNotExist() throws InterruptedException { final Optional<StreamInfo> streamInfo = getStreamInfo(); log.info("Stream {} exists {}", streamName, streamInfo.isPresent()); if (!streamInfo.isPresent()) { //create the stream. amazonKinesisVideo.createStream(new CreateStreamRequest().withStreamName(streamName) .withDataRetentionInHours(DATA_RETENTION_IN_HOURS) .withMediaType("video/h264")); log.info("CreateStream called for stream {}", streamName); //wait for stream to become active. final Optional<StreamInfo> createdStreamInfo = waitForStateToMatch((s) -> s.isPresent() && "ACTIVE".equals(s.get().getStatus())); //some basic validations on the response of the create stream Validate.isTrue(createdStreamInfo.isPresent()); Validate.isTrue(createdStreamInfo.get().getDataRetentionInHours() == DATA_RETENTION_IN_HOURS); log.info("Stream {} created ARN {}", streamName, createdStreamInfo.get().getStreamARN()); } } private void deleteStreamIfPresent() throws InterruptedException { final Optional<StreamInfo> streamInfo = getStreamInfo(); log.info("Stream {} exists {}", streamName, streamInfo.isPresent()); if (streamInfo.isPresent()) { //Delete the stream amazonKinesisVideo.deleteStream(new DeleteStreamRequest().withStreamARN(streamInfo.get().getStreamARN())); log.info("DeleteStream called for stream {} ARN {} ", streamName, streamInfo.get().getStreamARN()); //Wait for stream to be deleted waitForStateToMatch((s) -> !s.isPresent()); log.info("Stream {} deleted", streamName); } } private Optional<StreamInfo> waitForStateToMatch(Predicate<Optional<StreamInfo>> statePredicate) throws InterruptedException { Optional<StreamInfo> streamInfo; do { streamInfo = getStreamInfo(); if (!statePredicate.test(streamInfo)) { Thread.sleep(SLEEP_PERIOD_MILLIS); } } while (!statePredicate.test(streamInfo)); return streamInfo; } private Optional<StreamInfo> getStreamInfo() { try { return Optional.ofNullable(amazonKinesisVideo.describeStream(new DescribeStreamRequest().withStreamName( streamName)).getStreamInfo()); } catch (ResourceNotFoundException e) { return Optional.empty(); } } }
4,975
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/examples/KinesisVideoBoundingBoxFrameViewer.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.examples; import java.awt.image.BufferedImage; import com.amazonaws.kinesisvideo.parser.rekognition.pojo.RekognizedOutput; public class KinesisVideoBoundingBoxFrameViewer extends KinesisVideoFrameViewer { public KinesisVideoBoundingBoxFrameViewer(int width, int height) { super(width, height, "KinesisVideo Embedded Frame Viewer"); panel = new BoundingBoxImagePanel(); addImagePanel(panel); } public void update(BufferedImage image, RekognizedOutput rekognizedOutput) { ((BoundingBoxImagePanel) panel).setImage(image, rekognizedOutput); } }
4,976
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/examples/GetMediaWorker.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.examples; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.client.builder.AwsClientBuilder; import com.amazonaws.kinesisvideo.parser.ebml.InputStreamParserByteSource; import com.amazonaws.kinesisvideo.parser.mkv.MkvElementVisitException; import com.amazonaws.kinesisvideo.parser.mkv.MkvElementVisitor; import com.amazonaws.kinesisvideo.parser.mkv.StreamingMkvReader; import com.amazonaws.regions.Regions; import com.amazonaws.services.kinesisvideo.AmazonKinesisVideo; import com.amazonaws.services.kinesisvideo.AmazonKinesisVideoMedia; import com.amazonaws.services.kinesisvideo.AmazonKinesisVideoMediaClientBuilder; import com.amazonaws.services.kinesisvideo.model.APIName; import com.amazonaws.services.kinesisvideo.model.GetDataEndpointRequest; import com.amazonaws.services.kinesisvideo.model.GetMediaRequest; import com.amazonaws.services.kinesisvideo.model.GetMediaResult; import com.amazonaws.services.kinesisvideo.model.StartSelector; import lombok.extern.slf4j.Slf4j; /** * Worker used to make a GetMedia call to Kinesis Video and stream in data and parse it and apply a visitor. */ @Slf4j public class GetMediaWorker extends KinesisVideoCommon implements Runnable { private final AmazonKinesisVideoMedia videoMedia; private final MkvElementVisitor elementVisitor; private final StartSelector startSelector; private GetMediaWorker(Regions region, AWSCredentialsProvider credentialsProvider, String streamName, StartSelector startSelector, String endPoint, MkvElementVisitor elementVisitor) { super(region, credentialsProvider, streamName); AmazonKinesisVideoMediaClientBuilder builder = AmazonKinesisVideoMediaClientBuilder.standard() .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(endPoint, region.getName())) .withCredentials(getCredentialsProvider()); this.videoMedia = builder.build(); this.elementVisitor = elementVisitor; this.startSelector = startSelector; } public static GetMediaWorker create(Regions region, AWSCredentialsProvider credentialsProvider, String streamName, StartSelector startSelector, AmazonKinesisVideo amazonKinesisVideo, MkvElementVisitor visitor) { String endPoint = amazonKinesisVideo.getDataEndpoint(new GetDataEndpointRequest().withAPIName(APIName.GET_MEDIA) .withStreamName(streamName)).getDataEndpoint(); return new GetMediaWorker(region, credentialsProvider, streamName, startSelector, endPoint, visitor); } @Override public void run() { try { log.info("Start GetMedia worker on stream {}", streamName); GetMediaResult result = videoMedia.getMedia(new GetMediaRequest().withStreamName(streamName).withStartSelector(startSelector)); log.info("GetMedia called on stream {} response {} requestId {}", streamName, result.getSdkHttpMetadata().getHttpStatusCode(), result.getSdkResponseMetadata().getRequestId()); StreamingMkvReader mkvStreamReader = StreamingMkvReader.createDefault(new InputStreamParserByteSource(result.getPayload())); log.info("StreamingMkvReader created for stream {} ", streamName); try { mkvStreamReader.apply(this.elementVisitor); } catch (MkvElementVisitException e) { log.error("Exception while accepting visitor {}", e); } } catch (Throwable t) { log.error("Failure in GetMediaWorker for streamName {} {}", streamName, t.toString()); throw t; } finally { log.info("Exiting GetMediaWorker for stream {}", streamName); } } }
4,977
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/examples/KinesisVideoFrameViewer.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.examples; import java.awt.Color; import java.awt.Dimension; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.image.BufferedImage; import javax.swing.JFrame; public class KinesisVideoFrameViewer extends JFrame { private final int width; private final int height; private final String title; protected ImagePanel panel; protected KinesisVideoFrameViewer(int width, int height, String title) { this.width = width; this.height = height; this.title = title; this.setTitle(title); this.setBackground(Color.BLACK); } public KinesisVideoFrameViewer(int width, int height) { this(width, height, "Kinesis Video Frame Viewer "); panel = new ImagePanel(); addImagePanel(panel); } protected void addImagePanel(final ImagePanel panel) { panel.setPreferredSize(new Dimension(width, height)); this.add(panel); this.pack(); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.out.println(title + " closed"); System.exit(0); } }); } public void update(BufferedImage image) { panel.setImage(image); } }
4,978
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/examples/ImagePanel.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.examples; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import javax.swing.JPanel; /** * Panel for rendering buffered image. */ class ImagePanel extends JPanel { protected BufferedImage image; @Override public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; if (image != null) { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.clearRect(0, 0, image.getWidth(), image.getHeight()); g2.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null); } } public void setImage(BufferedImage bufferedImage) { image = bufferedImage; repaint(); } }
4,979
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/examples/PutMediaWorker.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.examples; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.regions.Regions; import com.amazonaws.services.kinesisvideo.AmazonKinesisVideo; import com.amazonaws.services.kinesisvideo.AmazonKinesisVideoPutMedia; import com.amazonaws.services.kinesisvideo.AmazonKinesisVideoPutMediaClient; import com.amazonaws.services.kinesisvideo.AmazonKinesisVideoPutMediaClientBuilder; import com.amazonaws.services.kinesisvideo.PutMediaAckResponseHandler; import com.amazonaws.services.kinesisvideo.model.APIName; import com.amazonaws.services.kinesisvideo.model.AckEvent; import com.amazonaws.services.kinesisvideo.model.AckEventType; import com.amazonaws.services.kinesisvideo.model.FragmentTimecodeType; import com.amazonaws.services.kinesisvideo.model.GetDataEndpointRequest; import com.amazonaws.services.kinesisvideo.model.PutMediaRequest; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import java.io.InputStream; import java.util.Date; import java.util.concurrent.CountDownLatch; /** * Worker used to make a PutMedia call to Kinesis Video for a stream and stream in some video. */ @Slf4j public class PutMediaWorker extends KinesisVideoCommon implements Runnable { private final InputStream inputStream; private final AmazonKinesisVideoPutMedia putMedia; @Getter private long numFragmentsPersisted = 0; private PutMediaWorker(Regions region, AWSCredentialsProvider credentialsProvider, String streamName, InputStream inputStream, String endPoint) { super(region, credentialsProvider, streamName); this.inputStream = inputStream; AmazonKinesisVideoPutMediaClientBuilder builder = AmazonKinesisVideoPutMediaClient.builder().withEndpoint(endPoint); conifgurePutMediaClient(builder); this.putMedia = builder.build(); } public static PutMediaWorker create(Regions region, AWSCredentialsProvider credentialsProvider, String streamName, InputStream inputStream, AmazonKinesisVideo amazonKinesisVideo) { String endPoint = amazonKinesisVideo.getDataEndpoint(new GetDataEndpointRequest().withAPIName(APIName.PUT_MEDIA) .withStreamName(streamName)).getDataEndpoint(); return new PutMediaWorker(region, credentialsProvider, streamName, inputStream, endPoint); } @Override public void run() { CountDownLatch latch = new CountDownLatch(1); putMedia.putMedia(new PutMediaRequest().withStreamName(streamName) .withFragmentTimecodeType(FragmentTimecodeType.RELATIVE) .withProducerStartTimestamp(new Date()) .withPayload(inputStream), new PutMediaAckResponseHandler() { @Override public void onAckEvent(AckEvent event) { log.info("PutMedia Ack for stream {}: {} ", streamName, event.toString()); if (AckEventType.Values.PERSISTED.equals(event.getAckEventType().getEnumValue())) { numFragmentsPersisted++; } } @Override public void onFailure(Throwable t) { log.error("PutMedia for {} has suffered error {}", streamName, t); latch.countDown(); } @Override public void onComplete() { log.info("PutMedia for {} is complete ", streamName); latch.countDown(); } }); log.info("Made PutMedia call for stream {}", streamName); try { latch.await(); log.info("PutMedia worker exiting for stream {} number of fragments persisted {} ", streamName, numFragmentsPersisted); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException("Failure while waiting for PutMedia to finish", e); } finally { putMedia.close(); } } }
4,980
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/examples/KinesisVideoCommon.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.examples; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.client.builder.AwsClientBuilder; import com.amazonaws.regions.Regions; import com.amazonaws.services.kinesisvideo.AmazonKinesisVideoPutMediaClientBuilder; import lombok.Getter; import lombok.RequiredArgsConstructor; /** * Abstract class for all example classes that use the Kinesis Video clients. */ @RequiredArgsConstructor @Getter public abstract class KinesisVideoCommon { private final Regions region; private final AWSCredentialsProvider credentialsProvider; protected final String streamName; protected void configureClient(AwsClientBuilder clientBuilder) { clientBuilder.withCredentials(credentialsProvider).withRegion(region); } protected void conifgurePutMediaClient(AmazonKinesisVideoPutMediaClientBuilder builder) { builder.withCredentials(credentialsProvider).withRegion(region); } }
4,981
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/examples/KinesisVideoRendererExample.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.examples; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.util.Optional; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.kinesisvideo.parser.utilities.FragmentMetadataVisitor; import com.amazonaws.kinesisvideo.parser.utilities.FrameVisitor; import com.amazonaws.kinesisvideo.parser.utilities.H264FrameRenderer; import com.amazonaws.regions.Regions; import com.amazonaws.services.kinesisvideo.model.StartSelector; import com.amazonaws.services.kinesisvideo.model.StartSelectorType; import lombok.Builder; import lombok.Getter; import lombok.extern.slf4j.Slf4j; /* * Example for integrating with Kinesis Video. * This example does: * 1. Create a stream, deleting and recreating if the stream of the same name already exists. It sets the retention period of the created stream to 48 hours. * 2. Call PutMedia to stream video fragments into the stream. * 3. Calls GetMedia to stream video fragments out of the stream. * 4. It uses the StreamingMkvParser to parse the returned the stream and perform these steps: * 2.1 The GetMedia output stream has one mkv segment for each fragment. Merge the mkv segments that share track * information into a single segment. * 2.2 Decodes the frames using h264 decoder (using JCodec) and * 2.3 It renders the image using JFrame for viewing * * To run the example: * Run the Unit test KinesisVideoRendererExampleTest * */ @Slf4j public class KinesisVideoRendererExample extends KinesisVideoCommon { private static final int FRAME_WIDTH=640; private static final int FRAME_HEIGHT=480; private final InputStream inputStream; private final StreamOps streamOps; private final ExecutorService executorService; private KinesisVideoRendererExample.GetMediaProcessingArguments getMediaProcessingArguments; private boolean renderFragmentMetadata = true; private boolean noSampleInputRequired = false; @Builder private KinesisVideoRendererExample(Regions region, String streamName, AWSCredentialsProvider credentialsProvider, InputStream inputVideoStream, boolean renderFragmentMetadata, boolean noSampleInputRequired) { super(region, credentialsProvider, streamName); this.inputStream = inputVideoStream; this.streamOps = new StreamOps(region, streamName, credentialsProvider); this.executorService = Executors.newFixedThreadPool(2); this.renderFragmentMetadata = renderFragmentMetadata; this.noSampleInputRequired = noSampleInputRequired; } /** * This method executes the example. * * @throws InterruptedException the thread is interrupted while waiting for the streamOps to enter the correct state. * @throws IOException fails to read video from the input stream or write to the output stream. */ public void execute() throws InterruptedException, IOException { streamOps.createStreamIfNotExist(); getMediaProcessingArguments = KinesisVideoRendererExample.GetMediaProcessingArguments.create( renderFragmentMetadata ? Optional.of(new FragmentMetadataVisitor.BasicMkvTagProcessor()) : Optional.empty()); try (KinesisVideoRendererExample.GetMediaProcessingArguments getMediaProcessingArgumentsLocal = getMediaProcessingArguments) { if (!noSampleInputRequired) { //Start a PutMedia worker to write data to a Kinesis Video Stream. PutMediaWorker putMediaWorker = PutMediaWorker.create(getRegion(), getCredentialsProvider(), getStreamName(), inputStream, streamOps.amazonKinesisVideo); executorService.submit(putMediaWorker); } //Start a GetMedia worker to read and process data from the Kinesis Video Stream. GetMediaWorker getMediaWorker = GetMediaWorker.create(getRegion(), getCredentialsProvider(), getStreamName(), new StartSelector().withStartSelectorType(StartSelectorType.NOW), streamOps.amazonKinesisVideo, getMediaProcessingArgumentsLocal.getFrameVisitor()); executorService.submit(getMediaWorker); //Wait for the workers to finish. executorService.shutdown(); executorService.awaitTermination(180, TimeUnit.SECONDS); if (!executorService.isTerminated()) { log.warn("Shutting down executor service by force"); executorService.shutdownNow(); } else { log.info("Executor service is shutdown"); } } } private static class GetMediaProcessingArguments implements Closeable { @Getter private final FrameVisitor frameVisitor; GetMediaProcessingArguments(FrameVisitor frameVisitor) { this.frameVisitor = frameVisitor; } private static GetMediaProcessingArguments create( Optional<FragmentMetadataVisitor.MkvTagProcessor> tagProcessor) throws IOException { KinesisVideoFrameViewer kinesisVideoFrameViewer = new KinesisVideoFrameViewer(FRAME_WIDTH, FRAME_HEIGHT); return new GetMediaProcessingArguments( FrameVisitor.create(H264FrameRenderer.create(kinesisVideoFrameViewer), tagProcessor, Optional.of(1L))); // Video track number } @Override public void close() throws IOException { } } }
4,982
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/examples/ContinuousGetMediaWorker.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.examples; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.client.builder.AwsClientBuilder; import com.amazonaws.kinesisvideo.parser.mkv.MkvElementVisitException; import com.amazonaws.kinesisvideo.parser.utilities.FragmentMetadata; import com.amazonaws.kinesisvideo.parser.mkv.FrameProcessException; import com.amazonaws.kinesisvideo.parser.utilities.consumer.GetMediaResponseStreamConsumer; import com.amazonaws.kinesisvideo.parser.utilities.consumer.GetMediaResponseStreamConsumerFactory; import com.amazonaws.regions.Regions; import com.amazonaws.services.kinesisvideo.AmazonKinesisVideo; import com.amazonaws.services.kinesisvideo.AmazonKinesisVideoMedia; import com.amazonaws.services.kinesisvideo.AmazonKinesisVideoMediaClientBuilder; import com.amazonaws.services.kinesisvideo.model.APIName; import com.amazonaws.services.kinesisvideo.model.GetDataEndpointRequest; import com.amazonaws.services.kinesisvideo.model.GetMediaRequest; import com.amazonaws.services.kinesisvideo.model.GetMediaResult; import com.amazonaws.services.kinesisvideo.model.StartSelector; import com.amazonaws.services.kinesisvideo.model.StartSelectorType; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.Validate; import java.io.IOException; import java.io.InputStream; import java.util.Optional; import java.util.concurrent.atomic.AtomicBoolean; /** * Worker used to make a GetMedia call to Kinesis Video and stream in data and parse it and apply a visitor. */ @Slf4j public class ContinuousGetMediaWorker extends KinesisVideoCommon implements Runnable { private static final int HTTP_STATUS_OK = 200; private final AmazonKinesisVideoMedia videoMedia; private final GetMediaResponseStreamConsumerFactory consumerFactory; private final StartSelector startSelector; private Optional<String> fragmentNumberToStartAfter = Optional.empty(); private volatile AtomicBoolean shouldStop = new AtomicBoolean(false); private ContinuousGetMediaWorker(Regions region, AWSCredentialsProvider credentialsProvider, String streamName, StartSelector startSelector, String endPoint, GetMediaResponseStreamConsumerFactory consumerFactory) { super(region, credentialsProvider, streamName); AmazonKinesisVideoMediaClientBuilder builder = AmazonKinesisVideoMediaClientBuilder.standard() .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(endPoint, region.getName())) .withCredentials(getCredentialsProvider()); this.videoMedia = builder.build(); this.consumerFactory = consumerFactory; this.startSelector = startSelector; } public static ContinuousGetMediaWorker create(Regions region, AWSCredentialsProvider credentialsProvider, String streamName, StartSelector startSelector, AmazonKinesisVideo amazonKinesisVideo, GetMediaResponseStreamConsumerFactory consumer) { String endPoint = amazonKinesisVideo.getDataEndpoint(new GetDataEndpointRequest().withAPIName(APIName.GET_MEDIA) .withStreamName(streamName)).getDataEndpoint(); return new ContinuousGetMediaWorker(region, credentialsProvider, streamName, startSelector, endPoint, consumer); } public void stop() { log.info("Stop ContinuousGetMediaWorker"); shouldStop.set(true); } @Override public void run() { log.info("Start ContinuousGetMedia worker for stream {}", streamName); while (!shouldStop.get()) { GetMediaResult getMediaResult = null; try { StartSelector selectorToUse = fragmentNumberToStartAfter.map(fn -> new StartSelector().withStartSelectorType(StartSelectorType.FRAGMENT_NUMBER) .withAfterFragmentNumber(fn)).orElse(startSelector); getMediaResult = videoMedia.getMedia(new GetMediaRequest().withStreamName(streamName).withStartSelector(selectorToUse)); log.info("Start processing GetMedia called for stream {} response {} requestId {}", streamName, getMediaResult.getSdkHttpMetadata().getHttpStatusCode(), getMediaResult.getSdkResponseMetadata().getRequestId()); if (getMediaResult.getSdkHttpMetadata().getHttpStatusCode() == HTTP_STATUS_OK) { try (GetMediaResponseStreamConsumer consumer = consumerFactory.createConsumer()) { consumer.process(getMediaResult.getPayload(), this::updateFragmentNumberToStartAfter); } } else { Thread.sleep(200); } } catch (FrameProcessException e) { log.error("FrameProcessException in ContinuousGetMedia worker for stream: " + streamName, e); break; } catch (IOException | MkvElementVisitException e) { log.error("Failure in ContinuousGetMedia worker for stream: " + streamName, e); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw new RuntimeException(ie); } catch (Throwable t) { log.error("Throwable",t); } finally { closeGetMediaResponse(getMediaResult); log.info("Exit processing GetMedia called for stream {}", streamName); } } log.info("Exit ContinuousGetMedia worker for stream {}", streamName); } private void closeGetMediaResponse(final GetMediaResult getMediaResult) { if (getMediaResult != null) { final InputStream payload = getMediaResult.getPayload(); if (payload != null) { try { payload.close(); } catch (final IOException e) { // Ignore close exception; } } } } private void updateFragmentNumberToStartAfter(FragmentMetadata f) { Validate.isTrue(!fragmentNumberToStartAfter.isPresent() || f.getFragmentNumberString().compareTo(fragmentNumberToStartAfter.get()) > 0); fragmentNumberToStartAfter = Optional.of(f.getFragmentNumberString()); } }
4,983
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/examples/KinesisVideoRekognitionIntegrationExample.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.examples; import java.io.IOException; import java.io.InputStream; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.kinesisvideo.parser.kinesis.KinesisDataStreamsWorker; import com.amazonaws.kinesisvideo.parser.rekognition.pojo.RekognitionInput; import com.amazonaws.kinesisvideo.parser.rekognition.pojo.RekognizedFragmentsIndex; import com.amazonaws.kinesisvideo.parser.rekognition.processor.RekognitionStreamProcessor; import com.amazonaws.kinesisvideo.parser.utilities.FrameVisitor; import com.amazonaws.kinesisvideo.parser.utilities.H264BoundingBoxFrameRenderer; import com.amazonaws.regions.Regions; import com.amazonaws.services.kinesisvideo.model.StartSelector; import com.amazonaws.services.kinesisvideo.model.StartSelectorType; import lombok.Builder; import lombok.Setter; import lombok.extern.slf4j.Slf4j; /** * This examples demonstrates how to integrate KVS with Rekognition and draw bounding boxes while * rendering each frame in KinesisVideoFrameViewer. */ @Slf4j public class KinesisVideoRekognitionIntegrationExample extends KinesisVideoCommon { private static final int DEFAULT_FRAME_WIDTH =640; private static final int DEFAULT_FRAME_HEIGHT =480; private static final int INITIAL_DELAY=10_000; private final StreamOps streamOps; private final InputStream inputStream; private final ExecutorService executorService; private RekognitionStreamProcessor rekognitionStreamProcessor; private KinesisDataStreamsWorker kinesisDataStreamsWorker; private GetMediaWorker getMediaWorker; private String kdsStreamName; private RekognitionInput rekognitionInput; @Setter private Integer rekognitionMaxTimeoutInMillis; @Setter private int width = DEFAULT_FRAME_WIDTH; @Setter private int height = DEFAULT_FRAME_HEIGHT; private RekognizedFragmentsIndex rekognizedFragmentsIndex = new RekognizedFragmentsIndex(); @Builder private KinesisVideoRekognitionIntegrationExample(Regions region, InputStream inputStream, String kvsStreamName, String kdsStreamName, RekognitionInput rekognitionInput, AWSCredentialsProvider credentialsProvider) { super(region, credentialsProvider, kvsStreamName); this.streamOps = new StreamOps(region, kvsStreamName, credentialsProvider); this.inputStream = inputStream; this.kdsStreamName = kdsStreamName; this.rekognitionInput = rekognitionInput; this.executorService = Executors.newFixedThreadPool(3); } /** * This method executes the example. * @param timeOutinSec Timeout in seconds * @throws InterruptedException the thread is interrupted while waiting for the stream to enter the correct state. * @throws IOException fails to read video from the input stream or write to the output stream. */ public void execute(Long timeOutinSec) throws InterruptedException, IOException { // Start the RekognitionStreamProcessor and the KinesisDataStreams worker to read and process rekognized // face results. NOTE: Starting up KinesisClientLibrary can take some time, so start that first. startRekognitionProcessor(); startKinesisDataStreamsWorker(); // Adding some initial delay to sync both KVS and KDS data Thread.sleep(INITIAL_DELAY); // Start a GetMedia worker to read and render KVS fragments. startGetMediaWorker(); // Start a PutMedia worker to write data to a Kinesis Video Stream. NOTE: Video fragments can also be ingested // using real-time producer like the Kinesis Video GStreamer sample app or AmazonKinesisVideoDemoApp if (inputStream != null) { startPutMediaWorker(); } // Wait for the workers to finish. waitForTermination(timeOutinSec); cleanup(); } private void startPutMediaWorker() { PutMediaWorker putMediaWorker = PutMediaWorker.create(getRegion(), getCredentialsProvider(), getStreamName(), inputStream, streamOps.getAmazonKinesisVideo()); executorService.submit(putMediaWorker); } private void startGetMediaWorker() { final KinesisVideoBoundingBoxFrameViewer kinesisVideoBoundingBoxFrameViewer = new KinesisVideoBoundingBoxFrameViewer(width, height); final H264BoundingBoxFrameRenderer h264BoundingBoxFrameRenderer = H264BoundingBoxFrameRenderer.create( kinesisVideoBoundingBoxFrameViewer, rekognizedFragmentsIndex); if (rekognitionMaxTimeoutInMillis != null) { // Change the below timeout value to if the frames need to be rendered with low latency when // rekognition results are not present. h264BoundingBoxFrameRenderer.setMaxTimeout(rekognitionMaxTimeoutInMillis); } final FrameVisitor frameVisitor = FrameVisitor.create(h264BoundingBoxFrameRenderer); this.getMediaWorker = GetMediaWorker.create(getRegion(), getCredentialsProvider(), getStreamName(), new StartSelector().withStartSelectorType(StartSelectorType.NOW), streamOps.getAmazonKinesisVideo(), frameVisitor); executorService.submit(getMediaWorker); } private void startRekognitionProcessor() { this.rekognitionStreamProcessor = RekognitionStreamProcessor.create(getRegion(), getCredentialsProvider(), rekognitionInput); this.rekognitionStreamProcessor.process(); } private void startKinesisDataStreamsWorker() { this.kinesisDataStreamsWorker = KinesisDataStreamsWorker.create(getRegion(), getCredentialsProvider(), kdsStreamName, rekognizedFragmentsIndex); executorService.submit(kinesisDataStreamsWorker); } private void waitForTermination(final Long timeOutinSec) throws InterruptedException { executorService.shutdown(); executorService.awaitTermination(timeOutinSec, TimeUnit.SECONDS); } private void cleanup() { if (!executorService.isTerminated()) { log.warn("Shutting down executor service by force"); executorService.shutdownNow(); } else { log.info("Executor service is shutdown"); } this.rekognitionStreamProcessor.stopStreamProcessor(); } }
4,984
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/examples/BoundingBoxImagePanel.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.examples; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import com.amazonaws.kinesisvideo.parser.rekognition.pojo.BoundingBox; import com.amazonaws.kinesisvideo.parser.rekognition.pojo.FaceType; import com.amazonaws.kinesisvideo.parser.rekognition.pojo.MatchedFace; import com.amazonaws.kinesisvideo.parser.rekognition.pojo.RekognizedOutput; import lombok.extern.slf4j.Slf4j; /** * Panel which is used for rendering frames and embedding bounding boxes on the frames. */ @Slf4j public class BoundingBoxImagePanel extends ImagePanel { private static final String DELIMITER = "-"; @Override public void paintComponent(final Graphics g) { super.paintComponent(g); } public void processRekognitionOutput(final Graphics2D g2, final int width, final int height, final RekognizedOutput rekognizedOutput) { if (rekognizedOutput != null) { // Draw bounding boxes for faces. if (rekognizedOutput.getFaceSearchOutputs() != null) { log.debug("Number of detected faces in a frame {}", rekognizedOutput.getFaceSearchOutputs().size()); for (final RekognizedOutput.FaceSearchOutput faceSearchOutput : rekognizedOutput.getFaceSearchOutputs()) { final FaceType detectedFaceType; final String title; if (!faceSearchOutput.getMatchedFaceList().isEmpty()) { // Taking First match as Rekognition returns set of matched faces sorted by confidence level final MatchedFace matchedFace = faceSearchOutput.getMatchedFaceList().get(0); final String externalImageId = matchedFace.getFace().getExternalImageId(); // Rekognition doesn't allow any extra attributes/tags to be associated with the 'Face'. // External Image Id is used here to draw title on top of the bounding box and change color // of the bounding box (based on the FaceType). External Image Id needs to be specified in // below format in order get this working. // Eg: PersonName1-Criminal, PersonName2-Trusted, PersonName3-Intruder etc. if (externalImageId == null) { // If the external image id is not specified, then draw confidence level as title. title = matchedFace.getFace().getConfidence() + ""; detectedFaceType = FaceType.NOT_RECOGNIZED; } else { final String[] imageIds = externalImageId.split(DELIMITER); if (imageIds.length > 1) { title = imageIds[0]; detectedFaceType = FaceType.fromString(imageIds[1]); } else { title = "No prefix"; detectedFaceType = FaceType.NOT_RECOGNIZED; } } log.debug("Number of matched faces for the detected face {}", faceSearchOutput.getMatchedFaceList().size()); } else { detectedFaceType = FaceType.NOT_RECOGNIZED; title = "Not recognized"; } drawFaces(g2, width, height, faceSearchOutput.getDetectedFace().getBoundingBox(), title, detectedFaceType.getColor()); } } } } private void drawFaces(final Graphics2D g2, final int width, final int height, final BoundingBox boundingBox, final String personName, final Color color) { final Color c = g2.getColor(); g2.setColor(color); // Draw bounding box drawBoundingBox(g2, width, height, boundingBox); // Draw title drawFaceTitle(g2, width, height, boundingBox, personName); g2.setColor(c); } private void drawFaceTitle(final Graphics2D g2, final int width, final int height, final BoundingBox boundingBox, final String personName) { final int left = (int) (boundingBox.getLeft() * width); final int top = (int) (boundingBox.getTop() * height); g2.drawString(personName, left, top); } private void drawBoundingBox(final Graphics2D g2, final int width, final int height, final BoundingBox boundingBox) { final int left = (int) (boundingBox.getLeft() * width); final int top = (int) (boundingBox.getTop() * height); final int bbWidth = (int) (boundingBox.getWidth() * width); final int bbHeight = (int) (boundingBox.getHeight() * height); // Draw bounding box g2.drawRect(left, top, bbWidth, bbHeight); } public void setImage(final BufferedImage bufferedImage, final RekognizedOutput rekognizedOutput) { this.image = bufferedImage; processRekognitionOutput(image.createGraphics(), image.getWidth(), image.getHeight(), rekognizedOutput); repaint(); } }
4,985
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/examples/ListFragmentWorker.java
package com.amazonaws.kinesisvideo.parser.examples; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.Callable; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.client.builder.AwsClientBuilder; import com.amazonaws.regions.Regions; import com.amazonaws.services.kinesisvideo.AmazonKinesisVideo; import com.amazonaws.services.kinesisvideo.AmazonKinesisVideoArchivedMedia; import com.amazonaws.services.kinesisvideo.AmazonKinesisVideoArchivedMediaClient; import com.amazonaws.services.kinesisvideo.model.*; import lombok.extern.slf4j.Slf4j; /* This worker retrieves all fragments within the specified TimestampRange from a specified Kinesis Video Stream and returns them in a list */ @Slf4j public class ListFragmentWorker extends KinesisVideoCommon implements Callable { private final FragmentSelector fragmentSelector; private final AmazonKinesisVideoArchivedMedia amazonKinesisVideoArchivedMedia; private final long fragmentsPerRequest = 100; public ListFragmentWorker(final String streamName, final AWSCredentialsProvider awsCredentialsProvider, final String endPoint, final Regions region, final FragmentSelector fragmentSelector) { super(region, awsCredentialsProvider, streamName); this.fragmentSelector = fragmentSelector; amazonKinesisVideoArchivedMedia = AmazonKinesisVideoArchivedMediaClient .builder() .withCredentials(awsCredentialsProvider) .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(endPoint, region.getName())) .build(); } public static ListFragmentWorker create(final String streamName, final AWSCredentialsProvider awsCredentialsProvider, final Regions region, final AmazonKinesisVideo amazonKinesisVideo, final FragmentSelector fragmentSelector) { final GetDataEndpointRequest request = new GetDataEndpointRequest() .withAPIName(APIName.LIST_FRAGMENTS).withStreamName(streamName); final String endpoint = amazonKinesisVideo.getDataEndpoint(request).getDataEndpoint(); return new ListFragmentWorker( streamName, awsCredentialsProvider, endpoint, region, fragmentSelector); } @Override public List<String> call() { List<String> fragmentNumbers = new ArrayList<>(); try { log.info("Start ListFragment worker on stream {}", streamName); ListFragmentsRequest request = new ListFragmentsRequest() .withStreamName(streamName).withFragmentSelector(fragmentSelector).withMaxResults(fragmentsPerRequest); ListFragmentsResult result = amazonKinesisVideoArchivedMedia.listFragments(request); log.info("List Fragments called on stream {} response {} request ID {}", streamName, result.getSdkHttpMetadata().getHttpStatusCode(), result.getSdkResponseMetadata().getRequestId()); for (Fragment f: result.getFragments()) { fragmentNumbers.add(f.getFragmentNumber()); } String nextToken = result.getNextToken(); /* If result is truncated, keep making requests until nextToken is empty */ while (nextToken != null) { request = new ListFragmentsRequest() .withStreamName(streamName).withNextToken(nextToken); result = amazonKinesisVideoArchivedMedia.listFragments(request); for (Fragment f: result.getFragments()) { fragmentNumbers.add(f.getFragmentNumber()); } nextToken = result.getNextToken(); } Collections.sort(fragmentNumbers); for (String f: fragmentNumbers) { log.info("Retrieved fragment number {} ", f); } } catch (Throwable t) { log.error("Failure in ListFragmentWorker for streamName {} {}", streamName, t.toString()); throw t; } finally { log.info("Retrieved {} Fragments and exiting ListFragmentWorker for stream {}", fragmentNumbers.size(), streamName); return fragmentNumbers; } } }
4,986
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/examples/KinesisVideoGStreamerPiperExample.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.examples; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.kinesisvideo.parser.utilities.consumer.MergedOutputPiperFactory; import com.amazonaws.regions.Regions; import com.amazonaws.services.kinesisvideo.AmazonKinesisVideo; import com.amazonaws.services.kinesisvideo.AmazonKinesisVideoClientBuilder; import com.amazonaws.services.kinesisvideo.model.StartSelector; import com.amazonaws.services.kinesisvideo.model.StartSelectorType; import lombok.Builder; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; /** * Example for continuously piping the output of GetMedia calls from a Kinesis Video stream to GStreamer. */ @Slf4j public class KinesisVideoGStreamerPiperExample extends KinesisVideoCommon { private static final String DEFAULT_PATH_TO_GSTREAMER = "/usr/bin/gst-launch-1.0"; private static final String [] FDSRC_ARGS = new String[] { "-v", "fdsrc", "!" }; private final AmazonKinesisVideo amazonKinesisVideo; private final InputStream inputStream; private final ExecutorService executorService; private PutMediaWorker putMediaWorker; private final StreamOps streamOps; //The arguments to construct the gstreamer pipeline. //The merged output of GetMedia will be piped to the gstreamer pipeline created using these arguments. private final List<String> gStreamerPipelineArguments; @Builder private KinesisVideoGStreamerPiperExample(Regions region, String streamName, AWSCredentialsProvider credentialsProvider, InputStream inputVideoStream, String gStreamerPipelineArgument) { super(region, credentialsProvider, streamName); final AmazonKinesisVideoClientBuilder builder = AmazonKinesisVideoClientBuilder.standard(); configureClient(builder); this.amazonKinesisVideo = builder.build(); this.inputStream = inputVideoStream; this.streamOps = new StreamOps(region, streamName, credentialsProvider); this.executorService = Executors.newFixedThreadPool(2); this.gStreamerPipelineArguments = new ArrayList<>(); addGStreamerPipelineArguments(gStreamerPipelineArgument); } private void addGStreamerPipelineArguments(String gStreamerPipeLineArgument) { this.gStreamerPipelineArguments.add(pathToExecutable("PATH_TO_GSTREAMER", DEFAULT_PATH_TO_GSTREAMER)); addToPipelineArguments(FDSRC_ARGS); addToPipelineArguments(gStreamerPipeLineArgument.split("\\s+")); } private String pathToExecutable(String environmentVariable, String defaultPath) { final String environmentVariableValue = System.getenv(environmentVariable); return StringUtils.isEmpty(environmentVariableValue) ? defaultPath : environmentVariableValue; } private void addToPipelineArguments(String []pipelineArguments) { for (String pipelineArgument : pipelineArguments) { this.gStreamerPipelineArguments.add(pipelineArgument); } } /** * This method executes the example. * * @throws InterruptedException the thread is interrupted while waiting for the stream to enter the correct state. * @throws IOException fails to read video from the input stream or write to the output stream. */ public void execute () throws InterruptedException, IOException { //Create the Kinesis Video stream, deleting and recreating if necessary. streamOps.recreateStreamIfNecessary(); ContinuousGetMediaWorker getWorker = ContinuousGetMediaWorker.create(getRegion(), getCredentialsProvider(), getStreamName(), new StartSelector().withStartSelectorType(StartSelectorType.EARLIEST), amazonKinesisVideo, new MergedOutputPiperFactory(Optional.empty(), true, gStreamerPipelineArguments)); executorService.submit(getWorker); //Start a PutMedia worker to write data to a Kinesis Video Stream. putMediaWorker = PutMediaWorker.create(getRegion(), getCredentialsProvider(), getStreamName(), inputStream, amazonKinesisVideo); executorService.submit(putMediaWorker); Thread.sleep(3000); getWorker.stop(); executorService.shutdown(); executorService.awaitTermination(120, TimeUnit.SECONDS); if (!executorService.isTerminated()) { log.warn("Shutting down executor service by force"); executorService.shutdownNow(); } else { log.info("Executor service is shutdown"); } } }
4,987
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/examples/GetMediaForFragmentListWorker.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.examples; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.client.builder.AwsClientBuilder; import com.amazonaws.kinesisvideo.parser.ebml.InputStreamParserByteSource; import com.amazonaws.kinesisvideo.parser.mkv.MkvElementVisitException; import com.amazonaws.kinesisvideo.parser.mkv.MkvElementVisitor; import com.amazonaws.kinesisvideo.parser.mkv.StreamingMkvReader; import com.amazonaws.regions.Regions; import com.amazonaws.services.kinesisvideo.AmazonKinesisVideo; import com.amazonaws.services.kinesisvideo.AmazonKinesisVideoArchivedMedia; import com.amazonaws.services.kinesisvideo.AmazonKinesisVideoArchivedMediaClient; import com.amazonaws.services.kinesisvideo.model.APIName; import com.amazonaws.services.kinesisvideo.model.GetDataEndpointRequest; import com.amazonaws.services.kinesisvideo.model.GetMediaForFragmentListRequest; import com.amazonaws.services.kinesisvideo.model.GetMediaForFragmentListResult; import lombok.extern.slf4j.Slf4j; import java.util.List; @Slf4j public class GetMediaForFragmentListWorker extends KinesisVideoCommon implements Runnable { private final AmazonKinesisVideoArchivedMedia amazonKinesisVideoArchivedMedia; private final MkvElementVisitor elementVisitor; private final List<String> fragmentNumbers; public GetMediaForFragmentListWorker(final String streamName, final List<String> fragmentNumbers, final AWSCredentialsProvider awsCredentialsProvider, final String endPoint, final Regions region, final MkvElementVisitor elementVisitor) { super(region, awsCredentialsProvider, streamName); this.fragmentNumbers = fragmentNumbers; this.elementVisitor = elementVisitor; amazonKinesisVideoArchivedMedia = AmazonKinesisVideoArchivedMediaClient .builder() .withCredentials(awsCredentialsProvider) .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(endPoint, region.getName())) .build(); } public static GetMediaForFragmentListWorker create(final String streamName, final List<String> fragmentNumbers, final AWSCredentialsProvider awsCredentialsProvider, final Regions region, final AmazonKinesisVideo amazonKinesisVideo, final MkvElementVisitor elementVisitor) { final GetDataEndpointRequest request = new GetDataEndpointRequest() .withAPIName(APIName.GET_MEDIA_FOR_FRAGMENT_LIST).withStreamName(streamName); final String endpoint = amazonKinesisVideo.getDataEndpoint(request).getDataEndpoint(); return new GetMediaForFragmentListWorker( streamName, fragmentNumbers, awsCredentialsProvider, endpoint, region, elementVisitor); } @Override public void run() { try { log.info("Start GetMediaForFragmentList worker on stream {}", streamName); final GetMediaForFragmentListResult result = amazonKinesisVideoArchivedMedia.getMediaForFragmentList( new GetMediaForFragmentListRequest() .withFragments(fragmentNumbers) .withStreamName(streamName)); log.info("GetMediaForFragmentList called on stream {} response {} requestId {}", streamName, result.getSdkHttpMetadata().getHttpStatusCode(), result.getSdkResponseMetadata().getRequestId()); final StreamingMkvReader mkvStreamReader = StreamingMkvReader.createDefault( new InputStreamParserByteSource(result.getPayload())); log.info("StreamingMkvReader created for stream {} ", streamName); try { mkvStreamReader.apply(this.elementVisitor); } catch (final MkvElementVisitException e) { log.error("Exception while accepting visitor {}", e); } } catch (final Throwable t) { log.error("Failure in GetMediaForFragmentListWorker for streamName {} {}", streamName, t); throw t; } finally { log.info("Exiting GetMediaWorker for stream {}", streamName); } } }
4,988
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/examples/KinesisVideoExample.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.examples; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.auth.profile.ProfileCredentialsProvider; import com.amazonaws.kinesisvideo.parser.ebml.MkvTypeInfos; import com.amazonaws.kinesisvideo.parser.mkv.MkvDataElement; import com.amazonaws.kinesisvideo.parser.mkv.MkvElementVisitException; import com.amazonaws.kinesisvideo.parser.mkv.MkvElementVisitor; import com.amazonaws.kinesisvideo.parser.mkv.MkvEndMasterElement; import com.amazonaws.kinesisvideo.parser.mkv.MkvStartMasterElement; import com.amazonaws.kinesisvideo.parser.mkv.visitors.CompositeMkvElementVisitor; import com.amazonaws.kinesisvideo.parser.utilities.FragmentMetadataVisitor; import com.amazonaws.kinesisvideo.parser.utilities.OutputSegmentMerger; import com.amazonaws.regions.Regions; import com.amazonaws.services.kinesisvideo.AmazonKinesisVideo; import com.amazonaws.services.kinesisvideo.AmazonKinesisVideoClientBuilder; import com.amazonaws.services.kinesisvideo.model.StartSelector; import com.amazonaws.services.kinesisvideo.model.StartSelectorType; import lombok.Builder; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import java.io.BufferedOutputStream; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; /** * Example for integrating with Kinesis Video. * This example does: * 1. Create a stream, deleting and recreating if the stream of the same name already exists. * It sets the retention period of the created stream to 48 hours. * 2. Call PutMedia to stream video fragments into the stream. * 3. Simultaneously call GetMedia to stream video fragments out of the stream. * 4. It uses the StreamingMkvParser to parse the returned the stream and perform these steps: * 4.1 The GetMedia output stream has one mkv segment for each fragment. Merge the mkv segments that share track * information into a single segment. * 4.2 Log when we receive the start and end of each fragment including the fragment sequence number and * millis behind now. * * */ @Slf4j public class KinesisVideoExample extends KinesisVideoCommon { private static final long SLEEP_PERIOD_MILLIS = TimeUnit.SECONDS.toMillis(3); private static final int DATA_RETENTION_IN_HOURS = 48; private final AmazonKinesisVideo amazonKinesisVideo; private final InputStream inputStream; private final ExecutorService executorService; private PutMediaWorker putMediaWorker; private final StreamOps streamOps; private GetMediaProcessingArguments getMediaProcessingArguments; private boolean noSampleInputRequired = false; @Builder private KinesisVideoExample(Regions region, String streamName, AWSCredentialsProvider credentialsProvider, InputStream inputVideoStream, boolean noSampleInputRequired) { super(region, credentialsProvider, streamName); final AmazonKinesisVideoClientBuilder builder = AmazonKinesisVideoClientBuilder.standard(); configureClient(builder); this.amazonKinesisVideo = builder.build(); this.inputStream = inputVideoStream; this.streamOps = new StreamOps(region, streamName, credentialsProvider); this.executorService = Executors.newFixedThreadPool(2); this.noSampleInputRequired = noSampleInputRequired; } /** * This method executes the example. * * @throws InterruptedException the thread is interrupted while waiting for the stream to enter the correct state. * @throws IOException fails to read video from the input stream or write to the output stream. */ public void execute () throws InterruptedException, IOException { //Create the Kinesis Video stream if it doesn't exist. streamOps.createStreamIfNotExist(); getMediaProcessingArguments = GetMediaProcessingArguments.create(); try (GetMediaProcessingArguments getMediaProcessingArgumentsLocal = getMediaProcessingArguments) { //Start a GetMedia worker to read and process data from the Kinesis Video Stream. GetMediaWorker getMediaWorker = GetMediaWorker.create(getRegion(), getCredentialsProvider(), getStreamName(), new StartSelector().withStartSelectorType(StartSelectorType.NOW), amazonKinesisVideo, getMediaProcessingArgumentsLocal.getMkvElementVisitor()); executorService.submit(getMediaWorker); if (!noSampleInputRequired) { //Start a PutMedia worker to write data to a Kinesis Video Stream. putMediaWorker = PutMediaWorker.create(getRegion(), getCredentialsProvider(), getStreamName(), inputStream, amazonKinesisVideo); executorService.submit(putMediaWorker); } //Wait for the workers to finish. executorService.shutdown(); executorService.awaitTermination(120, TimeUnit.SECONDS); if (!executorService.isTerminated()) { log.warn("Shutting down executor service by force"); executorService.shutdownNow(); } else { log.info("Executor service is shutdown"); } } } public long getFragmentsPersisted() { return putMediaWorker.getNumFragmentsPersisted(); } public long getFragmentsRead() { return getMediaProcessingArguments.getFragmentCount(); } @RequiredArgsConstructor private static class LogVisitor extends MkvElementVisitor { private final FragmentMetadataVisitor fragmentMetadataVisitor; @Getter private long fragmentCount = 0; @Override public void visit(MkvStartMasterElement startMasterElement) throws MkvElementVisitException { if (MkvTypeInfos.EBML.equals(startMasterElement.getElementMetaData().getTypeInfo())) { fragmentCount++; log.info("Start of segment {} ", fragmentCount); } } @Override public void visit(MkvEndMasterElement endMasterElement) throws MkvElementVisitException { if (MkvTypeInfos.SEGMENT.equals(endMasterElement.getElementMetaData().getTypeInfo())) { log.info("End of segment {} fragment # {} millisBehindNow {} ", fragmentCount, fragmentMetadataVisitor.getCurrentFragmentMetadata().get().getFragmentNumberString(), fragmentMetadataVisitor.getMillisBehindNow().getAsLong()); } } @Override public void visit(MkvDataElement dataElement) throws MkvElementVisitException { } } private static class GetMediaProcessingArguments implements Closeable { private final BufferedOutputStream outputStream; private final LogVisitor logVisitor; @Getter private final CompositeMkvElementVisitor mkvElementVisitor; public GetMediaProcessingArguments(BufferedOutputStream outputStream, LogVisitor logVisitor, CompositeMkvElementVisitor mkvElementVisitor) { this.outputStream = outputStream; this.mkvElementVisitor = mkvElementVisitor; this.logVisitor = logVisitor; } public static GetMediaProcessingArguments create() throws IOException { //Fragment metadata visitor to extract Kinesis Video fragment metadata from the GetMedia stream. FragmentMetadataVisitor fragmentMetadataVisitor = FragmentMetadataVisitor.create(); //A visitor used to log as the GetMedia stream is processed. LogVisitor logVisitor = new LogVisitor(fragmentMetadataVisitor); //An OutputSegmentMerger to combine multiple segments that share track and ebml metadata into one //mkv segment. OutputStream fileOutputStream = Files.newOutputStream(Paths.get("kinesis_video_example_merged_output2.mkv"), StandardOpenOption.WRITE, StandardOpenOption.CREATE); BufferedOutputStream outputStream = new BufferedOutputStream(fileOutputStream); OutputSegmentMerger outputSegmentMerger = OutputSegmentMerger.createDefault(outputStream); //A composite visitor to encapsulate the three visitors. CompositeMkvElementVisitor mkvElementVisitor = new CompositeMkvElementVisitor(fragmentMetadataVisitor, outputSegmentMerger, logVisitor); return new GetMediaProcessingArguments(outputStream, logVisitor, mkvElementVisitor); } @Override public void close() throws IOException { outputStream.close(); } public long getFragmentCount() { return logVisitor.fragmentCount; } } }
4,989
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/examples
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/examples/lambda/H264FrameProcessor.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.examples.lambda; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.kinesisvideo.client.KinesisVideoClient; import com.amazonaws.kinesisvideo.client.mediasource.CameraMediaSourceConfiguration; import com.amazonaws.kinesisvideo.common.exception.KinesisVideoException; import com.amazonaws.kinesisvideo.java.client.KinesisVideoJavaClientFactory; import com.amazonaws.kinesisvideo.parser.examples.BoundingBoxImagePanel; import com.amazonaws.kinesisvideo.parser.mkv.Frame; import com.amazonaws.kinesisvideo.parser.mkv.FrameProcessException; import com.amazonaws.kinesisvideo.parser.rekognition.pojo.RekognizedOutput; import com.amazonaws.kinesisvideo.parser.utilities.FragmentMetadata; import com.amazonaws.kinesisvideo.parser.utilities.FrameVisitor; import com.amazonaws.kinesisvideo.parser.utilities.H264FrameDecoder; import com.amazonaws.kinesisvideo.parser.utilities.H264FrameEncoder; import com.amazonaws.kinesisvideo.parser.utilities.MkvTrackMetadata; import com.amazonaws.kinesisvideo.parser.utilities.ProducerStreamUtil; import com.amazonaws.kinesisvideo.producer.StreamInfo; import com.amazonaws.regions.Regions; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import java.awt.image.BufferedImage; import java.util.List; import java.util.Optional; import static com.google.common.base.Preconditions.checkState; @Slf4j public class H264FrameProcessor implements FrameVisitor.FrameProcessor { private static final int VIDEO_TRACK_NO = 1; private static final int MILLIS_IN_SEC = 1000; private static final int OFFSET_DELTA_THRESHOLD = 10; private final BoundingBoxImagePanel boundingBoxImagePanel; private final Regions regionName; private RekognizedOutput currentRekognizedOutput = null; private H264FrameEncoder h264Encoder; private H264FrameDecoder h264Decoder; private KVSMediaSource KVSMediaSource; private boolean isKVSProducerInitialized = false; private boolean isEncoderInitialized = false; private final AWSCredentialsProvider credentialsProvider; private final String outputKvsStreamName; @Setter private List<RekognizedOutput> rekognizedOutputs; @Setter private int frameBitRate = 1024; private int frameNo = 0; private int currentWidth = 0; private int currentHeight = 0; private long keyFrameTimecode; private H264FrameProcessor(final AWSCredentialsProvider credentialsProvider, final String outputKvsStreamName, final Regions regionName) { this.boundingBoxImagePanel = new BoundingBoxImagePanel(); this.credentialsProvider = credentialsProvider; this.outputKvsStreamName = outputKvsStreamName; this.regionName = regionName; this.h264Decoder = new H264FrameDecoder(); } private void initializeKinesisVideoProducer(final int width, final int height, final byte[] cpd) { try { log.info("Initializing KVS Producer with stream name {} and region : {}", outputKvsStreamName, regionName); final KinesisVideoClient kinesisVideoClient = KinesisVideoJavaClientFactory .createKinesisVideoClient(regionName, credentialsProvider); final CameraMediaSourceConfiguration configuration = new CameraMediaSourceConfiguration.Builder() .withFrameRate(30) .withRetentionPeriodInHours(1) .withCameraId("/dev/video0") .withIsEncoderHardwareAccelerated(false) .withEncodingMimeType("video/avc") .withNalAdaptationFlags(StreamInfo.NalAdaptationFlags.NAL_ADAPTATION_ANNEXB_NALS) .withIsAbsoluteTimecode(true) .withEncodingBitRate(200000) .withHorizontalResolution(width) .withVerticalResolution(height) .withCodecPrivateData(cpd) .build(); this.KVSMediaSource = new KVSMediaSource( ProducerStreamUtil.toStreamInfo(outputKvsStreamName, configuration)); this.KVSMediaSource.configure(configuration); // register media source with Kinesis Video Client kinesisVideoClient.registerMediaSource(KVSMediaSource); } catch (final KinesisVideoException e) { log.error("Exception while initialize KVS Producer !", e); } } public void resetEncoder() { // Reset frame count for this fragment if (this.isEncoderInitialized) { this.frameNo = 0; this.h264Encoder.setFrameNumber(frameNo); } else { throw new IllegalStateException("Encoder not initialized !"); } } public static H264FrameProcessor create(final AWSCredentialsProvider credentialsProvider, final String rekognizedStreamName, final Regions regionName) { return new H264FrameProcessor(credentialsProvider, rekognizedStreamName, regionName); } /** * Process Rekognized outputs for each rekognized output. For each kinesis event record i.e for each * fragment number create a call getMediaForFragmentList, parse fragments, decode frame, draw bounding box, * encode frame, call KVS PutFrame. */ @Override public void process(final Frame frame, final MkvTrackMetadata trackMetadata, final Optional<FragmentMetadata> fragmentMetadata) throws FrameProcessException { if (rekognizedOutputs != null) { // Process only for video frames if (frame.getTrackNumber() == VIDEO_TRACK_NO) { checkState(trackMetadata.getPixelWidth().isPresent() && trackMetadata.getPixelHeight().isPresent(), "Missing video resolution in track metadata !"); checkState(fragmentMetadata.isPresent(), "FragmentMetadata should be present !"); // Decode H264 frame final BufferedImage decodedFrame = h264Decoder.decodeH264Frame(frame, trackMetadata); log.debug("Decoded frame : {} with timecode : {} and fragment metadata : {}", frameNo, frame.getTimeCode(), fragmentMetadata.get()); // Get Rekognition results for this fragment number final Optional<RekognizedOutput> rekognizedOutput = findRekognizedOutputForFrame(frame, fragmentMetadata); // Render frame with bounding box final BufferedImage compositeFrame = renderFrame(decodedFrame, rekognizedOutput); // Encode to H264 frame final EncodedFrame encodedH264Frame = encodeH264Frame(compositeFrame); encodedH264Frame.setTimeCode(fragmentMetadata.get().getProducerSideTimestampMillis() + frame.getTimeCode()); log.debug("Encoded frame : {} with timecode : {}", frameNo, encodedH264Frame.getTimeCode()); // Call PutFrame for processed encodedFrame. putFrame(encodedH264Frame, trackMetadata.getPixelWidth().get().intValue(), trackMetadata.getPixelHeight().get().intValue()); frameNo++; } else { log.debug("Skipping audio frames !"); } } else { log.warn("Rekognition output is empty"); } } private void putFrame(final EncodedFrame encodedH264Frame, final int width, final int height) { if (!isKVSProducerInitialized) { log.info("Initializing JNI..."); initializeKinesisVideoProducer(width, height, encodedH264Frame.getCpd().array()); isKVSProducerInitialized = true; } KVSMediaSource.putFrameData(encodedH264Frame); log.debug("PutFrame successful for frame no : {}", frameNo); } private EncodedFrame encodeH264Frame(final BufferedImage bufferedImage) { try { initializeEncoder(bufferedImage); return h264Encoder.encodeFrame(bufferedImage); } catch (final Exception e) { throw new RuntimeException("Unable to encode the bufferedImage !", e); } } private void initializeEncoder(final BufferedImage bufferedImage) { // Initialize the encoder if it's not initialized or if the current frame resolution changes from previous one. if (!isEncoderInitialized || (currentWidth != bufferedImage.getWidth() || currentHeight != bufferedImage.getHeight())) { this.h264Encoder = new H264FrameEncoder(bufferedImage.getWidth(), bufferedImage.getHeight(), frameBitRate); this.isEncoderInitialized = true; this.currentWidth = bufferedImage.getWidth(); this.currentHeight = bufferedImage.getHeight(); } } private Optional<RekognizedOutput> findRekognizedOutputForFrame(final Frame frame, final Optional<FragmentMetadata> fragmentMetadata) { Optional<RekognizedOutput> rekognizedOutput = Optional.empty(); if (fragmentMetadata.isPresent()) { final String fragmentNumber = fragmentMetadata.get().getFragmentNumberString(); // Currently Rekognition samples frames and calculates the frame offset from the fragment start time. // So, in order to match with rekognition results, we have to compute the same frame offset from the // beginning of the fragments. if (frame.isKeyFrame()) { keyFrameTimecode = frame.getTimeCode(); log.debug("Key frame timecode : {}", keyFrameTimecode); } final long frameOffset = (frame.getTimeCode() > keyFrameTimecode) ? frame.getTimeCode() - keyFrameTimecode : 0; log.debug("Current Fragment Number : {} Computed Frame offset : {}", fragmentNumber, frameOffset); if (log.isDebugEnabled()) { this.rekognizedOutputs .forEach(p -> log.debug("frameOffsetInSeconds from Rekognition : {}", p.getFrameOffsetInSeconds())); } // Check whether the computed offset matches the rekognized output frame offset. Rekognition // output is in seconds whereas the frame offset is calculated in milliseconds. // NOTE: Rekognition frame offset doesn't exactly match with the computed offset below. So // take the closest one possible within 10ms delta. rekognizedOutput = this.rekognizedOutputs.stream() .filter(p -> isOffsetDeltaWithinThreshold(frameOffset, p)) .findFirst(); // Remove from the index once the RekognizedOutput is processed. Else it would increase the memory // footprint and blow up the JVM. if (rekognizedOutput.isPresent()) { log.debug("Computed offset matched with retrieved offset. Delta : {}", Math.abs(frameOffset - (rekognizedOutput.get().getFrameOffsetInSeconds() * MILLIS_IN_SEC))); if (this.rekognizedOutputs.isEmpty()) { log.debug("All frames processed for this fragment number : {}", fragmentNumber); } } } return rekognizedOutput; } private boolean isOffsetDeltaWithinThreshold(final long frameOffset, final RekognizedOutput output) { return Math.abs(frameOffset - (output.getFrameOffsetInSeconds() * MILLIS_IN_SEC)) <= OFFSET_DELTA_THRESHOLD; } @SuppressWarnings("Duplicates") private BufferedImage renderFrame(final BufferedImage bufferedImage, final Optional<RekognizedOutput> rekognizedOutput) { if (rekognizedOutput.isPresent()) { log.debug("Rendering Rekognized sampled frame..."); boundingBoxImagePanel.processRekognitionOutput(bufferedImage.createGraphics(), bufferedImage.getWidth(), bufferedImage.getHeight(), rekognizedOutput.get()); currentRekognizedOutput = rekognizedOutput.get(); } else if (currentRekognizedOutput != null) { log.debug("Rendering non-sampled frame with previous rekognized results..."); boundingBoxImagePanel.processRekognitionOutput(bufferedImage.createGraphics(), bufferedImage.getWidth(), bufferedImage.getHeight(), currentRekognizedOutput); } else { log.debug("Rendering frame without any rekognized results..."); } return bufferedImage; } }
4,990
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/examples
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/examples/lambda/KinesisVideoRekognitionLambdaExample.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.examples.lambda; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.auth.DefaultAWSCredentialsProviderChain; import com.amazonaws.kinesisvideo.parser.examples.GetMediaForFragmentListWorker; import com.amazonaws.kinesisvideo.parser.examples.StreamOps; import com.amazonaws.kinesisvideo.parser.kinesis.KinesisDataStreamsWorker; import com.amazonaws.kinesisvideo.parser.rekognition.pojo.DetectedFace; import com.amazonaws.kinesisvideo.parser.rekognition.pojo.FaceSearchResponse; import com.amazonaws.kinesisvideo.parser.rekognition.pojo.MatchedFace; import com.amazonaws.kinesisvideo.parser.rekognition.pojo.RekognitionOutput; import com.amazonaws.kinesisvideo.parser.rekognition.pojo.RekognizedFragmentsIndex; import com.amazonaws.kinesisvideo.parser.rekognition.pojo.RekognizedOutput; import com.amazonaws.kinesisvideo.parser.utilities.FrameVisitor; import com.amazonaws.regions.Regions; import com.amazonaws.services.kinesis.model.Record; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.KinesisEvent; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.extern.slf4j.Slf4j; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.stream.Collectors; /** * Lambda example integratong Rekognition outputs with Kinesis Video streams fragments. This examples is triggered * when Rekognition publishes events in Kinesis Data Streams (KDS). It gets the corresponding fragments from * Kinesis Video Streams (KVS), decodes each frame, overlays bounding box on top of faces detected, encodes the * frame again (using Jcodec) and then publishes into new derived Kinesis Video streams. The new stream can be * viewed using Kinesis Video Streams console or using HLS playback. * * NOTE: For Instructions to run this Lambda, please refer README. * NOTE: As this lambda executes resource intense decoding and encoding (using Jcodec which is not optimal * https://github.com/jcodec/jcodec#performance--quality-considerations), the new Kinesis Video stream might be delayed significantly. */ @Slf4j public final class KinesisVideoRekognitionLambdaExample implements RequestHandler<KinesisEvent, Context> { private static final int NUM_RETRIES = 10; private static final int KCL_INIT_DELAY_MILLIS = 10_000; private final ExecutorService kdsWorkers = Executors.newFixedThreadPool(100); private final AWSCredentialsProvider credentialsProvider = new DefaultAWSCredentialsProviderChain(); private final RekognizedFragmentsIndex rekognizedFragmentsIndex = new RekognizedFragmentsIndex(); private String inputKvsStreamName; private String outputKvsStreamName; private StreamOps kvsClient; private FragmentCheckpointManager fragmentCheckpointManager; private H264FrameProcessor h264FrameProcessor; /** * Main method to test the integration locally in desktop. * * NOTE: This uses a different approach to get the KDS events using KCL to trigger lambda. * */ public static void main(final String[] args) throws Exception { final KinesisVideoRekognitionLambdaExample KinesisVideoRekognitionLambdaExample = new KinesisVideoRekognitionLambdaExample(); KinesisVideoRekognitionLambdaExample.initialize( System.getProperty("KVSStreamName"), Regions.fromName(System.getenv("AWS_REGION"))); KinesisVideoRekognitionLambdaExample.startKDSWorker(System.getProperty("KDSStreamName")); Thread.sleep(KCL_INIT_DELAY_MILLIS); // Initial delay to wait for KCL to initialize while (true) { // For local desktop testing. KinesisVideoRekognitionLambdaExample.processRekognizedOutputs(); } } /** * Initialize method to set variables. */ private void initialize(final String kvsStreamName, final Regions regionName) { this.inputKvsStreamName = kvsStreamName; outputKvsStreamName = kvsStreamName + "-Rekognized"; kvsClient = new StreamOps(regionName, kvsStreamName, credentialsProvider); h264FrameProcessor = H264FrameProcessor.create(credentialsProvider, outputKvsStreamName, regionName); fragmentCheckpointManager = new DDBBasedFragmentCheckpointManager(kvsClient.getRegion(), credentialsProvider); log.info("Initialized with input KVS stream: {}, output {}, region : {}", inputKvsStreamName, outputKvsStreamName, regionName); } /** * Process Rekognized outputs for each rekognized output. For each kinesis event record i.e for each * fragment number create a call getMediaForFragmentList, parse fragments, decode frame, draw bounding box, * encode frame, call KVS PutFrame. * * @throws InterruptedException */ private void processRekognizedOutputs() throws InterruptedException { // Get the last processed fragment number if any final Optional<FragmentCheckpoint> lastFragmentNumber = fragmentCheckpointManager .getLastProcessedItem(inputKvsStreamName); String fragmentNumber = null; while (!rekognizedFragmentsIndex.isEmpty()) { final RekognizedFragmentsIndex.RekognizedFragment rekognizedFragment = rekognizedFragmentsIndex.poll(); fragmentNumber = rekognizedFragment.getFragmentNumber(); final List<RekognizedOutput> rekognizedOutputList = rekognizedFragment.getRekognizedOutputs(); if (lastFragmentNumber.isPresent() && (fragmentNumber.equals(lastFragmentNumber.get().getFragmentNumber()) || rekognizedFragment.getServerTime() <= lastFragmentNumber.get().getServerTime())) { // If the current fragment number is equal to the last processed fragment number or if the current // fragment's server time is older than or equal than last processed fragment's server time then // skip this fragment number and proceed to next fragment. log.info("Current fragment number : {} is already processed or older than last processed fragment. " + "So skipping..", fragmentNumber); continue; } try { final FrameVisitor frameVisitor = FrameVisitor.create(h264FrameProcessor); final GetMediaForFragmentListWorker worker = GetMediaForFragmentListWorker.create( kvsClient.getStreamName(), Collections.singletonList(fragmentNumber), kvsClient.getCredentialsProvider(), kvsClient.getRegion(), kvsClient.getAmazonKinesisVideo(), frameVisitor); h264FrameProcessor.setRekognizedOutputs(rekognizedOutputList); worker.run(); // For every fragment, the rekognition output needs to be set and the encoder needs to be reset // as the JCodec encoder always treats first frame as IDR frame h264FrameProcessor.resetEncoder(); log.info("Fragment {} processed successfully ...", fragmentNumber); // Once the current fragment number is processed save it as a checkpoint. fragmentCheckpointManager.saveCheckPoint(inputKvsStreamName, fragmentNumber, rekognizedFragment.getProducerTime(), rekognizedFragment.getServerTime()); } catch (final Exception e) { log.error("Error while processing fragment number: {}", fragmentNumber, e); } } } /** * Start Kinesis Data Streams worker. */ public void startKDSWorker(final String kdsStreamName) { final KinesisDataStreamsWorker kinesisDataStreamsWorker = KinesisDataStreamsWorker.create(Regions.US_WEST_2, credentialsProvider, kdsStreamName, rekognizedFragmentsIndex); kdsWorkers.submit(kinesisDataStreamsWorker); } /** * Handle request for each lambda event. * * @param kinesisEvent Each kinesis event which describes the Rekognition output. * @param context Lambda context * @return context */ @Override public Context handleRequest(final KinesisEvent kinesisEvent, final Context context) { try { initialize(System.getProperty("KVSStreamName"), Regions.fromName(System.getenv("AWS_REGION"))); loadProducerJNI(context); final List<Record> records = kinesisEvent.getRecords() .stream() .map(KinesisEvent.KinesisEventRecord::getKinesis) .collect(Collectors.toList()); processRecordsWithRetries(records); processRekognizedOutputs(); } catch (final Exception e) { log.error("Unable to process lambda request !. Exiting... ", e); } return context; } /** * Load pre-built binary of Kinesis Video Streams Producer JNI. * * @param context */ private void loadProducerJNI(final Context context) throws IOException { log.info("Context : {}", context); log.info("Working Directory = {}", System.getProperty("user.dir")); log.info("Java library path = {}", System.getProperty("java.library.path")); log.info("Class path %s", this.getClass().getProtectionDomain().getCodeSource().getLocation()); log.info("Loading JNI .so file.."); final ClassLoader classLoader = getClass().getClassLoader(); final File cityFile = new File(classLoader.getResource("libKinesisVideoProducerJNI.so").getFile()); System.load(cityFile.getAbsolutePath()); log.info("Loaded JNI from {}", cityFile.getAbsolutePath()); } /** * Process records performing retries as needed. Skip "poison pill" records. * * @param records Data records to be processed. */ private void processRecordsWithRetries(final List<Record> records) { for (final Record record : records) { boolean processedSuccessfully = false; for (int i = 0; i < NUM_RETRIES; i++) { try { log.info("Processing single record..."); processSingleRecord(record); processedSuccessfully = true; break; } catch (final Throwable t) { log.error("Caught throwable while processing record {}", record, t); } } if (!processedSuccessfully) { log.warn("Couldn't processRekognizedOutputs record {}. Skipping the record.", record); } } log.info("Processed all {} KDS records.", records.size()); } /** * Process a single record. * * @param record The record to be processed. */ private void processSingleRecord(final Record record) { String data = null; final ObjectMapper mapper = new ObjectMapper(); try { final ByteBuffer buffer = record.getData(); data = new String(buffer.array(), "UTF-8"); final RekognitionOutput output = mapper.readValue(data, RekognitionOutput.class); // Get the fragment number from Rekognition Output final String fragmentNumber = output .getInputInformation() .getKinesisVideo() .getFragmentNumber(); final Double frameOffsetInSeconds = output .getInputInformation() .getKinesisVideo() .getFrameOffsetInSeconds(); final Double serverTimestamp = output .getInputInformation() .getKinesisVideo() .getServerTimestamp(); final Double producerTimestamp = output .getInputInformation() .getKinesisVideo() .getProducerTimestamp(); final double detectedTime = output.getInputInformation().getKinesisVideo().getServerTimestamp() + output.getInputInformation().getKinesisVideo().getFrameOffsetInSeconds() * 1000L; final RekognizedOutput rekognizedOutput = RekognizedOutput.builder() .fragmentNumber(fragmentNumber) .serverTimestamp(serverTimestamp) .producerTimestamp(producerTimestamp) .frameOffsetInSeconds(frameOffsetInSeconds) .detectedTime(detectedTime) .build(); // Add face search response final List<FaceSearchResponse> responses = output.getFaceSearchResponse(); responses.forEach(response -> { final DetectedFace detectedFace = response.getDetectedFace(); final List<MatchedFace> matchedFaces = response.getMatchedFaces(); final RekognizedOutput.FaceSearchOutput faceSearchOutput = RekognizedOutput.FaceSearchOutput.builder() .detectedFace(detectedFace) .matchedFaceList(matchedFaces) .build(); rekognizedOutput.addFaceSearchOutput(faceSearchOutput); }); // Add it to the index log.info("Found Rekognized results for fragment number : {}", fragmentNumber); rekognizedFragmentsIndex.add(fragmentNumber, producerTimestamp.longValue(), serverTimestamp.longValue(), rekognizedOutput); } catch (final NumberFormatException e) { log.warn("Record does not match sample record format. Ignoring record with data : {}", data, e); } catch (final Exception e) { log.error("Unable to process record !", e); } } }
4,991
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/examples
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/examples/lambda/KVSMediaSource.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.examples.lambda; import com.amazonaws.kinesisvideo.client.mediasource.CameraMediaSourceConfiguration; import com.amazonaws.kinesisvideo.client.mediasource.MediaSourceState; import com.amazonaws.kinesisvideo.common.exception.KinesisVideoException; import com.amazonaws.kinesisvideo.internal.client.mediasource.MediaSource; import com.amazonaws.kinesisvideo.internal.client.mediasource.MediaSourceConfiguration; import com.amazonaws.kinesisvideo.internal.client.mediasource.MediaSourceSink; import com.amazonaws.kinesisvideo.parser.utilities.ProducerStreamUtil; import com.amazonaws.kinesisvideo.producer.KinesisVideoFrame; import com.amazonaws.kinesisvideo.producer.StreamCallbacks; import com.amazonaws.kinesisvideo.producer.StreamInfo; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import javax.annotation.Nullable; import java.nio.ByteBuffer; @Slf4j @RequiredArgsConstructor public class KVSMediaSource implements MediaSource { private static final int FRAME_FLAG_KEY_FRAME = 1; private static final int FRAME_FLAG_NONE = 0; private static final long HUNDREDS_OF_NANOS_IN_MS = 10 * 1000; private static final long FRAME_DURATION_20_MS = 20L; private CameraMediaSourceConfiguration cameraMediaSourceConfiguration; private MediaSourceState mediaSourceState; private MediaSourceSink mediaSourceSink; private int frameIndex; private final StreamInfo streamInfo; private void putFrame(final KinesisVideoFrame kinesisVideoFrame) { try { mediaSourceSink.onFrame(kinesisVideoFrame); } catch (final KinesisVideoException ex) { throw new RuntimeException(ex); } } @Override public MediaSourceState getMediaSourceState() { return mediaSourceState; } @Override public MediaSourceConfiguration getConfiguration() { return cameraMediaSourceConfiguration; } @Override public StreamInfo getStreamInfo() throws KinesisVideoException { return streamInfo; } @Override public void initialize(final MediaSourceSink mediaSourceSink) { this.mediaSourceSink = mediaSourceSink; } @Override public void configure(final MediaSourceConfiguration configuration) { if (!(configuration instanceof CameraMediaSourceConfiguration)) { throw new IllegalStateException("Configuration must be an instance of CameraMediaSourceConfiguration"); } this.cameraMediaSourceConfiguration = (CameraMediaSourceConfiguration) configuration; this.frameIndex = 0; } @Override public void start() { mediaSourceState = MediaSourceState.RUNNING; } public void putFrameData(final EncodedFrame encodedFrame) { final int flags = encodedFrame.isKeyFrame() ? FRAME_FLAG_KEY_FRAME : FRAME_FLAG_NONE; if (encodedFrame.getByteBuffer() != null) { final KinesisVideoFrame frame = new KinesisVideoFrame( frameIndex++, flags, encodedFrame.getTimeCode() * HUNDREDS_OF_NANOS_IN_MS, encodedFrame.getTimeCode() * HUNDREDS_OF_NANOS_IN_MS, FRAME_DURATION_20_MS * HUNDREDS_OF_NANOS_IN_MS, encodedFrame.getByteBuffer()); if (frame.getSize() == 0) { return; } putFrame(frame); } else { log.info("Frame Data is null !"); } } @Override public void stop() { mediaSourceState = MediaSourceState.STOPPED; } @Override public boolean isStopped() { return mediaSourceState == MediaSourceState.STOPPED; } @Override public void free() { } @Override public MediaSourceSink getMediaSourceSink() { return mediaSourceSink; } @Nullable @Override public StreamCallbacks getStreamCallbacks() { return null; } }
4,992
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/examples
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/examples/lambda/FragmentCheckpointManager.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.examples.lambda; import java.util.Optional; /** * FragmentCheckpoint Manager interface which manages the checkpoints for last processed fragments. */ public interface FragmentCheckpointManager { /** * Get last processed fragment details from checkpoint for given stream name. * * @param streamName KVS Stream name * @return Optional of last processed fragment item if checkpoint exists. Empty otherwise */ Optional<FragmentCheckpoint> getLastProcessedItem(String streamName); /** * Save last processed fragment details checkpoint for the given stream name. * * @param streamName KVS Stream name * @param fragmentNumber Last processed fragment's fragment number * @param producerTime Last processed fragment's producer time * @param serverTime Last processed fragment's server time */ void saveCheckPoint(String streamName, String fragmentNumber, Long producerTime, Long serverTime); }
4,993
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/examples
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/examples/lambda/DDBBasedFragmentCheckpointManager.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.examples.lambda; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.kinesisvideo.parser.utilities.DynamoDBHelper; import com.amazonaws.regions.Regions; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import lombok.extern.slf4j.Slf4j; import java.util.Map; import java.util.Optional; /** * DynamdDB based FragmentCheckpoint Manager which manages the checkpoints for last processed fragments. */ @Slf4j public class DDBBasedFragmentCheckpointManager implements FragmentCheckpointManager { private static final String TABLE_NAME = "FragmentCheckpoint"; private static final String KVS_STREAM_NAME = "KVSStreamName"; private static final String FRAGMENT_NUMBER = "FragmentNumber"; private static final String SERVER_TIME = "ServerTime"; private static final String PRODUCER_TIME = "ProducerTime"; private static final String UPDATED_TIME = "UpdatedTime"; private final DynamoDBHelper dynamoDBHelper; public DDBBasedFragmentCheckpointManager(final Regions region, final AWSCredentialsProvider credentialsProvider) { dynamoDBHelper = new DynamoDBHelper(region, credentialsProvider); dynamoDBHelper.createTableIfDoesntExist(); } /** * Get last processed fragment details from checkpoint for given stream name. * * @param streamName KVS Stream name * @return Optional of last processed fragment item if checkpoint exists. Empty otherwise */ @Override public Optional<FragmentCheckpoint> getLastProcessedItem(final String streamName) { final Map<String, AttributeValue> result = dynamoDBHelper.getItem(streamName); if (result != null && result.containsKey(FRAGMENT_NUMBER)) { return Optional.of(new FragmentCheckpoint(streamName, result.get(FRAGMENT_NUMBER).getS(), Long.parseLong(result.get(PRODUCER_TIME).getN()), Long.parseLong(result.get(SERVER_TIME).getN()), Long.parseLong(result.get(UPDATED_TIME).getN()))); } return Optional.empty(); } /** * Save last processed fragment details checkpoint for the given stream name. * * @param streamName KVS Stream name * @param fragmentNumber Last processed fragment's fragment number * @param producerTime Last processed fragment's producer time * @param serverTime Last processed fragment's server time */ @Override public void saveCheckPoint(final String streamName, final String fragmentNumber, final Long producerTime, final Long serverTime) { if (fragmentNumber != null) { if (dynamoDBHelper.getItem(streamName) != null) { log.info("Checkpoint for stream name {} already exists. So updating checkpoint with fragment number: {}", streamName, fragmentNumber); dynamoDBHelper.updateItem(streamName, fragmentNumber, producerTime, serverTime, System.currentTimeMillis()); } else { log.info("Creating checkpoint for stream name {} with fragment number: {}", streamName, fragmentNumber); dynamoDBHelper.putItem(streamName, fragmentNumber, producerTime, serverTime, System.currentTimeMillis()); } } else { log.info("Fragment number is null. Skipping save checkpoint..."); } } }
4,994
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/examples
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/examples/lambda/FragmentCheckpoint.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.examples.lambda; import lombok.Getter; import lombok.RequiredArgsConstructor; /** * Class for the lambda checkpoint stored in DDB. */ @Getter @RequiredArgsConstructor public class FragmentCheckpoint { private final String streamName; private final String fragmentNumber; private final Long serverTime; private final Long producerTime; private final Long updatedTime; }
4,995
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/examples
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/examples/lambda/EncodedFrame.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.examples.lambda; import lombok.Builder; import lombok.Getter; import lombok.Setter; import java.nio.ByteBuffer; /** * Container class for H264 encoded frame */ @Getter @Builder public class EncodedFrame { private final ByteBuffer byteBuffer; private final ByteBuffer cpd; private final boolean isKeyFrame; @Setter private long timeCode; }
4,996
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/rekognition
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/rekognition/processor/RekognitionStreamProcessor.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.rekognition.processor; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.kinesisvideo.parser.rekognition.pojo.RekognitionInput; import com.amazonaws.regions.Regions; import com.amazonaws.services.rekognition.AmazonRekognition; import com.amazonaws.services.rekognition.AmazonRekognitionClientBuilder; import com.amazonaws.services.rekognition.model.CreateStreamProcessorRequest; import com.amazonaws.services.rekognition.model.CreateStreamProcessorResult; import com.amazonaws.services.rekognition.model.DeleteStreamProcessorRequest; import com.amazonaws.services.rekognition.model.DeleteStreamProcessorResult; import com.amazonaws.services.rekognition.model.DescribeStreamProcessorRequest; import com.amazonaws.services.rekognition.model.DescribeStreamProcessorResult; import com.amazonaws.services.rekognition.model.FaceSearchSettings; import com.amazonaws.services.rekognition.model.KinesisDataStream; import com.amazonaws.services.rekognition.model.KinesisVideoStream; import com.amazonaws.services.rekognition.model.ListStreamProcessorsRequest; import com.amazonaws.services.rekognition.model.ListStreamProcessorsResult; import com.amazonaws.services.rekognition.model.ResourceNotFoundException; import com.amazonaws.services.rekognition.model.StartStreamProcessorRequest; import com.amazonaws.services.rekognition.model.StartStreamProcessorResult; import com.amazonaws.services.rekognition.model.StopStreamProcessorRequest; import com.amazonaws.services.rekognition.model.StopStreamProcessorResult; import com.amazonaws.services.rekognition.model.StreamProcessor; import com.amazonaws.services.rekognition.model.StreamProcessorInput; import com.amazonaws.services.rekognition.model.StreamProcessorOutput; import com.amazonaws.services.rekognition.model.StreamProcessorSettings; import com.amazonaws.services.rekognition.model.StreamProcessorStatus; import lombok.extern.slf4j.Slf4j; /** * Rekognition Stream Processor client class which acts as a wrapper for invoking corresponding Rekognition APIs. * */ @Slf4j public class RekognitionStreamProcessor { private String streamProcessorName; private String kinesisVideoStreamArn; private String kinesisDataStreamArn; private String roleArn; private String collectionId; private float matchThreshold; private String region; private AmazonRekognition rekognitionClient; private RekognitionStreamProcessor(final Regions regions, final AWSCredentialsProvider provider, final RekognitionInput rekognitionInput) { this.streamProcessorName = rekognitionInput.getStreamingProcessorName(); this.kinesisVideoStreamArn = rekognitionInput.getKinesisVideoStreamArn(); this.kinesisDataStreamArn = rekognitionInput.getKinesisDataStreamArn(); this.roleArn = rekognitionInput.getIamRoleArn(); this.collectionId = rekognitionInput.getFaceCollectionId(); this.matchThreshold = rekognitionInput.getMatchThreshold(); rekognitionClient = AmazonRekognitionClientBuilder .standard() .withRegion(regions) .withCredentials(provider) .build(); } public static RekognitionStreamProcessor create(final Regions regions, final AWSCredentialsProvider provider, final RekognitionInput rekognitionInput) { return new RekognitionStreamProcessor(regions, provider, rekognitionInput); } /** * Creates a StreamProcess if it doesn't exist already. Once the stream processor is created, it's started and then * described to know the result of the stream processor. */ public void process() { // Creates a stream processor if it doesn't already exist and start. try { final DescribeStreamProcessorResult result = describeStreamProcessor(); if (!result.getStatus().equals(StreamProcessorStatus.RUNNING.toString())) { startStreamProcessor(); } } catch (final ResourceNotFoundException e) { log.info("StreamProcessor with name : {} doesnt exist. Creating...", streamProcessorName); createStreamProcessor(); startStreamProcessor(); } // Describe the Stream Processor results to log the status. describeStreamProcessor(); } public CreateStreamProcessorResult createStreamProcessor() { final KinesisVideoStream kinesisVideoStream = new KinesisVideoStream() .withArn(kinesisVideoStreamArn); final StreamProcessorInput streamProcessorInput = new StreamProcessorInput() .withKinesisVideoStream(kinesisVideoStream); final KinesisDataStream kinesisDataStream = new KinesisDataStream() .withArn(kinesisDataStreamArn); final StreamProcessorOutput streamProcessorOutput = new StreamProcessorOutput() .withKinesisDataStream(kinesisDataStream); final FaceSearchSettings faceSearchSettings = new FaceSearchSettings() .withCollectionId(collectionId) .withFaceMatchThreshold(matchThreshold); final StreamProcessorSettings streamProcessorSettings = new StreamProcessorSettings() .withFaceSearch(faceSearchSettings); final CreateStreamProcessorResult createStreamProcessorResult = rekognitionClient.createStreamProcessor(new CreateStreamProcessorRequest() .withInput(streamProcessorInput) .withOutput(streamProcessorOutput) .withSettings(streamProcessorSettings) .withRoleArn(roleArn) .withName(streamProcessorName)); log.info("StreamProcessorArn : {} ", createStreamProcessorResult.getStreamProcessorArn()); return createStreamProcessorResult; } public StartStreamProcessorResult startStreamProcessor() { final StartStreamProcessorResult startStreamProcessorResult = rekognitionClient.startStreamProcessor(new StartStreamProcessorRequest().withName(streamProcessorName)); log.info("SdkResponseMetadata : {} ", startStreamProcessorResult.getSdkResponseMetadata()); return startStreamProcessorResult; } public StopStreamProcessorResult stopStreamProcessor() { final StopStreamProcessorResult stopStreamProcessorResult = rekognitionClient.stopStreamProcessor(new StopStreamProcessorRequest().withName(streamProcessorName)); log.info("SdkResponseMetadata : {} ", stopStreamProcessorResult.getSdkResponseMetadata()); return stopStreamProcessorResult; } public DeleteStreamProcessorResult deleteStreamProcessor() { final DeleteStreamProcessorResult deleteStreamProcessorResult = rekognitionClient .deleteStreamProcessor(new DeleteStreamProcessorRequest().withName(streamProcessorName)); log.info("SdkResponseMetadata : {} ", deleteStreamProcessorResult.getSdkResponseMetadata()); return deleteStreamProcessorResult; } public DescribeStreamProcessorResult describeStreamProcessor() { final DescribeStreamProcessorResult describeStreamProcessorResult = rekognitionClient .describeStreamProcessor(new DescribeStreamProcessorRequest().withName(streamProcessorName)); log.info("Arn : {}", describeStreamProcessorResult.getStreamProcessorArn()); log.info("Input kinesisVideo stream : {} ", describeStreamProcessorResult.getInput().getKinesisVideoStream().getArn()); log.info("Output kinesisData stream {} ", describeStreamProcessorResult.getOutput().getKinesisDataStream().getArn()); log.info("RoleArn {} ", describeStreamProcessorResult.getRoleArn()); log.info( "CollectionId {} ", describeStreamProcessorResult.getSettings().getFaceSearch().getCollectionId()); log.info("Status {} ", describeStreamProcessorResult.getStatus()); log.info("Status message {} ", describeStreamProcessorResult.getStatusMessage()); log.info("Creation timestamp {} ", describeStreamProcessorResult.getCreationTimestamp()); log.info("Last update timestamp {} ", describeStreamProcessorResult.getLastUpdateTimestamp()); return describeStreamProcessorResult; } public ListStreamProcessorsResult listStreamProcessor() { final ListStreamProcessorsResult listStreamProcessorsResult = rekognitionClient.listStreamProcessors(new ListStreamProcessorsRequest().withMaxResults(100)); for (final StreamProcessor streamProcessor : listStreamProcessorsResult.getStreamProcessors()) { log.info("StreamProcessor name {} ", streamProcessor.getName()); log.info("Status {} ", streamProcessor.getStatus()); } return listStreamProcessorsResult; } }
4,997
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/rekognition
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/rekognition/pojo/KinesisVideo.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.rekognition.pojo; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; @JsonInclude(JsonInclude.Include.NON_NULL) public class KinesisVideo implements Serializable { @JsonProperty("StreamArn") private String streamArn; @JsonProperty("FragmentNumber") private String fragmentNumber; @JsonProperty("ServerTimestamp") private Double serverTimestamp; @JsonProperty("ProducerTimestamp") private Double producerTimestamp; @JsonProperty("FrameOffsetInSeconds") private Double frameOffsetInSeconds; @JsonIgnore private Map<String, Object> additionalProperties = new HashMap<String, Object>(); private final static long serialVersionUID = 4018546116449531242L; @JsonProperty("StreamArn") public String getStreamArn() { return streamArn; } @JsonProperty("StreamArn") public void setStreamArn(String streamArn) { this.streamArn = streamArn; } @JsonProperty("FragmentNumber") public String getFragmentNumber() { return fragmentNumber; } @JsonProperty("FragmentNumber") public void setFragmentNumber(String fragmentNumber) { this.fragmentNumber = fragmentNumber; } @JsonProperty("ServerTimestamp") public Double getServerTimestamp() { return serverTimestamp; } @JsonProperty("ServerTimestamp") public void setServerTimestamp(Double serverTimestamp) { this.serverTimestamp = serverTimestamp; } @JsonProperty("ProducerTimestamp") public Double getProducerTimestamp() { return producerTimestamp; } @JsonProperty("ProducerTimestamp") public void setProducerTimestamp(Double producerTimestamp) { this.producerTimestamp = producerTimestamp; } @JsonProperty("FrameOffsetInSeconds") public Double getFrameOffsetInSeconds() { return frameOffsetInSeconds; } @JsonProperty("FrameOffsetInSeconds") public void setFrameOffsetInSeconds(Double frameOffsetInSeconds) { this.frameOffsetInSeconds = frameOffsetInSeconds; } @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } @JsonAnySetter public void setAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); } @Override public String toString() { return new ToStringBuilder(this) .append("streamArn", streamArn) .append("fragmentNumber", fragmentNumber) .append("serverTimestamp", serverTimestamp) .append("producerTimestamp", producerTimestamp) .append("frameOffsetInSeconds", frameOffsetInSeconds) .append("additionalProperties", additionalProperties).toString(); } @Override public int hashCode() { return new HashCodeBuilder() .append(frameOffsetInSeconds) .append(fragmentNumber) .append(streamArn) .append(additionalProperties) .append(producerTimestamp) .append(serverTimestamp).toHashCode(); } @Override public boolean equals(Object other) { if (other == this) { return true; } if ((other instanceof KinesisVideo) == false) { return false; } KinesisVideo rhs = ((KinesisVideo) other); return new EqualsBuilder() .append(frameOffsetInSeconds, rhs.frameOffsetInSeconds) .append(fragmentNumber, rhs.fragmentNumber) .append(streamArn, rhs.streamArn) .append(additionalProperties, rhs.additionalProperties) .append(producerTimestamp, rhs.producerTimestamp) .append(serverTimestamp, rhs.serverTimestamp).isEquals(); } }
4,998
0
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/rekognition
Create_ds/amazon-kinesis-video-streams-parser-library/src/main/java/com/amazonaws/kinesisvideo/parser/rekognition/pojo/BoundingBox.java
/* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.amazonaws.kinesisvideo.parser.rekognition.pojo; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; @JsonInclude(JsonInclude.Include.NON_NULL) public class BoundingBox implements Serializable { @JsonProperty("Height") private Double height; @JsonProperty("Width") private Double width; @JsonProperty("Left") private Double left; @JsonProperty("Top") private Double top; @JsonIgnore private Map<String, Object> additionalProperties = new HashMap<String, Object>(); private final static long serialVersionUID = -3845089061670074615L; @JsonProperty("Height") public Double getHeight() { return height; } @JsonProperty("Height") public void setHeight(Double height) { this.height = height; } @JsonProperty("Width") public Double getWidth() { return width; } @JsonProperty("Width") public void setWidth(Double width) { this.width = width; } @JsonProperty("Left") public Double getLeft() { return left; } @JsonProperty("Left") public void setLeft(Double left) { this.left = left; } @JsonProperty("Top") public Double getTop() { return top; } @JsonProperty("Top") public void setTop(Double top) { this.top = top; } @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } @JsonAnySetter public void setAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); } @Override public String toString() { return new ToStringBuilder(this) .append("height", height) .append("width", width) .append("left", left) .append("top", top) .append("additionalProperties", additionalProperties) .toString(); } @Override public int hashCode() { return new HashCodeBuilder() .append(height) .append(additionalProperties) .append(width) .append(left) .append(top) .toHashCode(); } @Override public boolean equals(Object other) { if (other == this) { return true; } if ((other instanceof BoundingBox) == false) { return false; } BoundingBox rhs = ((BoundingBox) other); return new EqualsBuilder() .append(height, rhs.height) .append(additionalProperties, rhs.additionalProperties) .append(width, rhs.width) .append(left, rhs.left) .append(top, rhs.top) .isEquals(); } }
4,999