You need both ear training and music theory.
By "ear training", musicians mean the ability to identify musical intervals, chords, scales, etc. It means developing your relative pitch as opposed to perfect pitch. Perfect pitch is the ability to hear a tone and be able to identify what note it is ("is it a C# or a Bb?"). Relative pitch is the ability:
- to hear an interval and correctly identify its type (a major sixth, a perfect fifth, etc.).
- to hear a note and sing the note that's a specified interval above or below the given note ("sing the note a major third above this note I'm playing now.").
- to hear a chord and correctly identify its type (a major chord, a dominant chord, a diminished chord, etc.).
- to hear a scale or an arpeggio and identify its type (again, major, minor, etc.).
- to hear a chord progression and identify the chords' functions or relations (thanks to Ulf Åkerstedt for this suggestion).
You don't need perfect pitch at all. You need relative pitch in industrial-scale quantities.
Music theory is the knowledge of the component building blocks of music and the understanding of how they fit together. Some people would say that ear training is a component of music theory, and although I disagree, I also think it's splitting hairs to debate this point. More importantly, you need to know and understand:
- what musical intervals are, their types, and how to produce them on your instrument (this is where many people say ear training is a part of music theory, saying "how can you identify intervals if you don't even know what they are?" Again, I don't think it's worth arguing over the semantics).
- scales, especially major scales, and how to produce them on your instrument.
- how musical intervals combine to form chords, the various types of chords, and how to produce them on your instrument.
- the relationships between scales and chords, how chords emerge from scales, and how scales contain chords.
- how chords relate with each other to form chord progressions, and how those chord progressions work---this study is known as functional harmony (here's the answer I wrote on this site outlining the very basics of functional harmony).
Acquiring these skills will literally take years of focused daily practice, but I don't mean to scare you off---it's totally worth it. I highly recommend studying with a teacher. You can get all of this information from books, CDs, iPad apps, and other resources, but a teacher will give you both guidance tailored to your specific level of development and feedback on what you're doing right and wrong. Best of luck!