Three-Dimensional Optimal Spectral Extraction (TDOSE) from integral field spectroscopy