''It was premeditated ... otherwise you would not have gone to that area,'' Judge Emma Smith pointed out.
Half an hour later, the defendant positioned himself behind a large bookshelf, 3m from a girl who was on a beanbag, reading.
He covered his crotch with a book and masturbated, leaving the scene two minutes later.
The teenage girl was oblivious to the act but library staff had spotted it.
When he was shown a replay on CCTV, the defendant acknowledged he was the man on camera but denied he was masturbating.
''It was too embarrassing to talk about,'' he told police.
However, when the matter came before the court, the man pleaded guilty immediately.
His counsel, Sarah Saunderson-Warner, said the rape charge looming over him had been ''hugely distressing''.
The resulting anxiety and depression had produced the indecent act, she said.
As far as excuses went it was ''a poor one'', Judge Smith said.
Saunderson-Warner said the girl on the beanbag had been unaware of the offending and that her client had no similar previous convictions.
Regardless, the judge said the facts were ''disturbing''.
She imposed name suppression so the man's fair-trial rights were preserved but the order will lapse once his trial - which will be held outside Dunedin - is completed.
He will appear in court again in November.