Skip to content

Remove ItemKey::Unknown #521

Closed
Closed

Description

@Serial-ATA

ItemKey::Unknown has served its purpose, and has had better alternatives for a couple years now. It's been a source of confusion numerous times, and its existence also requires extra verification logic on conversions. I'd like to see it gone.

Comment taken from #520

ItemKey::Unknown was kind of a hacky way to retain tags that couldn't be mapped to concrete ItemKeys. There have been alternatives for awhile now though, with SplitTag, MergeTag, and GlobalOptions::preserve_format_specific_items() (see #302 for more info on that).

I envision people taking their Tags, converting them to a concrete format (e.g. VorbisComments), and then adding their custom fields to that. I'd rather not have a way to generically add custom fields, since the mappings for the concrete ItemKey variants are known to be valid, but with Unknown, there's extra verification that needs to be done on conversions that could be skipped if I just get rid of it entirely.

You'd go from:

tag.insert_text(ItemKey::Unknown(String::from("FOO")), String::from("BAR"));

to:

let mut vorbis_comments: VorbisComments = tag.into();
vorbis_comments.insert(String::from("FOO"), String::from("BAR"));

ItemKey supports the keys that the vast majority of users will need, anything else would be niche and require a little extra effort working with the concrete formats.

Activity

  1. added
    enhancement
    on May 7, 2025
  2. Undead34 commented on May 13, 2025

    @Undead34

    Hi! I understand the motivation behind simplifying the ItemKey enum and removing ItemKey::Unknown, but I'd like to offer a user perspective that may have been overlooked.

    I'm currently building a music library and metadata API where users can scan, view, and edit tags generically across different formats (MP3, FLAC, M4A, etc.). For this use case, ItemKey::Unknown has been extremely valuable.

    It allows me to support custom or non-standard tags like RATING, MOOD, BPM_LABEL, and others without needing to write backend-specific logic for each format. While these tags may seem niche from a spec point of view, they are actually very common in real-world scenarios — especially for advanced playback systems, smart playlisting, DJ software, and even consumer apps that want to store user preferences.

    By removing ItemKey::Unknown, I would be forced to detect the tag backend (e.g., Vorbis, ID3v2, MP4) and write logic per format just to set or read a single custom field — which breaks the abstraction that Tag provides.

    For example, I’ve encountered many high-quality FLAC files in the wild where fields like TRACKTOTAL or DISCTOTAL are not parsed via tag.track_total() or tag.disk_total() but are present as raw strings under those names. In my implementation, I handle this fallback like this:

    metadata.set_total_tracks(tag.track_total().map(|n| n as u16).or_else(|| {
        tag.get_string(&ItemKey::Unknown("TRACKTOTAL".to_string()))
            .and_then(|s| s.trim().parse::<u16>().ok())
    }));
    
    metadata.set_total_discs(tag.disk_total().map(|n| n as u16).or_else(|| {
        tag.get_string(&ItemKey::Unknown("DISCTOTAL".to_string()))
            .and_then(|s| s.trim().parse::<u16>().ok())
    }));

    I completely understand if ItemKey::Unknown needs to be deprecated or discouraged for performance or consistency reasons. But completely removing it would break a lot of real, practical use cases that rely on flexible metadata editing.

    Thanks for your work on Lofty — it’s a great library and I really appreciate the attention to correctness and long-term design!

  3. Serial-ATA commented on May 13, 2025

    @Serial-ATA
    OwnerAuthor

    @Undead34 Thanks for sharing your thoughts!

    It allows me to support custom or non-standard tags like RATING, MOOD, BPM_LABEL [...] While these tags may seem niche from a spec point of view, they are actually very common in real-world scenarios

    I'm always open to adding more ItemKey variants, feel free to suggest the ones that you have custom logic for (like BPM_LABEL, which I've haven't seen before).

    And for the record, RATING and MOOD map to ItemKey::Popularimeter and ItemKey::Mood for Vorbis Comments. You can see the full mapping here:

    gen_map!(
    VORBIS_MAP;
    "ALBUM" => AlbumTitle,
    "DISCSUBTITLE" => SetSubtitle,
    "GROUPING" => ContentGroup,
    "TITLE" => TrackTitle,
    "SUBTITLE" => TrackSubtitle,
    "WORK" => Work,
    "MOVEMENTNAME" => Movement,
    "MOVEMENT" => MovementNumber,
    "MOVEMENTTOTAL" => MovementTotal,
    "ALBUMSORT" => AlbumTitleSortOrder,
    "ALBUMARTISTSORT" => AlbumArtistSortOrder,
    "TITLESORT" => TrackTitleSortOrder,
    "ARTISTSORT" => TrackArtistSortOrder,
    "ALBUMARTIST" => AlbumArtist,
    "ARTIST" => TrackArtist,
    "ARTISTS" => TrackArtists,
    "ARRANGER" => Arranger,
    "AUTHOR" | "WRITER" => Writer,
    "COMPOSER" => Composer,
    "CONDUCTOR" => Conductor,
    "DIRECTOR" => Director,
    "ENGINEER" => Engineer,
    "LYRICIST" => Lyricist,
    "DJMIXER" => MixDj,
    "MIXER" => MixEngineer,
    "PERFORMER" => Performer,
    "PRODUCER" => Producer,
    "PUBLISHER" => Publisher,
    "LABEL" | "ORGANIZATION" => Label,
    "REMIXER" | "MIXARTIST" => Remixer,
    "DISCNUMBER" => DiscNumber,
    "DISCTOTAL" | "TOTALDISCS" => DiscTotal,
    "TRACKNUMBER" => TrackNumber,
    "TRACKTOTAL" | "TOTALTRACKS" => TrackTotal,
    "RATING" => Popularimeter,
    "DATE" => RecordingDate,
    "YEAR" => Year,
    "ORIGINALDATE" | "ORIGINALYEAR" => OriginalReleaseDate,
    "RELEASEDATE" => ReleaseDate,
    "ISRC" => Isrc,
    "BARCODE" => Barcode,
    "CATALOGNUMBER" => CatalogNumber,
    "COMPILATION" => FlagCompilation,
    "MEDIA" => OriginalMediaType,
    "ENCODEDBY" | "ENCODED-BY" | "ENCODED_BY" => EncodedBy,
    "ENCODER" => EncoderSoftware,
    "ENCODING" | "ENCODERSETTINGS" => EncoderSettings,
    "REPLAYGAIN_ALBUM_GAIN" => ReplayGainAlbumGain,
    "REPLAYGAIN_ALBUM_PEAK" => ReplayGainAlbumPeak,
    "REPLAYGAIN_TRACK_GAIN" => ReplayGainTrackGain,
    "REPLAYGAIN_TRACK_PEAK" => ReplayGainTrackPeak,
    "GENRE" => Genre,
    "COLOR" => Color,
    "MOOD" => Mood,
    "BPM" => Bpm,
    // MusicBrainz Picard suggests "KEY" (VirtualDJ, Denon Engine DJ), but "INITIALKEY"
    // seems to be more common (Rekordbox, Serato DJ, Traktor DJ, Mixxx).
    // <https://picard-docs.musicbrainz.org/en/appendices/tag_mapping.html#initial-key>
    // <https://github.com/beetbox/beets/issues/637#issuecomment-39528023>
    "INITIALKEY" | "KEY" => InitialKey,
    "COPYRIGHT" => CopyrightMessage,
    "LICENSE" => License,
    "COMMENT" => Comment,
    "LANGUAGE" => Language,
    "SCRIPT" => Script,
    "LYRICS" => Lyrics,
    "MUSICBRAINZ_TRACKID" => MusicBrainzRecordingId,
    "MUSICBRAINZ_RELEASETRACKID" => MusicBrainzTrackId,
    "MUSICBRAINZ_ALBUMID" => MusicBrainzReleaseId,
    "MUSICBRAINZ_RELEASEGROUPID" => MusicBrainzReleaseGroupId,
    "MUSICBRAINZ_ARTISTID" => MusicBrainzArtistId,
    "MUSICBRAINZ_ALBUMARTISTID" => MusicBrainzReleaseArtistId,
    "MUSICBRAINZ_WORKID" => MusicBrainzWorkId
    );

    For example, I’ve encountered many high-quality FLAC files in the wild where fields like TRACKTOTAL or DISCTOTAL are not parsed via tag.track_total() or tag.disk_total()

    You should be able to do:

    metadata.set_total_tracks(tag.track_total().map(|n| n as u16).or_else(|| {
        tag.get_string(&ItemKey::TrackTotal)
            .and_then(|s| s.trim().parse::<u16>().ok())
    }));
    
    metadata.set_total_discs(tag.disk_total().map(|n| n as u16).or_else(|| {
        tag.get_string(&ItemKey::DiscTotal)
            .and_then(|s| s.trim().parse::<u16>().ok())
    }));

    ItemKey::TrackTotal and ItemKey::DiscTotal should map to the expected keys:

    "DISCTOTAL" | "TOTALDISCS" => DiscTotal,
    "TRACKNUMBER" => TrackNumber,
    "TRACKTOTAL" | "TOTALTRACKS" => TrackTotal,

    Does that not work?

  4. Undead34 commented on May 13, 2025

    @Undead34

    Thanks for the clarification and for maintaining such a great library! 🙏 I just tested using ItemKey::TrackTotal and ItemKey::DiscTotal as you suggested and it works perfectly—my FLAC files now parse both fields without needing Unknown. I hadn’t tried it that way originally, so apologies for the extra noise!

    When I have a free moment, I’d be happy to contribute a small docs PR with these examples to help others avoid the same confusion. Thanks again! 😊

  5. added this to the 0.23.0 milestone on Jul 7, 2025
  6. abique commented on Apr 9, 2026

    @abique

    Hi, this change seemed to have made it worse for me.
    Before I could simply put my own tags into the file using the Unknown thing in a completely generic way.
    Now the complexity exploded, I have to adjust my code to deal with the file type, cast to the concrete tag type, and then I can't use the generic keys anymore.
    I hope that I'm doing something wrong.

  7. Serial-ATA commented on Apr 26, 2026

    @Serial-ATA
    OwnerAuthor

    @abique You can still use the generic types and move to concrete tag types only when necessary

    In the simple case, you can just split your custom items into a separate handler that does a concrete conversion and insertion:

    use lofty::tag::Tag;
    
    fn process_tag(tag: Tag) -> Tag {
        // Do all your generic stuff
        tag.set_artist(String::from("Foo"));
    
        // Then the custom stuff
        add_custom_tags(tag)
    }
    
    fn add_custom_tags(tag: Tag) -> Tag {
        match tag.tag_type() {
            TagType::Id3v2 => {
                let mut id3v2: Id3v2Tag = tag.into();
                id3v2.insert_user_text(String::from("MY_FIELD"), String::from("SOME_VALUE"));
                return id3v2.into();
            }
            // And so on for the other formats...
        }
    }

    Or, you could do the inverse and read concrete file types up front and use SplitTag/MergeTag. You can check out an example of that here: https://gitlab.com/uklotzde/aoide-rs/-/blob/main/crates/media-file/src/fmt/mod.rs#L1174

    It's definitely some extra effort, but I'd rather do it this way than have users pass in arbitrary keys that may:

    1. Be silently discarded if they don't fit the format's spec
    2. Be stored in an unexpected way (e.g., in ID3v2 if your custom key is 4 characters should it be used as a frame ID or a TXXX description?)
  8. raldone01 commented on Oct 8, 2026

    @raldone01

    I tried to use TaggedFile to keep the opening and writing the same across formats.
    However when I tried to step down to the format level when setting my custom tags, the into() -> Tag calls discard custom information.

    Is there a way to still do this using TaggedFile?

    fn add_custom_tag(tag: Tag, yt_id: &str) -> Result<Tag> {
      match tag.tag_type() {
        TagType::Id3v2 => {
          let mut id3v2: Id3v2Tag = tag.into();
          id3v2.remove_user_text(YT_ID_KEY);
          id3v2.insert_user_text(YT_ID_KEY.to_string(), yt_id.to_string());
          Ok(id3v2.into()) // uses split_tag and DISCARDS custom tags
        },
        TagType::Mp4Ilst => {
          let mut mp4: Ilst = tag.into();
          let _ = mp4.remove(&MP4_ATOM_YT_ID_KEY);
          mp4.insert(Atom::new(
            MP4_ATOM_YT_ID_KEY,
            AtomData::UTF8(yt_id.to_string()),
          ));
          Ok(mp4.into()) // uses split_tag and DISCARDS custom tags
        },
        TagType::VorbisComments => {
          let mut vorbis: VorbisComments = tag.into();
          let _ = vorbis.remove(YT_ID_KEY);
          vorbis.push(YT_ID_KEY.to_string(), yt_id.to_string());
          Ok(vorbis.into()) // uses split_tag and DISCARDS custom tags
        },
        other => bail!("unsupported tag type for custom fields: {other:?}"),
      }
    }

    What I would want is a way to apply format specific changes to a TaggedFile. If a way exists I didn't find it.

    With the current Tag api it is very easy to loose information and custom tags.

  9. Serial-ATA commented on Oct 8, 2026

    @Serial-ATA
    OwnerAuthor

    @raldone01 Tags should preserve any items it cant convert:

    let mut id3v2 = Id3v2Tag::new();
    id3v2.insert_user_text(String::from("YT_ID"), String::from("Some ID"));
    
    // Preserves `YT_ID`
    let tag: Tag = id3v2.into();
    assert_eq!(tag.len(), 0, "Should keep `YT_ID` hidden");
    
    // Restores `YT_ID`
    let id3v2: Id3v2Tag = tag.into();
    assert_eq!(id3v2.get_user_text("YT_ID"), Some("Some ID"));

    But if you:

    Then anything format-specific is discarded

  10. raldone01 commented on Oct 8, 2026

    @raldone01

    Mhh okay then I am very confused.

    let mut test_vorbis = VorbisComments::new();
    test_vorbis.insert("key".to_string(), "value".to_string());
    let tag: Tag = test_vorbis.into();
    let after_vorbis: VorbisComments = tag.into();
    assert!(after_vorbis.get("key").is_some());

    This fails for me. I did not change the global options but I am not 100% sure about the default value from the docs.

  11. Serial-ATA commented on Oct 8, 2026

    @Serial-ATA
    OwnerAuthor

    Yeah, looks like I forgot to add it for VorbisComments after #526. I'll fix that in 0.25.5. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions