2017-06-06 18:12:49 -05:00
|
|
|
// Copyright 2017 Vector Creations Ltd
|
|
|
|
//
|
|
|
|
// Licensed 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.
|
|
|
|
|
|
|
|
// +build !bimg
|
|
|
|
|
|
|
|
package thumbnailer
|
|
|
|
|
|
|
|
import (
|
2017-09-21 09:44:00 -05:00
|
|
|
"context"
|
2017-06-06 18:12:49 -05:00
|
|
|
"image"
|
|
|
|
"image/draw"
|
2019-06-19 08:05:03 -05:00
|
|
|
|
2017-06-06 18:12:49 -05:00
|
|
|
// Imported for gif codec
|
|
|
|
_ "image/gif"
|
|
|
|
"image/jpeg"
|
2019-06-19 08:05:03 -05:00
|
|
|
|
2017-06-06 18:12:49 -05:00
|
|
|
// Imported for png codec
|
|
|
|
_ "image/png"
|
|
|
|
"os"
|
|
|
|
"time"
|
|
|
|
|
2017-06-19 09:21:04 -05:00
|
|
|
"github.com/matrix-org/dendrite/common/config"
|
2017-06-06 18:12:49 -05:00
|
|
|
"github.com/matrix-org/dendrite/mediaapi/storage"
|
|
|
|
"github.com/matrix-org/dendrite/mediaapi/types"
|
|
|
|
"github.com/nfnt/resize"
|
2017-11-16 04:12:02 -06:00
|
|
|
log "github.com/sirupsen/logrus"
|
2017-06-06 18:12:49 -05:00
|
|
|
)
|
|
|
|
|
|
|
|
// GenerateThumbnails generates the configured thumbnail sizes for the source file
|
2017-09-21 09:44:00 -05:00
|
|
|
func GenerateThumbnails(
|
|
|
|
ctx context.Context,
|
|
|
|
src types.Path,
|
|
|
|
configs []config.ThumbnailSize,
|
|
|
|
mediaMetadata *types.MediaMetadata,
|
|
|
|
activeThumbnailGeneration *types.ActiveThumbnailGeneration,
|
|
|
|
maxThumbnailGenerators int,
|
2020-01-03 08:07:05 -06:00
|
|
|
db storage.Database,
|
2017-09-21 09:44:00 -05:00
|
|
|
logger *log.Entry,
|
|
|
|
) (busy bool, errorReturn error) {
|
2017-06-06 18:12:49 -05:00
|
|
|
img, err := readFile(string(src))
|
|
|
|
if err != nil {
|
|
|
|
logger.WithError(err).WithField("src", src).Error("Failed to read src file")
|
|
|
|
return false, err
|
|
|
|
}
|
2018-04-20 09:50:44 -05:00
|
|
|
for _, singleConfig := range configs {
|
2017-06-06 18:12:49 -05:00
|
|
|
// Note: createThumbnail does locking based on activeThumbnailGeneration
|
2017-09-21 09:44:00 -05:00
|
|
|
busy, err = createThumbnail(
|
2018-04-20 09:50:44 -05:00
|
|
|
ctx, src, img, types.ThumbnailSize(singleConfig), mediaMetadata,
|
2017-09-21 09:44:00 -05:00
|
|
|
activeThumbnailGeneration, maxThumbnailGenerators, db, logger,
|
|
|
|
)
|
2017-06-06 18:12:49 -05:00
|
|
|
if err != nil {
|
|
|
|
logger.WithError(err).WithField("src", src).Error("Failed to generate thumbnails")
|
|
|
|
return false, err
|
|
|
|
}
|
|
|
|
if busy {
|
|
|
|
return true, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// GenerateThumbnail generates the configured thumbnail size for the source file
|
2017-09-21 09:44:00 -05:00
|
|
|
func GenerateThumbnail(
|
|
|
|
ctx context.Context,
|
|
|
|
src types.Path,
|
|
|
|
config types.ThumbnailSize,
|
|
|
|
mediaMetadata *types.MediaMetadata,
|
|
|
|
activeThumbnailGeneration *types.ActiveThumbnailGeneration,
|
|
|
|
maxThumbnailGenerators int,
|
2020-01-03 08:07:05 -06:00
|
|
|
db storage.Database,
|
2017-09-21 09:44:00 -05:00
|
|
|
logger *log.Entry,
|
|
|
|
) (busy bool, errorReturn error) {
|
2017-06-06 18:12:49 -05:00
|
|
|
img, err := readFile(string(src))
|
|
|
|
if err != nil {
|
|
|
|
logger.WithError(err).WithFields(log.Fields{
|
|
|
|
"src": src,
|
|
|
|
}).Error("Failed to read src file")
|
|
|
|
return false, err
|
|
|
|
}
|
|
|
|
// Note: createThumbnail does locking based on activeThumbnailGeneration
|
2017-09-21 09:44:00 -05:00
|
|
|
busy, err = createThumbnail(
|
|
|
|
ctx, src, img, config, mediaMetadata, activeThumbnailGeneration,
|
|
|
|
maxThumbnailGenerators, db, logger,
|
|
|
|
)
|
2017-06-06 18:12:49 -05:00
|
|
|
if err != nil {
|
|
|
|
logger.WithError(err).WithFields(log.Fields{
|
|
|
|
"src": src,
|
|
|
|
}).Error("Failed to generate thumbnails")
|
|
|
|
return false, err
|
|
|
|
}
|
|
|
|
if busy {
|
|
|
|
return true, nil
|
|
|
|
}
|
|
|
|
return false, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func readFile(src string) (image.Image, error) {
|
|
|
|
file, err := os.Open(src)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2017-09-20 04:59:19 -05:00
|
|
|
defer file.Close() // nolint: errcheck
|
2017-06-06 18:12:49 -05:00
|
|
|
|
|
|
|
img, _, err := image.Decode(file)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return img, nil
|
|
|
|
}
|
|
|
|
|
2017-09-20 04:59:19 -05:00
|
|
|
func writeFile(img image.Image, dst string) (err error) {
|
2017-06-06 18:12:49 -05:00
|
|
|
out, err := os.Create(dst)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2017-09-20 04:59:19 -05:00
|
|
|
defer (func() { err = out.Close() })()
|
2017-06-06 18:12:49 -05:00
|
|
|
|
|
|
|
return jpeg.Encode(out, img, &jpeg.Options{
|
|
|
|
Quality: 85,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
// createThumbnail checks if the thumbnail exists, and if not, generates it
|
|
|
|
// Thumbnail generation is only done once for each non-existing thumbnail.
|
2017-09-21 09:44:00 -05:00
|
|
|
func createThumbnail(
|
|
|
|
ctx context.Context,
|
|
|
|
src types.Path,
|
|
|
|
img image.Image,
|
|
|
|
config types.ThumbnailSize,
|
|
|
|
mediaMetadata *types.MediaMetadata,
|
|
|
|
activeThumbnailGeneration *types.ActiveThumbnailGeneration,
|
|
|
|
maxThumbnailGenerators int,
|
2020-01-03 08:07:05 -06:00
|
|
|
db storage.Database,
|
2017-09-21 09:44:00 -05:00
|
|
|
logger *log.Entry,
|
|
|
|
) (busy bool, errorReturn error) {
|
2017-06-06 18:12:49 -05:00
|
|
|
logger = logger.WithFields(log.Fields{
|
|
|
|
"Width": config.Width,
|
|
|
|
"Height": config.Height,
|
|
|
|
"ResizeMethod": config.ResizeMethod,
|
|
|
|
})
|
|
|
|
|
2017-06-08 08:40:51 -05:00
|
|
|
// Check if request is larger than original
|
|
|
|
if config.Width >= img.Bounds().Dx() && config.Height >= img.Bounds().Dy() {
|
|
|
|
return false, nil
|
|
|
|
}
|
|
|
|
|
2017-06-06 18:12:49 -05:00
|
|
|
dst := GetThumbnailPath(src, config)
|
|
|
|
|
|
|
|
// Note: getActiveThumbnailGeneration uses mutexes and conditions from activeThumbnailGeneration
|
|
|
|
isActive, busy, err := getActiveThumbnailGeneration(dst, config, activeThumbnailGeneration, maxThumbnailGenerators, logger)
|
|
|
|
if err != nil {
|
|
|
|
return false, err
|
|
|
|
}
|
|
|
|
if busy {
|
|
|
|
return true, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
if isActive {
|
|
|
|
// Note: This is an active request that MUST broadcastGeneration to wake up waiting goroutines!
|
|
|
|
// Note: broadcastGeneration uses mutexes and conditions from activeThumbnailGeneration
|
|
|
|
defer func() {
|
|
|
|
// Note: errorReturn is the named return variable so we wrap this in a closure to re-evaluate the arguments at defer-time
|
|
|
|
// if err := recover(); err != nil {
|
|
|
|
// broadcastGeneration(dst, activeThumbnailGeneration, config, err.(error), logger)
|
|
|
|
// panic(err)
|
|
|
|
// }
|
|
|
|
broadcastGeneration(dst, activeThumbnailGeneration, config, errorReturn, logger)
|
|
|
|
}()
|
|
|
|
}
|
|
|
|
|
2017-09-21 09:44:00 -05:00
|
|
|
exists, err := isThumbnailExists(ctx, dst, config, mediaMetadata, db, logger)
|
2017-06-08 08:40:51 -05:00
|
|
|
if err != nil || exists {
|
2017-06-06 18:12:49 -05:00
|
|
|
return false, err
|
|
|
|
}
|
|
|
|
|
|
|
|
start := time.Now()
|
2017-09-20 09:25:25 -05:00
|
|
|
width, height, err := adjustSize(dst, img, config.Width, config.Height, config.ResizeMethod == types.Crop, logger)
|
2017-06-06 18:12:49 -05:00
|
|
|
if err != nil {
|
|
|
|
return false, err
|
|
|
|
}
|
|
|
|
logger.WithFields(log.Fields{
|
|
|
|
"ActualWidth": width,
|
|
|
|
"ActualHeight": height,
|
2017-09-20 08:15:38 -05:00
|
|
|
"processTime": time.Since(start),
|
2017-06-06 18:12:49 -05:00
|
|
|
}).Info("Generated thumbnail")
|
|
|
|
|
|
|
|
stat, err := os.Stat(string(dst))
|
|
|
|
if err != nil {
|
|
|
|
return false, err
|
|
|
|
}
|
|
|
|
|
2017-06-08 08:40:51 -05:00
|
|
|
thumbnailMetadata := &types.ThumbnailMetadata{
|
2017-06-06 18:12:49 -05:00
|
|
|
MediaMetadata: &types.MediaMetadata{
|
|
|
|
MediaID: mediaMetadata.MediaID,
|
|
|
|
Origin: mediaMetadata.Origin,
|
|
|
|
// Note: the code currently always creates a JPEG thumbnail
|
|
|
|
ContentType: types.ContentType("image/jpeg"),
|
|
|
|
FileSizeBytes: types.FileSizeBytes(stat.Size()),
|
|
|
|
},
|
|
|
|
ThumbnailSize: types.ThumbnailSize{
|
2017-06-08 08:40:51 -05:00
|
|
|
Width: config.Width,
|
|
|
|
Height: config.Height,
|
2017-06-06 18:12:49 -05:00
|
|
|
ResizeMethod: config.ResizeMethod,
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
2017-09-21 09:44:00 -05:00
|
|
|
err = db.StoreThumbnail(ctx, thumbnailMetadata)
|
2017-06-06 18:12:49 -05:00
|
|
|
if err != nil {
|
|
|
|
logger.WithError(err).WithFields(log.Fields{
|
|
|
|
"ActualWidth": width,
|
|
|
|
"ActualHeight": height,
|
|
|
|
}).Error("Failed to store thumbnail metadata in database.")
|
|
|
|
return false, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return false, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// adjustSize scales an image to fit within the provided width and height
|
|
|
|
// If the source aspect ratio is different to the target dimensions, one edge will be smaller than requested
|
|
|
|
// If crop is set to true, the image will be scaled to fill the width and height with any excess being cropped off
|
|
|
|
func adjustSize(dst types.Path, img image.Image, w, h int, crop bool, logger *log.Entry) (int, int, error) {
|
|
|
|
var out image.Image
|
|
|
|
var err error
|
|
|
|
if crop {
|
|
|
|
inAR := float64(img.Bounds().Dx()) / float64(img.Bounds().Dy())
|
|
|
|
outAR := float64(w) / float64(h)
|
|
|
|
|
|
|
|
var scaleW, scaleH uint
|
|
|
|
if inAR > outAR {
|
|
|
|
// input has shorter AR than requested output so use requested height and calculate width to match input AR
|
|
|
|
scaleW = uint(float64(h) * inAR)
|
|
|
|
scaleH = uint(h)
|
|
|
|
} else {
|
|
|
|
// input has taller AR than requested output so use requested width and calculate height to match input AR
|
|
|
|
scaleW = uint(w)
|
|
|
|
scaleH = uint(float64(w) / inAR)
|
|
|
|
}
|
|
|
|
|
|
|
|
scaled := resize.Resize(scaleW, scaleH, img, resize.Lanczos3)
|
|
|
|
|
|
|
|
xoff := (scaled.Bounds().Dx() - w) / 2
|
|
|
|
yoff := (scaled.Bounds().Dy() - h) / 2
|
|
|
|
|
|
|
|
tr := image.Rect(0, 0, w, h)
|
|
|
|
target := image.NewRGBA(tr)
|
|
|
|
draw.Draw(target, tr, scaled, image.Pt(xoff, yoff), draw.Src)
|
|
|
|
out = target
|
|
|
|
} else {
|
|
|
|
out = resize.Thumbnail(uint(w), uint(h), img, resize.Lanczos3)
|
|
|
|
}
|
|
|
|
|
|
|
|
if err = writeFile(out, string(dst)); err != nil {
|
|
|
|
logger.WithError(err).Error("Failed to encode and write image")
|
|
|
|
return -1, -1, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return out.Bounds().Max.X, out.Bounds().Max.Y, nil
|
|
|
|
}
|