1/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.camera.one.v2.sharedimagereader.ringbuffer;
18
19import com.android.camera.async.BufferQueue;
20import com.android.camera.async.BufferQueueController;
21import com.android.camera.async.Lifetime;
22import com.android.camera.async.Observable;
23import com.android.camera.one.v2.camera2proxy.ImageProxy;
24import com.android.camera.one.v2.sharedimagereader.ticketpool.TicketPool;
25import com.google.common.util.concurrent.MoreExecutors;
26
27/*
28 * Creates a dynamic ring buffer of images.
29 * <p>
30 * The ring buffer is implicitly defined by an input and an output.
31 * <p>
32 * The size of the ring-buffer is dictated by how many tickets it can retrieve from the root
33 * ticket pool.  As tickets become available, the ring-buffer expands.
34 * <p>
35 * The ring buffer also provides its own ticket pool.  When tickets are requested from this pool,
36 * the ring buffer shrinks.
37 * <p>
38 * Images which cannot be held in the ring-buffer are released immediately.
39 */
40public class DynamicRingBufferFactory {
41    private final TicketPool mOutputTicketPool;
42    private final BufferQueueController<ImageProxy> mRingBufferInput;
43    private final BufferQueue<ImageProxy> mRingBufferOutput;
44
45    public DynamicRingBufferFactory(Lifetime lifetime, TicketPool rootTicketPool,
46            final Observable<Integer> maxRingBufferSize) {
47        final DynamicRingBuffer ringBuffer = new DynamicRingBuffer(rootTicketPool);
48        lifetime.add(ringBuffer);
49        lifetime.add(maxRingBufferSize.addCallback(new Runnable() {
50            @Override
51            public void run() {
52                ringBuffer.setMaxSize(Math.max(0, maxRingBufferSize.get()));
53            }
54        }, MoreExecutors.sameThreadExecutor()));
55        ringBuffer.setMaxSize(Math.max(0, maxRingBufferSize.get()));
56
57        mOutputTicketPool = ringBuffer;
58        mRingBufferInput = ringBuffer;
59        mRingBufferOutput = ringBuffer;
60    }
61
62    public TicketPool provideTicketPool() {
63        return mOutputTicketPool;
64    }
65
66    public BufferQueueController<ImageProxy> provideRingBufferInput() {
67        return mRingBufferInput;
68    }
69
70    public BufferQueue<ImageProxy> provideRingBufferOutput() {
71        return mRingBufferOutput;
72    }
73}
74