diff --git a/catalog/common/catalog-common-video-thumbnail-impl/src/main/java/ddf/video/thumbnail/impl/VideoThumbnailImpl.java b/catalog/common/catalog-common-video-thumbnail-impl/src/main/java/ddf/video/thumbnail/impl/VideoThumbnailImpl.java index 70fcd05b29fd..a7927bc27c84 100644 --- a/catalog/common/catalog-common-video-thumbnail-impl/src/main/java/ddf/video/thumbnail/impl/VideoThumbnailImpl.java +++ b/catalog/common/catalog-common-video-thumbnail-impl/src/main/java/ddf/video/thumbnail/impl/VideoThumbnailImpl.java @@ -26,8 +26,6 @@ import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.time.Duration; -import java.util.ArrayList; -import java.util.List; import java.util.Optional; import java.util.concurrent.Semaphore; import java.util.regex.Matcher; @@ -59,9 +57,7 @@ public class VideoThumbnailImpl implements VideoThumbnail { private static final int THUMBNAIL_COUNT = 3; - private static final int FFMPEG_FILE_NUMBERING_START = 1; - - private static final int ROUGH_MINIMUM_SECONDS_FOR_MULTIPLE_THUMBNAILS = 10; + private static final Duration MAX_THUMBNAIL_SEARCH_WINDOW = Duration.ofSeconds(4); private static final String SUPPRESS_PRINTING_BANNER_FLAG = "-hide_banner"; @@ -75,7 +71,9 @@ public class VideoThumbnailImpl implements VideoThumbnail { private static final int TIMEOUT_SECONDS = 15; - private final String ffmpegPath; + private final String bundledFfmpegPath; + + private volatile String configuredFfmpegPath; private int maxFileSizeMB = DEFAULT_MAX_FILE_SIZE_MB; @@ -86,7 +84,7 @@ public VideoThumbnailImpl(final BundleContext bundleContext) throws IOException final String ffmpegBinaryName = StringUtils.substringAfterLast(bundledFFmpegBinaryPath, "/"); final String ffmpegFolderPath = FilenameUtils.concat(System.getProperty("ddf.home"), "bin_third_party/ffmpeg"); - ffmpegPath = FilenameUtils.concat(ffmpegFolderPath, ffmpegBinaryName); + bundledFfmpegPath = FilenameUtils.concat(ffmpegFolderPath, ffmpegBinaryName); try (final InputStream inputStream = bundleContext.getBundle().getEntry(bundledFFmpegBinaryPath).openStream()) { @@ -100,6 +98,14 @@ public void setMaxFileSizeMB(int maxFileSizeMB) { this.maxFileSizeMB = maxFileSizeMB; } + public void setFfmpegPath(String ffmpegPath) { + this.configuredFfmpegPath = StringUtils.isBlank(ffmpegPath) ? null : ffmpegPath; + } + + private String getFfmpegPath() { + return configuredFfmpegPath != null ? configuredFfmpegPath : bundledFfmpegPath; + } + @SuppressWarnings("UnstableApiUsage" /* we already using these APIs in the video plugin */) @Override public boolean isVideo(MimeType mimeType) { @@ -127,19 +133,14 @@ public Optional videoThumbnail(File file, MimeType mimeType) LOGGER.trace("About to create video thumbnail"); + limitFFmpegProcessesSemaphore.acquire(); + try { - limitFFmpegProcessesSemaphore.acquire(); - - try { - final byte[] thumbnailBytes = createThumbnail(file.toString()); - LOGGER.debug( - "Successfully created video thumbnail for {} with mime-type {}", file, mimeType); - return Optional.of(thumbnailBytes); - } finally { - limitFFmpegProcessesSemaphore.release(); - } + final byte[] thumbnailBytes = createThumbnail(file.toString()); + LOGGER.debug("Successfully created video thumbnail for {} with mime-type {}", file, mimeType); + return Optional.of(thumbnailBytes); } finally { - deleteImageFiles(); + limitFFmpegProcessesSemaphore.release(); } } @@ -148,53 +149,6 @@ public boolean isTooLarge(long size) { return size > maxFileSizeBytes; } - private void deleteImageFiles() { - final List imageFiles = getThumbnailFiles(); - - imageFiles.add(new File(getGifFilePath())); - - imageFiles.forEach( - file -> { - if (file.exists() && !file.delete()) { - file.deleteOnExit(); - } - }); - } - - private String getGifFilePath() { - final String thumbnailFilePath = getThumbnailFilePath(); - return thumbnailFilePath.substring(0, thumbnailFilePath.lastIndexOf('-')) + ".gif"; - } - - private String getThumbnailFilePath() { - final long threadId = Thread.currentThread().getId(); - - // FFmpeg replaces the "%1d" with a single digit when it creates the output file. This is - // necessary because FFmpeg requires a unique filename for each output file when outputting - // multiple images. - final String thumbnailFileName = String.format("thumbnail-%d-%%1d.png", threadId); - - final String tempDirectoryPath = System.getProperty("java.io.tmpdir"); - - return FilenameUtils.concat(tempDirectoryPath, thumbnailFileName); - } - - private List getThumbnailFiles() { - final List thumbnailFiles = new ArrayList<>(THUMBNAIL_COUNT); - - final String thumbnailFilePath = getThumbnailFilePath(); - - // FFmpeg starts numbering files with 1. - for (int i = FFMPEG_FILE_NUMBERING_START; i <= THUMBNAIL_COUNT; ++i) { - final File thumbnailFile = new File(String.format(thumbnailFilePath, i)); - if (thumbnailFile.exists()) { - thumbnailFiles.add(new File(String.format(thumbnailFilePath, i))); - } - } - - return thumbnailFiles; - } - private byte[] createThumbnail(final String videoFilePath) throws IOException, InterruptedException { Duration videoDuration = null; @@ -212,45 +166,32 @@ private byte[] createThumbnail(final String videoFilePath) "Couldn't get video duration from FFmpeg output for videoFilePath={}.", videoFilePath, e); } - /* Realistically, to get good thumbnails by dividing a video into segments, the video - should be at least 10 seconds long. This is because FFmpeg looks for thumbnails in - batches of 100 frames each, and these frames usually come from the portion of the - video immediately following the seek position. If the video isn't long enough, - the regions of the video FFmpeg will pick thumbnails from will likely overlap, - causing the same thumbnail to be generated for multiple segments. */ - if (videoDuration != null - && videoDuration.getSeconds() > ROUGH_MINIMUM_SECONDS_FOR_MULTIPLE_THUMBNAILS) { - return createGifThumbnailWithDuration(videoFilePath, videoDuration); - } else { - return createThumbnailWithoutDuration(videoFilePath); - } - } - - private byte[] createThumbnailWithoutDuration(final String videoFilePath) - throws IOException, InterruptedException { - generateThumbnailsWithoutDuration(videoFilePath); + final boolean hasDuration = videoDuration != null && !videoDuration.isZero(); + final File thumbnailFile = File.createTempFile("thumbnail-", hasDuration ? ".gif" : ".png"); - final List thumbnailFiles = getThumbnailFiles(); + try { + final CommandLine command = + hasDuration + ? getFFmpegCreateAnimatedGifCommand(videoFilePath, thumbnailFile, videoDuration) + : getFFmpegCreateThumbnailCommand(videoFilePath, thumbnailFile); + final DefaultExecuteResultHandler resultHandler = executeFFmpeg(command, DEV_NULL); - // FFmpeg looks for thumbnails in batches of 100 frames each, so even if we request more - // than one thumbnail for a very short video, we will only get one back. - if (thumbnailFiles.size() == 1) { - return createStaticImageThumbnail(); - } else { - return createGifFromThumbnailFiles(); - } - } + resultHandler.waitFor(); - private byte[] createGifFromThumbnailFiles() throws IOException, InterruptedException { - final DefaultExecuteResultHandler resultHandler = - executeFFmpeg(getFFmpegCreateAnimatedGifCommand(), DEV_NULL); + if (resultHandler.getException() != null) { + throw resultHandler.getException(); + } - resultHandler.waitFor(); + if (thumbnailFile.length() == 0) { + throw new IOException( + "FFmpeg binary " + command.getExecutable() + " didn't produce a thumbnail."); + } - if (resultHandler.getException() == null) { - return FileUtils.readFileToByteArray(new File(getGifFilePath())); - } else { - throw resultHandler.getException(); + return FileUtils.readFileToByteArray(thumbnailFile); + } finally { + if (!thumbnailFile.delete()) { + thumbnailFile.deleteOnExit(); + } } } @@ -291,104 +232,92 @@ private void executeWithPrivilege( } } - private CommandLine getFFmpegCreateAnimatedGifCommand() { - final String framerateFlag = "-framerate"; - final String framerate = "1"; + private CommandLine getFFmpegCreateAnimatedGifCommand( + final String videoFilePath, final File gifFile, final Duration duration) { + final String seekFlag = "-ss"; + final String searchWindowFlag = "-t"; + final String filterGraphFlag = "-filter_complex"; + final String mapFlag = "-map"; + final String outputLabel = "[o]"; final String loopFlag = "-loop"; final String loopValue = "0"; + final String lastFrameDelayFlag = "-final_delay"; + final String oneSecondInCentiseconds = "100"; - return new CommandLine(ffmpegPath) - .addArgument(SUPPRESS_PRINTING_BANNER_FLAG) - .addArgument(framerateFlag) - .addArgument(framerate) - .addArgument(INPUT_FILE_FLAG) - .addArgument(getThumbnailFilePath(), DONT_HANDLE_QUOTING) + final Duration durationFraction = duration.dividedBy(THUMBNAIL_COUNT); + final Duration searchWindow = + durationFraction.compareTo(MAX_THUMBNAIL_SEARCH_WINDOW) < 0 + ? durationFraction + : MAX_THUMBNAIL_SEARCH_WINDOW; + + final CommandLine command = + new CommandLine(getFfmpegPath()).addArgument(SUPPRESS_PRINTING_BANNER_FLAG); + + for (int i = 0; i < THUMBNAIL_COUNT; ++i) { + command + .addArgument(seekFlag) + .addArgument(durationToString(durationFraction.multipliedBy(i))) + .addArgument(searchWindowFlag) + .addArgument(durationToString(searchWindow)) + .addArgument(INPUT_FILE_FLAG) + .addArgument(videoFilePath, DONT_HANDLE_QUOTING); + } + + command + .addArgument(filterGraphFlag) + .addArgument(getThumbnailFilterGraph(outputLabel), DONT_HANDLE_QUOTING) + .addArgument(mapFlag) + .addArgument(outputLabel) .addArgument(loopFlag) .addArgument(loopValue) - .addArgument(getGifFilePath(), DONT_HANDLE_QUOTING) + .addArgument(lastFrameDelayFlag) + .addArgument(oneSecondInCentiseconds) + .addArgument(gifFile.getPath(), DONT_HANDLE_QUOTING) .addArgument(OVERWRITE_EXISTING_FILE_FLAG); - } - private byte[] createStaticImageThumbnail() throws IOException { - return FileUtils.readFileToByteArray(getThumbnailFiles().get(0)); + return command; } - private void generateThumbnailsWithoutDuration(final String videoFilePath) - throws IOException, InterruptedException { - final CommandLine command = - getFFmpegCreateThumbnailCommand( - videoFilePath, getThumbnailFilePath(), null, THUMBNAIL_COUNT); - final DefaultExecuteResultHandler resultHandler = executeFFmpeg(command, DEV_NULL); - - resultHandler.waitFor(); + private String getThumbnailFilterGraph(final String outputLabel) { + final StringBuilder filterGraph = new StringBuilder(); + final StringBuilder concatInputs = new StringBuilder(); - if (resultHandler.getException() != null) { - throw resultHandler.getException(); + for (int i = 0; i < THUMBNAIL_COUNT; ++i) { + filterGraph.append( + String.format("[%d:v]thumbnail,trim=end_frame=1,scale=200:-2[v%d];", i, i)); + concatInputs.append(String.format("[v%d]", i)); } + + return filterGraph + .append(concatInputs) + .append(String.format("concat=n=%d,setpts=N/TB%s", THUMBNAIL_COUNT, outputLabel)) + .toString(); } private CommandLine getFFmpegCreateThumbnailCommand( - final String videoFilePath, - final String thumbnailFilePath, - final String seek, - final int numFrames) { + final String videoFilePath, final File thumbnailFile) { final String filterChainFlag = "-vf"; final String filterChain = "thumbnail,scale=200:-1"; final String videoFramesToOutputFlag = "-frames:v"; - final String videoFramesToOutput = String.valueOf(numFrames); - final String videoSyncFlag = "-vsync"; - final String videoSyncVariableFrameRate = "vfr"; + final String videoFramesToOutput = "1"; - final CommandLine command = - new CommandLine(ffmpegPath).addArgument(SUPPRESS_PRINTING_BANNER_FLAG); - - if (seek != null) { - final String seekFlag = "-ss"; - command.addArgument(seekFlag).addArgument(seek); - } - - command + return new CommandLine(getFfmpegPath()) + .addArgument(SUPPRESS_PRINTING_BANNER_FLAG) .addArgument(INPUT_FILE_FLAG) .addArgument(videoFilePath, DONT_HANDLE_QUOTING) .addArgument(filterChainFlag) .addArgument(filterChain) .addArgument(videoFramesToOutputFlag) .addArgument(videoFramesToOutput) - // The "-vsync vfr" argument prevents frames from being duplicated, which allows us - // to get a different thumbnail for each of the output images. - .addArgument(videoSyncFlag) - .addArgument(videoSyncVariableFrameRate); - - command - .addArgument(thumbnailFilePath, DONT_HANDLE_QUOTING) + .addArgument(thumbnailFile.getPath(), DONT_HANDLE_QUOTING) .addArgument(OVERWRITE_EXISTING_FILE_FLAG); - - return command; - } - - private byte[] createGifThumbnailWithDuration(final String videoFilePath, final Duration duration) - throws IOException, InterruptedException { - final Duration durationFraction = duration.dividedBy(THUMBNAIL_COUNT); - - // Start numbering files with 1 to match FFmpeg's convention. - for (int clipNum = FFMPEG_FILE_NUMBERING_START; clipNum <= THUMBNAIL_COUNT; ++clipNum) { - final String thumbnailPath = String.format(getThumbnailFilePath(), clipNum); - - final String seek = durationToString(durationFraction.multipliedBy((long) clipNum - 1)); - - final CommandLine command = - getFFmpegCreateThumbnailCommand(videoFilePath, thumbnailPath, seek, 1); - - final DefaultExecuteResultHandler resultHandler = executeFFmpeg(command, DEV_NULL); - resultHandler.waitFor(); - } - - return createGifFromThumbnailFiles(); } private String durationToString(final Duration duration) { final long seconds = duration.getSeconds(); - return String.format("%02d:%02d:%02d", seconds / 3600, (seconds % 3600) / 60, seconds % 60); + return String.format( + "%02d:%02d:%02d.%03d", + seconds / 3600, (seconds % 3600) / 60, seconds % 60, duration.toMillisPart()); } private Duration getVideoDuration(final String videoFilePath) @@ -421,7 +350,7 @@ private Duration parseVideoDuration(final String ffmpegOutput) throws IOExceptio private CommandLine getFFmpegInfoCommand(final String videoFilePath) { CommandLine commandLine = - new CommandLine(ffmpegPath) + new CommandLine(getFfmpegPath()) .addArgument(SUPPRESS_PRINTING_BANNER_FLAG) .addArgument(INPUT_FILE_FLAG) .addArgument(videoFilePath, DONT_HANDLE_QUOTING); @@ -430,15 +359,15 @@ private CommandLine getFFmpegInfoCommand(final String videoFilePath) { } /** - * Deletes the directory that holds the FFmpeg binary. + * Deletes the directory that holds the bundled FFmpeg binary. * *

Called by Blueprint. */ public void destroy() { - if (ffmpegPath != null) { - String fullPathNoEndSeparator = FilenameUtils.getFullPathNoEndSeparator(ffmpegPath); + if (bundledFfmpegPath != null) { + String fullPathNoEndSeparator = FilenameUtils.getFullPathNoEndSeparator(bundledFfmpegPath); if (fullPathNoEndSeparator == null) { - fullPathNoEndSeparator = ffmpegPath; + fullPathNoEndSeparator = bundledFfmpegPath; } final File ffmpegDirectory = new File(fullPathNoEndSeparator); if (!FileUtils.deleteQuietly(ffmpegDirectory)) { @@ -448,14 +377,14 @@ public void destroy() { } private void copyFFmpegBinary(final InputStream inputStream) throws IOException { - final File ffmpegBinary = new File(ffmpegPath); + final File ffmpegBinary = new File(bundledFfmpegPath); if (!ffmpegBinary.exists()) { FileUtils.copyInputStreamToFile(inputStream, ffmpegBinary); if (!ffmpegBinary.setExecutable(true)) { LOGGER.warn( "Couldn't make FFmpeg binary at {} executable. It must be executable by its owner for the plugin to work.", - ffmpegPath); + bundledFfmpegPath); } } } diff --git a/catalog/common/catalog-common-video-thumbnail-impl/src/main/resources/OSGI-INF/metatype/metatype.xml b/catalog/common/catalog-common-video-thumbnail-impl/src/main/resources/OSGI-INF/metatype/metatype.xml index 4f8291428627..fc945ed51aca 100644 --- a/catalog/common/catalog-common-video-thumbnail-impl/src/main/resources/OSGI-INF/metatype/metatype.xml +++ b/catalog/common/catalog-common-video-thumbnail-impl/src/main/resources/OSGI-INF/metatype/metatype.xml @@ -19,6 +19,9 @@ + diff --git a/catalog/common/catalog-common-video-thumbnail-impl/src/test/java/ddf/video/thumbnail/impl/VideoThumbnailImplFakeFfmpegTest.java b/catalog/common/catalog-common-video-thumbnail-impl/src/test/java/ddf/video/thumbnail/impl/VideoThumbnailImplFakeFfmpegTest.java new file mode 100644 index 000000000000..6ce531df90fc --- /dev/null +++ b/catalog/common/catalog-common-video-thumbnail-impl/src/test/java/ddf/video/thumbnail/impl/VideoThumbnailImplFakeFfmpegTest.java @@ -0,0 +1,241 @@ +/** + * Copyright (c) Codice Foundation + * + *

This is free software: you can redistribute it and/or modify it under the terms of the GNU + * Lesser General Public License as published by the Free Software Foundation, either version 3 of + * the License, or any later version. + * + *

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. A copy of the GNU Lesser General Public + * License is distributed along with this program and can be found at + * . + */ +package ddf.video.thumbnail.impl; + +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.everyItem; +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.fail; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; +import javax.activation.MimeType; +import org.apache.commons.lang.SystemUtils; +import org.junit.After; +import org.junit.Assume; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; + +/** + * Uses a fake ffmpeg script so the ffmpegPath config and error handling get tested on any arch. + * {@link VideoThumbnailImplTest} covers the real bundled ffmpeg but only runs on x86. + */ +public class VideoThumbnailImplFakeFfmpegTest { + + @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); + + private String originalDdfHome; + + private File ddfHome; + + private File invocationLog; + + private File videoFile; + + private VideoThumbnailImpl videoThumbnailImpl; + + @BeforeClass + public static void setUpClass() { + Assume.assumeFalse( + "Skip on Windows, fake FFmpeg scripts need a POSIX shell.", SystemUtils.IS_OS_WINDOWS); + } + + @Before + public void setUp() throws Exception { + originalDdfHome = System.getProperty("ddf.home"); + ddfHome = temporaryFolder.newFolder("ddf-home"); + System.setProperty("ddf.home", ddfHome.getAbsolutePath()); + invocationLog = temporaryFolder.newFile("invocations.log"); + videoFile = temporaryFolder.newFile("video.mp4"); + + final File bundledScript = temporaryFolder.newFile("bundled-ffmpeg"); + Files.write( + bundledScript.toPath(), + new FakeFfmpeg("bundled").script().getBytes(StandardCharsets.UTF_8)); + videoThumbnailImpl = new VideoThumbnailImpl(createMockBundleContext(bundledScript)); + } + + @After + public void tearDown() { + if (videoThumbnailImpl != null) { + videoThumbnailImpl.destroy(); + } + if (originalDdfHome == null) { + System.clearProperty("ddf.home"); + } else { + System.setProperty("ddf.home", originalDdfHome); + } + } + + @Test + public void testConfiguredFfmpegPath() throws Exception { + videoThumbnailImpl.setFfmpegPath(install(new FakeFfmpeg("configured")).getAbsolutePath()); + + final Optional thumbnail = runThumbnail(); + + assertThat(new String(thumbnail.get(), StandardCharsets.US_ASCII), is("gif")); + assertThat(invokedBinaries(), everyItem(is("configured"))); + } + + @Test + public void testNoDurationMakesStaticThumbnail() throws Exception { + final FakeFfmpeg fake = new FakeFfmpeg("configured"); + fake.duration = null; + videoThumbnailImpl.setFfmpegPath(install(fake).getAbsolutePath()); + + final Optional thumbnail = runThumbnail(); + + assertThat(new String(thumbnail.get(), StandardCharsets.US_ASCII), is("png")); + } + + @Test + public void testBlankFfmpegPathUsesBundled() throws Exception { + videoThumbnailImpl.setFfmpegPath(install(new FakeFfmpeg("configured")).getAbsolutePath()); + videoThumbnailImpl.setFfmpegPath(" "); + + final Optional thumbnail = runThumbnail(); + + assertThat(thumbnail.isPresent(), is(true)); + assertThat(invokedBinaries(), everyItem(is("bundled"))); + } + + @Test + public void testNullFfmpegPathUsesBundled() throws Exception { + videoThumbnailImpl.setFfmpegPath(install(new FakeFfmpeg("configured")).getAbsolutePath()); + videoThumbnailImpl.setFfmpegPath(null); + + final Optional thumbnail = runThumbnail(); + + assertThat(thumbnail.isPresent(), is(true)); + assertThat(invokedBinaries(), everyItem(is("bundled"))); + } + + @Test + public void testDestroyKeepsConfiguredBinary() throws Exception { + final File configured = install(new FakeFfmpeg("configured")); + final File bundledDir = new File(ddfHome, "bin_third_party/ffmpeg"); + videoThumbnailImpl.setFfmpegPath(configured.getAbsolutePath()); + + videoThumbnailImpl.destroy(); + + assertThat(configured.exists(), is(true)); + assertThat(bundledDir.exists(), is(false)); + } + + @Test(expected = IOException.class) + public void testFfmpegFails() throws Exception { + final FakeFfmpeg fake = new FakeFfmpeg("configured"); + fake.thumbnailExitCode = 1; + videoThumbnailImpl.setFfmpegPath(install(fake).getAbsolutePath()); + + runThumbnail(); + } + + @Test + public void testFfmpegWritesNoThumbnail() throws Exception { + final FakeFfmpeg fake = new FakeFfmpeg("configured"); + fake.writesThumbnail = false; + final String ffmpegPath = install(fake).getAbsolutePath(); + videoThumbnailImpl.setFfmpegPath(ffmpegPath); + + try { + runThumbnail(); + fail("Expected an IOException when FFmpeg doesn't write a thumbnail"); + } catch (IOException e) { + assertThat(e.getMessage(), containsString(ffmpegPath)); + } + } + + private Optional runThumbnail() throws Exception { + return videoThumbnailImpl.videoThumbnail(videoFile, new MimeType("video/mp4")); + } + + private List invokedBinaries() throws IOException { + return Files.readAllLines(invocationLog.toPath()).stream() + .map(line -> line.split(" ", 2)[0]) + .collect(Collectors.toList()); + } + + private File install(FakeFfmpeg fake) throws IOException { + return install(fake, new File(temporaryFolder.newFolder(), "ffmpeg")); + } + + private File install(FakeFfmpeg fake, File file) throws IOException { + Files.createDirectories(file.getParentFile().toPath()); + Files.write(file.toPath(), fake.script().getBytes(StandardCharsets.UTF_8)); + if (!file.setExecutable(true)) { + fail("Couldn't make " + file + " executable"); + } + return file; + } + + private BundleContext createMockBundleContext(File bundledScript) throws IOException { + final BundleContext bundleContext = mock(BundleContext.class); + final Bundle bundle = mock(Bundle.class); + doReturn(bundle).when(bundleContext).getBundle(); + doReturn(bundledScript.toURI().toURL()).when(bundle).getEntry(anyString()); + return bundleContext; + } + + private class FakeFfmpeg { + private final String name; + + private String duration = "00:01:00.00"; + + private int thumbnailExitCode = 0; + + private boolean writesThumbnail = true; + + private FakeFfmpeg(String name) { + this.name = name; + } + + private String script() { + final String logInvocation = + String.format("echo \"%s $*\" >> '%s'", name, invocationLog.getAbsolutePath()); + final String findOutputPathBeforeOverwriteFlag = + "outputPath=''; last=''; for a in \"$@\"; do outputPath=\"$last\"; last=\"$a\"; done"; + final String reportDurationForInfoCommand = + duration == null ? "exit 1" : "echo 'Duration: " + duration + "' >&2; exit 1"; + final String writeStubThumbnail = writesThumbnail ? "printf \"$stub\" > \"$outputPath\"" : ""; + return String.join( + "\n", + "#!/bin/sh", + logInvocation, + findOutputPathBeforeOverwriteFlag, + "case \"$outputPath\" in", + " *.gif) stub='gif' ;;", + " *.png) stub='png' ;;", + " *) " + reportDurationForInfoCommand + " ;;", + "esac", + writeStubThumbnail, + "exit " + thumbnailExitCode, + ""); + } + } +} diff --git a/catalog/common/catalog-common-video-thumbnail-impl/src/test/java/ddf/video/thumbnail/impl/VideoThumbnailImplTest.java b/catalog/common/catalog-common-video-thumbnail-impl/src/test/java/ddf/video/thumbnail/impl/VideoThumbnailImplTest.java index e9d022330a02..46a4a726fdf7 100644 --- a/catalog/common/catalog-common-video-thumbnail-impl/src/test/java/ddf/video/thumbnail/impl/VideoThumbnailImplTest.java +++ b/catalog/common/catalog-common-video-thumbnail-impl/src/test/java/ddf/video/thumbnail/impl/VideoThumbnailImplTest.java @@ -14,7 +14,7 @@ package ddf.video.thumbnail.impl; import static ddf.video.thumbnail.impl.VideoThumbnailImpl.DEFAULT_MAX_FILE_SIZE_MB; -import static org.hamcrest.CoreMatchers.notNullValue; +import static org.hamcrest.CoreMatchers.hasItem; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; @@ -22,16 +22,24 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import java.awt.Color; +import java.awt.image.BufferedImage; +import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.Set; import javax.activation.MimeType; import javax.activation.MimeTypeParseException; +import javax.imageio.ImageIO; +import javax.imageio.ImageReader; +import javax.imageio.stream.ImageInputStream; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang.SystemUtils; @@ -98,10 +106,7 @@ public void tearDown() { } } - /** - * Tests processing short.mp4. This file is short enough that FFmpeg will only generate one - * thumbnail for it even if we request more than one. - */ + /** Tests processing short.mp4. */ @Test public void testProcessShortVideo() throws Exception { // given @@ -110,15 +115,12 @@ public void testProcessShortVideo() throws Exception { // when Optional optionalBytes = videoThumbnailImpl.videoThumbnail(file, VIDEO_MP4); + // then assertThat(optionalBytes.isPresent(), is(true)); - verifyThumbnailIsPng(optionalBytes.get()); + verifyThumbnailFormat(optionalBytes.get(), "gif"); } - /** - * Tests processing medium.mp4. This file is short enough that the plugin won't try to grab - * thumbnails from different portions of the video but is long enough that the resulting thumbnail - * will be a GIF. - */ + /** Tests processing medium.mp4. */ @Test public void testProcessMediumVideo() throws Exception { // given @@ -129,13 +131,10 @@ public void testProcessMediumVideo() throws Exception { // then assertThat(optionalBytes.isPresent(), is(true)); - verifyThumbnailIsGif(optionalBytes.get()); + verifyThumbnailFormat(optionalBytes.get(), "gif"); } - /** - * Tests processing long.mp4. This file is long enough that the plugin will try to grab thumbnails - * from different portions of the video. - */ + /** Tests processing long.mp4. */ @Test public void testProcessLongVideo() throws Exception { // given @@ -146,7 +145,47 @@ public void testProcessLongVideo() throws Exception { // then assertThat(optionalBytes.isPresent(), is(true)); - verifyThumbnailIsGif(optionalBytes.get()); + verifyThumbnailFormat(optionalBytes.get(), "gif"); + } + + @Test + public void testProcessVideoWithoutDuration() throws Exception { + // given + final File file = getResource("/no-duration.h264"); + + // when + Optional optionalBytes = videoThumbnailImpl.videoThumbnail(file, VIDEO_MP4); + + // then + assertThat(optionalBytes.isPresent(), is(true)); + verifyThumbnailFormat(optionalBytes.get(), "png"); + } + + @Test + public void testGifFramesComeFromEachThirdOfVideo() throws Exception { + // given + final File file = getResource("/scenes-tiny-10s.mp4"); + + // when + Optional optionalBytes = videoThumbnailImpl.videoThumbnail(file, VIDEO_MP4); + + // then + assertThat(optionalBytes.isPresent(), is(true)); + final ImageReader reader = ImageIO.getImageReadersByFormatName("gif").next(); + try (ImageInputStream input = + ImageIO.createImageInputStream(new ByteArrayInputStream(optionalBytes.get()))) { + reader.setInput(input); + final int lastFrame = reader.getNumImages(true) - 1; + final List middleColors = new ArrayList<>(); + for (int i = 1; i < lastFrame; i++) { + middleColors.add(centerColor(reader.read(i))); + } + assertThat(centerColor(reader.read(0)), is("red")); + assertThat(middleColors, hasItem("green")); + assertThat(centerColor(reader.read(lastFrame)), is("blue")); + } finally { + reader.dispose(); + } } @Test @@ -222,7 +261,7 @@ public void testProcessVideoSmallerThanConfiguredMaxFileSize() throws Exception // then assertThat(optionalBytes.isPresent(), is(true)); - verifyThumbnailIsGif(optionalBytes.get()); + verifyThumbnailFormat(optionalBytes.get(), "gif"); } /** create mock methods */ @@ -255,42 +294,23 @@ private BundleContext createMockBundleContext() { return mockBundleContext; } - private void verifyThumbnailIsGif(byte[] thumbnail) { - assertThat("The thumbnail should not be null", thumbnail, notNullValue()); - - assertThat( - "The thumbnail should have the right GIF header bytes", thumbnail[0], is((byte) 0x47)); - assertThat( - "The thumbnail should have the right GIF header bytes", thumbnail[1], is((byte) 0x49)); - assertThat( - "The thumbnail should have the right GIF header bytes", thumbnail[2], is((byte) 0x46)); - assertThat( - "The thumbnail should have the right GIF header bytes", thumbnail[3], is((byte) 0x38)); - assertThat( - "The thumbnail should have the right GIF header bytes", thumbnail[4], is((byte) 0x39)); - assertThat( - "The thumbnail should have the right GIF header bytes", thumbnail[5], is((byte) 0x61)); + private void verifyThumbnailFormat(byte[] thumbnail, String format) throws IOException { + try (ImageInputStream input = + ImageIO.createImageInputStream(new ByteArrayInputStream(thumbnail))) { + assertThat(ImageIO.getImageReaders(input).next().getFormatName(), is(format)); + } } - private void verifyThumbnailIsPng(byte[] thumbnail) { - assertThat("The thumbnail should not be null", thumbnail, notNullValue()); - - assertThat( - "The thumbnail should have the right PNG header bytes", thumbnail[0], is((byte) 0x89)); - assertThat( - "The thumbnail should have the right PNG header bytes", thumbnail[1], is((byte) 0x50)); - assertThat( - "The thumbnail should have the right PNG header bytes", thumbnail[2], is((byte) 0x4E)); - assertThat( - "The thumbnail should have the right PNG header bytes", thumbnail[3], is((byte) 0x47)); - assertThat( - "The thumbnail should have the right PNG header bytes", thumbnail[4], is((byte) 0x0D)); - assertThat( - "The thumbnail should have the right PNG header bytes", thumbnail[5], is((byte) 0x0A)); - assertThat( - "The thumbnail should have the right PNG header bytes", thumbnail[6], is((byte) 0x1A)); - assertThat( - "The thumbnail should have the right PNG header bytes", thumbnail[7], is((byte) 0x0A)); + private String centerColor(BufferedImage frame) { + final Color pixel = new Color(frame.getRGB(frame.getWidth() / 2, frame.getHeight() / 2)); + if (pixel.getRed() > pixel.getGreen() && pixel.getRed() > pixel.getBlue()) { + return "red"; + } else if (pixel.getGreen() > pixel.getRed() && pixel.getGreen() > pixel.getBlue()) { + return "green"; + } else if (pixel.getBlue() > pixel.getRed() && pixel.getBlue() > pixel.getGreen()) { + return "blue"; + } + return pixel.toString(); } private File getResource(String resource) throws URISyntaxException { diff --git a/catalog/common/catalog-common-video-thumbnail-impl/src/test/resources/no-duration.h264 b/catalog/common/catalog-common-video-thumbnail-impl/src/test/resources/no-duration.h264 new file mode 100644 index 000000000000..25d6008b4a5f Binary files /dev/null and b/catalog/common/catalog-common-video-thumbnail-impl/src/test/resources/no-duration.h264 differ diff --git a/catalog/common/catalog-common-video-thumbnail-impl/src/test/resources/scenes-tiny-10s.mp4 b/catalog/common/catalog-common-video-thumbnail-impl/src/test/resources/scenes-tiny-10s.mp4 new file mode 100644 index 000000000000..fbb68127ea3c Binary files /dev/null and b/catalog/common/catalog-common-video-thumbnail-impl/src/test/resources/scenes-tiny-10s.mp4 differ diff --git a/distribution/docs/src/main/resources/content/_architectures/_plugins/video-thumbnail-plugin.adoc b/distribution/docs/src/main/resources/content/_architectures/_plugins/video-thumbnail-plugin.adoc index 572d5a6b9b95..48f7f1a2e176 100644 --- a/distribution/docs/src/main/resources/content/_architectures/_plugins/video-thumbnail-plugin.adoc +++ b/distribution/docs/src/main/resources/content/_architectures/_plugins/video-thumbnail-plugin.adoc @@ -11,6 +11,8 @@ It is an implementation of both the `PostCreateStoragePlugin` and `PostUpdateSto This plugin uses a custom 32-bit LGPL build of https://ffmpeg.org/[FFmpeg] (a video processing program) to generate thumbnails. When this plugin is installed, it places the FFmpeg executable appropriate for the current operating system in `${home_directory}/bin_third_party/ffmpeg`. When invoked, this plugin runs the FFmpeg binary in a separate process to generate the thumbnail. The `${home_directory}/bin_third_party/ffmpeg` directory is deleted when the plugin is uninstalled. +To use a different FFmpeg binary, set *FFmpeg binary path* in the plugin configuration. This plugin runs that binary instead of the bundled one and doesn't delete it when uninstalled. When the security manager is enabled, a binary outside `${home_directory}/bin_third_party/ffmpeg` also needs a `java.io.FilePermission` grant with `execute` in `${home_directory}/security/configurations.policy`. + [NOTE] ==== Prebuilt FFmpeg binaries are provided for Linux, Mac, and Windows only. diff --git a/distribution/docs/src/main/resources/content/_reference/_tables/VideoThumbnailPlugin.adoc b/distribution/docs/src/main/resources/content/_reference/_tables/VideoThumbnailPlugin.adoc index d45ea6e67298..c7a3630a6a82 100644 --- a/distribution/docs/src/main/resources/content/_reference/_tables/VideoThumbnailPlugin.adoc +++ b/distribution/docs/src/main/resources/content/_reference/_tables/VideoThumbnailPlugin.adoc @@ -22,4 +22,11 @@ |120 |false +|FFmpeg binary path +|ffmpegPath +|String +|Path to an FFmpeg binary to use instead of the bundled one. Leave empty to use the bundled binary. +| +|false + |=== diff --git a/distribution/test/itests/test-itests-ddf/src/test/java/ddf/test/itests/catalog/TestCatalog.java b/distribution/test/itests/test-itests-ddf/src/test/java/ddf/test/itests/catalog/TestCatalog.java index 716ea11f75ec..3067a9465f0c 100644 --- a/distribution/test/itests/test-itests-ddf/src/test/java/ddf/test/itests/catalog/TestCatalog.java +++ b/distribution/test/itests/test-itests-ddf/src/test/java/ddf/test/itests/catalog/TestCatalog.java @@ -1570,15 +1570,25 @@ private Matcher hasMetacardAttributeXPath(String attributeName, String... @Test public void testVideoThumbnail() throws Exception { - try (InputStream inputStream = IOUtils.toInputStream(getFileContent("sample.mp4"))) { + final String id; + try (InputStream inputStream = getFileContentAsStream(SAMPLE_MP4)) { final byte[] fileBytes = IOUtils.toByteArray(inputStream); - given() - .multiPart("file", SAMPLE_MP4, fileBytes, "video/mp4") - .post(REST_PATH.getUrl()) - .then() - .statusCode(201); + id = + given() + .multiPart("file", SAMPLE_MP4, fileBytes, "video/mp4") + .expect() + .statusCode(201) + .when() + .post(REST_PATH.getUrl()) + .getHeader("id"); } + + getMetacardValidatableResponse(id) + .assertThat() + .body(hasXPath("/metacard/base64Binary[@name='thumbnail']")); + + delete(id); } @Test