summaryrefslogtreecommitdiffstats
path: root/src/com/android/gallery3d/ingest/data/MtpDeviceIndex.java
blob: ebfbc922785930f73654f5c134307fbc2d151e92 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
package com.android.gallery3d.ingest.data;

import android.annotation.TargetApi;
import android.mtp.MtpConstants;
import android.mtp.MtpDevice;
import android.mtp.MtpObjectInfo;
import android.os.Build;
import android.webkit.MimeTypeMap;

import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

/**
 * Index of MTP media objects organized into "buckets," or groupings, based on the date
 * they were created.
 *
 * When the index is created, the buckets are sorted in their natural
 * order, and the items within the buckets sorted by the date they are taken.
 *
 * The index enables the access of items and bucket labels as one unified list.
 * For example, let's say we have the following data in the index:
 *    [Bucket A]: [photo 1], [photo 2]
 *    [Bucket B]: [photo 3]
 *
 * Then the items can be thought of as being organized as a 5 element list:
 *   [Bucket A], [photo 1], [photo 2], [Bucket B], [photo 3]
 *
 * The data can also be accessed in descending order, in which case the list
 * would be a bit different from simply reversing the ascending list, since the
 * bucket labels need to always be at the beginning:
 *   [Bucket B], [photo 3], [Bucket A], [photo 2], [photo 1]
 *
 * The index enables all the following operations in constant time, both for
 * ascending and descending views of the data:
 *   - get/getAscending/getDescending: get an item at a specified list position
 *   - size: get the total number of items (bucket labels and MTP objects)
 *   - getFirstPositionForBucketNumber
 *   - getBucketNumberForPosition
 *   - isFirstInBucket
 *
 * See {@link MtpDeviceIndexRunnable} for implementation notes.
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
public class MtpDeviceIndex {

  /**
   * Indexing progress listener.
   */
  public interface ProgressListener {
    /**
     * A media item on the device was indexed.
     * @param object The media item that was just indexed
     * @param numVisited Number of items visited so far
     */
    public void onObjectIndexed(IngestObjectInfo object, int numVisited);

    /**
     * The metadata loaded from the device is being sorted.
     */
    public void onSortingStarted();

    /**
     * The indexing is done and the index is ready to be used.
     */
    public void onIndexingFinished();
  }

  /**
   * Media sort orders.
   */
  public enum SortOrder {
    ASCENDING, DESCENDING
  }

  /** Quicktime MOV container (not already defined in {@link MtpConstants}) **/
  public static final int FORMAT_MOV = 0x300D;

  public static final Set<Integer> SUPPORTED_IMAGE_FORMATS;
  public static final Set<Integer> SUPPORTED_VIDEO_FORMATS;

  static {
    Set<Integer> supportedImageFormats = new HashSet<Integer>();
    supportedImageFormats.add(MtpConstants.FORMAT_JFIF);
    supportedImageFormats.add(MtpConstants.FORMAT_EXIF_JPEG);
    supportedImageFormats.add(MtpConstants.FORMAT_PNG);
    supportedImageFormats.add(MtpConstants.FORMAT_GIF);
    supportedImageFormats.add(MtpConstants.FORMAT_BMP);
    supportedImageFormats.add(MtpConstants.FORMAT_TIFF);
    supportedImageFormats.add(MtpConstants.FORMAT_TIFF_EP);
    if (Build.VERSION.SDK_INT >= 24) {
      supportedImageFormats.add(MtpConstants.FORMAT_DNG);
    }
    SUPPORTED_IMAGE_FORMATS = Collections.unmodifiableSet(supportedImageFormats);

    Set<Integer> supportedVideoFormats = new HashSet<Integer>();
    supportedVideoFormats.add(MtpConstants.FORMAT_3GP_CONTAINER);
    supportedVideoFormats.add(MtpConstants.FORMAT_AVI);
    supportedVideoFormats.add(MtpConstants.FORMAT_MP4_CONTAINER);
    supportedVideoFormats.add(MtpConstants.FORMAT_MP2);
    supportedVideoFormats.add(MtpConstants.FORMAT_MPEG);
    // TODO(georgescu): add FORMAT_MOV once Android Media Scanner supports .mov files
    SUPPORTED_VIDEO_FORMATS = Collections.unmodifiableSet(supportedVideoFormats);
  }

  private MtpDevice mDevice;
  private long mGeneration;
  private ProgressListener mProgressListener;
  private volatile MtpDeviceIndexRunnable.Results mResults;
  private final MtpDeviceIndexRunnable.Factory mIndexRunnableFactory;

  private static final MtpDeviceIndex sInstance = new MtpDeviceIndex(
      MtpDeviceIndexRunnable.getFactory());

  private static final Map<String, Boolean> sCachedSupportedExtenstions = new HashMap<>();

  public static MtpDeviceIndex getInstance() {
    return sInstance;
  }

  protected MtpDeviceIndex(MtpDeviceIndexRunnable.Factory indexRunnableFactory) {
    mIndexRunnableFactory = indexRunnableFactory;
  }

  public synchronized MtpDevice getDevice() {
    return mDevice;
  }

  public synchronized boolean isDeviceConnected() {
    return (mDevice != null);
  }

  /**
   * @param mtpObjectInfo MTP object info
   * @return Whether the format is supported by this index.
   */
  public boolean isFormatSupported(MtpObjectInfo mtpObjectInfo) {
    // Checks whether the format is supported or not.
    final int format = mtpObjectInfo.getFormat();
    if (SUPPORTED_IMAGE_FORMATS.contains(format)
        || SUPPORTED_VIDEO_FORMATS.contains(format)) {
      return true;
    }

    // Checks whether the extension is supported or not.
    final String name = mtpObjectInfo.getName();
    if (name == null) {
      return false;
    }
    final int lastDot = name.lastIndexOf('.');
    if (lastDot >= 0) {
      final String extension = name.substring(lastDot + 1);

      Boolean result = sCachedSupportedExtenstions.get(extension);
      if (result != null) {
        return result;
      }
      final String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
          extension.toLowerCase(Locale.US));
      if (mime != null) {
        // This will also accept the newly added mimetypes for images and videos.
        result = mime.startsWith("image/") || mime.startsWith("video/");
        sCachedSupportedExtenstions.put(extension, result);
        return result;
      }
    }

    return false;
  }

  /**
   * Sets the MtpDevice that should be indexed and initializes state, but does
   * not kick off the actual indexing task, which is instead done by using
   * {@link #getIndexRunnable()}
   *
   * @param device The MtpDevice that should be indexed
   */
  public synchronized void setDevice(MtpDevice device) {
    if (device == mDevice) {
      return;
    }
    mDevice = device;
    resetState();
  }

  /**
   * Provides a Runnable for the indexing task (assuming the state has already
   * been correctly initialized by calling {@link #setDevice(MtpDevice)}).
   *
   * @return Runnable for the main indexing task
   */
  public synchronized Runnable getIndexRunnable() {
    if (!isDeviceConnected() || mResults != null) {
      return null;
    }
    return mIndexRunnableFactory.createMtpDeviceIndexRunnable(this);
  }

  /**
   * @return Whether the index is ready to be used.
   */
  public synchronized boolean isIndexReady() {
    return mResults != null;
  }

  /**
   * @param listener
   * @return Current progress (useful for configuring initial UI state)
   */
  public synchronized void setProgressListener(ProgressListener listener) {
    mProgressListener = listener;
  }

  /**
   * Make the listener null if it matches the argument
   *
   * @param listener Listener to unset, if currently registered
   */
  public synchronized void unsetProgressListener(ProgressListener listener) {
    if (mProgressListener == listener) {
      mProgressListener = null;
    }
  }

  /**
   * @return The total number of elements in the index (labels and items)
   */
  public int size() {
    MtpDeviceIndexRunnable.Results results = mResults;
    return results != null ? results.unifiedLookupIndex.length : 0;
  }

  /**
   * @param position Index of item to fetch, where 0 is the first item in the
   *            specified order
   * @param order
   * @return the bucket label or IngestObjectInfo at the specified position and
   *         order
   */
  public Object get(int position, SortOrder order) {
    MtpDeviceIndexRunnable.Results results = mResults;
    if (results == null) {
      return null;
    }
    if (order == SortOrder.ASCENDING) {
      DateBucket bucket = results.buckets[results.unifiedLookupIndex[position]];
      if (bucket.unifiedStartIndex == position) {
        return bucket.date;
      } else {
        return results.mtpObjects[bucket.itemsStartIndex + position - 1
            - bucket.unifiedStartIndex];
      }
    } else {
      int zeroIndex = results.unifiedLookupIndex.length - 1 - position;
      DateBucket bucket = results.buckets[results.unifiedLookupIndex[zeroIndex]];
      if (bucket.unifiedEndIndex == zeroIndex) {
        return bucket.date;
      } else {
        return results.mtpObjects[bucket.itemsStartIndex + zeroIndex
            - bucket.unifiedStartIndex];
      }
    }
  }

  /**
   * @param position Index of item to fetch from a view of the data that does not
   *            include labels and is in the specified order
   * @return position-th item in specified order, when not including labels
   */
  public IngestObjectInfo getWithoutLabels(int position, SortOrder order) {
    MtpDeviceIndexRunnable.Results results = mResults;
    if (results == null) {
      return null;
    }
    if (order == SortOrder.ASCENDING) {
      return results.mtpObjects[position];
    } else {
      return results.mtpObjects[results.mtpObjects.length - 1 - position];
    }
  }

  /**
   * @param position Index of item to map from a view of the data that does not
   *            include labels and is in the specified order
   * @param order
   * @return position in a view of the data that does include labels, or -1 if the index isn't
   *         ready
   */
  public int getPositionFromPositionWithoutLabels(int position, SortOrder order) {
        /* Although this is O(log(number of buckets)), and thus should not be used
           in hotspots, even if the attached device has items for every day for
           a five-year timeframe, it would still only take 11 iterations at most,
           so shouldn't be a huge issue. */
    MtpDeviceIndexRunnable.Results results = mResults;
    if (results == null) {
      return -1;
    }
    if (order == SortOrder.DESCENDING) {
      position = results.mtpObjects.length - 1 - position;
    }
    int bucketNumber = 0;
    int iMin = 0;
    int iMax = results.buckets.length - 1;
    while (iMax >= iMin) {
      int iMid = (iMax + iMin) / 2;
      if (results.buckets[iMid].itemsStartIndex + results.buckets[iMid].numItems
          <= position) {
        iMin = iMid + 1;
      } else if (results.buckets[iMid].itemsStartIndex > position) {
        iMax = iMid - 1;
      } else {
        bucketNumber = iMid;
        break;
      }
    }
    int mappedPos = results.buckets[bucketNumber].unifiedStartIndex + position
        - results.buckets[bucketNumber].itemsStartIndex + 1;
    if (order == SortOrder.DESCENDING) {
      mappedPos = results.unifiedLookupIndex.length - mappedPos;
    }
    return mappedPos;
  }

  /**
   * @param position Index of item to map from a view of the data that
   *            includes labels and is in the specified order
   * @param order
   * @return position in a view of the data that does not include labels, or -1 if the index isn't
   *         ready
   */
  public int getPositionWithoutLabelsFromPosition(int position, SortOrder order) {
    MtpDeviceIndexRunnable.Results results = mResults;
    if (results == null) {
      return -1;
    }
    if (order == SortOrder.ASCENDING) {
      DateBucket bucket = results.buckets[results.unifiedLookupIndex[position]];
      if (bucket.unifiedStartIndex == position) {
        position++;
      }
      return bucket.itemsStartIndex + position - 1 - bucket.unifiedStartIndex;
    } else {
      int zeroIndex = results.unifiedLookupIndex.length - 1 - position;
      DateBucket bucket = results.buckets[results.unifiedLookupIndex[zeroIndex]];
      if (bucket.unifiedEndIndex == zeroIndex) {
        zeroIndex--;
      }
      return results.mtpObjects.length - 1 - bucket.itemsStartIndex
          - zeroIndex + bucket.unifiedStartIndex;
    }
  }

  /**
   * @return The number of media items in the index
   */
  public int sizeWithoutLabels() {
    MtpDeviceIndexRunnable.Results results = mResults;
    return results != null ? results.mtpObjects.length : 0;
  }

  /**
   * @param bucketNumber Index of bucket in the specified order
   * @param order
   * @return position of bucket's first item in a view of the data that includes labels
   */
  public int getFirstPositionForBucketNumber(int bucketNumber, SortOrder order) {
    MtpDeviceIndexRunnable.Results results = mResults;
    if (order == SortOrder.ASCENDING) {
      return results.buckets[bucketNumber].unifiedStartIndex;
    } else {
      return results.unifiedLookupIndex.length
          - results.buckets[results.buckets.length - 1 - bucketNumber].unifiedEndIndex
          - 1;
    }
  }

  /**
   * @param position Index of item in the view of the data that includes labels and is in
   *                 the specified order
   * @param order
   * @return Index of the bucket that contains the specified item
   */
  public int getBucketNumberForPosition(int position, SortOrder order) {
    MtpDeviceIndexRunnable.Results results = mResults;
    if (order == SortOrder.ASCENDING) {
      return results.unifiedLookupIndex[position];
    } else {
      return results.buckets.length - 1
          - results.unifiedLookupIndex[results.unifiedLookupIndex.length - 1
          - position];
    }
  }

  /**
   * @param position Index of item in the view of the data that includes labels and is in
   *                 the specified order
   * @param order
   * @return Whether the specified item is the first item in its bucket
   */
  public boolean isFirstInBucket(int position, SortOrder order) {
    MtpDeviceIndexRunnable.Results results = mResults;
    if (order == SortOrder.ASCENDING) {
      return results.buckets[results.unifiedLookupIndex[position]].unifiedStartIndex
          == position;
    } else {
      position = results.unifiedLookupIndex.length - 1 - position;
      return results.buckets[results.unifiedLookupIndex[position]].unifiedEndIndex
          == position;
    }
  }

  /**
   * @param order
   * @return Array of buckets in the specified order
   */
  public DateBucket[] getBuckets(SortOrder order) {
    MtpDeviceIndexRunnable.Results results = mResults;
    if (results == null) {
      return null;
    }
    return (order == SortOrder.ASCENDING) ? results.buckets : results.reversedBuckets;
  }

  protected void resetState() {
    mGeneration++;
    mResults = null;
  }

  /**
   * @param device
   * @param generation
   * @return whether the index is at the given generation and the given device is connected
   */
  protected boolean isAtGeneration(MtpDevice device, long generation) {
    return (mGeneration == generation) && (mDevice == device);
  }

  protected synchronized boolean setIndexingResults(MtpDevice device, long generation,
      MtpDeviceIndexRunnable.Results results) {
    if (!isAtGeneration(device, generation)) {
      return false;
    }
    mResults = results;
    onIndexFinish(true /*successful*/);
    return true;
  }

  protected synchronized void onIndexFinish(boolean successful) {
    if (!successful) {
      resetState();
    }
    if (mProgressListener != null) {
      mProgressListener.onIndexingFinished();
    }
  }

  protected synchronized void onSorting() {
    if (mProgressListener != null) {
      mProgressListener.onSortingStarted();
    }
  }

  protected synchronized void onObjectIndexed(IngestObjectInfo object, int numVisited) {
    if (mProgressListener != null) {
      mProgressListener.onObjectIndexed(object, numVisited);
    }
  }

  protected long getGeneration() {
    return mGeneration;
  }
}