Skip to content

Reading year returns wrong value #565

Closed

Description

@UnknownSuperficialNight

Reproducer

year returns the wrong value

Set recorded date to 2007 in an opus file using set_year

"Recorded_Date":"2007",

try to read the year using tag.year() causes it to return 2025

I've an attached a reproducible build here:

lofty-year-bug.zip

if you read the year through any external tool it's 2007 while if you read it through lofty it's 2025

Edit1: Think I might have found out why using ffprobe -i 'test.opus' I get

Metadata:
  year            : 2025
  date            : 2007

Seems set_year writes to the date tag instead of the year tag, but year is reading the year tag

Summary

Using the year method seems to result in the wrong value in songs that have been edited via set_year

Expected behavior

It returns 2007 after it sets year = 2007

Activity

  1. added
    bug
    on Nov 8, 2025
  2. Serial-ATA commented on Nov 8, 2025

    @Serial-ATA
    Owner

    Interesting, good catch!

    So when using set_year(), it first checks if you have a RecordingDate, and if so, just replaces the year in that date:

    if let Some(item) = self.get_string(ItemKey::RecordingDate) {
    if item.len() >= 4 {
    let (_, remaining) = item.split_at(4);
    self.insert_text(ItemKey::RecordingDate, format!("{value}{remaining}"));
    return;
    }
    }

    I guess that path should also set ItemKey::Year if the format supports it.

  3. added this to the 0.23.0 milestone on Nov 8, 2025
  4. UnknownSuperficialNight commented on Nov 8, 2025

    @UnknownSuperficialNight
    ContributorAuthor

    This is maybe a bit off-topic, but why don't we have a set_year and set_date and if a year cannot be set on the type, then fallback to set_date ?

    As far as I'm a where year != date so shouldn't they be separated and since year can fall into date we can fallback on date then if year cannot be set?

  5. Serial-ATA commented on Nov 8, 2025

    @Serial-ATA
    Owner

    why don't we have a set_year and set_date

    I wouldn't be opposed to maybe adding a set_date() that takes a Timestamp.

    To make things work well generically, I only added year to Accessor since ID3v1 only supports a year field, and I used to only want Accessor to cover things that every format supports. I've relaxed that rule over the years, though.

    As far as I'm a where year != date

    The thing is, for almost every format, year should be part of date (it's even specified for Vorbis Comments). It's only ID3v1 and ID3v2.3 that officially separate year into its own field. Don't know why other formats have year fields, and I don't imagine many apps (if any) actually depend on it over date.

  6. UnknownSuperficialNight commented on Nov 8, 2025

    @UnknownSuperficialNight
    ContributorAuthor

    The thing is, for almost every format, year should be part of date (it's even specified for Vorbis Comments). It's only ID3v1 and ID3v2.3 that officially separate year into its own field. Don't know why other formats have year fields, and I don't imagine many apps (if any) actually depend on it over date.

    Thank you, I didn't look that deep into it, but the way set_year was programmed makes a lot more sense now.

    I guess that path should also set ItemKey::Year if the format supports it.

    So the problem is consistency at the moment. Another option to the proposed solution above would be to add a check, since we should be using date anyway if we set the date, then we should check if year is some and, if so, remove_key(ItemKey::Year);

    This way, we don't have duplicated values and there is no confusion, especially if someone uses another program/parser in that case, we have no idea what they will find.

    Code example:

    fn set_year(&mut self, value: u32) {
    	if let Some(item) = self.get_string(ItemKey::RecordingDate) {
    		if item.len() >= 4 {
    			let (_, remaining) = item.split_at(4);
    			self.insert_text(ItemKey::RecordingDate, format!("{value}{remaining}"));
    
    			// Remove the year value if we are using date to store year values
    			if ItemKey::Year.map_key(self.tag_type).is_some() {
    				self.remove_key(ItemKey::Year);
    			}
    			return;
    		}
    	}
    
    	// Some formats have a dedicated item for `Year`, others just have it as
    	// a part of `RecordingDate`
    	if ItemKey::Year.map_key(self.tag_type).is_some() {
    		self.insert_text(ItemKey::Year, value.to_string());
    	} else {
    		self.insert_text(ItemKey::RecordingDate, value.to_string());
    	}
    }

    I don't mind making a PR when we have decided what's best

  7. Serial-ATA commented on Nov 9, 2025

    @Serial-ATA
    Owner

    So it should be:

    • If the format supports ItemKey::RecordingDate
      • Check if there's an existing date, and if so update it
      • Otherwise set a new one at ItemKey::RecordingDate
    • Otherwise set ItemKey::Year

    And then in the ItemKey::RecordingDate case, maybe it should also check if the tag already has an ItemKey::Year, and only update it then? So that by default only dates are used, but we also prevent desync for existing year tags.

  8. UnknownSuperficialNight commented on Nov 9, 2025

    @UnknownSuperficialNight
    ContributorAuthor

    So it should be:

    * If the format supports `ItemKey::RecordingDate`
      
      * Check if there's an existing date, and if so update it
      * Otherwise set a new one at `ItemKey::RecordingDate`
    
    * Otherwise set `ItemKey::Year`
    

    And then in the ItemKey::RecordingDate case, maybe it should also check if the tag already has an ItemKey::Year, and only update it then? So that by default only dates are used, but we also prevent desync for existing year tags.

    Forgive me, I just woke up so I may be interpreting this wrongly, do you mean something like this?

    fn set_year(&mut self, value: u32) {
    	// Check if RecordingDate exists and is at least 4 chars
    	if let Some(recording_date) = self.get_string(ItemKey::RecordingDate) {
    		if recording_date.len() >= 4 {
    			// Check if Year is empty or missing before updating RecordingDate
    			let year_empty = match self.get_string(ItemKey::Year) {
    				Some(year_val) => year_val.is_empty(),
    				None => true,
    			};
    
    			if year_empty {
    				let (_, remaining) = recording_date.split_at(4);
    				self.insert_text(ItemKey::RecordingDate, format!("{value}{remaining}"));
    				return;
    			}
    		}
    	}
    
    	// Some formats have a dedicated item for `Year`, others just have it as
    	// a part of `RecordingDate`
    	if ItemKey::Year.map_key(self.tag_type).is_some() {
    		self.insert_text(ItemKey::Year, value.to_string());
    	} else {
    		self.insert_text(ItemKey::RecordingDate, value.to_string());
    	}
    }

    So we check year before writing in RecordingDate thus if year is some we use it, but by default we try to use date?

    Edit1: Might also be worth checking if both are equal to each other, if so then write it to date?

  9. Serial-ATA commented on Nov 9, 2025

    @Serial-ATA
    Owner

    I meant something like:

    fn set_year(&mut self, value: u32) {
        // For formats that don't support `ItemKey::RecordingDate`, just try to
        // insert an `ItemKey::Year`.
        if ItemKey::RecordingDate.map_key(self.tag_type).is_none() {
            self.insert_text(ItemKey::Year, value.to_string());
            return;
        }
    
        // Then for formats supporting `ItemKey::RecordingDate`
    
        // Check for an existing date
        match self.get_string(ItemKey::RecordingDate) {
            // Existing valid date, update the year portion
            Some(recording_date) if recording_date.len() >= 4 => {
                let (_, remaining) = item.split_at(4);
                self.insert_text(ItemKey::RecordingDate, format!("{value}{remaining}"));
            }
            // No date or invalid date, just replace the entire item
            None => {
                self.insert_text(ItemKey::RecordingDate, value.to_string());
            }
        }
    
        // Then, if there's an `ItemKey::Year` present, overwrite it as well
        if self.contains(&ItemKey::Year) {
            self.insert_text(ItemKey::Year, value.to_string());
        }
    }
  10. UnknownSuperficialNight commented on Nov 9, 2025

    @UnknownSuperficialNight
    ContributorAuthor

    Ah, I see, so basically setting both to keep them consistent. It's a little redundant but consistent

    Honestly, in my opinion, both of these could be useful, so what do you think of a hybrid between the two, like adding a bias_towards_recordingdate bool where, if false, does what you are doing but if true, it tries to set recordingdate if possible, or a second function that tries to enforce the usage of RecordingDate as much as possible?

    So, then we have the safe and consistent option one and the efficient deduplicated option?

  11. Serial-ATA commented on Nov 10, 2025

    @Serial-ATA
    Owner

    I'd prefer not to add anything extra to the Accessor methods. They're really just designed to do the safe defaults.

    Honestly, it might just be better to replace set_year() with set_date() and avoid ItemKey::Year entirely. It'd be nice to have a generic way to set full dates. And since it'd take a Timestamp, the impl for ID3v1 can just pull the year from it and discard the rest.

  12. UnknownSuperficialNight commented on Nov 10, 2025

    @UnknownSuperficialNight
    ContributorAuthor

    Honestly, it might just be better to replace set_year() with set_date() and avoid ItemKey::Year

    It would make sense with Timestamp as we can set the year and others through that and, from what I know, don't most, if not all metadata standards support dates, while year as a standalone field is the exception?

  13. Serial-ATA commented on Nov 10, 2025

    @Serial-ATA
    Owner

    Yeah, ID3v1 is the only exception since it only supports year. Though I have seen standalone year fields in the wild in Vorbis Comments, at least. Don't know why they exist or if anyone actually uses them.

    But if Lofty just consistently switches to date then it doesn't really matter what happens with the year field. set_date() could just remove the year field to prevent the desync entirely.

    And ItemKey::Year would still be around for anyone that wants to use it.

  14. UnknownSuperficialNight commented on Nov 10, 2025

    @UnknownSuperficialNight
    ContributorAuthor

    But if Lofty just consistently switches to date then it doesn't really matter what happens with the year field.

    True, and everything supports it.

    set_date() could just remove the year field to prevent the desync entirely.

    You mean just read the date field and set date field ignoring year, or do you mean when editing date field removing year?

    If it's the latter I don't see why we need to, I'd just keep it separated so if someone wants to make their own custom implementation for year in the year field that can do it but at least they don't have to deal with the main API clearing it.

    Another thing, how do you expect to read the date? Using those same timestamps?

    Though I have seen standalone year fields in the wild in Vorbis Comments, at least. Don't know why they exist or if anyone actually uses them.

    I'm that guy lol, I only wanted year, so I use the year column where possible but if it's not possible I fallback on date, but I care less about that now than I used too as long as what I write is what gets returned then I'm OK with it

  15. Serial-ATA commented on Nov 10, 2025

    @Serial-ATA
    Owner

    You mean just read the date field and set date field ignoring year, or do you mean when editing date field removing year?

    The latter. Calls to set_date() or remove_date() would also remove ItemKey::Year. If someone really wants to add a year, all they would need to do is:

    let tagged_file = lofty::read_from_path("foo.mp3")?;
    let tag = tagged_file.primary_tag_mut().unwrap();
    
    // Update the date, which removes `ItemKey::Year` if present
    tag.set_date(Timestamp {
        year: 2025,
        month: Some(11),
        day: Some(10),
        ..Default::default()
    });
    
    // Then update the year manually
    tag.insert_text(ItemKey::Year, 2025.to_string());

    Leaving the year as-is would cause a desync and keeping it synced adds extra work for a (mostly) useless field.

    Another thing, how do you expect to read the date? Using those same timestamps?

    Yeah, you can use Timestamp::parse(). It handles a bunch of common spec violations and timestamp formats.

    let tagged_file = lofty::read_from_path("foo.mp3")?;
    let tag = tagged_file.primary_tag_mut().unwrap();
    
    let date = tag.get_string(ItemKey::RecordingDate).unwrap();
    match Timestamp::parse(&mut date.as_bytes(), ParsingMode::Relaxed) {
    	Ok(Some(timestamp)) => println!("Date is: {timestamp}"),
        Ok(None) => eprintln!("Empty timestamp!"),
    	Err(e) => eprintln!("Failed to parse timestamp: {e}"),
    }

    I'm that guy lol, I only wanted year, so I use the year column where possible

    Do note that a year is a valid Timestamp, so you could just:

    let tagged_file = lofty::read_from_path("foo.mp3")?;
    let tag = tagged_file.primary_tag_mut().unwrap();
    
    tag.set_date(Timestamp {
        year: 2025,
        ..Default::default()
    });
  16. UnknownSuperficialNight commented on Nov 10, 2025

    @UnknownSuperficialNight
    ContributorAuthor

    Do note that a year is a valid Timestamp, so you could just:

    Yea, that's why I don't care too much about year anymore date makes a lot more sense now.

    But I think this looks good, I would assume for the read date we pass in ParsingMode and Timestamp then we get back the date?

    And you want me to make this and make a PR, or do you want to do it yourself?

  17. Serial-ATA commented on Nov 10, 2025

    @Serial-ATA
    Owner

    I would assume for the read date we pass in ParsingMode and Timestamp then we get back the date?

    For simplicity, the *_date() methods can just assume ParsingMode::Relaxed, and just be as simple as:

    impl Tag {
        fn date(&self) -> Option<Timestamp> {
            self.get_string(ItemKey::RecordingDate)
                .and_then(|d| Timestamp::parse(&mut d.as_bytes(), ParsingMode::Relaxed).ok())
        }
    
        fn set_date(&mut self, value: Timestamp) {
            let _ = self.remove_key(ItemKey::Year);
            self.insert_text(ItemKey::RecordingDate, value.to_string());
        }
    
        fn remove_date(&mut self) {
            let _ = self.remove_key(ItemKey::Year);
            let _ = self.remove_key(ItemKey::RecordingDate);
        }
    }

    And you want me to make this and make a PR, or do you want to do it yourself?

    Feel free to make a PR, otherwise I'll try to pick it up in the next few days if I have time.

    It's just a matter of changing:

    [year ]<u32>, [comment ]<Cow<'_, str>, String>,

    to [date ]<Timestamp>, then updating all the impls.

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

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions