| 28 | } |
| 29 | |
| 30 | func (t *CachingTranscoder) Transcode(ctx context.Context, profile Profile, in string, out io.Writer) error { |
| 31 | t.cache.RLock() |
| 32 | defer t.cache.RUnlock() |
| 33 | |
| 34 | // don't try cache partial transcodes |
| 35 | if profile.Seek() > 0 { |
| 36 | return t.transcoder.Transcode(ctx, profile, in, out) |
| 37 | } |
| 38 | |
| 39 | if err := os.MkdirAll(t.cache.Path(), perm^0o111); err != nil { |
| 40 | return fmt.Errorf("make cache path: %w", err) |
| 41 | } |
| 42 | |
| 43 | key, err := keyFor(profile, in) |
| 44 | if err != nil { |
| 45 | return err |
| 46 | } |
| 47 | |
| 48 | unlock := t.locks.Lock(key) |
| 49 | defer unlock() |
| 50 | |
| 51 | path := filepath.Join(t.cache.Path(), key) |
| 52 | cf, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0o644) |
| 53 | if err != nil { |
| 54 | return fmt.Errorf("open cache file: %w", err) |
| 55 | } |
| 56 | defer cf.Close() |
| 57 | |
| 58 | if i, err := cf.Stat(); err == nil && i.Size() > 0 { |
| 59 | _, _ = io.Copy(out, cf) |
| 60 | _ = os.Chtimes(path, time.Now(), time.Now()) // Touch for LRU cache purposes |
| 61 | return nil |
| 62 | } |
| 63 | |
| 64 | dest := io.MultiWriter(out, cf) |
| 65 | if err := t.transcoder.Transcode(ctx, profile, in, dest); err != nil { |
| 66 | os.Remove(path) |
| 67 | return fmt.Errorf("internal transcode: %w", err) |
| 68 | } |
| 69 | |
| 70 | return nil |
| 71 | } |
| 72 | |
| 73 | func (t *CachingTranscoder) CachedPath(profile Profile, in string) (string, func(), error) { |
| 74 | if profile.Seek() > 0 { |