MetadataParser.cpp 14.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/*****************************************************************************
 * Media Library
 *****************************************************************************
 * Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs
 *
 * Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

23 24 25 26
#if HAVE_CONFIG_H
# include "config.h"
#endif

27 28 29 30 31
#include "MetadataParser.h"
#include "Album.h"
#include "AlbumTrack.h"
#include "Artist.h"
#include "File.h"
32
#include "Genre.h"
33 34 35
#include "Media.h"
#include "Show.h"
#include "utils/Filename.h"
36
#include "utils/ModificationsNotifier.h"
37
#include <cstdlib>
38

39 40 41
namespace medialibrary
{

42 43
bool MetadataParser::initialize()
{
44
    m_unknownArtist = Artist::fetch( m_ml, UnknownArtistID );
45 46 47 48 49 50 51 52 53
    if ( m_unknownArtist == nullptr )
        LOG_ERROR( "Failed to cache unknown artist" );
    return m_unknownArtist != nullptr;
}

parser::Task::Status MetadataParser::run( parser::Task& task )
{
    auto& media = task.media;

54
    auto t = m_ml->getConn()->newTransaction();
55 56
    bool isAudio = task.videoTracks.empty();
    for ( const auto& t : task.videoTracks )
57
    {
58
        media->addVideoTrack( t.fcc, t.width, t.height, t.fps, t.language, t.description );
59
    }
60
    for ( const auto& t : task.audioTracks )
61
    {
62 63
        media->addAudioTrack( t.fcc, t.bitrate, t.samplerate, t.nbChannels,
                              t.language, t.description );
64 65 66 67
    }
    t->commit();
    if ( isAudio == true )
    {
68
        if ( parseAudioFile( task ) == false )
69 70 71 72
            return parser::Task::Status::Fatal;
    }
    else
    {
73
        if (parseVideoFile( task ) == false )
74 75
            return parser::Task::Status::Fatal;
    }
76
    auto duration = task.duration;
77 78 79 80 81 82 83 84
    media->setDuration( duration );
    if ( media->save() == false )
        return parser::Task::Status::Error;
    return parser::Task::Status::Success;
}

/* Video files */

85
bool MetadataParser::parseVideoFile( parser::Task& task ) const
86
{
87
    auto media = task.media.get();
88
    media->setType( IMedia::Type::VideoType );
89
    if ( task.title.length() == 0 )
90
        return true;
91 92

    if ( task.showName.length() == 0 )
93
    {
94
        auto show = m_ml->show( task.showName );
95 96
        if ( show == nullptr )
        {
97
            show = m_ml->createShow( task.showName );
98 99 100 101
            if ( show == nullptr )
                return false;
        }

102
        if ( task.episode != 0 )
103 104
        {
            std::shared_ptr<Show> s = std::static_pointer_cast<Show>( show );
105
            s->addEpisode( *media, task.title, task.episode );
106 107 108 109 110 111 112 113 114 115 116
        }
    }
    else
    {
        // How do we know if it's a movie or a random video?
    }
    return true;
}

/* Audio files */

117
bool MetadataParser::parseAudioFile( parser::Task& task ) const
118
{
119
    task.media->setType( IMedia::Type::AudioType );
120

121 122
    if ( task.artworkMrl.empty() == false )
        task.media->setThumbnail( task.artworkMrl );
123

124
    auto genre = handleGenre( task );
125
    auto artists = handleArtists( task );
126
    auto album = handleAlbum( task, artists.first, artists.second, genre.get() );
127 128 129 130 131
    if ( album == nullptr )
    {
        LOG_WARN( "Failed to get/create associated album" );
        return false;
    }
132
    auto t = m_ml->getConn()->newTransaction();
133
    auto res = link( *task.media, album, artists.first, artists.second );
134 135 136 137
    t->commit();
    return res;
}

138 139 140 141 142 143 144 145 146 147 148 149 150 151
std::shared_ptr<Genre> MetadataParser::handleGenre( parser::Task& task ) const
{
    if ( task.genre.length() == 0 )
        return nullptr;
    auto genre = Genre::fromName( m_ml, task.genre );
    if ( genre == nullptr )
    {
        genre = Genre::create( m_ml, task.genre );
        if ( genre == nullptr )
            LOG_ERROR( "Failed to get/create Genre", task.genre );
    }
    return genre;
}

152
/* Album handling */
153
std::shared_ptr<Album> MetadataParser::findAlbum( parser::Task& task, Artist* albumArtist ) const
154 155 156
{
    static const std::string req = "SELECT * FROM " + policy::AlbumTable::Name +
            " WHERE title = ?";
157
    auto albums = Album::fetchAll<Album>( m_ml, req, task.albumName );
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

    if ( albums.size() == 0 )
        return nullptr;

    /*
     * Even if we get only 1 album, we need to filter out invalid matches.
     * For instance, if we have already inserted an album "A" by an artist "john"
     * but we are now trying to handle an album "A" by an artist "doe", not filtering
     * candidates would yield the only "A" album we know, while we should return
     * nullptr, so handleAlbum can create a new one.
     */
    for ( auto it = begin( albums ); it != end( albums ); )
    {
        auto a = (*it).get();
        if ( albumArtist != nullptr )
        {
            // We assume that an album without album artist is a positive match.
            // At the end of the day, without proper tags, there's only so much we can do.
            auto candidateAlbumArtist = a->albumArtist();
            if ( candidateAlbumArtist != nullptr && candidateAlbumArtist->id() != albumArtist->id() )
            {
                it = albums.erase( it );
                continue;
            }
        }
        // If this is a multidisc album, assume it could be in a multiple amount of folders.
        // Since folders can come in any order, we can't assume the first album will be the
        // first media we see. If the discTotal or discNumber meta are provided, that's easy. If not,
        // we assume that another CD with the same name & artists, and a disc number > 1
        // denotes a multi disc album
        // Check the first case early to avoid fetching tracks if unrequired.
189
        if ( task.discTotal > 1 || task.discNumber > 1 )
190 191 192 193
        {
            ++it;
            continue;
        }
194
        const auto tracks = a->cachedTracks();
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
        assert( tracks.size() > 0 );

        auto multiDisc = false;
        for ( auto& t : tracks )
        {
            auto at = t->albumTrack();
            assert( at != nullptr );
            if ( at != nullptr && at->discNumber() > 1 )
            {
                multiDisc = true;
                break;
            }
        }
        if ( multiDisc )
        {
            ++it;
            continue;
        }

        // Assume album files will be in the same folder.
215
        auto newFileFolder = utils::file::directory( task.file->mrl() );
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
        auto trackFiles = tracks[0]->files();
        bool excluded = false;
        for ( auto& f : trackFiles )
        {
            auto candidateFolder = utils::file::directory( f->mrl() );
            if ( candidateFolder != newFileFolder )
            {
                excluded = true;
                break;
            }
        }
        if ( excluded == true )
        {
            it = albums.erase( it );
            continue;
        }
        ++it;
    }
    if ( albums.size() == 0 )
        return nullptr;
    if ( albums.size() > 1 )
    {
238
        LOG_WARN( "Multiple candidates for album ", task.albumName, ". Selecting first one out of luck" );
239 240 241 242
    }
    return std::static_pointer_cast<Album>( albums[0] );
}

243 244
std::shared_ptr<Album> MetadataParser::handleAlbum( parser::Task& task, std::shared_ptr<Artist> albumArtist,
                                                    std::shared_ptr<Artist> trackArtist, Genre* genre ) const
245 246 247 248 249 250 251 252 253 254 255 256 257
{
    std::shared_ptr<Album> album;
    std::shared_ptr<Artist> artist = albumArtist;
    if ( artist == nullptr )
    {
        if ( trackArtist != nullptr )
            artist = trackArtist;
        else
        {
            artist = m_unknownArtist;
        }
    }

258
    if ( task.albumName.length() > 0 )
259 260 261
    {
        // Album matching depends on the difference between artist & album artist.
        // Specificaly pass the albumArtist here.
262
        album = findAlbum( task, albumArtist.get() );
263 264 265

        if ( album == nullptr )
        {
266
            album = m_ml->createAlbum( task.albumName );
267 268
            if ( album != nullptr )
            {
269 270
                if ( task.artworkMrl.length() != 0 )
                    album->setArtworkMrl( task.artworkMrl );
271
            }
272
            m_notifier->notifyAlbumCreation( album );
273 274 275 276 277 278 279 280
        }
    }
    else
        album = artist->unknownAlbum();

    if ( album == nullptr )
        return nullptr;
    // If we know a track artist, specify it, otherwise, fallback to the album/unknown artist
281
    auto track = handleTrack( album, task, trackArtist ? trackArtist : artist, genre );
282 283 284 285 286 287 288 289 290 291 292
    return album;
}

///
/// \brief MetadataParser::handleArtists Returns Artist's involved on a track
/// \param media The track to analyze
/// \param vlcMedia VLC's media
/// \return A pair containing:
/// The album artist as a first element
/// The track artist as a second element, or nullptr if it is the same as album artist
///
293
std::pair<std::shared_ptr<Artist>, std::shared_ptr<Artist>> MetadataParser::handleArtists( parser::Task& task ) const
294 295 296 297
{
    std::shared_ptr<Artist> albumArtist;
    std::shared_ptr<Artist> artist;

298
    if ( task.albumArtist.empty() == true && task.artist.empty() == true )
299 300 301 302
    {
        return {nullptr, nullptr};
    }

303
    if ( task.albumArtist.empty() == false )
304
    {
305
        albumArtist = std::static_pointer_cast<Artist>( m_ml->artist( task.albumArtist ) );
306 307
        if ( albumArtist == nullptr )
        {
308
            albumArtist = m_ml->createArtist( task.albumArtist );
309 310
            if ( albumArtist == nullptr )
            {
311
                LOG_ERROR( "Failed to create new artist ", task.albumArtist );
312 313
                return {nullptr, nullptr};
            }
314
            m_notifier->notifyArtistCreation( albumArtist );
315 316
        }
    }
317
    if ( task.artist.empty() == false && task.artist != task.albumArtist )
318
    {
319
        artist = std::static_pointer_cast<Artist>( m_ml->artist( task.artist ) );
320 321
        if ( artist == nullptr )
        {
322
            artist = m_ml->createArtist( task.artist );
323 324
            if ( artist == nullptr )
            {
325
                LOG_ERROR( "Failed to create new artist ", task.artist );
326 327
                return {nullptr, nullptr};
            }
328
            m_notifier->notifyArtistCreation( albumArtist );
329 330 331 332 333 334 335
        }
    }
    return {albumArtist, artist};
}

/* Tracks handling */

336 337
std::shared_ptr<AlbumTrack> MetadataParser::handleTrack( std::shared_ptr<Album> album, parser::Task& task,
                                                         std::shared_ptr<Artist> artist, Genre* genre ) const
338
{
339
    auto title = task.title;
340 341 342
    if ( title.empty() == true )
    {
        LOG_WARN( "Failed to get track title" );
343
        if ( task.trackNumber != 0 )
344 345
        {
            title = "Track #";
346
            title += std::to_string( task.trackNumber );
347 348 349
        }
    }
    if ( title.empty() == false )
350
        task.media->setTitle( title );
351

352 353 354
    auto track = std::static_pointer_cast<AlbumTrack>( album->addTrack( task.media, task.trackNumber,
                                                                        task.discNumber, artist->id(),
                                                                        genre != nullptr ? genre->id() : 0 ) );
355 356 357 358 359
    if ( track == nullptr )
    {
        LOG_ERROR( "Failed to create album track" );
        return nullptr;
    }
360 361

    if ( task.releaseDate.empty() == false )
362
    {
363
        auto releaseYear = atoi( task.releaseDate.c_str() );
364
        task.media->setReleaseDate( releaseYear );
365 366 367 368 369
        // Let the album handle multiple dates. In order to do this properly, we need
        // to know if the date has been changed before, which can be known only by
        // using Album class internals.
        album->setReleaseYear( releaseYear, false );
    }
370
    m_notifier->notifyAlbumTrackCreation( track );
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
    return track;
}

/* Misc */

bool MetadataParser::link( Media& media, std::shared_ptr<Album> album,
                               std::shared_ptr<Artist> albumArtist, std::shared_ptr<Artist> artist ) const
{
    if ( albumArtist == nullptr && artist == nullptr )
        albumArtist = m_unknownArtist;
    else
    {
        if ( albumArtist == nullptr )
            albumArtist = artist;
    }

    // We might modify albumArtist later, hence handle thumbnails before.
    // If we have an albumArtist (meaning the track was properly tagged, we
    // can assume this artist is a correct match. We can use the thumbnail from
    // the current album for the albumArtist, if none has been set before.
    if ( albumArtist != nullptr && albumArtist->artworkMrl().empty() == true &&
         album != nullptr && album->artworkMrl().empty() == false )
        albumArtist->setArtworkMrl( album->artworkMrl() );

    if ( albumArtist != nullptr )
        albumArtist->addMedia( media );
    if ( artist != nullptr && ( albumArtist == nullptr || albumArtist->id() != artist->id() ) )
        artist->addMedia( media );

    auto currentAlbumArtist = album->albumArtist();

    // If we have no main artist yet, that's easy, we need to assign one.
    if ( currentAlbumArtist == nullptr )
    {
        // We don't know if the artist was tagged as artist or albumartist, however, we simply add it
        // as the albumartist until proven we were wrong (ie. until one of the next tracks
        // has a different artist)
408
        album->setAlbumArtist( albumArtist );
409 410 411 412 413 414 415 416 417 418
        // Always add the album artist as an artist
        album->addArtist( albumArtist );
        if ( artist != nullptr )
            album->addArtist( artist );
    }
    else
    {
        if ( albumArtist->id() != currentAlbumArtist->id() )
        {
            // We have more than a single artist on this album, fallback to various artists
419
            auto variousArtists = Artist::fetch( m_ml, VariousArtistID );
420
            album->setAlbumArtist( variousArtists );
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
            // Add those two artists as "featuring".
            album->addArtist( albumArtist );
        }
        if ( artist != nullptr && artist->id() != albumArtist->id() )
        {
            if ( albumArtist->id() != artist->id() )
               album->addArtist( artist );
        }
    }

    return true;
}


const char* MetadataParser::name() const
{
    return "Metadata";
}
439 440 441 442 443 444 445 446 447 448

uint8_t MetadataParser::nbThreads() const
{
//    auto nbProcs = std::thread::hardware_concurrency();
//    if ( nbProcs == 0 )
//        return 1;
//    return nbProcs;
    // Let's make this code thread-safe first :)
    return 1;
}
449 450

}