index int64 0 0 | repo_id stringlengths 9 205 | file_path stringlengths 31 246 | content stringlengths 1 12.2M | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/commons-pool/src/main/java/org/apache/commons/pool3 | Create_ds/commons-pool/src/main/java/org/apache/commons/pool3/proxy/JdkProxyHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License 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 org.apache.commons.pool3.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import org.apache.commons.pool3.UsageTracking;
/**
* Java reflection implementation of the proxy handler.
*
* @param <T> type of the wrapped pooled object
*
* @since 2.0
*/
final class JdkProxyHandler<T> extends BaseProxyHandler<T>
implements InvocationHandler {
/**
* Constructs a Java reflection proxy instance.
*
* @param pooledObject The object to wrap
* @param usageTracking The instance, if any (usually the object pool) to
* be provided with usage tracking information for this
* wrapped object
*/
JdkProxyHandler(final T pooledObject, final UsageTracking<T> usageTracking) {
super(pooledObject, usageTracking);
}
@Override
public Object invoke(final Object proxy, final Method method, final Object[] args)
throws Throwable {
return doInvoke(method, args);
}
}
| 5,300 |
0 | Create_ds/commons-pool/src/main/java/org/apache/commons/pool3 | Create_ds/commons-pool/src/main/java/org/apache/commons/pool3/proxy/ProxySource.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License 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 org.apache.commons.pool3.proxy;
import org.apache.commons.pool3.UsageTracking;
/**
* The interface that any provider of proxy instances must implement to allow the
* {@link ProxiedObjectPool} to create proxies as required.
*
* @param <T> type of the pooled object to be proxied
*
* @since 2.0
*/
interface ProxySource<T> {
/**
* Creates a new proxy object, wrapping the given pooled object.
*
* @param pooledObject The object to wrap
* @param usageTracking The instance, if any (usually the object pool) to
* be provided with usage tracking information for this
* wrapped object
*
* @return the new proxy object
*/
T createProxy(T pooledObject, UsageTracking<T> usageTracking);
/**
* Resolves the wrapped object from the given proxy.
*
* @param proxy The proxy object
*
* @return The pooled object wrapped by the given proxy
*/
T resolveProxy(T proxy);
}
| 5,301 |
0 | Create_ds/commons-pool/src/main/java/org/apache/commons/pool3 | Create_ds/commons-pool/src/main/java/org/apache/commons/pool3/proxy/CglibProxySource.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License 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 org.apache.commons.pool3.proxy;
import org.apache.commons.pool3.UsageTracking;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.Factory;
/**
* Provides proxy objects using CGLib.
*
* @param <T> type of the pooled object to be proxied
*
* @since 2.0
*/
public class CglibProxySource<T> implements ProxySource<T> {
private final Class<? extends T> superclass;
/**
* Constructs a new proxy source for the given class.
*
* @param superclass The class to proxy
*/
public CglibProxySource(final Class<? extends T> superclass) {
this.superclass = superclass;
}
@SuppressWarnings("unchecked") // Case to T on return
@Override
public T createProxy(final T pooledObject, final UsageTracking<T> usageTracking) {
final Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(superclass);
final CglibProxyHandler<T> proxyInterceptor =
new CglibProxyHandler<>(pooledObject, usageTracking);
enhancer.setCallback(proxyInterceptor);
return (T) enhancer.create();
}
@Override
public T resolveProxy(final T proxy) {
@SuppressWarnings("unchecked")
final
CglibProxyHandler<T> cglibProxyHandler =
(CglibProxyHandler<T>) ((Factory) proxy).getCallback(0);
return cglibProxyHandler.disableProxy();
}
/**
* @since 2.4.3
*/
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("CglibProxySource [superclass=");
builder.append(superclass);
builder.append("]");
return builder.toString();
}
}
| 5,302 |
0 | Create_ds/commons-pool/src/main/java/org/apache/commons/pool3 | Create_ds/commons-pool/src/main/java/org/apache/commons/pool3/proxy/ProxiedKeyedObjectPool.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License 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 org.apache.commons.pool3.proxy;
import java.util.List;
import java.util.NoSuchElementException;
import org.apache.commons.pool3.KeyedObjectPool;
import org.apache.commons.pool3.UsageTracking;
/**
* Create a new keyed object pool where the pooled objects are wrapped in
* proxies allowing better control of pooled objects and in particular the
* prevention of the continued use of an object by a client after that client
* returns the object to the pool.
*
* @param <K> type of the key
* @param <V> type of the pooled object
* @param <E> type of exception thrown by this pool
*
* @since 2.0
*/
public class ProxiedKeyedObjectPool<K, V, E extends Exception> implements KeyedObjectPool<K, V, E> {
private final KeyedObjectPool<K, V, E> pool;
private final ProxySource<V> proxySource;
/**
* Constructs a new proxied object pool.
*
* @param pool The object pool to wrap
* @param proxySource The source of the proxy objects
*/
public ProxiedKeyedObjectPool(final KeyedObjectPool<K, V, E> pool,
final ProxySource<V> proxySource) {
this.pool = pool;
this.proxySource = proxySource;
}
@Override
public void addObject(final K key) throws E, IllegalStateException,
UnsupportedOperationException {
pool.addObject(key);
}
@SuppressWarnings("unchecked")
@Override
public V borrowObject(final K key) throws E, NoSuchElementException,
IllegalStateException {
UsageTracking<V> usageTracking = null;
if (pool instanceof UsageTracking) {
usageTracking = (UsageTracking<V>) pool;
}
return proxySource.createProxy(pool.borrowObject(key), usageTracking);
}
@Override
public void clear() throws E, UnsupportedOperationException {
pool.clear();
}
@Override
public void clear(final K key) throws E, UnsupportedOperationException {
pool.clear(key);
}
@Override
public void close() {
pool.close();
}
@Override
public List<K> getKeys() {
return pool.getKeys();
}
@Override
public int getNumActive() {
return pool.getNumActive();
}
@Override
public int getNumActive(final K key) {
return pool.getNumActive(key);
}
@Override
public int getNumIdle() {
return pool.getNumIdle();
}
@Override
public int getNumIdle(final K key) {
return pool.getNumIdle(key);
}
@Override
public void invalidateObject(final K key, final V proxy) throws E {
pool.invalidateObject(key, proxySource.resolveProxy(proxy));
}
@Override
public void returnObject(final K key, final V proxy) throws E {
pool.returnObject(key, proxySource.resolveProxy(proxy));
}
/**
* @since 2.4.3
*/
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("ProxiedKeyedObjectPool [pool=");
builder.append(pool);
builder.append(", proxySource=");
builder.append(proxySource);
builder.append("]");
return builder.toString();
}
}
| 5,303 |
0 | Create_ds/commons-pool/src/main/java/org/apache/commons/pool3 | Create_ds/commons-pool/src/main/java/org/apache/commons/pool3/proxy/package-info.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License 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.
*/
/**
* Object pooling proxy implementation.
* <p>
* The <code>org.apache.commons.pool3.proxy</code> package defines a
* object pool that wraps all objects returned to clients. This allows it
* to disable those proxies when the objects are returned thereby enabling
* the continued use of those objects by clients to be detected..
* </p>
* <p>
* Support is provided for <code>java.lang.reflect.Proxy</code> and for
* <code>net.sf.cglib.proxy</code> based proxies. The latter, requires the
* additional of the optional Code Generation Library (GCLib).
* </p>
*/
package org.apache.commons.pool3.proxy;
| 5,304 |
0 | Create_ds/fineract-cn-api/src/test/java/org/apache/fineract/cn/api | Create_ds/fineract-cn-api/src/test/java/org/apache/fineract/cn/api/context/AutoUserContextTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License 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 org.apache.fineract.cn.api.context;
import org.apache.fineract.cn.api.util.UserContextHolder;
import org.junit.Assert;
import org.junit.Test;
/**
* @author Myrle Krantz
*/
public class AutoUserContextTest {
@Test
public void stateIsUndisturbedOutsideOfTryBlock()
{
UserContextHolder.setAccessToken("x", "y");
//noinspection EmptyTryBlock
try (final AutoUserContext ignored = new AutoUserContext("m", "n"))
{
Assert.assertEquals(UserContextHolder.checkedGetUser(), "m");
Assert.assertEquals(UserContextHolder.checkedGetAccessToken(), "n");
}
Assert.assertEquals(UserContextHolder.checkedGetUser(), "x");
Assert.assertEquals(UserContextHolder.checkedGetAccessToken(), "y");
UserContextHolder.clear();
}
} | 5,305 |
0 | Create_ds/fineract-cn-api/src/test/java/org/apache/fineract/cn/api | Create_ds/fineract-cn-api/src/test/java/org/apache/fineract/cn/api/util/UserContextHolderTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License 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 org.apache.fineract.cn.api.util;
import org.apache.commons.lang.RandomStringUtils;
import org.junit.Assert;
import org.junit.Test;
import java.util.Optional;
/**
* @author Myrle Krantz
*/
public class UserContextHolderTest {
@Test
public void testUserIdentifierCropping()
{
final String userIdentifier16 = RandomStringUtils.randomAlphanumeric(16);
UserContextHolder.setAccessToken(userIdentifier16, "x");
Assert.assertEquals(UserContextHolder.checkedGetUser(), userIdentifier16);
final String userIdentifier32 = RandomStringUtils.randomAlphanumeric(32);
UserContextHolder.setAccessToken(userIdentifier32, "x");
Assert.assertEquals(UserContextHolder.checkedGetUser(), userIdentifier32);
final String userIdentifier64 = userIdentifier32 + userIdentifier32;
UserContextHolder.setAccessToken(userIdentifier64, "x");
Assert.assertEquals(UserContextHolder.checkedGetUser(), userIdentifier32);
}
@Test(expected = IllegalStateException.class)
public void testUnsetUserIdentifier()
{
UserContextHolder.clear();
UserContextHolder.checkedGetUser();
}
@Test(expected = IllegalStateException.class)
public void testUnsetAccessToken()
{
UserContextHolder.clear();
UserContextHolder.checkedGetAccessToken();
}
@Test
public void testSimpleUnSetAndGet()
{
UserContextHolder.clear();
final Optional<UserContext> userContext = UserContextHolder.getUserContext();
Assert.assertTrue(!userContext.isPresent());
}
@Test
public void testSimpleSetAndGet()
{
final UserContext setUserContext = new UserContext("x", "y");
UserContextHolder.clear();
UserContextHolder.setUserContext(setUserContext);
UserContextHolder.getUserContext().ifPresent(x -> Assert.assertEquals(setUserContext, x));
}
}
| 5,306 |
0 | Create_ds/fineract-cn-api/src/test/java/org/apache/fineract/cn/api | Create_ds/fineract-cn-api/src/test/java/org/apache/fineract/cn/api/util/TokenedTargetInterceptorTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License 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 org.apache.fineract.cn.api.util;
import feign.RequestTemplate;
import org.apache.fineract.cn.api.context.AutoUserContext;
import org.junit.Assert;
import org.junit.Test;
/**
* @author Myrle Krantz
*/
public class TokenedTargetInterceptorTest {
@Test
public void test() {
final TokenedTargetInterceptor testSubject = new TokenedTargetInterceptor();
final RequestTemplate requestTemplate = new RequestTemplate();
try (final AutoUserContext ignored = new AutoUserContext("x", "y")) {
testSubject.apply(requestTemplate);
}
Assert.assertTrue(requestTemplate.headers().get(ApiConstants.USER_HEADER).contains("x"));
Assert.assertTrue(requestTemplate.headers().get(ApiConstants.AUTHORIZATION_HEADER).contains("y"));
}
} | 5,307 |
0 | Create_ds/fineract-cn-api/src/test/java/org/apache/fineract/cn/api | Create_ds/fineract-cn-api/src/test/java/org/apache/fineract/cn/api/util/AnnotatedErrorDecoderTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License 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 org.apache.fineract.cn.api.util;
import feign.Feign;
import feign.FeignException;
import feign.Response;
import org.apache.fineract.cn.api.annotation.ThrowsException;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
/**
* @author Myrle Krantz
*/
@RunWith(Parameterized.class)
public class AnnotatedErrorDecoderTest {
private final TestCase testCase;
public AnnotatedErrorDecoderTest(final TestCase testCase) {
this.testCase = testCase;
}
@Parameterized.Parameters
public static Collection testCases() throws NoSuchMethodException {
final Collection<TestCase> ret = new ArrayList<>();
final Response emptyInternalServerErrorResponse = Response.builder()
.status(HttpStatus.INTERNAL_SERVER_ERROR.value())
.body("blah", Charset.defaultCharset())
.headers(Collections.emptyMap())
.build();
final Response emptyBadRequestResponse = Response.builder()
.status(HttpStatus.BAD_REQUEST.value())
.body("blah", Charset.defaultCharset())
.headers(Collections.emptyMap())
.build();
final Response emptyBadRequestResponseWithNoBody = Response.builder()
.status(HttpStatus.BAD_REQUEST.value())
.headers(Collections.emptyMap())
.build();
final Response emptyNotFoundRequestResponse = Response.builder()
.status(HttpStatus.NOT_FOUND.value())
.body("blah", Charset.defaultCharset())
.headers(Collections.emptyMap())
.build();
final Response emptyConflictResponse = Response.builder()
.status(HttpStatus.CONFLICT.value())
.body("blah", Charset.defaultCharset())
.headers(Collections.emptyMap())
.build();
final Response emptyIAmATeapotResponse = Response.builder()
.status(HttpStatus.I_AM_A_TEAPOT.value())
.body("blah", Charset.defaultCharset())
.headers(Collections.emptyMap())
.build();
final Response emptyUnauthorizedResponse = Response.builder()
.status(HttpStatus.UNAUTHORIZED.value())
.body("blah", Charset.defaultCharset())
.headers(Collections.emptyMap())
.build();
final Response emptyForbiddenResponse = Response.builder()
.status(HttpStatus.FORBIDDEN.value())
.body("blah", Charset.defaultCharset())
.headers(Collections.emptyMap())
.build();
final String madeUpMethodKey = "x";
final String annotationlessMethodKey =
Feign.configKey(AnnotationlessInterface.class, AnnotationlessInterface.class.getMethod("method"));
final String oneAnnotatedMethodKey =
Feign.configKey(OneMethodInterface.class, OneMethodInterface.class.getMethod("method"));
final String onceAnnotatedMethodKey =
Feign.configKey(OneMethodOneAnnotationInterface.class, OneMethodOneAnnotationInterface.class.getMethod("method"));
final String onceAnnotatedWithStringExceptionMethodKey =
Feign.configKey(OneMethodOneAnnotationStringParameteredExceptionInterface.class, OneMethodOneAnnotationStringParameteredExceptionInterface.class.getMethod("method"));
ret.add(new TestCase("Methodless interface")
.clazz(MethodlessInterface.class)
.methodKey(madeUpMethodKey)
.response(emptyConflictResponse)
.expectedResult(FeignException.errorStatus(madeUpMethodKey, emptyConflictResponse)));
ret.add(new TestCase("Annotationless interface")
.clazz(AnnotationlessInterface.class)
.methodKey(annotationlessMethodKey)
.response(emptyConflictResponse)
.expectedResult(FeignException.errorStatus(annotationlessMethodKey, emptyConflictResponse)));
ret.add(new TestCase("Interface with one method mapped to parameterless exception")
.clazz(OneMethodInterface.class)
.methodKey(oneAnnotatedMethodKey)
.response(emptyBadRequestResponse)
.expectedResult(new ParameterlessException()));
ret.add(new TestCase("Interface with one method mapped to parametered exception")
.clazz(OneMethodInterface.class)
.methodKey(oneAnnotatedMethodKey)
.response(emptyConflictResponse)
.expectedResult(new ParameteredException(emptyConflictResponse)));
ret.add(new TestCase("Interface with one method mapped to an exception which can't be constructed by reflection")
.clazz(OneMethodInterface.class)
.methodKey(oneAnnotatedMethodKey)
.response(emptyIAmATeapotResponse)
.expectedResult(FeignException.errorStatus(oneAnnotatedMethodKey, emptyIAmATeapotResponse)));
ret.add(new TestCase("Interface with one method, not mapped to the response code returned")
.clazz(OneMethodInterface.class)
.methodKey(oneAnnotatedMethodKey)
.response(emptyUnauthorizedResponse)
.expectedResult(FeignException.errorStatus(oneAnnotatedMethodKey, emptyUnauthorizedResponse)));
ret.add(new TestCase("Interface with one method that has one annotation")
.clazz(OneMethodOneAnnotationInterface.class)
.methodKey(onceAnnotatedMethodKey)
.response(emptyBadRequestResponse)
.expectedResult(new ParameterlessException()));
ret.add(new TestCase("Interface with one method that has one annotation containing an exception which accepts a string parameter.")
.clazz(OneMethodOneAnnotationStringParameteredExceptionInterface.class)
.methodKey(onceAnnotatedWithStringExceptionMethodKey)
.response(emptyBadRequestResponse)
.expectedResult(new StringParameteredException("blah")));
ret.add(new TestCase("Bad request on an interface in which bad request isn't mapped.")
.clazz(AnnotationlessInterface.class)
.methodKey(annotationlessMethodKey)
.response(emptyBadRequestResponse)
.expectedResult(new IllegalArgumentException("blah")));
ret.add(new TestCase("Bad request with no body on an interface in which bad request isn't mapped.")
.clazz(AnnotationlessInterface.class)
.methodKey(annotationlessMethodKey)
.response(emptyBadRequestResponseWithNoBody)
.expectedResult(new IllegalArgumentException((String)null)));
ret.add(new TestCase("Not found request on an interface in which not found request isn't mapped.")
.clazz(AnnotationlessInterface.class)
.methodKey(annotationlessMethodKey)
.response(emptyNotFoundRequestResponse)
.expectedResult(new NotFoundException("blah")));
ret.add(new TestCase("Request with invalid token.")
.clazz(OneMethodOneAnnotationInterface.class)
.methodKey(onceAnnotatedMethodKey)
.response(emptyForbiddenResponse)
.expectedResult(new InvalidTokenException("blah")));
ret.add(new TestCase("Internal Server Error on an interface in which internal server error isn't mapped.")
.clazz(AnnotationlessInterface.class)
.methodKey(annotationlessMethodKey)
.response(emptyInternalServerErrorResponse)
.expectedResult(new InternalServerError("blah")));
return ret;
}
@SuppressWarnings("ThrowableResultOfMethodCallIgnored")
@Test
public void checkMapping() {
final AnnotatedErrorDecoder testSubject = new AnnotatedErrorDecoder(
LoggerFactory.getLogger(AnnotatedErrorDecoderTest.class.getName()), testCase.getClazz());
final Exception result = testSubject.decode(testCase.getMethodKey(), testCase.getResponse());
Assert.assertEquals("Test case \"" + testCase.getName() + "\" failed.",
testCase.expectedResult().getClass(), result.getClass());
Assert.assertEquals("Test case \"" + testCase.getName() + "\" failed.",
testCase.expectedResult().getMessage(), result.getMessage());
}
private interface MethodlessInterface {
}
private interface AnnotationlessInterface {
@SuppressWarnings("unused")
void method();
}
private interface OneMethodInterface {
@SuppressWarnings("unused")
@ThrowsException(status = HttpStatus.BAD_REQUEST, exception = ParameterlessException.class)
@ThrowsException(status = HttpStatus.CONFLICT, exception = ParameteredException.class)
@ThrowsException(status = HttpStatus.I_AM_A_TEAPOT, exception = WrongParameteredException.class)
void method();
}
private interface OneMethodOneAnnotationInterface {
@SuppressWarnings("unused")
@ThrowsException(status = HttpStatus.BAD_REQUEST, exception = ParameterlessException.class)
void method();
}
private interface OneMethodOneAnnotationStringParameteredExceptionInterface {
@SuppressWarnings("unused")
@ThrowsException(status = HttpStatus.BAD_REQUEST, exception = StringParameteredException.class)
void method();
}
private static class TestCase {
private final String name;
private Class clazz;
private String methodKey;
private Response response;
private Exception expectedResult;
private TestCase(final String name) {
this.name = name;
}
public String toString() {
return name;
}
TestCase clazz(final Class newVal) {
clazz = newVal;
return this;
}
TestCase methodKey(final String newVal) {
methodKey = newVal;
return this;
}
TestCase response(final Response newVal) {
response = newVal;
return this;
}
TestCase expectedResult(final Exception newVal) {
expectedResult = newVal;
return this;
}
Class getClazz() {
return clazz;
}
String getMethodKey() {
return methodKey;
}
Response getResponse() {
return response;
}
Exception expectedResult() {
return expectedResult;
}
String getName() {
return name;
}
}
private static class ParameterlessException extends RuntimeException {
@SuppressWarnings("WeakerAccess")
public ParameterlessException() {
super("I am a parameterless exception. Aren't I cool.");
}
}
private static class ParameteredException extends RuntimeException {
@SuppressWarnings("WeakerAccess")
public ParameteredException(final Response response) {
super("I am a parametered exception with a response of " + response.toString());
}
}
private static class StringParameteredException extends RuntimeException {
@SuppressWarnings("WeakerAccess")
public StringParameteredException(final String response) {
super(response);
}
}
private static class WrongParameteredException extends RuntimeException {
public WrongParameteredException(final Integer message) {
super(message.toString());
}
}
}
| 5,308 |
0 | Create_ds/fineract-cn-api/src/test/java/org/apache/fineract/cn/api | Create_ds/fineract-cn-api/src/test/java/org/apache/fineract/cn/api/util/TenantedTargetInterceptorTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License 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 org.apache.fineract.cn.api.util;
import feign.RequestTemplate;
import org.apache.fineract.cn.lang.TenantContextHolder;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;
/**
* @author Myrle Krantz
*/
@RunWith(BlockJUnit4ClassRunner.class)
public class TenantedTargetInterceptorTest {
@Test
public void test() {
final TenantedTargetInterceptor testSubject = new TenantedTargetInterceptor();
final RequestTemplate requestTemplate = new RequestTemplate();
final String tenantId = "bleblablub";
TenantContextHolder.setIdentifier(tenantId);
testSubject.apply(requestTemplate);
Assert.assertTrue(requestTemplate.headers().get("X-Tenant-Identifier").contains(tenantId));
}
}
| 5,309 |
0 | Create_ds/fineract-cn-api/src/test/java/org/apache/fineract/cn/api | Create_ds/fineract-cn-api/src/test/java/org/apache/fineract/cn/api/util/CookieInterceptingClientTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License 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 org.apache.fineract.cn.api.util;
import feign.Request;
import feign.RequestTemplate;
import feign.Response;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
import org.springframework.http.HttpStatus;
import java.io.IOException;
import java.net.CookieManager;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.*;
/**
* @author Myrle Krantz
*/
public class CookieInterceptingClientTest {
private final static String TEST_URL = "http://igle.pop.org/app/v1/";
@Test
public void cookiesPlacedInJarThenAttachedToRequest() throws IOException, URISyntaxException {
final CookieInterceptingClient testSubject = new CookieInterceptingClient(TEST_URL);
//response
final CookieInterceptingClient spiedTestSubject = Mockito.spy(testSubject);
final Map<String, Collection<String>> cookieHeaders = new HashMap<>();
cookieHeaders.put("Set-Cookie", Collections.singleton("x=y;Path=/app/v1"));
final Response dummyResponse = Response.builder()
.status(HttpStatus.INTERNAL_SERVER_ERROR.value())
.reason("blah")
.headers(cookieHeaders)
.build();
Mockito.doReturn(dummyResponse).when(spiedTestSubject).superExecute(Mockito.anyObject(), Mockito.anyObject());
spiedTestSubject.execute(Request.create("", TEST_URL +"request", Collections.emptyMap(), new byte[]{}, Charset.defaultCharset()), new Request.Options());
final Map<String, List<String>> ret = testSubject.cookieManager.get(new URI(TEST_URL), Collections.emptyMap());
Assert.assertEquals(ret.get("Cookie"), Collections.singletonList("x=y"));
//request
final RequestTemplate dummyRequestTemplate = new RequestTemplate();
dummyRequestTemplate.append("/request");
testSubject.getCookieInterceptor().apply(dummyRequestTemplate);
Assert.assertEquals(dummyRequestTemplate.headers().get("Cookie"), Collections.singletonList("x=y"));
}
@Test(expected = IllegalStateException.class)
public void unexpectedCookieManagerFailure() throws IOException {
final CookieManager cookieManagerMock = Mockito.mock(CookieManager.class);
//noinspection unchecked
Mockito.when(cookieManagerMock.get(Mockito.anyObject(), Mockito.anyObject())).thenThrow(IOException.class);
final CookieInterceptingClient testSubject = new CookieInterceptingClient(TEST_URL, cookieManagerMock);
final RequestTemplate dummyRequestTemplate = new RequestTemplate();
dummyRequestTemplate.append("/request");
testSubject.getCookieInterceptor().apply(dummyRequestTemplate);
}
@Test()
public void setCookieBetweenRemoteCalls() {
final CookieInterceptingClient testSubject = new CookieInterceptingClient(TEST_URL);
testSubject.putCookie("/blah", "token", "Bearerbear");
//request
final RequestTemplate dummyRequestTemplate = new RequestTemplate();
dummyRequestTemplate.append("/request");
testSubject.getCookieInterceptor().apply(dummyRequestTemplate);
Assert.assertEquals(Collections.singletonList("token=Bearerbear"), dummyRequestTemplate.headers().get("Cookie"));
}
} | 5,310 |
0 | Create_ds/fineract-cn-api/src/main/java/org/apache/fineract/cn/api | Create_ds/fineract-cn-api/src/main/java/org/apache/fineract/cn/api/context/AutoUserContext.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License 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 org.apache.fineract.cn.api.context;
import org.apache.fineract.cn.api.util.UserContext;
import org.apache.fineract.cn.api.util.UserContextHolder;
import java.util.Optional;
/**
* @author Myrle Krantz
*/
@SuppressWarnings({"OptionalUsedAsFieldOrParameterType", "WeakerAccess"})
public class AutoUserContext implements AutoCloseable {
private final Optional<UserContext> previousUserContext;
public AutoUserContext(final String userName, final String accessToken) {
previousUserContext = UserContextHolder.getUserContext();
UserContextHolder.setAccessToken(userName, accessToken);
}
@Override public void close() {
UserContextHolder.clear();
previousUserContext.ifPresent(UserContextHolder::setUserContext);
}
} | 5,311 |
0 | Create_ds/fineract-cn-api/src/main/java/org/apache/fineract/cn/api | Create_ds/fineract-cn-api/src/main/java/org/apache/fineract/cn/api/context/AutoGuest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License 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 org.apache.fineract.cn.api.context;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("unused")
public class AutoGuest extends AutoUserContext {
public AutoGuest() {
super("guest", "N/A");
}
}
| 5,312 |
0 | Create_ds/fineract-cn-api/src/main/java/org/apache/fineract/cn/api | Create_ds/fineract-cn-api/src/main/java/org/apache/fineract/cn/api/context/AutoSeshat.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License 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 org.apache.fineract.cn.api.context;
import org.apache.fineract.cn.api.util.ApiConstants;
/**
* @author Myrle Krantz
*/
@SuppressWarnings({"WeakerAccess", "unused"})
public class AutoSeshat extends AutoUserContext{
public AutoSeshat(String token) {
super(ApiConstants.SYSTEM_SU, token);
}
}
| 5,313 |
0 | Create_ds/fineract-cn-api/src/main/java/org/apache/fineract/cn/api | Create_ds/fineract-cn-api/src/main/java/org/apache/fineract/cn/api/util/AnnotatedErrorDecoder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License 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 org.apache.fineract.cn.api.util;
import feign.Feign;
import feign.FeignException;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import org.apache.fineract.cn.api.annotation.ThrowsException;
import org.apache.fineract.cn.api.annotation.ThrowsExceptions;
import org.slf4j.Logger;
import org.springframework.http.HttpStatus;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Optional;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("WeakerAccess")
public class AnnotatedErrorDecoder implements ErrorDecoder {
private final Class feignClientClass;
private final Logger logger;
public AnnotatedErrorDecoder(final Logger logger, final Class feignClientClass) {
this.logger = logger;
this.feignClientClass = feignClientClass;
}
@Override
public Exception decode(
final String methodKey,
final Response response) {
final Optional<Exception> ret =
Arrays.stream(feignClientClass.getMethods())
.filter(method -> Feign.configKey(feignClientClass, method).equals(methodKey))
.map(method -> {
final Optional<ThrowsException> annotation = getMatchingAnnotation(response, method);
return annotation.flatMap(a -> constructException(response, a));
})
.findAny().flatMap(x -> x);
return ret.orElse(getAlternative(methodKey, response));
}
private RuntimeException getAlternative(final String methodKey, final Response response) {
final String bodyText = stringifyBody(response);
if (response.status() == HttpStatus.BAD_REQUEST.value()) {
return new IllegalArgumentException(bodyText);
} else if (response.status() == HttpStatus.FORBIDDEN.value()) {
return new InvalidTokenException(bodyText);
} else if (response.status() == HttpStatus.NOT_FOUND.value()) {
return new NotFoundException(bodyText);
} else if (response.status() == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
return new InternalServerError(bodyText);
} else {
return FeignException.errorStatus(methodKey, response);
}
}
private String stringifyBody(final Response response) {
try {
if (response.body() != null)
return Util.toString(response.body().asReader());
} catch (IOException ignored) {
}
return null;
}
private Optional<ThrowsException> getMatchingAnnotation(
final Response response,
final Method method) {
final ThrowsExceptions throwsExceptionsAnnotation =
method.getAnnotation(ThrowsExceptions.class);
if (throwsExceptionsAnnotation == null) {
final ThrowsException throwsExceptionAnnotation =
method.getAnnotation(ThrowsException.class);
if ((throwsExceptionAnnotation != null) &&
statusMatches(response, throwsExceptionAnnotation)) {
return Optional.of(throwsExceptionAnnotation);
}
} else {
return Arrays.stream(throwsExceptionsAnnotation.value())
.filter(throwsExceptionAnnotation -> statusMatches(response,
throwsExceptionAnnotation))
.findAny();
}
return Optional.empty();
}
private boolean statusMatches(final Response response,
final ThrowsException throwsExceptionAnnotation) {
return throwsExceptionAnnotation.status().value() == response.status();
}
private Optional<Exception> constructException(
final Response response,
final ThrowsException throwsExceptionAnnotations) {
try {
try {
final Constructor<? extends RuntimeException> oneResponseArgumentConstructor =
throwsExceptionAnnotations.exception().getConstructor(Response.class);
return Optional.of(oneResponseArgumentConstructor.newInstance(response));
} catch (final NoSuchMethodException e) {
try {
final Constructor<? extends RuntimeException> noArgumentConstructor =
throwsExceptionAnnotations.exception().getConstructor();
return Optional.of(noArgumentConstructor.newInstance());
}
catch (final NoSuchMethodException e2) {
final Constructor<? extends RuntimeException> noStringArgumentConstructor =
throwsExceptionAnnotations.exception().getConstructor(String.class);
return Optional.of(noStringArgumentConstructor.newInstance(stringifyBody(response)));
}
}
} catch (final InvocationTargetException
| IllegalAccessException
| InstantiationException
| NoSuchMethodException e) {
logger.error("Instantiating exception {}, in for status {} failed with an exception",
throwsExceptionAnnotations.exception(), throwsExceptionAnnotations.status(), e);
return Optional.empty();
}
}
}
| 5,314 |
0 | Create_ds/fineract-cn-api/src/main/java/org/apache/fineract/cn/api | Create_ds/fineract-cn-api/src/main/java/org/apache/fineract/cn/api/util/TokenedTargetInterceptor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License 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 org.apache.fineract.cn.api.util;
import feign.RequestInterceptor;
import feign.RequestTemplate;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("WeakerAccess")
public class TokenedTargetInterceptor implements RequestInterceptor {
@Override
public void apply(final RequestTemplate template) {
UserContextHolder.getUserContext()
.map(UserContext::getAccessToken)
.ifPresent(token -> template.header(ApiConstants.AUTHORIZATION_HEADER, token));
UserContextHolder.getUserContext()
.map(UserContext::getUser)
.ifPresent(user -> template.header(ApiConstants.USER_HEADER, user));
}
}
| 5,315 |
0 | Create_ds/fineract-cn-api/src/main/java/org/apache/fineract/cn/api | Create_ds/fineract-cn-api/src/main/java/org/apache/fineract/cn/api/util/CookieInterceptingClient.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License 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 org.apache.fineract.cn.api.util;
import feign.*;
import java.io.IOException;
import java.net.CookieManager;
import java.net.URI;
import java.util.*;
import java.util.stream.Collectors;
/**
* Keeps the cookies for this client and appends them to requests.
* See also CookieInterceptor.
*
* @author Myrle Krantz
*/
class CookieInterceptingClient extends Client.Default {
final CookieManager cookieManager;
private final String target;
CookieInterceptingClient(final String target) {
this(target, new CookieManager());
}
CookieInterceptingClient(final String target, final CookieManager cookieManager)
{
super(null, null);
this.cookieManager = cookieManager;
this.target = target;
}
RequestInterceptor getCookieInterceptor() {
return new CookieInterceptor();
}
void putCookie(final String relativeUrl, final String cookieName, final String cookieValue) {
try {
final Map<String, List<String>> map = new HashMap<>();
map.put("Set-Cookie", Collections.singletonList(cookieName + "=" + cookieValue));
cookieManager.put(mapUriType(target + relativeUrl), map);
} catch (final IOException e) {
throw new IllegalStateException("Mapping cookies failed unexpectedly.");
}
}
private class CookieInterceptor implements RequestInterceptor {
@Override
public void apply(final RequestTemplate template) {
try {
final Map<String, List<String>> cookieHeaders =
cookieManager.get(mapUriType(target + template.url()), mapHeadersType(template.headers()));
cookieHeaders.entrySet().forEach(entry -> template.header(entry.getKey(), entry.getValue()));
} catch (final IOException e) {
throw new IllegalStateException("Mapping cookies failed unexpectedly.");
}
}
}
/**
* Seam for testing
*/
Response superExecute(final Request request, final Request.Options options) throws IOException {
return super.execute(request, options);
}
@Override
public Response execute(final Request request, final Request.Options options) throws IOException {
final Response ret = superExecute(request, options);
cookieManager.put(mapUriType(request.url()), mapHeadersType(ret.headers()));
return ret;
}
private static URI mapUriType(final String url) {
return URI.create(url);
}
private static Map<String, List<String>> mapHeadersType(final Map<String, Collection<String>> headers) {
final HashMap<String, List<String>> ret = new HashMap<>();
headers.entrySet().forEach(entry ->
ret.put(entry.getKey(), changeCollectionToList(entry.getValue())));
return ret;
}
private static List<String> changeCollectionToList(final Collection<String> value) {
return value.stream().collect(Collectors.toList());
}
} | 5,316 |
0 | Create_ds/fineract-cn-api/src/main/java/org/apache/fineract/cn/api | Create_ds/fineract-cn-api/src/main/java/org/apache/fineract/cn/api/util/FeignTargetWithCookieJar.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License 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 org.apache.fineract.cn.api.util;
/**
* @author Myrle Krantz
*/
@SuppressWarnings({"WeakerAccess", "unused"})
public class FeignTargetWithCookieJar<T> {
private final T feignTarget;
private final CookieInterceptingClient cookieInterceptor;
FeignTargetWithCookieJar(final T feignTarget, final CookieInterceptingClient cookieInterceptor) {
this.feignTarget = feignTarget;
this.cookieInterceptor = cookieInterceptor;
}
public void putCookie(final String relativeUrl, final String cookieName, final String cookieValue) {
this.cookieInterceptor.putCookie(relativeUrl, cookieName, cookieValue);
}
public T getFeignTarget() {
return feignTarget;
}
}
| 5,317 |
0 | Create_ds/fineract-cn-api/src/main/java/org/apache/fineract/cn/api | Create_ds/fineract-cn-api/src/main/java/org/apache/fineract/cn/api/util/InternalServerError.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License 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 org.apache.fineract.cn.api.util;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("WeakerAccess")
public class InternalServerError extends RuntimeException {
InternalServerError(final String reason) {
super(reason);
}
}
| 5,318 |
0 | Create_ds/fineract-cn-api/src/main/java/org/apache/fineract/cn/api | Create_ds/fineract-cn-api/src/main/java/org/apache/fineract/cn/api/util/CustomFeignClientsConfiguration.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License 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 org.apache.fineract.cn.api.util;
import feign.Feign;
import feign.Target;
import feign.codec.Decoder;
import feign.codec.Encoder;
import feign.gson.GsonDecoder;
import feign.gson.GsonEncoder;
import org.apache.fineract.cn.api.config.ApiConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.cloud.netflix.feign.FeignClientsConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;
/**
* @author Myrle Krantz
*/
//@EnableApiFactory (for logger)
@SuppressWarnings({"unused"})
public class CustomFeignClientsConfiguration extends FeignClientsConfiguration {
private static class AnnotatedErrorDecoderFeignBuilder extends Feign.Builder {
private final Logger logger;
AnnotatedErrorDecoderFeignBuilder(final Logger logger) {
this.logger = logger;
}
public <T> T target(Target<T> target) {
this.errorDecoder(new AnnotatedErrorDecoder(logger, target.type()));
return build().newInstance(target);
}
}
@Bean
@ConditionalOnMissingBean
public TenantedTargetInterceptor tenantedTargetInterceptor()
{
return new TenantedTargetInterceptor();
}
@Bean
@ConditionalOnMissingBean
public TokenedTargetInterceptor tokenedTargetInterceptor()
{
return new TokenedTargetInterceptor();
}
@Bean
@ConditionalOnMissingBean
public Decoder feignDecoder() {
return new GsonDecoder();
}
@Bean
@ConditionalOnMissingBean
public Encoder feignEncoder() {
return new GsonEncoder();
}
@Bean(name = ApiConfiguration.LOGGER_NAME)
public Logger logger() {
return LoggerFactory.getLogger(ApiConfiguration.LOGGER_NAME);
}
@Bean
@Scope("prototype")
@ConditionalOnMissingBean
public Feign.Builder feignBuilder(@Qualifier(ApiConfiguration.LOGGER_NAME) final Logger logger) {
return new AnnotatedErrorDecoderFeignBuilder(logger);
}
} | 5,319 |
0 | Create_ds/fineract-cn-api/src/main/java/org/apache/fineract/cn/api | Create_ds/fineract-cn-api/src/main/java/org/apache/fineract/cn/api/util/ApiFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License 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 org.apache.fineract.cn.api.util;
import feign.Feign;
import feign.gson.GsonDecoder;
import feign.gson.GsonEncoder;
import org.apache.fineract.cn.api.config.ApiConfiguration;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.netflix.feign.support.SpringMvcContract;
import org.springframework.stereotype.Component;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("unused")
@Component
public class ApiFactory {
private final Logger logger;
@Autowired
public ApiFactory(@Qualifier(ApiConfiguration.LOGGER_NAME) final Logger logger) {
this.logger = logger;
}
public <T> T create(final Class<T> clazz, final String target) {
final CookieInterceptingClient client = new CookieInterceptingClient(target);
return Feign.builder()
.contract(new SpringMvcContract())
.client(client)
.errorDecoder(new AnnotatedErrorDecoder(logger, clazz))
.requestInterceptor(new TenantedTargetInterceptor())
.requestInterceptor(new TokenedTargetInterceptor())
.requestInterceptor(new EmptyBodyInterceptor())
.requestInterceptor(client.getCookieInterceptor())
.decoder(new GsonDecoder())
.encoder(new GsonEncoder())
.target(clazz, target);
}
public <T> FeignTargetWithCookieJar<T> createWithCookieJar(final Class<T> clazz, final String target) {
final CookieInterceptingClient client = new CookieInterceptingClient(target);
final T feignTarget = Feign.builder()
.contract(new SpringMvcContract())
.client(client)
.errorDecoder(new AnnotatedErrorDecoder(logger, clazz))
.requestInterceptor(new TenantedTargetInterceptor())
.requestInterceptor(new TokenedTargetInterceptor())
.requestInterceptor(new EmptyBodyInterceptor())
.requestInterceptor(client.getCookieInterceptor())
.decoder(new GsonDecoder())
.encoder(new GsonEncoder())
.target(clazz, target);
return new FeignTargetWithCookieJar<>(feignTarget, client);
}
}
| 5,320 |
0 | Create_ds/fineract-cn-api/src/main/java/org/apache/fineract/cn/api | Create_ds/fineract-cn-api/src/main/java/org/apache/fineract/cn/api/util/InvalidTokenException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License 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 org.apache.fineract.cn.api.util;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("WeakerAccess")
public class InvalidTokenException extends RuntimeException {
public InvalidTokenException(final String reason) {
super(reason);
}
}
| 5,321 |
0 | Create_ds/fineract-cn-api/src/main/java/org/apache/fineract/cn/api | Create_ds/fineract-cn-api/src/main/java/org/apache/fineract/cn/api/util/ApiConstants.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License 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 org.apache.fineract.cn.api.util;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("WeakerAccess")
public interface ApiConstants {
String AUTHORIZATION_HEADER = "Authorization";
String USER_HEADER = "User";
String SYSTEM_SU = "wepemnefret";
}
| 5,322 |
0 | Create_ds/fineract-cn-api/src/main/java/org/apache/fineract/cn/api | Create_ds/fineract-cn-api/src/main/java/org/apache/fineract/cn/api/util/UserContext.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License 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 org.apache.fineract.cn.api.util;
import javax.annotation.Nonnull;
import java.util.Objects;
/**
* @author Myrle Krantz
*/
public class UserContext {
private final String user;
private final String accessToken;
UserContext(@Nonnull String user, @Nonnull String accessToken) {
this.user = user;
this.accessToken = accessToken;
}
@SuppressWarnings("WeakerAccess")
@Nonnull public String getUser() {
return user;
}
@SuppressWarnings("WeakerAccess")
@Nonnull public String getAccessToken() {
return accessToken;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UserContext that = (UserContext) o;
return Objects.equals(user, that.user) &&
Objects.equals(accessToken, that.accessToken);
}
@Override
public int hashCode() {
return Objects.hash(user, accessToken);
}
}
| 5,323 |
0 | Create_ds/fineract-cn-api/src/main/java/org/apache/fineract/cn/api | Create_ds/fineract-cn-api/src/main/java/org/apache/fineract/cn/api/util/NotFoundException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License 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 org.apache.fineract.cn.api.util;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("WeakerAccess")
public class NotFoundException extends RuntimeException {
public NotFoundException(final String reason) {
super(reason);
}
}
| 5,324 |
0 | Create_ds/fineract-cn-api/src/main/java/org/apache/fineract/cn/api | Create_ds/fineract-cn-api/src/main/java/org/apache/fineract/cn/api/util/TenantedTargetInterceptor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License 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 org.apache.fineract.cn.api.util;
import static org.apache.fineract.cn.lang.config.TenantHeaderFilter.TENANT_HEADER;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.apache.fineract.cn.lang.TenantContextHolder;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("WeakerAccess")
public class TenantedTargetInterceptor implements RequestInterceptor {
@Override
public void apply(final RequestTemplate template) {
TenantContextHolder.identifier()
.ifPresent(tenantIdentifier -> template.header(TENANT_HEADER, tenantIdentifier));
}
}
| 5,325 |
0 | Create_ds/fineract-cn-api/src/main/java/org/apache/fineract/cn/api | Create_ds/fineract-cn-api/src/main/java/org/apache/fineract/cn/api/util/UserContextHolder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License 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 org.apache.fineract.cn.api.util;
import org.springframework.util.Assert;
import javax.annotation.Nonnull;
import java.util.Optional;
/**
* @author Myrle Krantz
*/
@SuppressWarnings({"WeakerAccess", "unused"})
public class UserContextHolder {
private static final InheritableThreadLocal<UserContext> THREAD_LOCAL = new InheritableThreadLocal<>();
private UserContextHolder() {
}
@Nonnull
public static String checkedGetAccessToken() {
return Optional.ofNullable(UserContextHolder.THREAD_LOCAL.get())
.map(UserContext::getAccessToken)
.orElseThrow(IllegalStateException::new);
}
@Nonnull
public static String checkedGetUser() {
return Optional.ofNullable(UserContextHolder.THREAD_LOCAL.get())
.map(UserContext::getUser)
.map(UserContextHolder::cropIdentifier)
.orElseThrow(IllegalStateException::new);
}
private static String cropIdentifier(final String identifier) {
if (identifier.length() > 32)
return identifier.substring(0, 32);
else
return identifier;
}
@Nonnull
public static Optional<UserContext> getUserContext() {
return Optional.ofNullable(UserContextHolder.THREAD_LOCAL.get());
}
public static void setAccessToken(@Nonnull final String user, @Nonnull final String accessToken) {
Assert.notNull(user, "User may not be null.");
Assert.notNull(accessToken, "Access token may not be null.");
UserContextHolder.THREAD_LOCAL.set(new UserContext(user, accessToken));
}
public static void setUserContext(@Nonnull final UserContext userContext)
{
UserContextHolder.THREAD_LOCAL.set(userContext);
}
public static void clear() {
UserContextHolder.THREAD_LOCAL.remove();
}
}
| 5,326 |
0 | Create_ds/fineract-cn-api/src/main/java/org/apache/fineract/cn/api | Create_ds/fineract-cn-api/src/main/java/org/apache/fineract/cn/api/util/EmptyBodyInterceptor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License 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 org.apache.fineract.cn.api.util;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.web.bind.annotation.RequestMethod;
import java.nio.charset.Charset;
/**
* Sets the content length of a request to zero if the request is of type POST or PUT, and contains
* no request body.
*/
public class EmptyBodyInterceptor implements RequestInterceptor {
public EmptyBodyInterceptor() {
super();
}
@Override
public void apply(final RequestTemplate template) {
if ((template.method().equalsIgnoreCase(RequestMethod.POST.name())
|| template.method().equalsIgnoreCase(RequestMethod.PUT.name()))
&& template.body() == null) {
template.body(new byte[0], Charset.defaultCharset());
}
}
}
| 5,327 |
0 | Create_ds/fineract-cn-api/src/main/java/org/apache/fineract/cn/api | Create_ds/fineract-cn-api/src/main/java/org/apache/fineract/cn/api/config/ApiConfiguration.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License 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 org.apache.fineract.cn.api.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
/**
* @author Myrle Krantz
*/
@Configuration
@ComponentScan({"org.apache.fineract.cn.api.util"})
public class ApiConfiguration {
public static final String LOGGER_NAME = "api-logger";
@Bean(name = LOGGER_NAME)
public Logger logger() {
return LoggerFactory.getLogger(LOGGER_NAME);
}
}
| 5,328 |
0 | Create_ds/fineract-cn-api/src/main/java/org/apache/fineract/cn/api | Create_ds/fineract-cn-api/src/main/java/org/apache/fineract/cn/api/config/EnableApiFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License 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 org.apache.fineract.cn.api.config;
import org.springframework.context.annotation.Import;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author Myrle Krantz
*/
@SuppressWarnings("unused")
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Import({ApiConfiguration.class})
public @interface EnableApiFactory {
}
| 5,329 |
0 | Create_ds/fineract-cn-api/src/main/java/org/apache/fineract/cn/api | Create_ds/fineract-cn-api/src/main/java/org/apache/fineract/cn/api/annotation/ThrowsException.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License 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 org.apache.fineract.cn.api.annotation;
import org.springframework.http.HttpStatus;
import java.lang.annotation.ElementType;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Repeatable(value = ThrowsExceptions.class)
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ThrowsException {
HttpStatus status();
Class<? extends RuntimeException> exception();
}
| 5,330 |
0 | Create_ds/fineract-cn-api/src/main/java/org/apache/fineract/cn/api | Create_ds/fineract-cn-api/src/main/java/org/apache/fineract/cn/api/annotation/ThrowsExceptions.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License 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 org.apache.fineract.cn.api.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author Myrle Krantz
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ThrowsExceptions {
ThrowsException[] value();
}
| 5,331 |
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());
}
}
}
| 5,332 |
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);
}
}
| 5,333 |
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();
}
}
| 5,334 |
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));
}
}
| 5,335 |
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);
}
}
}
| 5,336 |
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);
}
}
| 5,337 |
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);
}
}
}
| 5,338 |
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);
}
}
}
| 5,339 |
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
}
}
| 5,340 |
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));
}
}
| 5,341 |
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);
}
}
| 5,342 |
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);
}
}
| 5,343 |
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);
}
}
| 5,344 |
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());
}
}
| 5,345 |
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();
}
}
| 5,346 |
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));
}
}
| 5,347 |
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();
}
}
| 5,348 |
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);
}
} | 5,349 |
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);
}
}
| 5,350 |
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();
}
}
| 5,351 |
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));
}
}
| 5,352 |
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
}
| 5,353 |
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);
}
}
}
| 5,354 |
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();
}
}
} | 5,355 |
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);
}
}
}
}
| 5,356 |
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);
}
}
| 5,357 |
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;
}
}
| 5,358 |
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);
}
}
| 5,359 |
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;
}
}
}
| 5,360 |
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));
}
}
| 5,361 |
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);
}
}
| 5,362 |
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;
}
}
| 5,363 |
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();
}
}
| 5,364 |
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();
}
}
}
| 5,365 |
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));
}
}
}
| 5,366 |
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);
}
}
| 5,367 |
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;
}
}
| 5,368 |
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);
}
}
}
| 5,369 |
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);
}
}
}
| 5,370 |
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);
}
}
}
| 5,371 |
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();
}
}
| 5,372 |
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();
}
}
| 5,373 |
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;
}
| 5,374 |
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);
}
}
}
}
| 5,375 |
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();
}
}
}
| 5,376 |
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;
}
}
| 5,377 |
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++;
}
}
}
}
}
| 5,378 |
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);
}
}
| 5,379 |
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);
}
}
}
| 5,380 |
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();
}
}
| 5,381 |
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);
}
}
| 5,382 |
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);
}
}
}
| 5,383 |
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());
}
}
}
| 5,384 |
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);
}
}
| 5,385 |
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 = "";
}
| 5,386 |
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);
}
}
}
}
} | 5,387 |
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
}
}
| 5,388 |
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();
}
}
| 5,389 |
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);
}
| 5,390 |
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 {
}
}
}
| 5,391 |
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.
}
}
| 5,392 |
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;
}
| 5,393 |
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;
}
}
| 5,394 |
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();
}
}
}
| 5,395 |
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);
}
}
| 5,396 |
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);
}
}
}
| 5,397 |
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);
}
}
| 5,398 |
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();
}
}
| 5,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.