summaryrefslogtreecommitdiffstats
path: root/media/mtp/MtpMediaScanner.cpp
blob: 1db1b9d3a090106db9ebc80fdac484a4c2692048 (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
/*
 * Copyright (C) 2010 The Android Open Source Project
 *
 * 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.
 */

#include "MtpDatabase.h"
#include "MtpMediaScanner.h"
#include "mtp.h"

#include <sys/types.h>
#include <sys/stat.h>
#include <sys/statfs.h>
#include <unistd.h>
#include <dirent.h>
#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <limits.h>

#include <media/mediascanner.h>
#include <media/stagefright/StagefrightMediaScanner.h>

namespace android {

class MtpMediaScannerClient : public MediaScannerClient
{
public:
    MtpMediaScannerClient()
    {
        reset();
    }

    virtual ~MtpMediaScannerClient()
    {
    }

    // returns true if it succeeded, false if an exception occured in the Java code
    virtual bool scanFile(const char* path, long long lastModified, long long fileSize)
    {
        printf("scanFile %s\n", path);
        return true;
    }

    // returns true if it succeeded, false if an exception occured in the Java code
    virtual bool handleStringTag(const char* name, const char* value)
    {
        int temp;

        if (!strcmp(name, "title")) {
            mTitle = value;
            mHasTitle = true;
        } else if  (!strcmp(name, "artist")) {
            mArtist = value;
            mHasArtist = true;
        } else if  (!strcmp(name, "album")) {
            mAlbum = value;
            mHasAlbum = true;
        } else if  (!strcmp(name, "albumartist")) {
            mAlbumArtist = value;
            mHasAlbumArtist = true;
        } else if  (!strcmp(name, "genre")) {
            // FIXME - handle numeric values here
            mGenre = value;
            mHasGenre = true;
        } else if  (!strcmp(name, "composer")) {
            mComposer = value;
            mHasComposer = true;
        } else if  (!strcmp(name, "tracknumber")) {
            if (sscanf(value, "%d", &temp) == 1)
                mTrack = temp;
        } else if  (!strcmp(name, "discnumber")) {
            // currently unused
        } else if  (!strcmp(name, "year") || !strcmp(name, "date")) {
            if (sscanf(value, "%d", &temp) == 1)
                mYear = temp;
        } else if  (!strcmp(name, "duration")) {
            if (sscanf(value, "%d", &temp) == 1)
                mDuration = temp;
        } else {
            printf("handleStringTag %s : %s\n", name, value);
        }
        return true;
    }

    // returns true if it succeeded, false if an exception occured in the Java code
    virtual bool setMimeType(const char* mimeType)
    {
        mMimeType = mimeType;
        mHasMimeType = true;
        return true;
    }

    // returns true if it succeeded, false if an exception occured in the Java code
    virtual bool addNoMediaFolder(const char* path)
    {
        printf("addNoMediaFolder %s\n", path);
        return true;
    }

    void reset()
    {
        mHasTitle = false;
        mHasArtist = false;
        mHasAlbum = false;
        mHasAlbumArtist = false;
        mHasGenre = false;
        mHasComposer = false;
        mHasMimeType = false;
        mTrack = mYear = mDuration = 0;
    }

    inline const char* getTitle() const { return mHasTitle ? (const char *)mTitle : NULL; }
    inline const char* getArtist() const { return mHasArtist ? (const char *)mArtist : NULL; }
    inline const char* getAlbum() const { return mHasAlbum ? (const char *)mAlbum : NULL; }
    inline const char* getAlbumArtist() const { return mHasAlbumArtist ? (const char *)mAlbumArtist : NULL; }
    inline const char* getGenre() const { return mHasGenre ? (const char *)mGenre : NULL; }
    inline const char* getComposer() const { return mHasComposer ? (const char *)mComposer : NULL; }
    inline const char* getMimeType() const { return mHasMimeType ? (const char *)mMimeType : NULL; }
    inline int getTrack() const { return mTrack; }
    inline int getYear() const { return mYear; }
    inline int getDuration() const { return mDuration; }

private:
    MtpString   mTitle;
    MtpString   mArtist;
    MtpString   mAlbum;
    MtpString   mAlbumArtist;
    MtpString   mGenre;
    MtpString   mComposer;
    MtpString   mMimeType;

    bool        mHasTitle;
    bool        mHasArtist;
    bool        mHasAlbum;
    bool        mHasAlbumArtist;
    bool        mHasGenre;
    bool        mHasComposer;
    bool        mHasMimeType;

    int         mTrack;
    int         mYear;
    int         mDuration;
};


MtpMediaScanner::MtpMediaScanner(MtpStorageID id, const char* filePath, MtpDatabase* db)
    :   mStorageID(id),
        mFilePath(filePath),
        mDatabase(db),
        mMediaScanner(NULL),
        mMediaScannerClient(NULL),
        mFileList(NULL),
        mFileCount(0)
{
    mMediaScanner = new StagefrightMediaScanner;
    mMediaScannerClient = new MtpMediaScannerClient;
}

MtpMediaScanner::~MtpMediaScanner() {
}

bool MtpMediaScanner::scanFiles() {
    mDatabase->beginTransaction();
    mFileCount = 0;
    mFileList = mDatabase->getFileList(mFileCount);

    int ret = scanDirectory(mFilePath, MTP_PARENT_ROOT);

    for (int i = 0; i < mFileCount; i++) {
        MtpObjectHandle test = mFileList[i];
        if (! (test & kObjectHandleMarkBit)) {
            printf("delete missing file %08X\n", test);
            mDatabase->deleteFile(test);
        }
    }

    delete[] mFileList;
    mFileCount = 0;
    mDatabase->commitTransaction();
    return (ret == 0);
}


static const struct MediaFileTypeEntry
{
    const char*     extension;
    MtpObjectFormat format;
    uint32_t        table;
} sFileTypes[] =
{
    { "MP3",    MTP_FORMAT_MP3,             kObjectHandleTableAudio     },
    { "M4A",    MTP_FORMAT_UNDEFINED_AUDIO, kObjectHandleTableAudio     },
    { "WAV",    MTP_FORMAT_WAV,             kObjectHandleTableAudio     },
    { "AMR",    MTP_FORMAT_UNDEFINED_AUDIO, kObjectHandleTableAudio     },
    { "AWB",    MTP_FORMAT_UNDEFINED_AUDIO, kObjectHandleTableAudio     },
    { "WMA",    MTP_FORMAT_WMA,             kObjectHandleTableAudio     },
    { "OGG",    MTP_FORMAT_OGG,             kObjectHandleTableAudio     },
    { "OGA",    MTP_FORMAT_UNDEFINED_AUDIO, kObjectHandleTableAudio     },
    { "AAC",    MTP_FORMAT_AAC,             kObjectHandleTableAudio     },
    { "MID",    MTP_FORMAT_UNDEFINED_AUDIO, kObjectHandleTableAudio     },
    { "MIDI",   MTP_FORMAT_UNDEFINED_AUDIO, kObjectHandleTableAudio     },
    { "XMF",    MTP_FORMAT_UNDEFINED_AUDIO, kObjectHandleTableAudio     },
    { "RTTTL",  MTP_FORMAT_UNDEFINED_AUDIO, kObjectHandleTableAudio     },
    { "SMF",    MTP_FORMAT_UNDEFINED_AUDIO, kObjectHandleTableAudio     },
    { "IMY",    MTP_FORMAT_UNDEFINED_AUDIO, kObjectHandleTableAudio     },
    { "RTX",    MTP_FORMAT_UNDEFINED_AUDIO, kObjectHandleTableAudio     },
    { "OTA",    MTP_FORMAT_UNDEFINED_AUDIO, kObjectHandleTableAudio     },
    { "MPEG",   MTP_FORMAT_UNDEFINED_VIDEO, kObjectHandleTableVideo     },
    { "MP4",    MTP_FORMAT_UNDEFINED_VIDEO, kObjectHandleTableVideo     },
    { "M4V",    MTP_FORMAT_UNDEFINED_VIDEO, kObjectHandleTableVideo     },
    { "3GP",    MTP_FORMAT_UNDEFINED_VIDEO, kObjectHandleTableVideo     },
    { "3GPP",   MTP_FORMAT_UNDEFINED_VIDEO, kObjectHandleTableVideo     },
    { "3G2",    MTP_FORMAT_UNDEFINED_VIDEO, kObjectHandleTableVideo     },
    { "3GPP2",  MTP_FORMAT_UNDEFINED_VIDEO, kObjectHandleTableVideo     },
    { "WMV",    MTP_FORMAT_UNDEFINED_VIDEO, kObjectHandleTableVideo     },
    { "ASF",    MTP_FORMAT_UNDEFINED_VIDEO, kObjectHandleTableVideo     },
    { "JPG",    MTP_FORMAT_EXIF_JPEG,       kObjectHandleTableImage     },
    { "JPEG",   MTP_FORMAT_EXIF_JPEG,       kObjectHandleTableImage     },
    { "GIF",    MTP_FORMAT_GIF,             kObjectHandleTableImage     },
    { "PNG",    MTP_FORMAT_PNG,             kObjectHandleTableImage     },
    { "BMP",    MTP_FORMAT_BMP,             kObjectHandleTableImage     },
    { "WBMP",   MTP_FORMAT_BMP,             kObjectHandleTableImage     },
    { "M3U",    MTP_FORMAT_M3U_PLAYLIST,    kObjectHandleTablePlaylist  },
    { "PLS",    MTP_FORMAT_PLS_PLAYLIST,    kObjectHandleTablePlaylist  },
    { "WPL",    MTP_FORMAT_WPL_PLAYLIST,    kObjectHandleTablePlaylist  },
};

MtpObjectFormat MtpMediaScanner::getFileFormat(const char* path, uint32_t& table)
{
    const char* extension = strrchr(path, '.');
    if (!extension)
        return MTP_FORMAT_UNDEFINED;
    extension++; // skip the dot

    for (unsigned i = 0; i < sizeof(sFileTypes) / sizeof(sFileTypes[0]); i++) {
        if (!strcasecmp(extension, sFileTypes[i].extension)) {
            table = sFileTypes[i].table;
            return sFileTypes[i].format;
        }
    }
    table = kObjectHandleTableFile;
    return MTP_FORMAT_UNDEFINED;
}

int MtpMediaScanner::scanDirectory(const char* path, MtpObjectHandle parent)
{
    char buffer[PATH_MAX];
    struct dirent* entry;

    unsigned length = strlen(path);
    if (length > sizeof(buffer) + 2) {
        fprintf(stderr, "path too long: %s\n", path);
    }

    DIR* dir = opendir(path);
    if (!dir) {
        fprintf(stderr, "opendir %s failed, errno: %d", path, errno);
        return -1;
    }

    strncpy(buffer, path, sizeof(buffer));
    char* fileStart = buffer + length;
    // make sure we have a trailing slash
    if (fileStart[-1] != '/') {
        *(fileStart++) = '/';
    }
    int fileNameLength = sizeof(buffer) + fileStart - buffer;

    while ((entry = readdir(dir))) {
        const char* name = entry->d_name;

        // ignore "." and "..", as well as any files or directories staring with dot
        if (name[0] == '.') {
            continue;
        }
        if (strlen(name) + 1 > fileNameLength) {
            fprintf(stderr, "path too long for %s\n", name);
            continue;
        }
        strcpy(fileStart, name);

        struct stat statbuf;
        memset(&statbuf, 0, sizeof(statbuf));
        stat(buffer, &statbuf);

        if (S_ISDIR(statbuf.st_mode)) {
            MtpObjectHandle handle = mDatabase->getObjectHandle(buffer);
            if (handle) {
                markFile(handle);
            } else {
                handle = mDatabase->addFile(buffer, MTP_FORMAT_ASSOCIATION,
                        parent, mStorageID, 0, statbuf.st_mtime);
            }
            scanDirectory(buffer, handle);
        } else if (S_ISREG(statbuf.st_mode)) {
            scanFile(buffer, parent, statbuf);
        }
    }

    closedir(dir);
    return 0;
}

void MtpMediaScanner::scanFile(const char* path, MtpObjectHandle parent, struct stat& statbuf) {
    uint32_t table;
    MtpObjectFormat format = getFileFormat(path, table);
    // don't scan unknown file types
    if (format == MTP_FORMAT_UNDEFINED)
        return;
    MtpObjectHandle handle = mDatabase->getObjectHandle(path);
    // fixme - rescan if mod date changed
    if (handle) {
        markFile(handle);
    } else {
        mDatabase->beginTransaction();
        handle = mDatabase->addFile(path, format, parent, mStorageID,
                statbuf.st_size, statbuf.st_mtime);
        if (handle <= 0) {
            fprintf(stderr, "addFile failed in MtpMediaScanner::scanFile()\n");
            mDatabase->rollbackTransaction();
            return;
        }

        if (table == kObjectHandleTableAudio) {
            mMediaScannerClient->reset();
            mMediaScanner->processFile(path, NULL, *mMediaScannerClient);
            handle = mDatabase->addAudioFile(handle,
                    mMediaScannerClient->getTitle(),
                    mMediaScannerClient->getArtist(),
                    mMediaScannerClient->getAlbum(),
                    mMediaScannerClient->getAlbumArtist(),
                    mMediaScannerClient->getGenre(),
                    mMediaScannerClient->getComposer(),
                    mMediaScannerClient->getMimeType(),
                    mMediaScannerClient->getTrack(),
                    mMediaScannerClient->getYear(),
                    mMediaScannerClient->getDuration());
        }
        mDatabase->commitTransaction();
    }
}

void MtpMediaScanner::markFile(MtpObjectHandle handle) {
    if (mFileList) {
        handle &= kObjectHandleIndexMask;
        // binary search for the file in mFileList
        int low = 0;
        int high = mFileCount;
        int index;

        while (low < high) {
            index = (low + high) >> 1;
            MtpObjectHandle test = (mFileList[index] & kObjectHandleIndexMask);
            if (handle < test)
                high = index;       // item is less than index
            else if (handle > test)
                low = index + 1;    // item is greater than index
            else {
                mFileList[index] |= kObjectHandleMarkBit;
                return;
            }
        }
        fprintf(stderr, "file %d not found in mFileList\n", handle);
    }
}

}  // namespace android